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/duplicates.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
"""`keepfold concept duplicates` (v6 agenda 8): candidate pairs of catalog concepts that probably
|
|
2
|
+
mean the same thing, each with its evidence and the `keepfold concept merge SRC DST` command to
|
|
3
|
+
run. Read-only: it never merges, writes or downloads. Private concepts (and everything under a
|
|
4
|
+
private domain or area, `planner.hidden`) are left out; concept text is untrusted and printed
|
|
5
|
+
through `render.plain` with control characters dropped.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import difflib
|
|
11
|
+
import re
|
|
12
|
+
from dataclasses import dataclass, field
|
|
13
|
+
|
|
14
|
+
import numpy as np
|
|
15
|
+
|
|
16
|
+
from keepfold import planner, render
|
|
17
|
+
from keepfold.catalog import Catalog, slugify
|
|
18
|
+
from keepfold.index import _edge_targets
|
|
19
|
+
from keepfold.vault import ID_RE, Vault
|
|
20
|
+
|
|
21
|
+
LIMIT = 20
|
|
22
|
+
NAME_RATIO = 0.85 # same as the add-time check; 0.8-0.85 was all noise when judged
|
|
23
|
+
JACCARD = 0.5 # token overlap of the slugified titles and aliases
|
|
24
|
+
COSINE = 0.85 # embedding cosine of "title; aliases", only when the model is already present
|
|
25
|
+
# score weights: lexical and semantic evidence make a candidate; parent and problems only add
|
|
26
|
+
W_NAME, W_JACCARD, W_COSINE, W_PROBLEMS, W_PARENT, W_DOMAIN = 0.35, 0.25, 0.25, 0.1, 0.05, 0.02
|
|
27
|
+
_CTRL = re.compile(r"[\x00-\x1f\x7f-\x9f]")
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass
|
|
31
|
+
class Pair:
|
|
32
|
+
src: str
|
|
33
|
+
dst: str
|
|
34
|
+
score: float
|
|
35
|
+
evidence: list[str] = field(default_factory=list)
|
|
36
|
+
titles: tuple[str, str] = ("", "")
|
|
37
|
+
|
|
38
|
+
@property
|
|
39
|
+
def command(self) -> str:
|
|
40
|
+
return f"keepfold concept merge {self.src} {self.dst}"
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def safe(text: str, limit: int = 80) -> str:
|
|
44
|
+
"""Untrusted concept text as one plain terminal line (no links, HTML or control chars)."""
|
|
45
|
+
return render.plain(_CTRL.sub("", str(text or "")), limit)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _matchers(names: dict[str, str]) -> list[difflib.SequenceMatcher]:
|
|
49
|
+
"""One matcher per name with it as seq2: difflib caches its index for seq2."""
|
|
50
|
+
out = []
|
|
51
|
+
for n in names:
|
|
52
|
+
m = difflib.SequenceMatcher(None)
|
|
53
|
+
m.set_seq2(n)
|
|
54
|
+
out.append(m)
|
|
55
|
+
return out
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _best_ratio(a: dict[str, str], b: dict[str, str],
|
|
59
|
+
mb: list[difflib.SequenceMatcher]) -> tuple[float, str]:
|
|
60
|
+
"""(best name similarity, the name of `a` it came from); a and b map name -> slug, `mb`
|
|
61
|
+
is `_matchers(b)`. Below NAME_RATIO only the fact that it is below matters."""
|
|
62
|
+
same = next((x for x, s in a.items() if s and s in b.values()), None)
|
|
63
|
+
if same is not None:
|
|
64
|
+
return 1.0, same
|
|
65
|
+
best = (0.0, "")
|
|
66
|
+
for x in a:
|
|
67
|
+
for m in mb:
|
|
68
|
+
lo = max(best[0], NAME_RATIO)
|
|
69
|
+
if 2 * min(len(x), len(m.b)) / ((len(x) + len(m.b)) or 1) < lo:
|
|
70
|
+
continue # the length bound alone rules it out
|
|
71
|
+
m.set_seq1(x)
|
|
72
|
+
if m.quick_ratio() >= lo and (r := m.ratio()) > best[0]:
|
|
73
|
+
best = (r, x)
|
|
74
|
+
return best
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def find(vault: Vault, embed=None, limit: int = LIMIT) -> tuple[list[Pair], int, int]:
|
|
78
|
+
"""(the top `limit` candidate pairs by score, how many candidates in all, how many
|
|
79
|
+
concepts were compared). `embed` is semantic.load_embedder() or None; never a download."""
|
|
80
|
+
cat = Catalog.load(vault)
|
|
81
|
+
hidden = planner.hidden(vault, cat)
|
|
82
|
+
cons = [e for e in cat.entries.values()
|
|
83
|
+
if e.kind == "concept" and e.id not in hidden and ID_RE.fullmatch(e.id)]
|
|
84
|
+
names = {e.id: {n.casefold(): slugify(n) for n in (e.title, *e.aliases)} for e in cons}
|
|
85
|
+
toks = {e.id: {t for s in names[e.id].values() for t in s.split("-") if t} for e in cons}
|
|
86
|
+
mats = {e.id: _matchers(names[e.id]) for e in cons}
|
|
87
|
+
problems: dict[str, set[str]] = {e.id: set() for e in cons}
|
|
88
|
+
for p in vault.iter_notes("problem"):
|
|
89
|
+
for c in _edge_targets(p.fields.get("concepts") or []):
|
|
90
|
+
if c in problems:
|
|
91
|
+
problems[c].add(p.id)
|
|
92
|
+
sims = None
|
|
93
|
+
if embed is not None and len(cons) > 1:
|
|
94
|
+
v = np.asarray(embed(["; ".join((e.title, *e.aliases)) for e in cons]), np.float32)
|
|
95
|
+
v /= np.maximum(np.linalg.norm(v, axis=1, keepdims=True), 1e-9)
|
|
96
|
+
sims = v @ v.T
|
|
97
|
+
|
|
98
|
+
out = []
|
|
99
|
+
# shortcut: every pair is compared (about 3 s for 1,000 concepts); block by token or
|
|
100
|
+
# trigram if the catalog grows past a few thousand.
|
|
101
|
+
for i, a in enumerate(cons):
|
|
102
|
+
for j in range(i + 1, len(cons)):
|
|
103
|
+
b = cons[j]
|
|
104
|
+
ta, tb = toks[a.id], toks[b.id]
|
|
105
|
+
jac = len(ta & tb) / len(ta | tb) if ta | tb else 0.0
|
|
106
|
+
ratio, na = _best_ratio(names[a.id], names[b.id], mats[b.id])
|
|
107
|
+
cos = float(sims[i, j]) if sims is not None else None
|
|
108
|
+
if ratio < NAME_RATIO and jac < JACCARD and (cos is None or cos < COSINE):
|
|
109
|
+
continue
|
|
110
|
+
shared = problems[a.id] & problems[b.id]
|
|
111
|
+
ev = [f"same name after normalising ('{safe(na, 40)}')" if ratio == 1.0 else
|
|
112
|
+
f"name similarity {ratio:.2f}"] if ratio else []
|
|
113
|
+
ev.append(f"token overlap {jac:.2f}")
|
|
114
|
+
score = W_NAME * ratio + W_JACCARD * jac
|
|
115
|
+
if cos is not None:
|
|
116
|
+
ev.append(f"embedding cosine {cos:.2f}")
|
|
117
|
+
score += W_COSINE * max(cos, 0.0)
|
|
118
|
+
if a.parent and a.parent == b.parent:
|
|
119
|
+
ev.append(f"same area {a.parent}")
|
|
120
|
+
score += W_PARENT
|
|
121
|
+
elif a.domain and a.domain == b.domain:
|
|
122
|
+
ev.append(f"same domain {a.domain}")
|
|
123
|
+
score += W_DOMAIN
|
|
124
|
+
if shared:
|
|
125
|
+
ev.append(f"{len(shared)} shared problem{'s' if len(shared) > 1 else ''}")
|
|
126
|
+
score += W_PROBLEMS * min(len(shared), 2) / 2
|
|
127
|
+
# keep the concept with more linked problems, then more aliases, then the shorter id
|
|
128
|
+
dst, src = sorted((a, b), key=lambda e: (-len(problems[e.id]), -len(e.aliases),
|
|
129
|
+
len(e.id), e.id))
|
|
130
|
+
out.append(Pair(src.id, dst.id, round(score, 3), ev, (src.title, dst.title)))
|
|
131
|
+
out.sort(key=lambda p: (-p.score, p.dst, p.src))
|
|
132
|
+
return out[:max(limit, 0)], len(out), len(cons)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def report(pairs: list[Pair], total: int, compared: int) -> str:
|
|
136
|
+
if not pairs:
|
|
137
|
+
return f"No likely duplicates among {compared} concepts. Nothing was merged."
|
|
138
|
+
lines = [f"{total} candidate pair{'s' if total != 1 else ''} among {compared} concepts"
|
|
139
|
+
f" (showing {len(pairs)}). Read-only: nothing was merged; check each before "
|
|
140
|
+
"running its command (SRC folds into DST)."]
|
|
141
|
+
for k, p in enumerate(pairs, 1):
|
|
142
|
+
lines += ["", f"{k}. {p.src} -> {p.dst} score {p.score:.2f}",
|
|
143
|
+
f" '{safe(p.titles[0])}' / '{safe(p.titles[1])}'",
|
|
144
|
+
f" evidence: {'; '.join(p.evidence)}", f" run: {p.command}"]
|
|
145
|
+
return "\n".join(lines)
|
keepfold/egress.py
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
"""Every way data can leave Keepfold, in one place (E1). tests/test_egress.py fails when code under
|
|
2
|
+
src/keepfold reaches the network from a module that has no entry here, and when an entry's module
|
|
3
|
+
no longer does; `keepfold doctor --privacy` and the app's Status print `summary()`.
|
|
4
|
+
|
|
5
|
+
`loopback` is True when nothing leaves this PC (127.0.0.1 only, or nothing sent at all)."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import NamedTuple
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Egress(NamedTuple):
|
|
13
|
+
module: str # path under src/keepfold
|
|
14
|
+
dest: str # host, or a plain name for one the person chooses
|
|
15
|
+
what: str # what is sent or fetched, in plain words
|
|
16
|
+
when: str # who starts it
|
|
17
|
+
loopback: bool = False
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
REGISTRY: tuple[Egress, ...] = (
|
|
21
|
+
Egress("update.py", "github.com",
|
|
22
|
+
"a request for the newest Keepfold version (nothing about you, not even your version) "
|
|
23
|
+
"and, when there is a newer one, the installer and its checksum",
|
|
24
|
+
"a minute after the app starts and every 6 hours while it runs, unless Status → "
|
|
25
|
+
"Updates → Check for updates automatically is off, and when you click Check for "
|
|
26
|
+
"updates or Update now"),
|
|
27
|
+
Egress("app/wizard.py", "ollama.com, git-scm.com and LM Studio's catalogue",
|
|
28
|
+
"the name of a local model to look up its size, and the downloads of Ollama, Git "
|
|
29
|
+
"or a local model (through winget, Homebrew, ollama pull or lms get)",
|
|
30
|
+
"only when you click Install, Download or Get in Setup or Local model"),
|
|
31
|
+
Egress("voice_memos.py", "pypi.org and huggingface.co",
|
|
32
|
+
"the faster-whisper package and the speech model for voice memos",
|
|
33
|
+
"only when you run `keepfold model download --voice` or click its Download button"),
|
|
34
|
+
Egress("semantic.py", "huggingface.co",
|
|
35
|
+
"the search model and the reranker (about 150 MB, once, into ~/.keepfold/models)",
|
|
36
|
+
"only when you run `keepfold model download` or click Download search model; "
|
|
37
|
+
"searches never download"),
|
|
38
|
+
Egress("cloudllm.py", "your cloud model's address",
|
|
39
|
+
"titles of browsed pages and their sites, for pages in categories you set to cloud, "
|
|
40
|
+
"with your API key",
|
|
41
|
+
"only when you turn on cloud processing and set a cloud model"),
|
|
42
|
+
Egress("cli.py", "github.com (through Claude Code)",
|
|
43
|
+
"Claude Code's download of the Keepfold plugin",
|
|
44
|
+
"only when `keepfold setup` asks to install the Claude Code plugin and you say yes"),
|
|
45
|
+
Egress("app/targets.py", "github.com (through Claude Code)",
|
|
46
|
+
"Claude Code's download of the Keepfold plugin",
|
|
47
|
+
"when you connect Claude Code in Connect AI apps"),
|
|
48
|
+
Egress("localllm.py", "localhost (Ollama or LM Studio)",
|
|
49
|
+
"your question and the notes it needs, to the local model on this PC",
|
|
50
|
+
"when you use Chat or a local-model feature", loopback=True),
|
|
51
|
+
Egress("app/server.py", "localhost",
|
|
52
|
+
"the app's own page, and a check whether an app is already running",
|
|
53
|
+
"while the app runs", loopback=True),
|
|
54
|
+
Egress("_proc.py", "nothing (reads this PC's proxy setting)",
|
|
55
|
+
"nothing: the system proxy is read and handed to the downloads above",
|
|
56
|
+
"with those downloads", loopback=True),
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def summary() -> list[str]:
|
|
61
|
+
"""One plain line per destination off this PC and what goes there; two modules that start
|
|
62
|
+
the same download share its line, their `when`s joined."""
|
|
63
|
+
whens: dict[tuple[str, str], list[str]] = {}
|
|
64
|
+
for e in REGISTRY:
|
|
65
|
+
if not e.loopback:
|
|
66
|
+
whens.setdefault((e.dest, e.what), []).append(e.when)
|
|
67
|
+
return [f"{dest}: {what}. {(w := ', or '.join(ws))[0].upper()}{w[1:]}."
|
|
68
|
+
for (dest, what), ws in whens.items()]
|
keepfold/eval_history.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""`keepfold eval all`: one eval report and its paired history (v6 CONSENSUS "one eval history").
|
|
2
|
+
|
|
3
|
+
`.keepfold/eval-history.jsonl` (tool-private, gitignored): one row per metric per run,
|
|
4
|
+
`{date, git_sha, index, metric, variant, value, n, baseline_value}`. Numbers only, never a
|
|
5
|
+
query or page text. The recall eval replays old queries on today's index, which grows, so
|
|
6
|
+
absolute numbers from different days are not comparable (panel X4). A run therefore pairs
|
|
7
|
+
only with rows of the same local `date` and `index` (a hash of the indexed files' size and
|
|
8
|
+
mtime, and whether vectors were used): `baseline_value` is `current` for each recall variant
|
|
9
|
+
(the constant base-rate Brier for learning), and the printer shows each metric's delta against
|
|
10
|
+
the latest earlier run on that day and index from another `git_sha`, the before/after pair.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import hashlib
|
|
16
|
+
import json
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
from keepfold import learning_eval, recall_log
|
|
20
|
+
from keepfold.session import _git
|
|
21
|
+
from keepfold.vault import Vault
|
|
22
|
+
|
|
23
|
+
FILE = ".keepfold/eval-history.jsonl"
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def fingerprint(index, embed: bool) -> str:
|
|
27
|
+
"""Same key = same indexed pages (path, mtime, size) and the same recall mode."""
|
|
28
|
+
stats = sorted((index._rel(p), st) for p, st in index._stats.items())
|
|
29
|
+
return hashlib.sha1(repr((stats, embed)).encode()).hexdigest()[:12]
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def git_sha() -> str:
|
|
33
|
+
"""The code's commit (`-dirty` with uncommitted changes), or "unknown" outside a repo."""
|
|
34
|
+
try:
|
|
35
|
+
out = _git(Path(__file__).parent, "describe", "--always", "--dirty", "--exclude=*")
|
|
36
|
+
except OSError:
|
|
37
|
+
return "unknown"
|
|
38
|
+
return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else "unknown"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def rows(recall: dict, n_queries: int, k: int, learning: dict, *, date: str, sha: str,
|
|
42
|
+
index: str) -> list[dict]:
|
|
43
|
+
"""History rows for one run: recall@k and MRR per variant against `current`, and the
|
|
44
|
+
learning Brier against its base rate. A signal with n = 0 has no rows."""
|
|
45
|
+
base = {"date": date, "git_sha": sha, "index": index}
|
|
46
|
+
out = []
|
|
47
|
+
cur = recall.get("current")
|
|
48
|
+
for variant, m in recall.items() if n_queries and cur else ():
|
|
49
|
+
if m is None: # rerank variant without the reranker
|
|
50
|
+
continue
|
|
51
|
+
for metric, value, b in ((f"recall@{k}", m[0], cur[0]), (f"mrr@{k}", m[1], cur[1])):
|
|
52
|
+
out.append({**base, "metric": metric, "variant": variant, "value": round(value, 4),
|
|
53
|
+
"n": n_queries, "baseline_value": round(b, 4)})
|
|
54
|
+
if learning.get("n"):
|
|
55
|
+
out.append({**base, "metric": "brier", "variant": "all", "value": learning["brier"],
|
|
56
|
+
"n": learning["n"], "baseline_value": learning["brier_base"]})
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def read(vault: Vault) -> list[dict]:
|
|
61
|
+
path = vault.root / FILE
|
|
62
|
+
out = []
|
|
63
|
+
for line in path.read_text("utf-8").splitlines() if path.is_file() else []:
|
|
64
|
+
try:
|
|
65
|
+
out.append(json.loads(line))
|
|
66
|
+
except ValueError:
|
|
67
|
+
continue
|
|
68
|
+
return out
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def append(vault: Vault, new: list[dict]) -> None:
|
|
72
|
+
path = vault.root / FILE
|
|
73
|
+
with vault.lock(): # the lock creates .keepfold/
|
|
74
|
+
old = path.read_text("utf-8").splitlines() if path.is_file() else []
|
|
75
|
+
lines = [json.dumps(r, separators=(",", ":")) for r in new]
|
|
76
|
+
vault.write_text(path,"\n".join([*old, *lines]) + "\n")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def before(history: list[dict], run: list[dict]) -> dict[tuple[str, str], dict]:
|
|
80
|
+
"""(metric, variant) -> the latest earlier row on the run's day and index, with the same
|
|
81
|
+
n, from another git_sha. Rows from other days or another index never pair."""
|
|
82
|
+
if not run:
|
|
83
|
+
return {}
|
|
84
|
+
key = (run[0]["date"], run[0]["index"])
|
|
85
|
+
n = {(r["metric"], r["variant"]): r["n"] for r in run}
|
|
86
|
+
return {(r["metric"], r["variant"]): r for r in history
|
|
87
|
+
if (r.get("date"), r.get("index")) == key and r.get("git_sha") != run[0]["git_sha"]
|
|
88
|
+
and n.get((r.get("metric"), r.get("variant"))) == r.get("n")}
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def text(run: list[dict], prior: dict[tuple[str, str], dict]) -> str:
|
|
92
|
+
if not run:
|
|
93
|
+
return "nothing to measure yet: no opened recall queries and no graded items"
|
|
94
|
+
r0 = run[0]
|
|
95
|
+
shas = sorted({r["git_sha"] for r in prior.values()})
|
|
96
|
+
out = [f"eval all {r0['date']} at {r0['git_sha']}, index {r0['index']}",
|
|
97
|
+
f"{'metric':<10} {'variant':<12} {'value':>7} {'n':>5} {'vs base':>8} "
|
|
98
|
+
f"{'vs ' + (shas[-1] if len(shas) == 1 else 'before'):>14}"]
|
|
99
|
+
for r in run:
|
|
100
|
+
floor = learning_eval.MIN_PAIRS if r["metric"] == "brier" else recall_log.MIN_TRUST
|
|
101
|
+
p = prior.get((r["metric"], r["variant"]))
|
|
102
|
+
paired = f"{r['value'] - p['value']:+.3f}" if p else "-"
|
|
103
|
+
out.append(f"{r['metric']:<10} {r['variant']:<12} {r['value']:>7.3f} {r['n']:>5} "
|
|
104
|
+
f"{r['value'] - r['baseline_value']:>+8.3f} {paired:>14}"
|
|
105
|
+
+ (" (too few)" if r["n"] < floor else ""))
|
|
106
|
+
if not prior:
|
|
107
|
+
out.append("no earlier run on this day and index from another commit: "
|
|
108
|
+
"run this before and after a change, same day, to get a paired delta")
|
|
109
|
+
return "\n".join(out)
|