├── ankix ├── __init__.py ├── config.py ├── jupyter.py ├── preview.py ├── util.py ├── migration.py ├── ankix.py └── db.py ├── dev ├── __init__.py ├── do_extract.py ├── do_convert.py ├── test_regex.py ├── do_sample.py └── sample.json ├── sample ├── __init__.py ├── database_viewer.ipynb ├── chinese.ipynb ├── edit_css.ipynb └── example.ipynb ├── .gitattributes ├── pyproject.toml ├── LICENSE ├── README.md ├── .gitignore └── pyproject.lock /ankix/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /dev/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /sample/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.ipynb linguist-vendored 2 | -------------------------------------------------------------------------------- /dev/do_extract.py: -------------------------------------------------------------------------------- 1 | from zipfile import ZipFile 2 | 3 | if __name__ == '__main__': 4 | with ZipFile('/Users/patarapolw/Google Drive/Zanki Physiology and Pathology .apkg') as zf: 5 | zf.extractall('.') 6 | -------------------------------------------------------------------------------- /dev/do_convert.py: -------------------------------------------------------------------------------- 1 | from ankix import Ankix 2 | 3 | if __name__ == '__main__': 4 | Ankix.from_apkg( 5 | src_apkg='/Users/patarapolw/Google Drive/Zanki Physiology and Pathology .apkg', 6 | dst_ankix='../sample/medical.ankix' 7 | ) 8 | -------------------------------------------------------------------------------- /dev/test_regex.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | 4 | if __name__ == '__main__': 5 | with open('sample.json') as f: 6 | print(re.findall(r'src=[\'\"]((?!//)[^\'\"]+)[\'\"]', json.load(f)['tables']['notes']['flds'])) 7 | 8 | print(len(dict({ 9 | 'a': 1, 10 | 'b': 2 11 | }).items())) 12 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "ankix" 3 | version = "0.2" 4 | description = "New file format for Anki with improved review intervals and Peewee SQLite powered" 5 | authors = ["Pacharapol Withayasakpunt "] 6 | license = "MIT" 7 | readme = "README.md" 8 | include = ["datauri/**/*.py"] 9 | repository = "https://github.com/patarapolw/ankix" 10 | homepage = "https://github.com/patarapolw/ankix" 11 | keywords = ["anki", "spaced-repetition", "SRS"] 12 | 13 | [tool.poetry.dependencies] 14 | python = "*" 15 | peewee = "^3.7" 16 | tqdm = "^4.27" 17 | mistune = "^0.8.4" 18 | pytimeparse = "^1.1" 19 | python-magic = "^0.4.15" 20 | 21 | [tool.poetry.dev-dependencies] 22 | htmlviewer = "^0.1.7" 23 | -------------------------------------------------------------------------------- /ankix/config.py: -------------------------------------------------------------------------------- 1 | from datetime import timedelta 2 | 3 | from .util import parse_srs 4 | 5 | 6 | class Config(dict): 7 | DEFAULT = { 8 | 'markdown': True, 9 | 'srs': [ 10 | timedelta(minutes=10), # 0 11 | timedelta(hours=1), # 1 12 | timedelta(hours=4), # 2 13 | timedelta(hours=8), # 3 14 | timedelta(days=1), # 4 15 | timedelta(days=3), # 5 16 | timedelta(weeks=1), # 6 17 | timedelta(weeks=2), # 7 18 | timedelta(weeks=4), # 8 19 | timedelta(weeks=16) # 9 20 | ] 21 | } 22 | 23 | def __init__(self): 24 | super(Config, self).__init__(**self.DEFAULT) 25 | 26 | def to_db(self): 27 | d = dict() 28 | for k, v in self.items(): 29 | d[k] = { 30 | 'srs': lambda x: parse_srs(x, self.DEFAULT['srs']), 31 | }.get(k, lambda x: x)(v) 32 | 33 | return d 34 | 35 | 36 | 37 | 38 | config = Config() 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Pacharapol Withayasakpunt 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ankix/jupyter.py: -------------------------------------------------------------------------------- 1 | from .util import is_html, MediaType, do_markdown 2 | from .config import config 3 | 4 | 5 | class HTML: 6 | def __init__(self, html, media=None, model=None): 7 | if media is None: 8 | media = [] 9 | 10 | self.media = media 11 | self._raw = do_markdown(html) 12 | self.model = model 13 | 14 | def _repr_html_(self): 15 | return self.html 16 | 17 | def __repr__(self): 18 | return self.html 19 | 20 | def __str__(self): 21 | return self.html 22 | 23 | @property 24 | def html(self): 25 | return f''' 26 | 27 |
28 | {self.raw} 29 | 30 | ''' 31 | 32 | @property 33 | def raw(self): 34 | result = self._raw 35 | 36 | for medium in self.media: 37 | if medium.type_ == MediaType.audio: 38 | result = result.replace(f'[sound:{medium.name}]', medium.html) 39 | 40 | result = result.replace(medium.name, medium.src) 41 | 42 | return result 43 | 44 | @property 45 | def raw_css(self): 46 | css = '' 47 | 48 | if self.model: 49 | css += self.model.css 50 | for font in self.model.fonts: 51 | css = css.replace(font.name, font.src) 52 | 53 | return css 54 | -------------------------------------------------------------------------------- /dev/do_sample.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | import json 3 | 4 | 5 | def get_tables(src='collection.anki2', dst='sample.json'): 6 | conn = sqlite3.connect(src) 7 | conn.row_factory = sqlite3.Row 8 | 9 | d = dict() 10 | c = conn.execute('''SELECT tbl_name FROM sqlite_master WHERE type="table"''') 11 | for r in c: 12 | try: 13 | c1 = conn.execute(f''' 14 | SELECT * FROM "{r[0]}" 15 | WHERE id >= (abs(random()) % (SELECT max(id) FROM "{r[0]}")) 16 | LIMIT 1''') 17 | r1 = c1.fetchone() 18 | if r1: 19 | d[r[0]] = dict(r1) 20 | except sqlite3.OperationalError: 21 | pass 22 | 23 | with open(dst, 'w') as f: 24 | d0 = dict() 25 | d0['tables'] = d 26 | json.dump(d0, f, indent=2, ensure_ascii=False) 27 | 28 | 29 | def get_miscellaneous(src='collection.anki2', dst='sample.json'): 30 | conn = sqlite3.connect(src) 31 | conn.row_factory = sqlite3.Row 32 | 33 | with open(dst) as f: 34 | d0 = json.load(f) 35 | 36 | c = conn.execute('''SELECT * FROM col''') 37 | for k, v in dict(c.fetchone()).items(): 38 | if isinstance(v, str): 39 | d0.setdefault('col', dict())[k] = json.loads(v) 40 | d0['tables']['col'][k] = 'See below' 41 | 42 | with open(dst, 'w') as f: 43 | json.dump(d0, f, indent=2, ensure_ascii=False) 44 | 45 | 46 | if __name__ == '__main__': 47 | get_tables() 48 | get_miscellaneous() 49 | -------------------------------------------------------------------------------- /ankix/preview.py: -------------------------------------------------------------------------------- 1 | from uuid import uuid4 2 | import re 3 | 4 | from .util import do_markdown 5 | 6 | 7 | class TemplateMaker: 8 | def __init__(self, name, question, answer, css='', js='', _id=None): 9 | self.name = name 10 | self.question = do_markdown(question) 11 | self.answer = do_markdown(answer) 12 | self.css = css 13 | self.js = js 14 | self.sample = dict() 15 | 16 | if _id is None: 17 | self._id = str(uuid4()) 18 | else: 19 | self._id = _id 20 | 21 | @property 22 | def html(self): 23 | raw = f''' 24 | 25 |
26 |
27 |
{self.question}
28 | 29 |
30 | 31 | 32 | 43 | ''' 44 | 45 | for k, v in self.sample.items(): 46 | raw = raw.replace('{{%s}}' % k, do_markdown(str(v))) 47 | raw = raw.replace('{{cloze:%s}}' % k, do_markdown(str(v))) 48 | 49 | raw = re.sub('{{[^}]+}}', '', raw) 50 | 51 | return raw 52 | 53 | def _repr_html_(self): 54 | return self.html 55 | 56 | def __getitem__(self, item): 57 | return getattr(self, item) 58 | 59 | def get_sample(self, **kwargs): 60 | self.sample.update(kwargs) 61 | -------------------------------------------------------------------------------- /ankix/util.py: -------------------------------------------------------------------------------- 1 | import re 2 | import json 3 | from datetime import timedelta 4 | from pytimeparse.timeparse import timeparse 5 | import mistune 6 | from pathlib import Path 7 | import base64 8 | import mimetypes 9 | 10 | markdown = mistune.Markdown() 11 | RE_IS_HTML = re.compile(r"(?:)|(?:<[^<]+/>)") 12 | 13 | 14 | def is_html(s): 15 | return RE_IS_HTML.search(s) is not None 16 | 17 | 18 | class MediaType: 19 | image = 'image' 20 | font = 'font' 21 | audio = 'audio' 22 | 23 | 24 | def timedelta2str(x): 25 | if isinstance(x, str): 26 | x = timedelta(seconds=timeparse(x)) 27 | 28 | return str(x) 29 | 30 | 31 | def parse_srs(value, default): 32 | if isinstance(value, (list, tuple, dict)): 33 | if isinstance(value, dict): 34 | d = default 35 | for k, v in value.items(): 36 | d[int(k)] = v 37 | 38 | value = d 39 | else: 40 | raise ValueError 41 | 42 | return json.dumps([timedelta2str(x) for x in value]) 43 | 44 | 45 | def do_markdown(s): 46 | from .config import config 47 | if config.get('markdown'): 48 | return markdown(s) 49 | 50 | return s 51 | 52 | 53 | def build_base64(fp): 54 | """ 55 | Build data URI according to RFC 2397 56 | (data:[][;base64],) 57 | :param str|Path|bytes fp: 58 | :return: 59 | """ 60 | if isinstance(fp, (str, Path)) and Path(fp).is_file(): 61 | b = Path(fp).read_bytes() 62 | try: 63 | import magic 64 | mime = magic.from_file(fp, mime=True) 65 | except ImportError: 66 | mime, _ = mimetypes.guess_type(str(fp)) 67 | else: 68 | import magic 69 | b = fp 70 | mime = magic.from_buffer(fp, mime=True) 71 | 72 | data64 = base64.b64encode(b).decode() 73 | 74 | return 'data:{};base64,{}'.format(mime, data64) 75 | 76 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ankix 2 | 3 | [![PyPI version shields.io](https://img.shields.io/pypi/v/ankix.svg)](https://pypi.python.org/pypi/ankix/) 4 | [![PyPI license](https://img.shields.io/pypi/l/ankix.svg)](https://pypi.python.org/pypi/ankix/) 5 | 6 | New file format for Anki with improved review intervals. Pure [peewee](https://github.com/coleifer/peewee) SQLite database, no zipfile. Available to work with on Jupyter Notebook. 7 | 8 | ## Usage 9 | 10 | On Jupyter Notebook, 11 | 12 | ```python 13 | >>> from ankix import ankix, db as a 14 | >>> ankix.init('test.ankix') # A file named 'test.ankix' will be created. 15 | >>> ankix.import_apkg('foo.apkg') # Import the contents from 'foo.apkg' 16 | >>> iter_quiz = a.iter_quiz() 17 | >>> card = next(iter_quiz) 18 | >>> card 19 | 'A flashcard is show on Jupyter Notebook. You can click to change card side, to answer-side.' 20 | 'It is HTML, CSS, Javascript, Image enabled. Cloze test is also enabled. Audio is not yet tested.' 21 | >>> card.right() # Mark the card as right 22 | >>> card.wrong() # Mark the card as wrong 23 | >>> card.mark() # Add the tag 'marked' to the note. 24 | ``` 25 | 26 | You can directly make use of Peewee capabilities, 27 | 28 | ```python 29 | >>> a.Card.select().join(a.Note).where(a.Note.data['field_a'] == 'bar')[0] 30 | 'The front side of the card is shown.' 31 | ``` 32 | 33 | ## Adding new cards 34 | 35 | Adding new cards is now possible. This has been tested in https://github.com/patarapolw/zhlib/blob/master/zhlib/export.py#L15 36 | 37 | ```python 38 | from ankix import ankix, db as a 39 | ankix.init('test.ankix') 40 | a_model = a.Model.add( 41 | name='foo', 42 | templates=[ 43 | a.TemplateMaker( 44 | name='Forward', 45 | question=Q_FORMAT, 46 | answer=A_FORMAT 47 | ), 48 | a.TemplateMaker( 49 | name='Reverse', 50 | question=Q_FORMAT, 51 | answer=A_FORMAT) 52 | ], 53 | css=CSS, 54 | js=JS 55 | ) 56 | # Or, a_model = a.Model.get(name='foo') 57 | for record in records: 58 | a.Note.add( 59 | data=record, 60 | model=a_model, 61 | card_to_decks={ 62 | 'Forward': 'Forward deck', 63 | 'Reverse': 'Reverse deck' 64 | }, 65 | tags=['bar', 'baz'] 66 | ) 67 | ``` 68 | 69 | ## Installation 70 | 71 | ```commandline 72 | $ pip install ankix 73 | ``` 74 | 75 | ## Plans 76 | 77 | - Test by using it a lot. 78 | -------------------------------------------------------------------------------- /ankix/migration.py: -------------------------------------------------------------------------------- 1 | import peewee as pv 2 | from playhouse.migrate import SqliteMigrator, migrate 3 | 4 | from . import db 5 | 6 | 7 | def do_migrate(src_version, dst_version, forced=False): 8 | migrator = SqliteMigrator(db.database) 9 | 10 | if (src_version, dst_version) == ('0.1.4', '0.1.5'): 11 | with db.database.atomic(): 12 | for table_name in ['media', 'template', 'note', 'card']: 13 | try: 14 | migrate( 15 | migrator.add_column(table_name, 'h', pv.TextField(unique=True, null=True)) 16 | ) 17 | except pv.OperationalError: 18 | pass 19 | 20 | db.create_all_tables() 21 | 22 | for record in db.Media.select(): 23 | try: 24 | record.h = '' 25 | record.save() 26 | except pv.IntegrityError: 27 | print('{} is duplicated: {}'.format(record.id, record.name)) 28 | if not forced: 29 | raise 30 | else: 31 | record.delete_instance() 32 | 33 | for record in db.Template.select(): 34 | try: 35 | record.h = '' 36 | record.save() 37 | except pv.IntegrityError: 38 | print('{} is duplicated: {}'.format(record.id, record.question + record.answer)) 39 | if not forced: 40 | raise 41 | else: 42 | record.delete_instance() 43 | 44 | for record in db.Note.select(): 45 | try: 46 | data = record.data 47 | for k, v in data.items(): 48 | record.data[k] = str(v) 49 | record.save() 50 | except pv.IntegrityError: 51 | print('{} is duplicated: {}'.format(record.id, record.data)) 52 | if not forced: 53 | raise 54 | else: 55 | record.delete_instance() 56 | 57 | for record in db.Card.select(): 58 | try: 59 | record.h = '' 60 | record.save() 61 | except pv.IntegrityError: 62 | print('{} is duplicated: {}'.format(record.id, record.question.raw)) 63 | if not forced: 64 | raise 65 | else: 66 | record.delete_instance() 67 | elif (src_version, dst_version) == ('0.1.5', '0.1.6'): 68 | migrate( 69 | migrator.add_column('model', 'js', pv.TextField(default='')) 70 | ) 71 | else: 72 | raise ValueError('Not supported for {}, {}'.format(src_version, dst_version)) 73 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | # Created by https://www.gitignore.io/api/osx,python,pycharm,jupyternotebook 3 | 4 | ### JupyterNotebook ### 5 | .ipynb_checkpoints 6 | */.ipynb_checkpoints/* 7 | 8 | # Remove previous ipynb_checkpoints 9 | # git rm -r .ipynb_checkpoints/ 10 | # 11 | 12 | ### OSX ### 13 | # General 14 | .DS_Store 15 | .AppleDouble 16 | .LSOverride 17 | 18 | # Icon must end with two \r 19 | Icon 20 | 21 | # Thumbnails 22 | ._* 23 | 24 | # Files that might appear in the root of a volume 25 | .DocumentRevisions-V100 26 | .fseventsd 27 | .Spotlight-V100 28 | .TemporaryItems 29 | .Trashes 30 | .VolumeIcon.icns 31 | .com.apple.timemachine.donotpresent 32 | 33 | # Directories potentially created on remote AFP share 34 | .AppleDB 35 | .AppleDesktop 36 | Network Trash Folder 37 | Temporary Items 38 | .apdisk 39 | 40 | ### PyCharm ### 41 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm 42 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839 43 | 44 | # User-specific stuff 45 | .idea/**/workspace.xml 46 | .idea/**/tasks.xml 47 | .idea/**/usage.statistics.xml 48 | .idea/**/dictionaries 49 | .idea/**/shelf 50 | 51 | # Generated files 52 | .idea/**/contentModel.xml 53 | 54 | # Sensitive or high-churn files 55 | .idea/**/dataSources/ 56 | .idea/**/dataSources.ids 57 | .idea/**/dataSources.local.xml 58 | .idea/**/sqlDataSources.xml 59 | .idea/**/dynamic.xml 60 | .idea/**/uiDesigner.xml 61 | .idea/**/dbnavigator.xml 62 | 63 | # Gradle 64 | .idea/**/gradle.xml 65 | .idea/**/libraries 66 | 67 | # Gradle and Maven with auto-import 68 | # When using Gradle or Maven with auto-import, you should exclude module files, 69 | # since they will be recreated, and may cause churn. Uncomment if using 70 | # auto-import. 71 | # .idea/modules.xml 72 | # .idea/*.iml 73 | # .idea/modules 74 | 75 | # CMake 76 | cmake-build-*/ 77 | 78 | # Mongo Explorer plugin 79 | .idea/**/mongoSettings.xml 80 | 81 | # File-based project format 82 | *.iws 83 | 84 | # IntelliJ 85 | out/ 86 | 87 | # mpeltonen/sbt-idea plugin 88 | .idea_modules/ 89 | 90 | # JIRA plugin 91 | atlassian-ide-plugin.xml 92 | 93 | # Cursive Clojure plugin 94 | .idea/replstate.xml 95 | 96 | # Crashlytics plugin (for Android Studio and IntelliJ) 97 | com_crashlytics_export_strings.xml 98 | crashlytics.properties 99 | crashlytics-build.properties 100 | fabric.properties 101 | 102 | # Editor-based Rest Client 103 | .idea/httpRequests 104 | 105 | # Android studio 3.1+ serialized cache file 106 | .idea/caches/build_file_checksums.ser 107 | 108 | ### PyCharm Patch ### 109 | # Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721 110 | 111 | # *.iml 112 | # modules.xml 113 | # .idea/misc.xml 114 | # *.ipr 115 | 116 | # Sonarlint plugin 117 | .idea/sonarlint 118 | 119 | ### Python ### 120 | # Byte-compiled / optimized / DLL files 121 | __pycache__/ 122 | *.py[cod] 123 | *$py.class 124 | 125 | # C extensions 126 | *.so 127 | 128 | # Distribution / packaging 129 | .Python 130 | build/ 131 | develop-eggs/ 132 | dist/ 133 | downloads/ 134 | eggs/ 135 | .eggs/ 136 | lib/ 137 | lib64/ 138 | parts/ 139 | sdist/ 140 | var/ 141 | wheels/ 142 | *.egg-info/ 143 | .installed.cfg 144 | *.egg 145 | MANIFEST 146 | 147 | # PyInstaller 148 | # Usually these files are written by a python script from a template 149 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 150 | *.manifest 151 | *.spec 152 | 153 | # Installer logs 154 | pip-log.txt 155 | pip-delete-this-directory.txt 156 | 157 | # Unit test / coverage reports 158 | htmlcov/ 159 | .tox/ 160 | .nox/ 161 | .coverage 162 | .coverage.* 163 | .cache 164 | nosetests.xml 165 | coverage.xml 166 | *.cover 167 | .hypothesis/ 168 | .pytest_cache/ 169 | 170 | # Translations 171 | *.mo 172 | *.pot 173 | 174 | # Django stuff: 175 | *.log 176 | local_settings.py 177 | db.sqlite3 178 | 179 | # Flask stuff: 180 | instance/ 181 | .webassets-cache 182 | 183 | # Scrapy stuff: 184 | .scrapy 185 | 186 | # Sphinx documentation 187 | docs/_build/ 188 | 189 | # PyBuilder 190 | target/ 191 | 192 | # Jupyter Notebook 193 | 194 | # IPython 195 | profile_default/ 196 | ipython_config.py 197 | 198 | # pyenv 199 | .python-version 200 | 201 | # celery beat schedule file 202 | celerybeat-schedule 203 | 204 | # SageMath parsed files 205 | *.sage.py 206 | 207 | # Environments 208 | .env 209 | .venv 210 | env/ 211 | venv/ 212 | ENV/ 213 | env.bak/ 214 | venv.bak/ 215 | 216 | # Spyder project settings 217 | .spyderproject 218 | .spyproject 219 | 220 | # Rope project settings 221 | .ropeproject 222 | 223 | # mkdocs documentation 224 | /site 225 | 226 | # mypy 227 | .mypy_cache/ 228 | .dmypy.json 229 | dmypy.json 230 | 231 | ### Python Patch ### 232 | .venv/ 233 | 234 | ### Python.VirtualEnv Stack ### 235 | # Virtualenv 236 | # http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ 237 | [Bb]in 238 | [Ii]nclude 239 | [Ll]ib 240 | [Ll]ib64 241 | [Ll]ocal 242 | [Ss]cripts 243 | pyvenv.cfg 244 | pip-selfcheck.json 245 | 246 | 247 | # End of https://www.gitignore.io/api/osx,python,pycharm,jupyternotebook 248 | 249 | *.apkg 250 | *.anki2 251 | *.ankix 252 | *.db 253 | **/media 254 | .vscode/ 255 | .idea/ 256 | setup.py 257 | -------------------------------------------------------------------------------- /sample/database_viewer.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from ankix import Ankix\n", 10 | "db = Ankix('medical.ankix')" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "metadata": {}, 17 | "outputs": [ 18 | { 19 | "data": { 20 | "text/plain": [ 21 | "{'settings': ,\n", 22 | " 'tag': ,\n", 23 | " 'media': ,\n", 24 | " 'model': ,\n", 25 | " 'template': ,\n", 26 | " 'deck': ,\n", 27 | " 'note': ,\n", 28 | " 'note_tag': ,\n", 29 | " 'note_media': ,\n", 30 | " 'card': }" 31 | ] 32 | }, 33 | "execution_count": 2, 34 | "metadata": {}, 35 | "output_type": "execute_result" 36 | } 37 | ], 38 | "source": [ 39 | "db.tables" 40 | ] 41 | }, 42 | { 43 | "cell_type": "code", 44 | "execution_count": 2, 45 | "metadata": {}, 46 | "outputs": [ 47 | { 48 | "data": { 49 | "text/html": [ 50 | "\n", 51 | " \n", 58 | " " 59 | ], 60 | "text/plain": [ 61 | "" 62 | ] 63 | }, 64 | "metadata": {}, 65 | "output_type": "display_data" 66 | }, 67 | { 68 | "data": { 69 | "text/html": [], 70 | "text/plain": [ 71 | "" 72 | ] 73 | }, 74 | "execution_count": 2, 75 | "metadata": {}, 76 | "output_type": "execute_result" 77 | } 78 | ], 79 | "source": [ 80 | "viewer = db['note'].get_viewer(db['note'].select())\n", 81 | "viewer" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": 3, 87 | "metadata": {}, 88 | "outputs": [ 89 | { 90 | "data": { 91 | "text/html": [ 92 | "\n", 93 | " \n", 147 | "
\n", 148 | "
\n", 149 | "
我没有问题。
\n", 150 | " \n", 163 | "
\n", 164 | "\n", 165 | " \n", 176 | " " 177 | ], 178 | "text/plain": [ 179 | "" 180 | ] 181 | }, 182 | "execution_count": 3, 183 | "metadata": {}, 184 | "output_type": "execute_result" 185 | } 186 | ], 187 | "source": [ 188 | "db['card'].select()[0]" 189 | ] 190 | }, 191 | { 192 | "cell_type": "code", 193 | "execution_count": null, 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [] 197 | } 198 | ], 199 | "metadata": { 200 | "kernelspec": { 201 | "display_name": "Python 3", 202 | "language": "python", 203 | "name": "python3" 204 | }, 205 | "language_info": { 206 | "codemirror_mode": { 207 | "name": "ipython", 208 | "version": 3 209 | }, 210 | "file_extension": ".py", 211 | "mimetype": "text/x-python", 212 | "name": "python", 213 | "nbconvert_exporter": "python", 214 | "pygments_lexer": "ipython3", 215 | "version": "3.7.0" 216 | } 217 | }, 218 | "nbformat": 4, 219 | "nbformat_minor": 2 220 | } 221 | -------------------------------------------------------------------------------- /ankix/ankix.py: -------------------------------------------------------------------------------- 1 | import sqlite3 2 | from zipfile import ZipFile 3 | from tempfile import TemporaryDirectory 4 | import json 5 | from tqdm import tqdm 6 | import os 7 | import re 8 | import logging 9 | 10 | from .config import config 11 | from .util import MediaType 12 | from . import db 13 | 14 | 15 | def init(database, **kwargs): 16 | db.database.init(database, **kwargs) 17 | if not os.path.exists(database): 18 | db.create_all_tables() 19 | 20 | 21 | def update_config(markdown=False, srs=None): 22 | config.update(markdown=markdown, srs=srs) 23 | if db.Settings.get_or_none() is None: 24 | db.Settings().save() 25 | else: 26 | config.update(db.Settings.to_dict()) 27 | 28 | 29 | def import_apkg(src_apkg, skip_media=False): 30 | """ 31 | 32 | :param src_apkg: 33 | :param bool|list skip_media: 34 | :return: 35 | """ 36 | info = dict() 37 | 38 | with TemporaryDirectory() as temp_dir: 39 | with db.database.atomic(): 40 | with ZipFile(src_apkg) as zf: 41 | zf.extractall(temp_dir) 42 | 43 | conn = sqlite3.connect(os.path.join(temp_dir, 'collection.anki2')) 44 | conn.row_factory = sqlite3.Row 45 | 46 | try: 47 | d = dict(conn.execute('''SELECT * FROM col LIMIT 1''').fetchone()) 48 | for model in tqdm(tuple(json.loads(d['models']).values()), desc='models'): 49 | db.Model.create( 50 | id=model['id'], 51 | name=model['name'], 52 | css=model['css'] 53 | ) 54 | 55 | info.setdefault('model', dict())[int(model['id'])] = model 56 | for media_name in re.findall(r'url\([\'\"]((?!.*//)[^\'\"]+)[\'\"]\)', model['css']): 57 | info.setdefault('media', dict())\ 58 | .setdefault(MediaType.font, dict())\ 59 | .setdefault(media_name, [])\ 60 | .append(model['id']) 61 | 62 | for template in model['tmpls']: 63 | db_template = db.Template.get_or_create( 64 | model_id=model['id'], 65 | name=template['name'], 66 | question=template['qfmt'], 67 | answer=template['afmt'], 68 | )[0] 69 | 70 | info.setdefault('template', dict())[db_template.id] = template 71 | 72 | for deck in tqdm(tuple(json.loads(d['decks']).values()), desc='decks'): 73 | db.Deck.create( 74 | id=deck['id'], 75 | name=deck['name'] 76 | ) 77 | 78 | c = conn.execute('''SELECT * FROM notes''') 79 | for note in tqdm(c.fetchall(), desc='notes'): 80 | info_model = info['model'][note['mid']] 81 | header = [field['name'] for field in info_model['flds']] 82 | 83 | db_note = db.Note.create( 84 | id=note['id'], 85 | model_id=note['mid'], 86 | data=dict(zip(header, note['flds'].split('\u001f'))) 87 | ) 88 | 89 | for tag in set(t for t in note['tags'].split(' ') if t): 90 | db_tag = db.Tag.get_or_create( 91 | name=tag 92 | )[0] 93 | 94 | db_tag.notes.add(db_note) 95 | 96 | info.setdefault('note', dict())[note['id']] = dict(note) 97 | 98 | for media_name in re.findall(r'src=[\'\"]((?!.*//)[^\'\"]+)[\'\"]', note['flds']): 99 | info.setdefault('media', dict())\ 100 | .setdefault(MediaType.image, dict())\ 101 | .setdefault(media_name, [])\ 102 | .append(note['id']) 103 | 104 | for media_name in re.findall(r'\[sound:[^\]]+\]', note['flds']): 105 | info.setdefault('media', dict()) \ 106 | .setdefault(MediaType.audio, dict()) \ 107 | .setdefault(media_name, []) \ 108 | .append(note['id']) 109 | 110 | c = conn.execute('''SELECT * FROM cards''') 111 | for card in tqdm(c.fetchall(), desc='cards'): 112 | info_note = info['note'][card['nid']] 113 | info_model = info['model'][info_note['mid']] 114 | db_model = db.Model.get(id=info_model['id']) 115 | db_template = db_model.templates[0] 116 | 117 | if '{{cloze:' not in db_template.question: 118 | db_template = db_model.templates[card['ord']] 119 | db.Card.create( 120 | id=card['id'], 121 | note_id=card['nid'], 122 | deck_id=card['did'], 123 | template_id=db_template.id 124 | ) 125 | else: 126 | for db_template_n in db_model.templates: 127 | db.Card.create( 128 | id=card['id'], 129 | note_id=card['nid'], 130 | deck_id=card['did'], 131 | cloze_order=card['ord'] + 1, 132 | template_id=db_template_n.id 133 | ) 134 | 135 | for db_deck in db.Deck.select(): 136 | if not db_deck.cards: 137 | db_deck.delete_instance() 138 | finally: 139 | conn.close() 140 | 141 | if not skip_media: 142 | if skip_media is False: 143 | skip_media = [] 144 | 145 | with open(os.path.join(temp_dir, 'media')) as f: 146 | info_media = info.get('media', dict()) 147 | for media_id, media_name in tqdm(json.load(f).items(), desc='media'): 148 | with open(os.path.join(temp_dir, media_id), 'rb') as image_f: 149 | db_media = db.Media.create( 150 | id=int(media_id), 151 | name=media_name, 152 | data=image_f.read() 153 | ) 154 | 155 | if MediaType.image not in skip_media: 156 | for note_id in info_media.get(MediaType.image, dict()).get(media_name, []): 157 | db_media.notes.add(db.Note.get(id=note_id)) 158 | 159 | if MediaType.audio not in skip_media: 160 | for note_id in info_media.get(MediaType.audio, dict()).get(media_name, []): 161 | db_media.notes.add(db.Note.get(id=note_id)) 162 | 163 | if MediaType.font not in skip_media: 164 | for model_id in info_media.get(MediaType.font, dict()).get(media_name, []): 165 | db_media.models.add(db.Model.get(id=model_id)) 166 | 167 | if not db_media.notes and db_media.models: 168 | logging.error('%s not connected to Notes or Models. Deleting...', media_name) 169 | db_media.delete_instance() 170 | -------------------------------------------------------------------------------- /sample/chinese.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [ 8 | { 9 | "data": { 10 | "text/plain": [ 11 | "{'tag': ,\n", 12 | " 'media': ,\n", 13 | " 'model': ,\n", 14 | " 'template': ,\n", 15 | " 'deck': ,\n", 16 | " 'note': ,\n", 17 | " 'note_tag': ,\n", 18 | " 'note_media': ,\n", 19 | " 'card': }" 20 | ] 21 | }, 22 | "execution_count": 1, 23 | "metadata": {}, 24 | "output_type": "execute_result" 25 | } 26 | ], 27 | "source": [ 28 | "from ankix import Ankix\n", 29 | "db = Ankix('user.ankix')\n", 30 | "db.tables" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 2, 36 | "metadata": {}, 37 | "outputs": [ 38 | { 39 | "data": { 40 | "text/plain": [ 41 | "[,\n", 42 | " ,\n", 43 | " ,\n", 44 | " ,\n", 45 | " ,\n", 46 | " ,\n", 47 | " ,\n", 48 | " ,\n", 49 | " ,\n", 50 | " ,\n", 51 | " ,\n", 52 | " ,\n", 53 | " ,\n", 54 | " ,\n", 55 | " ,\n", 56 | " ,\n", 57 | " ,\n", 58 | " ,\n", 59 | " ,\n", 60 | " ,\n", 61 | " ,\n", 62 | " ,\n", 63 | " ,\n", 64 | " ,\n", 65 | " ,\n", 66 | " ,\n", 67 | " ,\n", 68 | " ,\n", 69 | " ,\n", 70 | " ,\n", 71 | " ,\n", 72 | " ,\n", 73 | " ,\n", 74 | " ,\n", 75 | " ,\n", 76 | " ,\n", 77 | " ,\n", 78 | " ,\n", 79 | " ,\n", 80 | " ,\n", 81 | " ,\n", 82 | " ,\n", 83 | " ,\n", 84 | " ,\n", 85 | " ,\n", 86 | " ,\n", 87 | " ,\n", 88 | " ,\n", 89 | " ]" 90 | ] 91 | }, 92 | "execution_count": 2, 93 | "metadata": {}, 94 | "output_type": "execute_result" 95 | } 96 | ], 97 | "source": [ 98 | "list(db['tag'].select())" 99 | ] 100 | }, 101 | { 102 | "cell_type": "code", 103 | "execution_count": 2, 104 | "metadata": {}, 105 | "outputs": [], 106 | "source": [ 107 | "iter_quiz = db.iter_quiz(tags=['HSK_Level_1'])" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 35, 113 | "metadata": {}, 114 | "outputs": [ 115 | { 116 | "data": { 117 | "text/html": [ 118 | "\n", 119 | " \n", 200 | "
\n", 201 | "
\n", 202 | "
\n", 203 | "
  1. student
  2. schoolchild
\n", 204 | "
\n", 205 | " \n", 213 | "
\n", 214 | "\n", 215 | " \n", 226 | " " 227 | ], 228 | "text/plain": [ 229 | "" 230 | ] 231 | }, 232 | "execution_count": 35, 233 | "metadata": {}, 234 | "output_type": "execute_result" 235 | } 236 | ], 237 | "source": [ 238 | "card = next(iter_quiz)\n", 239 | "card" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": 36, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "card.right()" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 28, 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "card.wrong()" 258 | ] 259 | }, 260 | { 261 | "cell_type": "code", 262 | "execution_count": null, 263 | "metadata": {}, 264 | "outputs": [], 265 | "source": [] 266 | } 267 | ], 268 | "metadata": { 269 | "kernelspec": { 270 | "display_name": "Python 3", 271 | "language": "python", 272 | "name": "python3" 273 | }, 274 | "language_info": { 275 | "codemirror_mode": { 276 | "name": "ipython", 277 | "version": 3 278 | }, 279 | "file_extension": ".py", 280 | "mimetype": "text/x-python", 281 | "name": "python", 282 | "nbconvert_exporter": "python", 283 | "pygments_lexer": "ipython3", 284 | "version": "3.7.0" 285 | } 286 | }, 287 | "nbformat": 4, 288 | "nbformat_minor": 2 289 | } 290 | -------------------------------------------------------------------------------- /sample/edit_css.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from ankix import Ankix\n", 10 | "db = Ankix('chinese.ankix')" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "metadata": {}, 17 | "outputs": [ 18 | { 19 | "data": { 20 | "text/html": [ 21 | "\n", 22 | " \n", 103 | "
\n", 104 | "
\n", 105 | "
\n", 106 | "
  1. to love
  2. affection
  3. to be fond of
  4. to like
\n", 107 | "
\n", 108 | " \n", 116 | "
\n", 117 | "\n", 118 | " \n", 129 | " " 130 | ], 131 | "text/plain": [ 132 | "" 133 | ] 134 | }, 135 | "execution_count": 2, 136 | "metadata": {}, 137 | "output_type": "execute_result" 138 | } 139 | ], 140 | "source": [ 141 | "card = db.select()[0]\n", 142 | "card" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 3, 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stdout", 152 | "output_type": "stream", 153 | "text": [ 154 | "\n", 155 | ".card {\n", 156 | " font-family: arial;\n", 157 | " font-size: 1.2em;\n", 158 | " text-align: center;\n", 159 | " color: black;\n", 160 | " background-color: white;\n", 161 | "}\n", 162 | "\n", 163 | ".nobr {\n", 164 | " white-space: nowrap;\n", 165 | "}\n", 166 | "\n", 167 | ".character_wrapper {\n", 168 | " position: relative;\n", 169 | " margin-top: 10px;\n", 170 | " margin-bottom: 10px;\n", 171 | "}\n", 172 | "\n", 173 | ".character {\n", 174 | " font-size: 3em;\n", 175 | " height: 1em;\n", 176 | "}\n", 177 | "\n", 178 | ".character_type {\n", 179 | " color: #AAA;\n", 180 | " position: absolute;\n", 181 | "}\n", 182 | "\n", 183 | ".pinyin {\n", 184 | " font-size: 2em;\n", 185 | " height: 1em;\n", 186 | "}\n", 187 | "\n", 188 | ".words_with_same_pinyin {\n", 189 | " font-size: 1.2em;\n", 190 | " color: #888;\n", 191 | "}\n", 192 | "\n", 193 | ".classifier {\n", 194 | " font-size: 1.2em;\n", 195 | "}\n", 196 | "\n", 197 | ".english_wrapper > ol {\n", 198 | " display: inline-block;\n", 199 | " text-align: left;\n", 200 | "}\n", 201 | "\n", 202 | ".nobr {\n", 203 | " display:inline-block;\n", 204 | "}\n", 205 | "\n", 206 | "@media (min-width: 480px) {\n", 207 | " /* On devices at least 480px wide, put a 15% margin on both sides of the\n", 208 | " English definitions list */\n", 209 | " .english_wrapper {\n", 210 | " margin-left: 15%;\n", 211 | " margin-right: 15%;\n", 212 | " }\n", 213 | "}\n", 214 | "\n", 215 | ".card1 {\n", 216 | " background-color: #ffffff;\n", 217 | "}\n", 218 | "\n", 219 | ".tone1 {\n", 220 | " color: #ff0000;\n", 221 | "}\n", 222 | "\n", 223 | ".tone2 {\n", 224 | " color: #d89000;\n", 225 | "}\n", 226 | "\n", 227 | ".tone3 {\n", 228 | " color: #00a000;\n", 229 | "}\n", 230 | "\n", 231 | ".tone4 {\n", 232 | " color: #0000ff;\n", 233 | "}\n", 234 | "\n" 235 | ] 236 | } 237 | ], 238 | "source": [ 239 | "print(card.template.model.css)" 240 | ] 241 | }, 242 | { 243 | "cell_type": "code", 244 | "execution_count": null, 245 | "metadata": {}, 246 | "outputs": [], 247 | "source": [ 248 | "card.template.model.css = '''\n", 249 | ".card {\n", 250 | " font-family: arial;\n", 251 | " font-size: 1.2em;\n", 252 | " text-align: center;\n", 253 | " color: black;\n", 254 | " background-color: white;\n", 255 | "}\n", 256 | "\n", 257 | ".nobr {\n", 258 | " white-space: nowrap;\n", 259 | "}\n", 260 | "\n", 261 | ".character_wrapper {\n", 262 | " position: relative;\n", 263 | " margin-top: 10px;\n", 264 | " margin-bottom: 10px;\n", 265 | "}\n", 266 | "\n", 267 | ".character {\n", 268 | " font-size: 3em;\n", 269 | " height: 1em;\n", 270 | "}\n", 271 | "\n", 272 | ".character_type {\n", 273 | " color: #AAA;\n", 274 | " position: absolute;\n", 275 | "}\n", 276 | "\n", 277 | ".pinyin {\n", 278 | " font-size: 2em;\n", 279 | " height: 1em;\n", 280 | "}\n", 281 | "\n", 282 | ".words_with_same_pinyin {\n", 283 | " font-size: 1.2em;\n", 284 | " color: #888;\n", 285 | "}\n", 286 | "\n", 287 | ".classifier {\n", 288 | " font-size: 1.2em;\n", 289 | "}\n", 290 | "\n", 291 | ".english_wrapper > ol {\n", 292 | " display: inline-block;\n", 293 | " text-align: left;\n", 294 | "}\n", 295 | "\n", 296 | ".nobr {\n", 297 | " display:inline-block;\n", 298 | "}\n", 299 | "\n", 300 | "@media (min-width: 480px) {\n", 301 | " /* On devices at least 480px wide, put a 15% margin on both sides of the\n", 302 | " English definitions list */\n", 303 | " .english_wrapper {\n", 304 | " margin-left: 15%;\n", 305 | " margin-right: 15%;\n", 306 | " }\n", 307 | "}\n", 308 | "\n", 309 | ".card1 {\n", 310 | " background-color: #ffffff;\n", 311 | "}\n", 312 | "\n", 313 | ".tone1 {\n", 314 | " color: #ff0000;\n", 315 | "}\n", 316 | "\n", 317 | ".tone2 {\n", 318 | " color: #d89000;\n", 319 | "}\n", 320 | "\n", 321 | ".tone3 {\n", 322 | " color: #00a000;\n", 323 | "}\n", 324 | "\n", 325 | ".tone4 {\n", 326 | " color: #0000ff;\n", 327 | "}\n", 328 | "'''\n", 329 | "card.template.model.save()" 330 | ] 331 | } 332 | ], 333 | "metadata": { 334 | "kernelspec": { 335 | "display_name": "Python 3", 336 | "language": "python", 337 | "name": "python3" 338 | }, 339 | "language_info": { 340 | "codemirror_mode": { 341 | "name": "ipython", 342 | "version": 3 343 | }, 344 | "file_extension": ".py", 345 | "mimetype": "text/x-python", 346 | "name": "python", 347 | "nbconvert_exporter": "python", 348 | "pygments_lexer": "ipython3", 349 | "version": "3.7.0" 350 | } 351 | }, 352 | "nbformat": 4, 353 | "nbformat_minor": 2 354 | } 355 | -------------------------------------------------------------------------------- /ankix/db.py: -------------------------------------------------------------------------------- 1 | import peewee as pv 2 | from playhouse import sqlite_ext, signals 3 | from playhouse.shortcuts import model_to_dict 4 | 5 | from datetime import datetime, timedelta 6 | from pytimeparse.timeparse import timeparse 7 | import random 8 | import sys 9 | import re 10 | import json 11 | import hashlib 12 | import magic 13 | 14 | from .config import config 15 | from .jupyter import HTML 16 | from .util import MediaType, parse_srs, do_markdown, build_base64 17 | from .preview import TemplateMaker 18 | 19 | database = sqlite_ext.SqliteDatabase(None) 20 | 21 | 22 | class BaseModel(signals.Model): 23 | viewer_config = dict() 24 | 25 | def to_viewer(self): 26 | return model_to_dict(self) 27 | 28 | @classmethod 29 | def get_viewer(cls, records): 30 | from htmlviewer import PagedViewer 31 | 32 | return PagedViewer([r.to_viewer() for r in records], **cls.viewer_config) 33 | 34 | class Meta: 35 | database = database 36 | 37 | 38 | class Settings(BaseModel): 39 | DEFAULT = config.to_db() 40 | 41 | markdown = pv.BooleanField(default=DEFAULT['markdown']) 42 | _srs = pv.TextField(default=DEFAULT['srs']) 43 | 44 | @classmethod 45 | def to_dict(cls): 46 | db_settings = cls.get() 47 | d = model_to_dict(db_settings) 48 | d.pop('_srs') 49 | d['srs'] = db_settings.srs 50 | 51 | return d 52 | 53 | @property 54 | def srs(self): 55 | d = dict() 56 | for i, s in enumerate(json.loads(str(self._srs))): 57 | d[i] = timedelta(seconds=timeparse(s)) 58 | 59 | return d 60 | 61 | @srs.setter 62 | def srs(self, value): 63 | self._srs = parse_srs(value, self.srs) 64 | self.save() 65 | 66 | 67 | @signals.post_save(sender=Settings) 68 | def auto_update_config(model_class, instance, created): 69 | config.update(model_class.to_dict()) 70 | 71 | 72 | class Tag(BaseModel): 73 | name = pv.TextField(unique=True, collation='NOCASE') 74 | # notes 75 | 76 | def __repr__(self): 77 | return f'' 78 | 79 | def to_viewer(self): 80 | d = model_to_dict(self) 81 | d['notes'] = [repr(n) for n in self.notes] 82 | 83 | return d 84 | 85 | 86 | class Media(BaseModel): 87 | name = pv.TextField(unique=True) 88 | type_ = pv.TextField(default=MediaType.font) 89 | data = pv.BlobField() 90 | h = pv.TextField(unique=True) 91 | # models (for css) 92 | # notes 93 | 94 | def __repr__(self): 95 | return f'' 96 | 97 | @property 98 | def src(self): 99 | return build_base64(bytes(self.data)) 100 | 101 | @property 102 | def html(self): 103 | if self.type_ == MediaType.font: 104 | return f'' 105 | elif self.type_ == MediaType.audio: 106 | return f'