-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathanki_importer.py
More file actions
93 lines (74 loc) · 2.63 KB
/
Copy pathanki_importer.py
File metadata and controls
93 lines (74 loc) · 2.63 KB
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""
Helpers to create Anki notes/cards programmatically
By Gibran Ali
https://gibranali.com
"""
import re
from anki.notes import Note
from aqt import mw
def ensure_deck(deck_name: str) -> int:
"""Get or create a deck by name, return deck id"""
did = mw.col.decks.id(deck_name)
mw.col.decks.save()
return did
def ensure_note_type(note_type_name: str):
"""Return existing note type or create a basic one"""
model = mw.col.models.by_name(note_type_name)
if model:
return model
# Create a simple Basic note type
model = mw.col.models.new(note_type_name)
front_field = mw.col.models.new_field("Front")
back_field = mw.col.models.new_field("Back")
mw.col.models.add_field(model, front_field)
mw.col.models.add_field(model, back_field)
template = mw.col.models.new_template("Card 1")
template["qfmt"] = "{{Front}}"
template["afmt"] = "{{FrontSide}}<hr id=answer>{{Back}}"
mw.col.models.add_template(model, template)
mw.col.models.add(model)
return model
def add_card(deck_name: str, note_type_name: str, front: str, back: str, tags: list[str]) -> bool:
"""
Add a single card to Anki. Returns True if added, False if duplicate.
"""
did = ensure_deck(deck_name)
model = ensure_note_type(note_type_name)
note = Note(mw.col, model)
note["Front"] = front
note["Back"] = back
clean_tags = [re.sub(r"\s+", "_", t.strip()) for t in tags if t.strip()]
note.tags = clean_tags
# Check for duplicates (Anki checks by first field)
if mw.col.find_notes(f'"Front:{front}"'):
return False
mw.col.add_note(note, did)
return True
def import_cards(deck_name: str, note_type_name: str, cards: list[dict], extra_tags: list[str] = None) -> dict:
"""
Bulk import cards.
cards: list of {front, back, tags}
Returns {added: int, skipped: int, errors: list}
"""
added = 0
skipped = 0
errors = []
for i, card in enumerate(cards):
try:
front = card.get("front", "").strip()
back = card.get("back", "").strip()
tags = list(card.get("tags", []))
if extra_tags:
tags.extend(extra_tags)
if not front or not back:
errors.append(f"Card {i+1}: missing front or back")
continue
was_added = add_card(deck_name, note_type_name, front, back, tags)
if was_added:
added += 1
else:
skipped += 1
except Exception as e:
errors.append(f"Card {i+1}: {str(e)}")
mw.col.save()
return {"added": added, "skipped": skipped, "errors": errors}