Search code examples
pythonanki

how to programmatically import text file into anki?


I'm trying to make an Addon that converts text from a website into an Anki deck, so now I have a text file that is formatted correctly and I can't figure out how to import it into an existing deck, I checked the official manual but it offers very little explanation, this may be sounding very newbie but this is my first time working on an Addon, so if someone with more experience can give me more thorough explanation, thanks in advance!

This is the code snippet from the website that I'm trying to understand:

from anki.importing import TextImporter
file = u"/path/to/text.txt"
# select deck
did = mw.col.decks.id("ImportDeck")
mw.col.decks.select(did)
# anki defaults to the last note type used in the selected deck
m = mw.col.models.byName("Basic")
deck = mw.col.decks.get(did)
deck['mid'] = m['id']
mw.col.decks.save(deck)
# and puts cards in the last deck used by the note type
m['did'] = did
# import into the collection
ti = TextImporter(mw.col, file)
ti.initMapping()
ti.run()

Solution

  • I take it that you're trying to make an Anki 2.0 add-on. I would strongly recommend that you make an Anki 2.1 add-on instead, since it is cleaner, has more development features and uses Python 3.

    That aside, here's an explanation of the code:

    • from anki.importing import TextImporter
      
      This imports the TextImporter class into the add-on's module's namespace.
    • file = u"/path/to/text.txt"
      
      This is pretty self-explanatory. It's assigning a Unicode file path to the variable file. In Anki 2.1 this could just be file = "/path/to/text.txt" because strings represent text, not a byte array, in Python 3.
    • # select deck
      did = mw.col.decks.id("ImportDeck")
      mw.col.decks.select(did)
      
      This selects the deck with identifier "ImportDeck". You'll need mw, which you can get with from aqt import mw.
    • # anki defaults to the last note type used in the selected deck
      m = mw.col.models.byName("Basic")
      deck = mw.col.decks.get(did)
      deck['mid'] = m['id']
      mw.col.decks.save(deck)
      
      This changes the note type of (the deck that's currently selected) to the "Basic" type. Note types are called "models" inside the code. 'mid' is the model identifier.
    • # and puts cards in the last deck used by the note type
      m['did'] = did
      
      Well, that's the first time I realised that Anki did that. For some reason, you also need to set the model( card type)'s deck identifier to the current deck's. I suppose that's because of how TextImporter works.
    • # import into the collection
      ti = TextImporter(mw.col, file)
      ti.initMapping()
      ti.run()
      
      Create a TextImporter, initialise its mapping and run it.