pankohub 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. panko/__init__.py +22 -0
  2. panko/__main__.py +4 -0
  3. panko/anki/__init__.py +0 -0
  4. panko/anki/addon.py +19 -0
  5. panko/anki/apkg.py +152 -0
  6. panko/anki/export.py +44 -0
  7. panko/anki/mcp_client.py +57 -0
  8. panko/anki/migrate.py +213 -0
  9. panko/anki/remote.py +168 -0
  10. panko/anki/sync.py +124 -0
  11. panko/anki_addon/__init__.py +13 -0
  12. panko/anki_addon/config.json +1 -0
  13. panko/anki_addon/config.md +2 -0
  14. panko/anki_addon/core.py +186 -0
  15. panko/anki_addon/manifest.json +1 -0
  16. panko/anki_addon/net.py +60 -0
  17. panko/anki_addon/ui.py +125 -0
  18. panko/cards/__init__.py +0 -0
  19. panko/cards/build.py +102 -0
  20. panko/cards/design.py +149 -0
  21. panko/cards/note_types.py +192 -0
  22. panko/cards/render.py +88 -0
  23. panko/checks.py +187 -0
  24. panko/clashes.py +182 -0
  25. panko/cli.py +693 -0
  26. panko/config.py +266 -0
  27. panko/dedupe.py +118 -0
  28. panko/evidence.py +345 -0
  29. panko/examples.py +110 -0
  30. panko/host/__init__.py +5 -0
  31. panko/host/app.py +843 -0
  32. panko/host/cli.py +106 -0
  33. panko/host/oauth.py +324 -0
  34. panko/host/pages.py +107 -0
  35. panko/host/pankos.py +218 -0
  36. panko/host/store.py +229 -0
  37. panko/host/watch.py +150 -0
  38. panko/hub/__init__.py +267 -0
  39. panko/hub/api.py +1843 -0
  40. panko/hub/jobs.py +203 -0
  41. panko/hub/preview.py +147 -0
  42. panko/hub/static/app.css +656 -0
  43. panko/hub/static/app.js +2476 -0
  44. panko/hub/static/favicon.svg +7 -0
  45. panko/hub/static/index.html +32 -0
  46. panko/hub/static/logo.svg +65 -0
  47. panko/ingest/__init__.py +87 -0
  48. panko/ingest/decks.py +97 -0
  49. panko/ingest/verify.py +86 -0
  50. panko/lang/__init__.py +288 -0
  51. panko/lang/arabic.py +151 -0
  52. panko/library.py +660 -0
  53. panko/llm.py +249 -0
  54. panko/mcp_server.py +433 -0
  55. panko/media/__init__.py +0 -0
  56. panko/media/audio.py +94 -0
  57. panko/media/audition.py +101 -0
  58. panko/media/choose.py +216 -0
  59. panko/media/clips.py +106 -0
  60. panko/media/pictures.py +402 -0
  61. panko/media/reuse.py +137 -0
  62. panko/media/voices.py +172 -0
  63. panko/modes.py +62 -0
  64. panko/pipeline.py +252 -0
  65. panko/prompts/__init__.py +98 -0
  66. panko/prompts/_evidence.md +13 -0
  67. panko/prompts/_item.md +35 -0
  68. panko/prompts/_verdict.md +33 -0
  69. panko/prompts/chat.md +86 -0
  70. panko/prompts/check.md +19 -0
  71. panko/prompts/clashes.md +22 -0
  72. panko/prompts/deck.md +51 -0
  73. panko/prompts/examples.md +25 -0
  74. panko/prompts/extract.md +34 -0
  75. panko/prompts/pictures-pick.md +17 -0
  76. panko/prompts/pictures-plan.md +34 -0
  77. panko/prompts/schemas.py +53 -0
  78. panko/providers/__init__.py +49 -0
  79. panko/providers/base.py +124 -0
  80. panko/providers/imagegen/__init__.py +108 -0
  81. panko/providers/images/__init__.py +11 -0
  82. panko/providers/images/arasaac.py +33 -0
  83. panko/providers/images/commons.py +42 -0
  84. panko/providers/images/inaturalist.py +42 -0
  85. panko/providers/images/openverse.py +19 -0
  86. panko/providers/images/pexels.py +23 -0
  87. panko/providers/images/pixabay.py +38 -0
  88. panko/providers/images/source.py +12 -0
  89. panko/providers/images/web.py +82 -0
  90. panko/providers/images/wikidata.py +60 -0
  91. panko/providers/images/yours.py +16 -0
  92. panko/providers/llm/__init__.py +39 -0
  93. panko/providers/llm/claude.py +141 -0
  94. panko/providers/llm/openai_chat.py +77 -0
  95. panko/providers/morph/__init__.py +1 -0
  96. panko/providers/morph/camel.py +77 -0
  97. panko/providers/stt/__init__.py +1 -0
  98. panko/providers/stt/elevenlabs.py +41 -0
  99. panko/providers/tts/__init__.py +1 -0
  100. panko/providers/tts/azure.py +31 -0
  101. panko/providers/tts/elevenlabs.py +44 -0
  102. panko/providers/tts/native.py +16 -0
  103. panko/review.py +143 -0
  104. panko/sandbox/__init__.py +0 -0
  105. panko/sandbox/seed.py +106 -0
  106. panko/setup.py +261 -0
  107. panko/skill.py +27 -0
  108. panko/store/__init__.py +191 -0
  109. panko/store/normalize.py +7 -0
  110. panko/templates/env.example +21 -0
  111. panko/templates/languages/moroccan-darija.toml +45 -0
  112. panko/templates/languages/spanish.toml +36 -0
  113. panko/templates/panko.example.toml +140 -0
  114. panko/work.py +628 -0
  115. pankohub-0.1.0.dist-info/METADATA +258 -0
  116. pankohub-0.1.0.dist-info/RECORD +119 -0
  117. pankohub-0.1.0.dist-info/WHEEL +4 -0
  118. pankohub-0.1.0.dist-info/entry_points.txt +2 -0
  119. pankohub-0.1.0.dist-info/licenses/LICENSE +661 -0
