AnkiNoteTemplate/antp/importer.py

47 lines
1.3 KiB
Python
Raw Normal View History

2021-04-20 10:32:25 +00:00
# Importer imports note types from ../templates/ to Anki.
2021-04-20 10:20:20 +00:00
import json
import os
from urllib.error import URLError
2021-04-20 16:46:04 +00:00
import antp.common as ac
2021-04-20 10:20:20 +00:00
from antp.ankiconnect import invoke
2021-04-20 13:23:50 +00:00
def read_template(model_name: str):
2021-04-20 16:46:04 +00:00
with open(os.path.join(ac.NOTE_TYPES_DIR, model_name, ac.JSON_FILENAME), 'r') as f:
2021-04-20 10:20:20 +00:00
return json.load(f)
2021-04-20 13:23:50 +00:00
def send_note_type(template_json: dict):
2021-04-20 10:55:41 +00:00
models = invoke('modelNames')
while template_json["modelName"] in models:
template_json["modelName"] = input("Model with this name already exists. Enter new name: ")
2021-04-20 10:20:20 +00:00
invoke("createModel", **template_json)
2021-04-20 13:23:50 +00:00
def store_fonts(fonts: list[str]):
2021-04-20 16:46:04 +00:00
for file in os.listdir(ac.FONTS_DIR):
2021-04-20 13:23:50 +00:00
if file in fonts:
2021-04-20 16:46:04 +00:00
invoke("storeMediaFile", filename=file, path=os.path.join(ac.FONTS_DIR, file))
2021-04-20 13:23:50 +00:00
2021-04-20 10:20:20 +00:00
def import_note_type():
2021-04-20 16:46:04 +00:00
model = ac.select(os.listdir(ac.NOTE_TYPES_DIR))
2021-04-20 10:20:20 +00:00
if not model:
return
print(f"Selected model: {model}")
2021-04-20 13:23:50 +00:00
template = read_template(model)
2021-04-20 16:46:04 +00:00
store_fonts(ac.get_used_fonts(template['css']))
2021-04-20 13:23:50 +00:00
send_note_type(template)
2021-04-20 10:20:20 +00:00
print("Done.")
if __name__ == '__main__':
try:
import_note_type()
except URLError:
print("Couldn't connect. Make sure Anki is open and AnkiConnect is installed.")
except Exception as ex:
print(ex)