genanki

repository·main·Indexed 25 days ago

https://github.com/kerrickstaley/genanki

A Python library used to programmatically generate Anki deck files (.apkg). It enables the automation of flashcard creation with custom models, fields, and media, providing functionality to define Models, create Notes, and package them into importable .apkg files.

Tokens
1.1K
Snippets
5
Records
8
Agent score
33%

What's inside genanki

  1. Add Media Files to a Package

    main

    To include sounds or images in your deck, you must perform two steps:

    1. Assign files to the Package: Set the media_files attribute on your Package instance with a list of paths (relative or absolute) to the files.
    2. Reference files in Note fields: In your Note fields, use the specific Anki syntax for media. Use the filename only (basename), not the full path, inside the field value.

    Media Syntax:

    • Audio: [sound:filename.mp3]
    • Images: <img src="filename.jpg">
  2. Generate a Deck and Package

    main

    To create an Anki-importable file (.apkg), you must add your notes to a Deck and then wrap that deck in a Package.

    1. Create a Deck with a unique deck_id (similar to model_id).
    2. Add notes to the deck using add_note().
    3. Create a Package and use write_to_file() to save it.
    my_deck = genanki.Deck(
      2059400110,
      'Country Capitals')
    
    my_deck.add_note(my_note)
    
    genanki.Package(my_deck).write_to_file('output.apkg')
  3. Handle HTML Encoding for Field Data

    main
    Field data in genanki is treated as HTML. If your text contains literal <, >, or & characters, they may be garbled in Anki. You must HTML-encode these characters using html.escape from the Python standard library.
  4. Fix CLOZE_MODEL DeprecationWarning

    main

    If you receive a DeprecationWarning when using genanki.CLOZE_MODEL, it is because the model requires two fields instead of one. To fix this, add a second field (it can be an empty string) to your Note definition.

    my_note = genanki.Note(
      model=genanki.CLOZE_MODEL,
      fields=['{{c1::Rome}} is the capital of {{c2::Italy}}', ''])
  5. Customize Note GUIDs

    main

    A Note has a guid property that uniquely identifies it. If you import a note with an existing GUID, it will overwrite the old one in Anki. This allows you to update existing notes without creating duplicates.

    By default, the GUID is a hash of all field values. To prevent the GUID from changing when non-identifying fields are updated, subclass genanki.Note and override the guid property to hash only specific fields.

    class MyNote(genanki.Note):
      @property
      def guid(self):
        return genanki.guid_for(self.fields[0], self.fields[1])
  6. Define a Model

    main

    A Model defines the fields and card templates for a Note.

    Key requirements:

    • model_id: A unique integer. You must use a unique ID for every different model you define so Anki can track it.
    • fields: A list of dictionaries, each containing a 'name'.
    • templates: A list of dictionaries defining the card layout. Each template needs a 'name', 'qfmt' (front format), and 'afmt' (back format).
    • css (optional): A string to supply custom CSS for the cards.

    To generate a unique model_id, you can use this command in your terminal:

    python3 -c "import random; print(random.randrange(1 << 30, 1 << 31))"
    my_model = genanki.Model(
      1607392319,
      'Simple Model',
      fields=[
        {'name': 'Question'},
        {'name': 'Answer'},
      ],
      templates=[
        {
          'name': 'Card 1',
          'qfmt': '{{Question}}',
          'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
        },
      ])
  7. Configure the sort_field

    main

    The sort_field determines how notes are sorted in the Anki Browse interface. By default, it is the first field (index 0).

    You can change this in two ways:

    1. Pass sort_field= to the Note() constructor.
    2. Pass sort_field_index= to the Model() constructor (e.g., 0 for the first field, 1 for the second).
    3. Implement sort_field as a property in a Note subclass.
  8. Create a Note

    main

    A Note is the basic unit in Anki containing the facts to memorize. You create a note by passing a Model and a list of fields (which are encoded as HTML) to the genanki.Note constructor.

    my_note = genanki.Note(
      model=my_model,
      fields=['Capital of Argentina', 'Buenos Aires'])