Skip to content

Commit

Permalink
run black
Browse files Browse the repository at this point in the history
  • Loading branch information
tatsumoto-ren committed Aug 29, 2024
1 parent 90ccc4d commit 24167a8
Show file tree
Hide file tree
Showing 10 changed files with 72 additions and 81 deletions.
32 changes: 15 additions & 17 deletions gomi/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,25 +33,23 @@ def program_name() -> str:
def print_help():
options = (
("import", "Add one of the stored note types to Anki."),
("update", "Overwrite a previously imported note type with new data. "
"Fields will not be updated."),
("overwrite", "Overwrite a note type in Anki with new data from a stored note type. "
"Fields will not be updated."),
("update", "Overwrite a previously imported note type with new data. " "Fields will not be updated."),
(
"overwrite",
"Overwrite a note type in Anki with new data from a stored note type. " "Fields will not be updated.",
),
("export", "Save your note type to disk as a template."),
("list", "List models stored in the templates folder."),
("-v, --verbose", "Show detailed info when errors occur."),
)
print(
f"Usage: {program_name()} [OPTIONS]\n\n"
"Options:"
)
print(f"Usage: {program_name()} [OPTIONS]\n\n" "Options:")
col_width = [max(len(word) for word in col) + 2 for col in zip(*options)]
for row in options:
print(" " * 4, "".join(col.ljust(col_width[i]) for i, col in enumerate(row)), sep='')
print(" " * 4, "".join(col.ljust(col_width[i]) for i, col in enumerate(row)), sep="")


def list_stored_note_types():
print('\n'.join(os.listdir(NOTE_TYPES_DIR)))
print("\n".join(os.listdir(NOTE_TYPES_DIR)))


def is_correct_cwd():
Expand All @@ -75,17 +73,17 @@ def main() -> int:

for arg in sys.argv[1:]:
match arg:
case 'export':
case "export":
action = export_note_type
case 'import':
case "import":
action = import_note_type
case 'update':
case "update":
action = update_note_type
case 'overwrite':
case "overwrite":
action = overwrite_note_type
case 'list':
case "list":
action = list_stored_note_types
case '-v' | '--verbose':
case "-v" | "--verbose":
wrap = False

if action and wrap:
Expand All @@ -99,5 +97,5 @@ def main() -> int:
return 0


if __name__ == '__main__':
if __name__ == "__main__":
sys.exit(main())
31 changes: 15 additions & 16 deletions gomi/ankiconnect.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# Copyright: Ren Tatsumoto <tatsu at autistici.org>
# License: GNU GPL, version 3 or later; http://www.gnu.org/licenses/agpl.html

__all__ = ['invoke', 'request_model_names']
__all__ = ["invoke", "request_model_names"]

import json
import urllib.request
Expand All @@ -11,25 +11,24 @@


def request(action, **params):
return {'action': action, 'params': params, 'version': 6}
return {"action": action, "params": params, "version": 6}


def invoke(action, **params):
request_json = json.dumps(request(action, **params)).encode('utf-8')
response = json.load(urllib.request.urlopen(
urllib.request.Request('http://127.0.0.1:8765', request_json),
timeout=10
))
request_json = json.dumps(request(action, **params)).encode("utf-8")
response = json.load(
urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:8765", request_json), timeout=10)
)
if len(response) != 2:
raise ANTPError('response has an unexpected number of fields')
if 'error' not in response:
raise ANTPError('response is missing required error field')
if 'result' not in response:
raise ANTPError('response is missing required result field')
if response['error'] is not None:
raise ANTPError(response['error'])
return response['result']
raise ANTPError("response has an unexpected number of fields")
if "error" not in response:
raise ANTPError("response is missing required error field")
if "result" not in response:
raise ANTPError("response is missing required result field")
if response["error"] is not None:
raise ANTPError(response["error"])
return response["result"]


def request_model_names() -> list[str]:
return invoke('modelNames')
return invoke("modelNames")
14 changes: 7 additions & 7 deletions gomi/consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@
import pathlib

