keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/anki.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
"""Anki (R22): one `sources.Source` page per deck, so an agent sees what the owner studies in
|
|
2
|
+
Anki and how well it is sticking, without a page per card or a second scheduler. Anki's reviews
|
|
3
|
+
never become Keepfold grades (levels.py is untouched).
|
|
4
|
+
|
|
5
|
+
What it reads, from a temp copy opened read-only (`mode=ro`), never Anki's own file:
|
|
6
|
+
- an `.apkg` or `.colpkg` export: its `collection.anki21`, else its `collection.anki2` (an
|
|
7
|
+
export holding `collection.anki21b`, Anki's zstd format, keeps a stub `collection.anki2`
|
|
8
|
+
beside it, so that one is refused with how to export again);
|
|
9
|
+
- Anki's profile collection (`collection.anki2`, given as the file or its profile folder), with
|
|
10
|
+
its `-wal`, as the Zotero import copies Zotero's.
|
|
11
|
+
Both schemas: the legacy one (decks as JSON in `col.decks`, names split by `::`) and schema 18
|
|
12
|
+
(a `decks` table, names split by \\x1f). Tables read: decks, notes (first field and tags),
|
|
13
|
+
cards (deck, type, interval, lapses), revlog (time, card, button, type). A card in a filtered
|
|
14
|
+
deck counts in its home deck (`odid`).
|
|
15
|
+
|
|
16
|
+
A deck's page counts its cards with its subdecks' (as Anki's deck list does); each subdeck has
|
|
17
|
+
its own page too. `link` then points each page at its parent deck's (`related`) and at a concept
|
|
18
|
+
whose title or alias is the deck's last name part (`covers`).
|
|
19
|
+
"""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import json
|
|
24
|
+
import re
|
|
25
|
+
import shutil
|
|
26
|
+
import sqlite3
|
|
27
|
+
import tempfile
|
|
28
|
+
import time
|
|
29
|
+
import zipfile
|
|
30
|
+
from contextlib import closing
|
|
31
|
+
from datetime import UTC, datetime
|
|
32
|
+
from pathlib import Path
|
|
33
|
+
|
|
34
|
+
from keepfold import importers, render, sources
|
|
35
|
+
from keepfold.life_sources import html_text # HTML to text, as mail bodies and Zotero notes
|
|
36
|
+
from keepfold.vault import Vault, VaultError, is_private
|
|
37
|
+
|
|
38
|
+
LABEL = "Anki"
|
|
39
|
+
PACKAGES = (".apkg", ".colpkg")
|
|
40
|
+
COLLECTION = "collection.anki2" # a profile's collection; an old export's too
|
|
41
|
+
MATURE = 21 # days: Anki's young/mature split
|
|
42
|
+
MIN_REVIEWS = 20 # review answers in 30 days under which no retention is given
|
|
43
|
+
LEECHES = 10 # leeches listed on a page
|
|
44
|
+
DAY_MS = 86_400_000
|
|
45
|
+
EXPORT_AGAIN = ('in Anki, choose File > Export, tick "Support older Anki versions" and export '
|
|
46
|
+
"again")
|
|
47
|
+
_SOUND = re.compile(r"\[sound:[^\]]*\]")
|
|
48
|
+
_CLOZE = re.compile(r"\{\{c\d+::(.*?)(?:::[^{}]*?)?\}\}", re.S)
|
|
49
|
+
_STUB = sources.Source("anki", LABEL, "file", tuple) # `source_pages`' labels only
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def holds(path: Path | str, top: bool = False) -> bool:
|
|
53
|
+
"""Whether `path` is Anki's alone: an export, a collection file or a profile folder (one
|
|
54
|
+
holding collection.anki2). With `top`, also a folder with .apkg/.colpkg files at its top,
|
|
55
|
+
which may hold other kinds too (importers.detect adds "anki" to them)."""
|
|
56
|
+
p = Path(path)
|
|
57
|
+
try:
|
|
58
|
+
if p.is_dir():
|
|
59
|
+
return (p / COLLECTION).is_file() or top and any(
|
|
60
|
+
c.suffix.lower() in PACKAGES and c.is_file() for c in p.iterdir())
|
|
61
|
+
except OSError:
|
|
62
|
+
return False
|
|
63
|
+
return p.suffix.lower() in PACKAGES or p.name.lower() in (COLLECTION, "collection.anki21")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _inputs(path: Path) -> list[Path]:
|
|
67
|
+
if path.is_dir():
|
|
68
|
+
if (path / COLLECTION).is_file():
|
|
69
|
+
return [path / COLLECTION]
|
|
70
|
+
got = sorted(c for c in path.iterdir() if c.suffix.lower() in PACKAGES and c.is_file())
|
|
71
|
+
else:
|
|
72
|
+
got = [path] if path.is_file() else []
|
|
73
|
+
if not got:
|
|
74
|
+
raise VaultError("invalid_argument", f"Found no Anki collection in {path.name}: give an "
|
|
75
|
+
".apkg or .colpkg export, or Anki's profile folder (it holds "
|
|
76
|
+
f"{COLLECTION}).")
|
|
77
|
+
return got
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _bad(name: str, why: object = "") -> VaultError:
|
|
81
|
+
return VaultError("invalid_argument", f"Cannot read {name}: it is not an Anki collection "
|
|
82
|
+
f"Keepfold can read{f' ({why})' if why else ''}.")
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def _copy(f: Path, tmp: Path) -> Path:
|
|
86
|
+
"""A copy of `f`'s collection in `tmp`: the export's member, or the profile's file and its
|
|
87
|
+
-wal. Anki's own files are only read."""
|
|
88
|
+
out = tmp / "collection"
|
|
89
|
+
if f.suffix.lower() not in PACKAGES:
|
|
90
|
+
for name in (f.name, f.name + "-wal"): # the WAL may hold reviews not checkpointed yet
|
|
91
|
+
if name == f.name or (f.parent / name).is_file():
|
|
92
|
+
try:
|
|
93
|
+
shutil.copyfile(f.parent / name, out.with_name(out.name + name[len(f.name):]))
|
|
94
|
+
except OSError:
|
|
95
|
+
raise VaultError("busy", "Anki holds its collection; close Anki and try "
|
|
96
|
+
"again.") from None
|
|
97
|
+
return out
|
|
98
|
+
try:
|
|
99
|
+
with zipfile.ZipFile(f) as z:
|
|
100
|
+
members = {i.filename: i for i in z.infolist()}
|
|
101
|
+
if "collection.anki21b" in members and "collection.anki21" not in members:
|
|
102
|
+
raise VaultError("invalid_argument", f"{f.name} is in Anki's newest export "
|
|
103
|
+
f"format, which Keepfold does not read: {EXPORT_AGAIN}.")
|
|
104
|
+
i = members.get("collection.anki21") or members.get(COLLECTION)
|
|
105
|
+
if i is None:
|
|
106
|
+
raise _bad(f.name, "no collection in it")
|
|
107
|
+
if i.file_size > importers.MAX_TOTAL:
|
|
108
|
+
raise importers._too_big(f.name, importers.MAX_TOTAL)
|
|
109
|
+
with z.open(i) as src, out.open("wb") as dst: # stops at the declared size
|
|
110
|
+
shutil.copyfileobj(src, dst, importers.STREAM_CHUNK)
|
|
111
|
+
except (OSError, zipfile.BadZipFile, NotImplementedError, EOFError) as e:
|
|
112
|
+
if isinstance(e, NotImplementedError): # a zstd-compressed member
|
|
113
|
+
raise VaultError("invalid_argument", f"{f.name} is in Anki's newest export "
|
|
114
|
+
f"format, which Keepfold does not read: {EXPORT_AGAIN}.") from None
|
|
115
|
+
raise _bad(f.name, e) from None
|
|
116
|
+
return out
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def decks(path: Path | str, now: float | None = None) -> list[dict]:
|
|
120
|
+
"""Every deck of the collections at `path` (see `_inputs`), with its own counts (`_read`)."""
|
|
121
|
+
now_ms = int((time.time() if now is None else now) * 1000)
|
|
122
|
+
out = []
|
|
123
|
+
for f in _inputs(Path(path)):
|
|
124
|
+
with tempfile.TemporaryDirectory(prefix="keepfold-anki-") as tmp:
|
|
125
|
+
db = _copy(f, Path(tmp))
|
|
126
|
+
try:
|
|
127
|
+
with closing(sqlite3.connect(db.as_uri() + "?mode=ro", uri=True)) as con:
|
|
128
|
+
# a shared deck is a stranger's file: no functions from its schema
|
|
129
|
+
con.execute("PRAGMA trusted_schema = OFF")
|
|
130
|
+
out += _read(con, now_ms)
|
|
131
|
+
except (sqlite3.Error, ValueError, TypeError, KeyError, AttributeError) as e:
|
|
132
|
+
raise _bad(f.name, e) from None
|
|
133
|
+
return out
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _read(con: sqlite3.Connection, now_ms: int) -> list[dict]:
|
|
137
|
+
q = con.execute
|
|
138
|
+
tables = {r[0] for r in q("SELECT name FROM sqlite_master WHERE type = 'table'")}
|
|
139
|
+
if not {"cards", "notes", "revlog"} <= tables or not tables & {"decks", "col"}:
|
|
140
|
+
raise ValueError("no cards, notes, revlog or decks tables")
|
|
141
|
+
if "decks" in tables: # schema 18: a table, names split by \x1f
|
|
142
|
+
names = {int(i): str(n).replace("\x1f", "::") for i, n in q("SELECT id, name FROM decks")}
|
|
143
|
+
else: # legacy: one JSON object in col.decks
|
|
144
|
+
names = {int(d["id"]): str(d["name"])
|
|
145
|
+
for d in json.loads(q("SELECT decks FROM col").fetchone()[0]).values()}
|
|
146
|
+
home = "CASE WHEN c.odid != 0 THEN c.odid ELSE c.did END" # a filtered deck's card: its own
|
|
147
|
+
own = {i: {"id": i, "name": n, "new": 0, "learning": 0, "young": 0, "mature": 0, "r30": 0,
|
|
148
|
+
"r365": 0, "rev30": 0, "again30": 0, "last": 0, "newest": 0, "leeches": {}}
|
|
149
|
+
for i, n in names.items()}
|
|
150
|
+
for d, new, learning, young, mature, newest in q(f"""SELECT {home}, SUM(c.type = 0),
|
|
151
|
+
SUM(c.type IN (1, 3)), SUM(c.type = 2 AND c.ivl < {MATURE}),
|
|
152
|
+
SUM(c.type = 2 AND c.ivl >= {MATURE}), MAX(c.id) FROM cards c GROUP BY 1"""):
|
|
153
|
+
if d in own:
|
|
154
|
+
own[d].update(new=new, learning=learning, young=young, mature=mature, newest=newest)
|
|
155
|
+
m30, m365 = now_ms - 30 * DAY_MS, now_ms - 365 * DAY_MS
|
|
156
|
+
for d, r30, r365, rev30, again30, last in q(f"""SELECT {home},
|
|
157
|
+
SUM(r.id >= ? AND r.ease BETWEEN 1 AND 4), SUM(r.id >= ? AND r.ease BETWEEN 1 AND 4),
|
|
158
|
+
SUM(r.id >= ? AND r.type = 1), SUM(r.id >= ? AND r.type = 1 AND r.ease = 1),
|
|
159
|
+
MAX(r.id) FROM revlog r JOIN cards c ON c.id = r.cid GROUP BY 1""",
|
|
160
|
+
(m30, m365, m30, m30)):
|
|
161
|
+
if d in own:
|
|
162
|
+
own[d].update(r30=r30 or 0, r365=r365 or 0, rev30=rev30 or 0, again30=again30 or 0,
|
|
163
|
+
last=last or 0)
|
|
164
|
+
from keepfold.levels import LEECH_LAPSES # levels loads fsrs: only when a collection is read
|
|
165
|
+
for d, nid, flds, tags, lapses in q(f"""SELECT {home}, n.id, n.flds, n.tags, c.lapses
|
|
166
|
+
FROM cards c JOIN notes n ON n.id = c.nid
|
|
167
|
+
WHERE c.lapses >= ? OR lower(' ' || n.tags || ' ') LIKE '% leech %'""",
|
|
168
|
+
(LEECH_LAPSES,)):
|
|
169
|
+
if d in own: # a note is one leech, however many of its cards lapse
|
|
170
|
+
tagged = "leech" in str(tags).casefold().split()
|
|
171
|
+
got = own[d]["leeches"].get(nid)
|
|
172
|
+
if got is None or (tagged, lapses) > got[:2]:
|
|
173
|
+
own[d]["leeches"][nid] = (tagged, lapses, card_text(str(flds).split("\x1f")[0]))
|
|
174
|
+
return list(own.values())
|
|
175
|
+
|
|
176
|
+
|
|
177
|
+
def card_text(field: str) -> str:
|
|
178
|
+
"""A card's first field as one safe line: sounds dropped, clozes as their answers, HTML
|
|
179
|
+
tags (scripts and styles with their content) stripped, entities decoded, links, images and
|
|
180
|
+
URLs dropped, at most 80 characters."""
|
|
181
|
+
return render.plain(html_text(_CLOZE.sub(r"\1", _SOUND.sub("", field))), limit=80) \
|
|
182
|
+
or "(no text)"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
def _tree(all_decks: list[dict]) -> list[dict]:
|
|
186
|
+
"""Each deck with its subdecks' counts added (Anki's deck list counts them so); decks with
|
|
187
|
+
no cards in them or under them are dropped by `item`."""
|
|
188
|
+
out = []
|
|
189
|
+
for d in all_decks:
|
|
190
|
+
low = d["name"].casefold()
|
|
191
|
+
kids = [x for x in all_decks if x["name"].casefold().startswith(low + "::")]
|
|
192
|
+
t = {**d, "subdecks": bool(kids), "leeches": dict(d["leeches"])}
|
|
193
|
+
for k in kids:
|
|
194
|
+
for f in ("new", "learning", "young", "mature", "r30", "r365", "rev30", "again30"):
|
|
195
|
+
t[f] += k[f]
|
|
196
|
+
t["last"], t["newest"] = max(t["last"], k["last"]), max(t["newest"], k["newest"])
|
|
197
|
+
for nid, lee in k["leeches"].items():
|
|
198
|
+
if nid not in t["leeches"] or lee[:2] > t["leeches"][nid][:2]:
|
|
199
|
+
t["leeches"][nid] = lee
|
|
200
|
+
out.append(t)
|
|
201
|
+
return out
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def _day(ms: int) -> str:
|
|
205
|
+
return importers._day(ms / 1000)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def item(d: dict) -> sources.Item | str:
|
|
209
|
+
"""One deck's page (see the module docstring), or "empty deck"."""
|
|
210
|
+
cards = d["new"] + d["learning"] + d["young"] + d["mature"]
|
|
211
|
+
if not cards:
|
|
212
|
+
return "empty deck"
|
|
213
|
+
name = render.plain(d["name"], limit=200) or "Default"
|
|
214
|
+
lee = sorted(d["leeches"].values(), key=lambda x: (not x[0], -x[1], x[2]))
|
|
215
|
+
n = len(lee)
|
|
216
|
+
enough = d["rev30"] >= MIN_REVIEWS
|
|
217
|
+
pct = round(100 * (d["rev30"] - d["again30"]) / d["rev30"]) if enough else 0
|
|
218
|
+
recall = (f"{pct}% recalled in the last 30 days" if enough else
|
|
219
|
+
"not enough reviews in the last 30 days to say how much is recalled")
|
|
220
|
+
lines = [f"{cards:,} cards, {d['mature']:,} mature, {recall}, {n:,} "
|
|
221
|
+
f"leech{'es' * (n != 1)}.", ""]
|
|
222
|
+
if "::" in name:
|
|
223
|
+
lines.append(f"Parent deck: {name.rsplit('::', 1)[0]}.")
|
|
224
|
+
lines += [
|
|
225
|
+
f"Cards{' (with its subdecks)' if d['subdecks'] else ''}: {d['new']:,} new, "
|
|
226
|
+
f"{d['learning']:,} learning, {d['young']:,} young, {d['mature']:,} mature (an "
|
|
227
|
+
f"interval of {MATURE} days or more).",
|
|
228
|
+
f"Reviews: {d['r30']:,} in the last 30 days, {d['r365']:,} in the last 365 days.",
|
|
229
|
+
f"Recalled in the last 30 days: {pct}% of {d['rev30']:,} review answers (not answered "
|
|
230
|
+
"Again)." if enough else
|
|
231
|
+
f"Recalled in the last 30 days: not enough reviews ({d['rev30']:,} review answers; "
|
|
232
|
+
f"{MIN_REVIEWS} needed).",
|
|
233
|
+
f"Last review: {_day(d['last'])}." if d["last"] else "Last review: never."]
|
|
234
|
+
if lee:
|
|
235
|
+
lines += ["", "## Leeches (cards forgotten again and again)",
|
|
236
|
+
*(f"- {text}" for _, _, text in lee[:LEECHES])]
|
|
237
|
+
if n > LEECHES:
|
|
238
|
+
lines.append(f"- and {n - LEECHES:,} more")
|
|
239
|
+
day = _day(d["last"] or d["newest"]) if d["last"] or d["newest"] else \
|
|
240
|
+
importers._day(datetime.now(UTC).timestamp())
|
|
241
|
+
return sources.Item(f"{LABEL}: {name}", day, "\n".join(lines) + "\n", key=f"anki {d['id']}")
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def source(path: Path | str, now: float | None = None) -> sources.Source:
|
|
245
|
+
"""Every deck of the collections at `path` as a page, keyed by the deck's id, so a re-import
|
|
246
|
+
updates the page in place (unless the owner edited it). Read now: a bad file refuses here."""
|
|
247
|
+
got = [item(d) for d in _tree(decks(path, now))]
|
|
248
|
+
return sources.Source("anki", LABEL, "file", lambda: iter(got), prefix="deck",
|
|
249
|
+
skips=("empty deck",), updates=True, keeps_edits=True)
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def link(vault: Vault) -> int:
|
|
253
|
+
"""After an import: each Anki page's `related` gets its parent deck's page and its `covers`
|
|
254
|
+
a concept whose title or alias is the deck's last name part (case-insensitive). A public
|
|
255
|
+
page never links a private one. Links are only added, never removed; the pages changed."""
|
|
256
|
+
from keepfold.index import _edge_targets, aliases
|
|
257
|
+
pages = {}
|
|
258
|
+
for p in sources.source_pages(vault, _STUB):
|
|
259
|
+
try:
|
|
260
|
+
n = vault.read_path(p)
|
|
261
|
+
except VaultError:
|
|
262
|
+
continue
|
|
263
|
+
pages[str(n.fields.get("title") or "").casefold()] = n
|
|
264
|
+
concepts: dict[str, object] = {}
|
|
265
|
+
for c in vault.iter_notes("concept"):
|
|
266
|
+
for name in (str(c.fields.get("title") or ""), *aliases(c.fields)):
|
|
267
|
+
if name.strip():
|
|
268
|
+
concepts.setdefault(name.strip().casefold(), c)
|
|
269
|
+
head, made = f"{LABEL.casefold()}: ", 0
|
|
270
|
+
for title, n in pages.items():
|
|
271
|
+
name, hidden = title.removeprefix(head), is_private(n)
|
|
272
|
+
want = {"related": pages.get(head + name.rsplit("::", 1)[0]) if "::" in name else None,
|
|
273
|
+
"covers": concepts.get(name.rsplit("::", 1)[-1].strip())}
|
|
274
|
+
values = {}
|
|
275
|
+
for key, to in want.items():
|
|
276
|
+
if to is None or (is_private(to) and not hidden):
|
|
277
|
+
continue
|
|
278
|
+
have = n.fields.get(key) or []
|
|
279
|
+
have = [have] if isinstance(have, str) else list(have)
|
|
280
|
+
if to.id not in _edge_targets(have):
|
|
281
|
+
values[key] = [*have, f"[[{to.id}]]"]
|
|
282
|
+
if values:
|
|
283
|
+
vault._edit_fields("resource", n.id, values)
|
|
284
|
+
made += 1
|
|
285
|
+
return made
|
keepfold/app/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
"""`keepfold app`: a local web page to set up and manage Keepfold (docs/design/keepfold-app.md).
|
|
2
|
+
|
|
3
|
+
`server` (routes, auth, jobs), `targets` (the AI-app connectors), `status` (read-only checks
|
|
4
|
+
and the thin adapters to localllm and the browse code), `actions` (the long jobs), `wizard`
|
|
5
|
+
(the Setup steps). The page is `src/keepfold/assets/app/`."""
|