panko/__init__.py ADDED
@@ -0,0 +1,22 @@
1
+ """Panko: language-learning sources in, verified Anki cards out."""
2
+
3
+ # How Panko names itself to the sites it reads. Wikimedia refuses a vague name from a server (403, "robot policy"):
4
+ # it wants a way to reach the tool's authors, so the name carries the project's address.
5
+ SOURCE = "https://github.com/NotAHill/panko"
6
+ USER_AGENT = f"panko ({SOURCE})"
7
+ # Panko's name on PyPI ("panko" there is another project); the command and the module stay `panko`.
8
+ DIST = "pankohub"
9
+ # How a person installs Panko on their own computer (the install page, docs/ROADMAP.md track D): from GitHub until
10
+ # the first release is on PyPI, then `uv tool install pankohub`.
11
+ INSTALL = f"uv tool install git+{SOURCE}"
12
+ UPGRADE = f"uv tool upgrade {DIST}"
13
+
14
+
15
+ def version() -> str:
16
+ """This Panko's version, or "" when it isn't installed as a package."""
17
+ from importlib.metadata import PackageNotFoundError
18
+ from importlib.metadata import version as v
19
+ try:
20
+ return v(DIST)
21
+ except PackageNotFoundError:
22
+ return ""
panko/__main__.py ADDED
@@ -0,0 +1,4 @@
1
+ """`python -m panko` runs the command line (the hosted front door starts each user's Panko this way)."""
2
+ from panko.cli import main
3
+
4
+ main()
panko/anki/__init__.py ADDED
File without changes
panko/anki/addon.py ADDED
@@ -0,0 +1,19 @@
1
+ """The Panko sync add-on as a file to open in Anki: a zip of `src/panko/anki_addon`. Served by a Panko (its sync
2
+ page) and by the front door of a hosted one (the install page, for people without an account)."""
3
+ from __future__ import annotations
4
+
5
+ import io
6
+ import zipfile
7
+ from pathlib import Path
8
+
9
+ NAME = "panko-sync.ankiaddon"
10
+
11
+
12
+ def addon_zip() -> bytes:
13
+ src = Path(__file__).resolve().parent.parent / "anki_addon"
14
+ buf = io.BytesIO()
15
+ with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
16
+ for f in sorted(src.rglob("*")):
17
+ if f.is_file() and "__pycache__" not in f.parts and f.suffix in (".py", ".json", ".md"):
18
+ z.write(f, f.relative_to(src).as_posix())
19
+ return buf.getvalue()
panko/anki/apkg.py ADDED
@@ -0,0 +1,152 @@
1
+ """Your cards as an Anki package (.apkg), to share with a friend.
2
+
3
+ The package is built in a scratch collection with Anki's own library (`uv sync --extra apkg`), so your Anki and its
4
+ review history are never touched. It holds your active cards with Panko's note types, templates and styling, the
5
+ pictures and the audio already made (nothing new is paid for), and no scheduling: a friend starts from new cards.
6
+ MyNotes stays empty. Unless you choose `personal`, where each word came from is left out (source names can name your
7
+ teacher) and so are clips cut from your lesson recordings; photo credits always stay, because the licences need them.
8
+ Each note's id comes from its Panko id, so importing a newer package updates the friend's notes instead of adding
9
+ copies.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import os
15
+ import re
16
+ import shutil
17
+ import tempfile
18
+ from pathlib import Path
19
+
20
+ from panko.anki.sync import MEDIA_DIRS, PREFIX
21
+ from panko.cards import build as B
22
+ from panko.cards import note_types as T
23
+ from panko.media import audio
24
+ from panko.store import Store
25
+
26
+ NATIVE = "_panko_native_" # clips cut from your own recordings (panko.media.clips)
27
+ MEDIA_REF = re.compile(r'\[sound:([^\]]+)\]|src="([^"]+)"')
28
+
29
+
30
+ class _Made(audio.Narrator):
31
+ """Audio already made: never generates (or pays for) a clip, and leaves your recordings out unless asked."""
32
+
33
+ def __init__(self, personal: bool):
34
+ super().__init__(prefix=PREFIX)
35
+ self.personal, self.missing = personal, 0
36
+
37
+ def say(self, text, variety, slot=0):
38
+ v = audio.speak(text, variety, self.prefix, slot, dry=[])
39
+ if not v or v.source == "not generated yet":
40
+ self.missing += bool(v)
41
+ return None
42
+ if not self.personal and v.filename.startswith(NATIVE):
43
+ return None
44
+ return v
45
+
46
+
47
+ def _shared(e: dict, personal: bool) -> dict:
48
+ """The entry as it goes in a package: without where it came from, unless that's wanted."""
49
+ if personal:
50
+ return e
51
+ exs = [{**x, "source": "", "audio": "" if str(x.get("audio", "")).startswith(NATIVE) else x.get("audio", "")}
52
+ for x in e.get("examples", [])]
53
+ return {**e, "sources": [], "examples": exs, "review": False,
54
+ "tags": [t for t in e.get("tags", []) if not t.startswith(("src::", "panko::"))]}
55
+
56
+
57
+ def _room(where: Path, files, tmp: Path) -> None:
58
+ """Enough free space for the package (and a copy of the media when it can't be linked)? Say so before writing."""
59
+ size = sum(f.stat().st_size for f in files)
60
+ linkable = all(f.stat().st_dev == tmp.stat().st_dev for f in files)
61
+ need = int(size * (1.1 if linkable else 2.1)) + 50_000_000
62
+ free = shutil.disk_usage(where).free
63
+ if free < need:
64
+ raise RuntimeError(f"the package needs about {need // 1_000_000:,} MB free in {where}, and there's "
65
+ f"{free // 1_000_000:,} MB: set [export] dir in your config to a folder on a bigger disk")
66
+
67
+
68
+ def _guid(eid: str) -> str:
69
+ return "panko-" + hashlib.sha1(eid.encode()).hexdigest()[:16]
70
+
71
+
72
+ def _model_id(name: str) -> int:
73
+ return 1_700_000_000_000 + int(hashlib.sha1(name.encode()).hexdigest()[:8], 16) % 1_000_000_000
74
+
75
+
76
+ def export(out: Path, varieties: list[str] | None = None, personal: bool = False, store: Store | None = None) -> dict:
77
+ """Your active cards (of these varieties) as a package for a friend."""
78
+ store = store or Store()
79
+ entries = [e for e in store.entries("active") if not varieties or e["variety"] in varieties]
80
+ if not entries:
81
+ raise ValueError("no active cards to put in it" + (f" for {', '.join(varieties)}" if varieties else ""))
82
+ from panko.media import clips
83
+ narrator = _Made(personal)
84
+ notes = []
85
+ for e in entries:
86
+ n = B.to_note(_shared(e, personal), narrator)
87
+ n["deck"] = f"Panko::{e['variety'].title()}" # not your own deck names
88
+ n["tags"] = [t for t in n["tags"] if personal or not t.startswith("panko::")]
89
+ notes.append((_guid(e["id"]), n))
90
+ rep = package(out, notes, [*MEDIA_DIRS, audio.MEDIA, clips._media()])
91
+ return {**rep, "audio_not_made": narrator.missing, "personal": personal}
92
+
93
+
94
+ def package(out: Path, notes: list[tuple[str, dict]], media_dirs: list[Path]) -> dict:
95
+ """Write rendered notes ((guid, note) pairs, decks under `Panko::`) with the media they use, found in these
96
+ folders, as an .apkg built in a scratch collection beside it."""
97
+ try:
98
+ from anki.collection import Collection, DeckIdLimit, ExportAnkiPackageOptions
99
+ except ImportError as e:
100
+ raise RuntimeError("making an .apkg needs Anki's library: run `uv sync --extra apkg`") from e
101
+ out = Path(out)
102
+ out.parent.mkdir(parents=True, exist_ok=True)
103
+ tmp = Path(tempfile.mkdtemp(prefix=".panko-apkg-", dir=out.parent)) # beside the package, not on the system disk
104
+ try:
105
+ col = Collection(str(tmp / "collection.anki2"))
106
+ mm, models = col.models, {}
107
+ for name, fields, tmpls in [(T.WORD_MODEL, T.WORD_FIELDS, T.word_templates()),
108
+ (T.PHRASE_MODEL, T.PHRASE_FIELDS, T.phrase_templates())]:
109
+ m = mm.new(name)
110
+ for f in fields:
111
+ mm.add_field(m, mm.new_field(f))
112
+ for t in tmpls:
113
+ tt = mm.new_template(t["Name"])
114
+ tt["qfmt"], tt["afmt"] = t["Front"], t["Back"]
115
+ mm.add_template(m, tt)
116
+ m["css"] = T.css()
117
+ new = mm.add_dict(m).id
118
+ fixed = _model_id(name) # the same on every export, so a newer package updates the old one
119
+ for table, col_name in (("notetypes", "id"), ("fields", "ntid"), ("templates", "ntid")):
120
+ col.db.execute(f"UPDATE {table} SET {col_name} = ? WHERE {col_name} = ?", fixed, new)
121
+ models[name] = fixed
122
+ col.models._clear_cache()
123
+ used: set[str] = set()
124
+ added, empty = 0, 0
125
+ for guid, note in notes:
126
+ n = col.new_note(mm.get(models[note["model"]]))
127
+ for k, v in note["fields"].items():
128
+ if k in n:
129
+ n[k] = v
130
+ n.tags = note["tags"]
131
+ n.guid = guid
132
+ try:
133
+ col.add_note(n, col.decks.id(note["deck"]))
134
+ except Exception: # a note whose card switches make no card at all
135
+ empty += 1
136
+ continue
137
+ added += 1
138
+ used |= {a or b for a, b in MEDIA_REF.findall(" ".join(note["fields"].values()))}
139
+ files = {f.name: f for d in media_dirs if d.exists() for f in d.iterdir() if f.name in used}
140
+ _room(out.parent, files.values(), tmp)
141
+ for f in files.values():
142
+ try:
143
+ os.link(f, Path(col.media.dir()) / f.name) # no second copy when on the same disk
144
+ except OSError:
145
+ shutil.copy2(f, Path(col.media.dir()) / f.name)
146
+ opts = ExportAnkiPackageOptions(with_scheduling=False, with_deck_configs=False, with_media=True, legacy=False)
147
+ col.export_anki_package(out_path=str(out), options=opts, limit=DeckIdLimit(col.decks.id("Panko")))
148
+ col.close()
149
+ finally:
150
+ shutil.rmtree(tmp, ignore_errors=True)
151
+ return {"path": str(out), "notes": added, "skipped": empty, "media": len(files), "media_missing": len(used - set(files)),
152
+ "bytes": out.stat().st_size}
panko/anki/export.py ADDED
@@ -0,0 +1,44 @@
1
+ """Export an Anki deck's notes (read-only) so its rows can be worked through as a source.
2
+
3
+ Writes {"deck", "notes": [{nid, model, tags, fields {name: html}, studied}]}: the shape `panko.ingest.decks` reads.
4
+ `studied` = any of the note's cards has been reviewed (Anki's `-is:new`), so Panko never adds those notes again;
5
+ `panko migrate` converts them in place with their history instead.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from pathlib import Path
11
+
12
+
13
+ def _note_ids(query: str) -> list[int]:
14
+ """Every matching note id. The add-on returns at most 500 per call, so page until it says there are no more."""
15
+ from panko.anki.sync import tool
16
+ ids: list[int] = []
17
+ while True:
18
+ r = tool("find_notes", {"query": query, "limit": 500, "offset": len(ids)})
19
+ page = r.get("noteIds", [])
20
+ ids += page
21
+ if not page or not r.get("hasMore"):
22
+ return ids
23
+
24
+
25
+ def export_deck(name: str, path: Path) -> dict:
26
+ from panko.anki import mcp_client as mcp
27
+ from panko.anki.sync import tool
28
+ mcp.init()
29
+ q = 'deck:"' + name.replace('"', '\\"') + '"'
30
+ ids = _note_ids(q)
31
+ if not ids:
32
+ raise ValueError(f"no notes in an Anki deck called {name!r}")
33
+ studied = set(_note_ids(q + " -is:new"))
34
+ notes = []
35
+ for i in range(0, len(ids), 100):
36
+ for n in tool("notes_info", {"notes": ids[i:i + 100]})["notes"]:
37
+ fields = sorted(n["fields"].items(), key=lambda kv: kv[1].get("order", 0) if isinstance(kv[1], dict) else 0)
38
+ notes.append({"nid": n["noteId"], "model": n.get("modelName", ""), "tags": n.get("tags", []),
39
+ "fields": {k: v["value"] if isinstance(v, dict) else v for k, v in fields},
40
+ "studied": n["noteId"] in studied})
41
+ out = {"deck": name, "notes": notes}
42
+ path.parent.mkdir(parents=True, exist_ok=True)
43
+ path.write_text(json.dumps(out, ensure_ascii=False))
44
+ return out
@@ -0,0 +1,57 @@
1
+ """Minimal client for the Anki MCP Server add-on (streamable-HTTP JSON-RPC).
2
+
3
+ Used for everyday reads/writes while Anki is open. Schema-changing migrations go
4
+ through the anki pylib with Anki closed instead (see docs/ARCHITECTURE.md).
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import json
9
+ import sys
10
+ import urllib.request
11
+
12
+ _sid: str | None = None
13
+
14
+
15
+ def rpc(method: str, params: dict | None = None, id_: int = 1, notify: bool = False):
16
+ global _sid
17
+ body: dict = {"jsonrpc": "2.0", "method": method}
18
+ if params is not None:
19
+ body["params"] = params
20
+ if not notify:
21
+ body["id"] = id_
22
+ headers = {"Content-Type": "application/json", "Accept": "application/json, text/event-stream",
23
+ "MCP-Protocol-Version": "2025-06-18"}
24
+ if _sid:
25
+ headers["Mcp-Session-Id"] = _sid
26
+ from panko.config import anki
27
+ req = urllib.request.Request(anki()["url"], data=json.dumps(body).encode(), method="POST", headers=headers)
28
+ with urllib.request.urlopen(req, timeout=120) as r:
29
+ _sid = r.headers.get("Mcp-Session-Id") or _sid
30
+ raw = r.read().decode()
31
+ if notify or not raw.strip():
32
+ return None
33
+ if raw.lstrip().startswith("event:") or "data:" in raw[:20]:
34
+ raw = [line[5:].strip() for line in raw.splitlines() if line.startswith("data:")][-1]
35
+ return json.loads(raw)
36
+
37
+
38
+ def init():
39
+ rpc("initialize", {"protocolVersion": "2025-06-18", "capabilities": {},
40
+ "clientInfo": {"name": "panko", "version": "0.1"}})
41
+ rpc("notifications/initialized", notify=True)
42
+
43
+
44
+ def call(name: str, args: dict | None = None):
45
+ return rpc("tools/call", {"name": name, "arguments": args or {}}, id_=2)
46
+
47
+
48
+ def tools() -> list[dict]:
49
+ return rpc("tools/list", {}, id_=3)["result"]["tools"]
50
+
51
+
52
+ if __name__ == "__main__":
53
+ init()
54
+ if len(sys.argv) < 2 or sys.argv[1] == "list":
55
+ print("\n".join(sorted(t["name"] for t in tools())))
56
+ else:
57
+ print(json.dumps(call(sys.argv[1], json.loads(sys.argv[2]) if len(sys.argv) > 2 else {}), ensure_ascii=False, indent=1))
panko/anki/migrate.py ADDED
@@ -0,0 +1,213 @@
1
+ """Phase 6: turn the old-deck notes you studied into Panko notes in place, so their review history stays.
2
+
3
+ Uses the official `anki` library (extra `migrate`, pinned to the desktop version) on the collection file, with Anki
4
+ closed: the MCP add-on can't change note types, and Change Note Type forces one full sync.
5
+
6
+ For each studied store entry (origin.notes[].nid), the old note:
7
+ - changes note type to Panko Word/Phrase; each old card keeps its id, reviews and schedule, mapped by direction:
8
+ the target language on the front → Recognition, the gloss language on the front → Production;
9
+ - keeps its old Front/Back verbatim in Spare3/Spare4 (hidden; nothing of yours is lost);
10
+ - gets the rendered Panko fields (never MyNotes), Panko tags on top of its own, and moves to Panko Sandbox;
11
+ - is linked in the store, so `panko sync` updates it in place from then on.
12
+ A note that fed two entries goes to the first; the second entry becomes a new note on the next `panko sync`.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ import shutil
18
+ import subprocess
19
+ from pathlib import Path
20
+
21
+ from panko import lang
22
+ from panko.anki.sync import MEDIA_DIRS, PREFIX
23
+ from panko.cards import build as B
24
+ from panko.cards import note_types as T
25
+
26
+ KEEP = ("Spare3", "Spare4") # old Front, old Back
27
+ TEMPLATE_INDEX = {"recognition": 0, "production": 1}
28
+
29
+
30
+ def anki_running() -> bool:
31
+ return subprocess.run(["pgrep", "-x", "Anki"], capture_output=True).returncode == 0
32
+
33
+
34
+ def card_map(note) -> dict[int, str]:
35
+ """Old card ord → Panko card for this note's type: `[anki.card_map]` in config if it names the type, else by
36
+ which side each template shows first (the target language's script on the front → recognition, anything else →
37
+ production; when the gloss language shares the script, name the type in `[anki.card_map]`)."""
38
+ from panko.config import anki
39
+ model = note.note_type()
40
+ given = anki()["card_map"].get(model["name"])
41
+ if given:
42
+ return {i: c for i, c in enumerate(given) if c}
43
+ out = {}
44
+ for t in model["tmpls"]:
45
+ names = [re.sub(r"^(type|text|furigana|kana|kanji):", "", f).strip()
46
+ for f in re.findall(r"\{\{([^#/^!}][^}]*)\}\}", t["qfmt"])]
47
+ shown = " ".join(note[f] for f in names if f in note.keys())
48
+ out[t["ord"]] = "recognition" if lang.in_target(shown) else "production"
49
+ return out
50
+
51
+
52
+ def plan(store, col) -> list[dict]:
53
+ """One row per old note to convert. Raises on an old note type with no card map."""
54
+ rows, taken = [], set()
55
+ for e in sorted(store.entries("candidate"), key=lambda x: x["id"]):
56
+ olds = [n for n in (e.get("origin") or {}).get("notes", []) if n.get("studied") and n.get("nid")]
57
+ if not olds:
58
+ continue
59
+ nid = olds[0]["nid"]
60
+ if nid not in taken and col.get_note(nid).note_type()["name"] in (T.WORD_MODEL, T.PHRASE_MODEL):
61
+ taken.add(nid) # converted in an earlier run (e.g. the test batch) for the entry it fed first
62
+ if nid in taken:
63
+ rows.append({"eid": e["id"], "nid": None, "ar": e["ar"], "gloss": e.get("gloss", ""), "shared_with": nid})
64
+ continue
65
+ taken.add(nid)
66
+ note = col.get_note(nid)
67
+ old_model = note.note_type()["name"]
68
+ cmap = card_map(note)
69
+ if any(c.ord not in cmap for c in note.cards()):
70
+ raise ValueError(f"{e['id']}: [anki.card_map] for {old_model!r} doesn't cover all its cards")
71
+ cards = [{"cid": c.id, "ord": c.ord, "to": cmap[c.ord], "reps": c.reps,
72
+ "deck": col.decks.name(c.did)} for c in note.cards()]
73
+ rows.append({"eid": e["id"], "nid": nid, "ar": e["ar"], "gloss": e.get("gloss", ""), "kind": e["kind"],
74
+ "old_model": old_model, "old_fields": dict(note.items()), "cards": cards})
75
+ return rows
76
+
77
+
78
+ def _cards_for(entry: dict, row: dict) -> list[str]:
79
+ """Panko's card switches, plus any card the old note already reviewed (its history must keep a front)."""
80
+ want = list(entry.get("cards", B.DEFAULT_CARDS))
81
+ for c in row["cards"]:
82
+ if c["reps"] and c["to"] not in want:
83
+ want.append(c["to"])
84
+ return want
85
+
86
+
87
+ def _copy_media(note: dict, media_dir: Path) -> list[str]:
88
+ import json
89
+ used = set(re.findall(rf"({re.escape(PREFIX)}[\w.-]+?\.(?:mp3|jpg|jpeg|png|svg|webp))", json.dumps(note, ensure_ascii=False)))
90
+ missing = []
91
+ for name in sorted(used):
92
+ src = next((d / name for d in MEDIA_DIRS if (d / name).exists()), None)
93
+ if src is None:
94
+ missing.append(name)
95
+ elif not (media_dir / name).exists():
96
+ shutil.copy2(src, media_dir / name)
97
+ return missing
98
+
99
+
100
+ def convert(store, col, rows: list[dict], narrator=None) -> dict:
101
+ """Change note type, fill fields, move cards, link in the store. `rows` from `plan` (a subset is fine)."""
102
+ from anki.models import ChangeNotetypeRequest # noqa: F401 (pylib present)
103
+
104
+ todo = [r for r in rows if r.get("nid")]
105
+ models = {"word": col.models.by_name(T.WORD_MODEL), "phrase": col.models.by_name(T.PHRASE_MODEL)}
106
+ # 1. change note type, grouped by (old type, new type)
107
+ groups: dict[tuple, list[dict]] = {}
108
+ for r in todo:
109
+ groups.setdefault((r["old_model"], r["kind"]), []).append(r)
110
+ for (old_name, kind), rs in groups.items():
111
+ old, new = col.models.by_name(old_name), models[kind]
112
+ info = col.models.change_notetype_info(old_notetype_id=old["id"], new_notetype_id=new["id"])
113
+ req = info.input
114
+ n_old = len(old["flds"]) # old field i → KEEP[i] (Spare3 = old first field, Spare4 = old second)
115
+ req.new_fields[:] = [KEEP.index(f["name"]) if f["name"] in KEEP and KEEP.index(f["name"]) < n_old else -1
116
+ for f in new["flds"]]
117
+ tmpl = [-1] * len(new["tmpls"])
118
+ for c in (c for r in rs for c in r["cards"]): # same note type → same map
119
+ tmpl[TEMPLATE_INDEX[c["to"]]] = c["ord"]
120
+ req.new_templates[:] = tmpl
121
+ req.note_ids[:] = [r["nid"] for r in rs]
122
+ col.models.change_notetype_of_notes(req)
123
+ # 2. fields, tags, media, deck, store link
124
+ media_dir = Path(col.media.dir())
125
+ missing = []
126
+ for r in todo:
127
+ e = store.get(r["eid"])
128
+ e["cards"] = _cards_for(e, r)
129
+ e["status"] = "active"
130
+ rendered = B.to_note(e, narrator) if narrator else B.to_note(e)
131
+ note = col.get_note(r["nid"])
132
+ for k, v in rendered["fields"].items():
133
+ if k not in KEEP:
134
+ note[k] = v
135
+ for t in rendered["tags"]:
136
+ note.add_tag(t)
137
+ col.update_note(note)
138
+ unwanted = [c.id for c in note.cards() if c.ord not in {TEMPLATE_INDEX.get(x, -1) for x in e["cards"]}
139
+ and c.ord in TEMPLATE_INDEX.values() and c.reps == 0] # never-reviewed old card for a card type that's off
140
+ if unwanted:
141
+ col.remove_cards_and_orphaned_notes(unwanted)
142
+ missing += _copy_media(rendered, media_dir)
143
+ did = col.decks.id(rendered["deck"])
144
+ col.set_deck([c.id for c in note.cards()], did)
145
+ store.put(e, "active")
146
+ store.set_link(r["eid"], r["nid"], B.note_hash(rendered))
147
+ # 3. the second entry of a shared note becomes a new note on the next sync
148
+ for r in rows:
149
+ if not r.get("nid") and r.get("shared_with"):
150
+ store.set_status(r["eid"], "active")
151
+ return {"converted": len(todo), "new_on_next_sync": sum(1 for r in rows if not r.get("nid")),
152
+ "missing_media": sorted(set(missing))}
153
+
154
+
155
+ def report(rows: list[dict]) -> str:
156
+ """The dry-run list, as Markdown."""
157
+ name = {"recognition": "Recognition", "production": "Production"}
158
+ out = ["| Entry | Word | Meaning | Old deck · note type | Cards (reviews) → Panko |", "|---|---|---|---|---|"]
159
+ for r in rows:
160
+ if not r.get("nid"):
161
+ out.append(f"| {r['eid']} | {r['ar']} | {r['gloss']} | shares note {r['shared_with']} | new note on next sync |")
162
+ continue
163
+ cards = ", ".join(f"{c['ord'] + 1} ({c['reps']}) → {name[c['to']]}" for c in sorted(r["cards"], key=lambda c: c["ord"]))
164
+ deck = r["cards"][0]["deck"] if r["cards"] else ""
165
+ out.append(f"| {r['eid']} | {r['ar']} | {r['gloss']} | {deck} · {r['old_model']} | {cards} |")
166
+ return "\n".join(out)
167
+
168
+
169
+ def run(dry_run: bool = True, ids: list[str] | None = None, collection: Path | None = None,
170
+ scratch: Path | None = None, store=None, narrator=None) -> dict:
171
+ """Dry run: plan against a throwaway copy (safe with Anki open). Real run: Anki must be closed; backs up first."""
172
+ import tempfile
173
+ import time
174
+
175
+ from anki.collection import Collection
176
+
177
+ from panko.config import collection_path
178
+ collection = Path(collection) if collection else collection_path()
179
+
180
+ from panko.store import Store
181
+
182
+ st = store or Store()
183
+ base = scratch or (Path("/Volumes/external_ssd/panko-scratch") if Path("/Volumes/external_ssd").exists()
184
+ else Path(tempfile.gettempdir()))
185
+ base.mkdir(parents=True, exist_ok=True)
186
+ if dry_run:
187
+ tmp = Path(tempfile.mkdtemp(dir=base))
188
+ for suffix in ("", "-wal"):
189
+ if Path(f"{collection}{suffix}").exists():
190
+ shutil.copy2(f"{collection}{suffix}", tmp / f"collection.anki2{suffix}")
191
+ path = tmp / "collection.anki2"
192
+ else:
193
+ if anki_running():
194
+ raise SystemExit("Close Anki first (Change Note Type needs the collection to itself).")
195
+ backup = base / f"collection-before-phase6-{time.strftime('%Y%m%d-%H%M%S')}.anki2"
196
+ shutil.copy2(collection, backup)
197
+ print("backup:", backup)
198
+ path = collection
199
+ col = Collection(str(path))
200
+ try:
201
+ rows = plan(st, col)
202
+ if ids:
203
+ rows = [r for r in rows if r["eid"] in ids]
204
+ if dry_run:
205
+ return {"rows": rows, "report": report(rows)}
206
+ if narrator is None:
207
+ from panko.media import audio
208
+ narrator = audio.Narrator(prefix=PREFIX)
209
+ return {"rows": rows, **convert(st, col, rows, narrator)}
210
+ finally:
211
+ col.close()
212
+ if dry_run:
213
+ shutil.rmtree(path.parent, ignore_errors=True)