AnkiNoteTemplate/antp/exporter.py

77 lines
2.3 KiB
Python
Raw Normal View History

2021-04-20 10:32:25 +00:00
# Exporter exports note types from Anki to ../templates/
2021-04-20 07:54:06 +00:00
import json
2021-04-20 09:25:54 +00:00
import os
import random
from typing import AnyStr
2021-04-20 07:54:06 +00:00
from urllib.error import URLError
2021-04-20 09:25:54 +00:00
from antp.ankiconnect import invoke
2021-04-20 11:02:13 +00:00
from antp.common import NOTE_TYPES_DIR, JSON_INDENT, select, JSON_FILENAME, README_FILENAME
2021-04-20 07:54:06 +00:00
def fetch_card_templates(model_name: str):
card_templates = []
for key, val in invoke("modelTemplates", modelName=model_name).items():
card_templates.append({
"Name": key,
"Front": val["Front"],
"Back": val["Back"],
})
return card_templates
def fetch_template(model_name: str):
return {
"modelName": model_name,
"inOrderFields": invoke("modelFieldNames", modelName=model_name),
"css": invoke("modelStyling", modelName=model_name)["css"],
"cardTemplates": fetch_card_templates(model_name),
}
2021-04-20 13:23:19 +00:00
def create_template_dir(template_name: str) -> AnyStr:
2021-04-20 09:25:54 +00:00
dir_path = os.path.join(NOTE_TYPES_DIR, template_name)
dir_content = os.listdir(NOTE_TYPES_DIR)
if template_name in dir_content:
2021-04-20 12:35:49 +00:00
ans = input("Template with this name already exists. Overwrite [y/N]? ")
2021-04-20 09:25:54 +00:00
if ans.lower() != 'y':
2021-04-20 13:23:19 +00:00
while os.path.basename(dir_path) in dir_content:
2021-04-20 09:25:54 +00:00
dir_path = os.path.join(NOTE_TYPES_DIR, f"{template_name}_{random.randint(0, 9999)}")
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
return dir_path
def save_note_type(template_json):
template_dir = create_template_dir(template_json["modelName"])
2021-04-20 10:27:47 +00:00
template_fp = os.path.join(template_dir, JSON_FILENAME)
2021-04-20 11:02:13 +00:00
readme_fp = os.path.join(template_dir, README_FILENAME)
2021-04-20 09:25:54 +00:00
with open(template_fp, 'w') as f:
f.write(json.dumps(template_json, indent=JSON_INDENT))
2021-04-20 12:36:10 +00:00
if not os.path.isfile(readme_fp):
with open(readme_fp, 'w') as f:
f.write(f"# {template_json['modelName']}\n\n*Description and screenshots here.*")
2021-04-20 09:25:54 +00:00
2021-04-20 07:54:06 +00:00
def export_note_type():
2021-04-20 10:27:47 +00:00
model = select(invoke('modelNames'))
if not model:
2021-04-20 07:54:06 +00:00
return
print(f"Selected model: {model}")
2021-04-20 09:25:54 +00:00
save_note_type(fetch_template(model))
print("Done.")
2021-04-20 07:54:06 +00:00
if __name__ == '__main__':
try:
export_note_type()
except URLError:
print("Couldn't connect. Make sure Anki is open and AnkiConnect is installed.")
except Exception as ex:
print(ex)