Skip to content

Instantly share code, notes, and snippets.

@arturz
Last active May 25, 2023 11:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arturz/bed3507e9039c93a53b5b97b576ba241 to your computer and use it in GitHub Desktop.
Save arturz/bed3507e9039c93a53b5b97b576ba241 to your computer and use it in GitHub Desktop.
This Python script uploads cards from a given text file into Anki. More in comments ⬇️
import re
import sys
import getopt
import json
import urllib.request
def request(action, **params):
try:
requestData = json.dumps(
{"action": action, "params": params, "version": 6}).encode("utf-8")
response = json.load(urllib.request.urlopen(
urllib.request.Request('http://localhost:8765', requestData)))
return response
except:
print("Can't connect. Make sure that you've AnkiConnect installed: https://foosoft.net/projects/anki-connect/")
def invoke(action, **params):
response = request(action, **params)
if len(response) != 2:
raise Exception('response has an unexpected number of fields')
if 'error' not in response:
raise Exception('response is missing required error field')
if 'result' not in response:
raise Exception('response is missing required result field')
if response['error'] is not None:
raise Exception(response['error'])
return response['result']
def list_deck_names():
return invoke("deckNames")
def list_model_names():
return invoke("modelNames")
def add_notes(deck, model, notes):
invoke("addNotes", notes=list(map(lambda note: {
"deckName": deck,
"modelName": model,
"fields": {
"Front": note[0],
"Back": note[1]
}
}, notes)))
def print_help():
print("""
This script uploads cards from a given text file into Anki.
AnkiConnect extension needs to be installed: https://foosoft.net/projects/anki-connect/
Every line in an input file should match this format:
- back - front
Fronts cannot be duplicated.
Available options:
-h, --help Prints this message.
-f, --file=FILENAME Sets the path to the input file. The default is "Words.md".
-d, --deck=DECK Sets output deck name to which cards are append. The default is "English".
-m, --model Sets model (type) of cards. The default is "Basic".
-r, --regex=PATTERN Changes regular expression used to read front and back from a line. The default is "-\s+(.*)\s+-\s+(.*)".
Example usage:
python anki.py --file="notes.txt" --deck="Spanish" --model="Basic (and reversed card)"
""")
def main(argv):
regex = r"-\s+(.*)\s+-\s+(.*)"
file = "Words.md"
deck = "English"
model = "Basic"
opts, args = getopt.getopt(
argv, "hf:r:d:m:", ["help", "file=", "regex=", "deck=", "model="])
for opt, arg in opts:
if opt in ("-h", "--help"):
print_help()
sys.exit()
elif opt in ("-f", "--file"):
file = arg
elif opt in ("-r", "--regex"):
regex = arg
elif opt in ("-d", "--deck"):
deck = arg
elif opt in ("-m", "--model"):
model = arg
file = open(file, "r")
translations = {}
for line in file.readlines():
line = line.strip()
if len(line) == 0:
continue
search = re.search(regex, line)
if search is None:
print("Suspended, unparsable line:", line)
print(
"Every line in an input file should match this format: \"- back - front\"")
return
(back, front) = search.groups()
if front in translations:
print(f"Suspended, duplicated card fronts:")
print(f" 1. {front} | {translations[front]}")
print(f" 2. {front} | {back}")
print("Please remove duplicated fronts and run the script again.")
sys.exit()
translations[front] = back
print(f"Successfully loaded {len(translations)} translations!")
if deck not in list_deck_names():
print(
f"You don't have a deck named {deck}.")
print("You can use another deck with --deck=\"your's deck name\" param.")
return
if model not in list_model_names():
print(
f"You don't have a model named {model}.")
print("You can use another model with --model=\"your's model name\" param.")
return
add_notes(deck, model, translations.items())
print(f"Successfully added {len(translations)} notes to Anki!")
if __name__ == "__main__":
main(sys.argv[1:])
@arturz
Copy link
Author

arturz commented Mar 7, 2023

This script uploads cards from a given text file into Anki.
AnkiConnect extension needs to be installed: https://foosoft.net/projects/anki-connect/

Every line in an input file should match this format:
- back - front

Fronts cannot be duplicated.

Available options:
    -h, --help                 Prints this message.
    -f, --file=FILENAME        Sets the path to the input file. The default is "Words.md".
    -d, --deck=DECK            Sets output deck name to which cards are append. The default is "English".
    -m, --model                Sets model (type) of cards. The default is "Basic".
    -r, --regex=PATTERN        Changes regular expression used to read front and back from a line. The default is "-\s+(.*)\s+-\s+(.*)".

Example usage:
    python anki.py --file="notes.txt" --deck="Spanish" --model="Basic (and reversed card)"

@arturz
Copy link
Author

arturz commented May 25, 2023

Update!
I've wrote a CLI tool with the same functionality in Elixir: https://github.com/arturz/anki_connect#command-line-interface-cli (scroll down to CLI section)
Updates and new features will be added to this Elixir package.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment