Skip to content
Snippets Groups Projects
Select Git revision
  • 2027cfad0cdb5fab7da93315a2f844d1b3ea78cd
  • main default protected
2 results

create_from_reference.py

Blame
  • create_from_reference.py 2.15 KiB
    from anki.collection import *
    from anki.import_export_pb2 import *
    import os
    
    # Step 1: create a temporary collection
    try:
        # delete if exists already
        os.remove("temporary.anki2")
    except OSError:
      pass
    # then start fresh
    col = Collection("temporary.anki2")
    
    # Step 2: import the template APKG with the note type, so that you can add data
    col.import_anki_package(ImportAnkiPackageRequest(
        # this is what you exported from Anki
        package_path="reference.apkg",
        # the options don't matter that much in our case
        # since the collection we import into is empty anyway
        options=ImportAnkiPackageOptions(
            merge_notetypes=True,
            update_notes=ImportAnkiPackageUpdateCondition.IMPORT_ANKI_PACKAGE_UPDATE_CONDITION_ALWAYS,
            update_notetypes=ImportAnkiPackageUpdateCondition.IMPORT_ANKI_PACKAGE_UPDATE_CONDITION_NEVER,
            with_scheduling=False,
            with_deck_configs=False,
        )
    ))
    
    ## Step 3: find the note type id we want to modify, and get the dictionary
    note_type_id_for_template_replacement = None
    for note_type in col.models.all_names_and_ids():
      if note_type.name == "Japanese vocabulary":
        note_type_id_for_template_replacement = note_type.id
    if note_type_id_for_template_replacement is None:
      raise Exception("Note type to modify templates of not found")
    
    ## Step 4: get the current note type dict
    note_type = col.models.get(note_type_id_for_template_replacement)
    
    ## Step 5: set your one template (or more, in the same way)
    with open("dist/front.html", "r") as front_file:
      with open("dist/back.html") as back_file:
        front_html = front_file.read()
        back_html = back_file.read()
    note_type["tmpls"][0]["qfmt"] = front_html
    note_type["tmpls"][0]["afmt"] = back_html
    
    ## Step 5: write your changes back to the Anki collection
    col.models.update_dict(note_type)
    
    # Step 6: Done, now we just need to export an APKG
    col.export_anki_package(
        # anki fails if this is just an apkg filename without a dir,
        # with ./ it's fine
        out_path="./cool_new_template.apkg",
        options=ExportAnkiPackageOptions(
            with_deck_configs=False,
            with_media=True,
            with_scheduling=False,
            legacy=True,
        ),
        limit=None)