JSON_INDENT = 4
JSON_FILENAME = 'template.json'
CSS_FILENAME = 'template.css'
FRONT_FILENAME = 'front.html'
BACK_FILENAME = 'back.html'
README_FILENAME = 'README.md'
JSON_FILENAME = "template.json"
CSS_FILENAME = "template.css"
FRONT_FILENAME = "front.html"
BACK_FILENAME = "back.html"
README_FILENAME = "README.md"
THIS_DIR = pathlib.Path.cwd()
NOTE_TYPES_DIR = THIS_DIR / 'templates'
FONTS_DIR = THIS_DIR / 'fonts'
NOTE_TYPES_DIR = THIS_DIR / "templates"
FONTS_DIR = THIS_DIR / "fonts"
26 changes: 17 additions & 9 deletions gomi/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,16 @@

from .ankiconnect import invoke, request_model_names
from .common import CardTemplate, NoteType, get_used_fonts, select
from .consts import NOTE_TYPES_DIR, FRONT_FILENAME, BACK_FILENAME, JSON_FILENAME, CSS_FILENAME, README_FILENAME, \
JSON_INDENT, FONTS_DIR
from .consts import (
NOTE_TYPES_DIR,
FRONT_FILENAME,
BACK_FILENAME,
JSON_FILENAME,
CSS_FILENAME,
README_FILENAME,
JSON_INDENT,
FONTS_DIR,
)


def fetch_card_templates(model_name: str) -> list[CardTemplate]:
Expand All @@ -39,7 +47,7 @@ def select_model_dir_path(model_name: str) -> pathlib.Path:

if model_name in dir_content:
ans = input("Template with this name already exists. Overwrite [y/N]? ")
if ans.lower() != 'y':
if ans.lower() != "y":
while dir_path.name in dir_content:
dir_path = NOTE_TYPES_DIR / f"{model_name}_{random.randint(0, 9999)}"

Expand All @@ -52,15 +60,15 @@ def write_card_templates(model_dir_path: pathlib.Path, templates: list[CardTempl
if not os.path.isdir(dir_path):
os.mkdir(dir_path)
for filename, content in zip((FRONT_FILENAME, BACK_FILENAME), (template.front, template.back)):
with open(os.path.join(dir_path, filename), 'w', encoding='utf8') as f:
with open(os.path.join(dir_path, filename), "w", encoding="utf8") as f:
f.write(content)


def format_export(model: NoteType) -> dict[str, Any]:
return {
"modelName": model.name,
"inOrderFields": model.fields,
"cardTemplates": [template.name for template in model.templates]
"cardTemplates": [template.name for template in model.templates],
}


Expand All @@ -80,25 +88,25 @@ def save_note_type(model: NoteType):
if not os.path.isdir(dir_path):
os.mkdir(dir_path)

with open(json_path, 'w', encoding='utf8') as f:
with open(json_path, "w", encoding="utf8") as f:
json.dump(format_export(model), f, indent=JSON_INDENT, ensure_ascii=False)

with open(css_path, 'w', encoding='utf8') as f:
with open(css_path, "w", encoding="utf8") as f:
f.write(model.css)

write_card_templates(dir_path, model.templates)
remove_deleted_templates(dir_path, [template.name for template in model.templates])

if not readme_path.is_file():
with open(readme_path, 'w', encoding='utf8') as f:
with open(readme_path, "w", encoding="utf8") as f:
f.write(f"# {model.name}\n\n*Description and screenshots here.*")


def save_fonts(model: NoteType) -> None:
linked_fonts = get_used_fonts(model.css)
for font in linked_fonts:
if file_b64 := invoke("retrieveMediaFile", filename=font):
with open(os.path.join(FONTS_DIR, font), 'bw') as f:
with open(os.path.join(FONTS_DIR, font), "bw") as f:
f.write(base64.b64decode(file_b64))


Expand Down
18 changes: 9 additions & 9 deletions gomi/importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@


def read_css(model_dir_name: str) -> str:
with open(NOTE_TYPES_DIR / model_dir_name / CSS_FILENAME, encoding='utf8') as f:
with open(NOTE_TYPES_DIR / model_dir_name / CSS_FILENAME, encoding="utf8") as f:
return f.read()


Expand All @@ -21,25 +21,25 @@ def read_card_templates(model_dir_name: str, template_names: list[str]) -> list[
for template_name in template_names:
dir_path = NOTE_TYPES_DIR / model_dir_name / template_name
with (
open(dir_path / FRONT_FILENAME, encoding='utf8') as front,
open(dir_path / BACK_FILENAME, encoding='utf8') as back
open(dir_path / FRONT_FILENAME, encoding="utf8") as front,
open(dir_path / BACK_FILENAME, encoding="utf8") as back,
):
templates.append(CardTemplate(template_name, front.read(), back.read()))
return templates


def read_model_dict(model_dir_name: str) -> dict[str, Any]:
with open(os.path.join(NOTE_TYPES_DIR, model_dir_name, JSON_FILENAME), encoding='utf8') as f:
with open(os.path.join(NOTE_TYPES_DIR, model_dir_name, JSON_FILENAME), encoding="utf8") as f:
return json.load(f)


def read_model(model_dir_name: str) -> NoteType:
model_dict = read_model_dict(model_dir_name)
return NoteType(
name=model_dict['modelName'],
fields=model_dict['inOrderFields'],
name=model_dict["modelName"],
fields=model_dict["inOrderFields"],
css=read_css(model_dir_name),
templates=read_card_templates(model_dir_name, model_dict['cardTemplates']),
templates=read_card_templates(model_dir_name, model_dict["cardTemplates"]),
)


Expand All @@ -55,7 +55,7 @@ def format_import(model: NoteType) -> dict[str, Any]:
"Back": template.back,
}
for template in model.templates
]
],
}


