1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
|
#!/usr/bin/env python
import anki
from anki import DeckStorage
import re
import argparse
def add_fact(deck, front, back, atomic = True):
"""
Add a fact to the deck of name deck.
@param deck:str the name of the deck to use under ~/.anki/decks
@param front:str the text for the front of the deck
@param back:str the name for the back of the deck
"""
if type(deck) == str:
deck = DeckStorage.Deck("/home/tedks/.anki/decks/%s.anki" % deck)
fact = anki.facts.Fact(deck.currentModel)
fact.fields[0].value = unicode(front)
fact.fields[1].value = unicode(back)
deck.addFact(fact)
if atomic:
deck.save()
deck.close()
return None
else:
return deck
# code for clozing stolen from ankiqt/ui/facteditor.py and modified from there
# from head of that file in Ubuntu:
# Copyright: Damien Elmes <anki@ichi2.net>
# License: GNU GPL, version 3 or later; http://www.gnu.org/copyleft/gpl.html
# modified version accepts one string with a cloze, and returns two
# strings suitable for adding to a fact's fields in cloze-deleted
# format
def cloze(front):
clozeColor = "#0000ff"
re1 = "\[(?:<.+?>)?.+?(:(.+?))?\](?:</.+?>)?"
re2 = "\[(?:<.+?>)?(.+?)(:.+?)?\](?:</.+?>)?"
# create
s = unicode(front)
def repl(match):
exp = ""
if match.group(2):
exp = match.group(2)
return '<font color="%s"><b>[...%s]</b></font>' % (
clozeColor, exp)
new = re.sub(re1, repl, s)
old = re.sub(re2, '<font color="%s"><b>\\1</b></font>'
% clozeColor, s)
return (new, old)
if __name__ == "__main__":
p = argparse.ArgumentParser(description="Add cards to Anki decks")
p.add_argument('--deck', '-d', type=str,
help="The name of the deck to add to")
p.add_argument('--front', '-f', type=str,
help="The front of the card to add.")
p.add_argument('--back', '-b', type=str, default=None,
help="The back of the card. If not present, " +
"will generate a cloze-deleted card from the Front field.")
args = p.parse_args()
front = args.front
back = args.back
if args.back == None:
(front, back) = cloze(args.front)
[front, back] = [i.replace("\n", "<br />") for i in front, back]
add_fact(args.deck, front, back)
exit(0)
|