Genanki and fastcore
by Audrey M. Roy Greenfeld | Sun, Jan 19, 2025
Working with Anki flashcard decks in Python, with genanki to work with the decks and fastcore for ease of use.
import genanki
from fastcore.utils import *
Model
First I define a model with Q&A fields and a card template:
my_model = genanki.Model(
1607392319,
'Simple Model',
fields=[
{'name': 'Question'},
{'name': 'Answer'},
],
templates=[
{
'name': 'Card 1',
'qfmt': '{{Question}}',
'afmt': '{{FrontSide}}<hr id="answer">{{Answer}}',
},
])
Notes
I create a note:
note_gm = genanki.Note(model=my_model, fields=['Magandang umaga', 'Good morning'])
note_gm
It's nice to bulk-create notes like this:
notes = L(['Magandang hapon', 'Good afternoon'],
['Magandang gabi', 'Good evening'],
['Paalam', 'Goodbye'])
notes
Recall before that in my_model
the first field goes into Question
and the second goes into Answer
.
Then to actually turn those list items into notes:
def add_note(qa): return genanki.Note(model=my_model, fields=qa)
gn = notes.map(add_note)
gn
Deck
Let's create a deck and add 1 starter note:
my_deck = genanki.Deck(
2059400110,
'Tagalog Greetings')
my_deck.add_note(note_gm)
We can see the note's in the deck:
We extend it with the rest of the notes we bulk-created:
Packaging the Deck for Anki
This writes out an Anki package file that we can import:
genanki.Package(my_deck).write_to_file('tagalog_greetings.apkg')
Opening the Deck in Anki
In Anki Desktop:
- I went to File > Import
- I chose tagalog_greetings.apkg
- I was able to go through the cards like any other deck!
Resources
- Genanki: https://github.com/kerrickstaley/genanki
- fastcore: https://fastcore.fast.ai/