Expand All @@ -67,7 +67,7 @@ def send_note_type(model: NoteType):


def available_fonts(required_fonts: Collection[str]) -> Iterable[str]:
""" Filter required fonts and leave only those available on disk. """
"""Filter required fonts and leave only those available on disk."""
for file in os.listdir(FONTS_DIR):
if file in required_fonts:
yield file
Expand Down
5 changes: 1 addition & 4 deletions gomi/overwriter.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,7 @@

def overwrite_note_type():
anki_models = request_model_names()
models_on_disk = {
(model := read_model(dir_name)).name: model
for dir_name in os.listdir(NOTE_TYPES_DIR)
}
models_on_disk = {(model := read_model(dir_name)).name: model for dir_name in os.listdir(NOTE_TYPES_DIR)}
model_name_on_disk = select(list(models_on_disk), "Take stored model: ")
model_name_in_anki = select(anki_models, "Replace templates in model: ")

Expand Down
19 changes: 4 additions & 15 deletions gomi/updater.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,13 @@ def format_templates(model: NoteType) -> dict[str, Any]:
"name": model.name,
"templates": {
template.name: {"Front": template.front, "Back": template.back} for template in model.templates
}
},
}
}


def format_styling(model: NoteType) -> dict[str, Any]:
return {
"model": {
"name": model.name,
"css": model.css
}
}
return {"model": {"name": model.name, "css": model.css}}


def send_note_type(model: NoteType):
Expand All @@ -37,14 +32,8 @@ def send_note_type(model: NoteType):

def update_note_type():
anki_models = request_model_names()
models_on_disk = {
(model := read_model(dir_name)).name: model
for dir_name in os.listdir(NOTE_TYPES_DIR)
}
updatable_models = [
model_name for model_name in models_on_disk
if model_name in anki_models
]
models_on_disk = {(model := read_model(dir_name)).name: model for dir_name in os.listdir(NOTE_TYPES_DIR)}
updatable_models = [model_name for model_name in models_on_disk if model_name in anki_models]
if not updatable_models:
print("No note types can be updated.")
return
Expand Down
2 changes: 1 addition & 1 deletion tests/export.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from gomi.exporter import export_note_type

if __name__ == '__main__':
if __name__ == "__main__":
export_note_type()
2 changes: 1 addition & 1 deletion tests/import.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from gomi.importer import import_note_type

if __name__ == '__main__':
if __name__ == "__main__":
import_note_type()
4 changes: 2 additions & 2 deletions tests/list_decks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@


def list_decks():
decks = invoke('deckNames')
decks = invoke("deckNames")
print("List of decks:")
for deck in decks:
print(deck)


if __name__ == '__main__':
if __name__ == "__main__":
list_decks()

0 comments on commit 24167a8

Please sign in to comment.