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/semantic.py
ADDED
|
@@ -0,0 +1,1254 @@
|
|
|
1
|
+
"""Semantic recall (SPEC §0 U7): vector cosine + FTS BM25, then graph neighbours.
|
|
2
|
+
|
|
3
|
+
The embedder is injected as `embed(texts) -> (n, d) array`, so tests use a fake one and never
|
|
4
|
+
download the model. The real one is fastembed `BAAI/bge-small-en-v1.5` in ~/.keepfold/models,
|
|
5
|
+
fetched only by `keepfold model download`. A page is embedded as chunks (`_chunks`: its head,
|
|
6
|
+
then overlapping windows over the rest of the body) and scores by its best chunk. Vectors are a
|
|
7
|
+
disposable per-vault cache, the SQLite store `.keepfold/vectors.db` (`keepfold.vecstore`: a row per
|
|
8
|
+
page with its manifest (path, mtime_ns, size), chunk starts and float16 vectors; a save writes
|
|
9
|
+
the changed pages only); only pages whose file changed are re-embedded. A process reads the
|
|
10
|
+
store on its first query into one float32 matrix and then only the rows other processes saved
|
|
11
|
+
since. A damaged store is moved aside and started again (keepfold.quarantine). The older
|
|
12
|
+
`.keepfold/vectors-v3.npz` is read into it once and never written again; a prune that finds
|
|
13
|
+
rows of pages that went or changed in it deletes it (the store holds every row). A recall
|
|
14
|
+
embeds missing heads for at most HEAD_BUDGET seconds and
|
|
15
|
+
other missing chunks for at most RECALL_BUDGET; `keepfold model build` builds the rest.
|
|
16
|
+
Private pages and raw/ never enter the index, so they are never embedded. Background work (the
|
|
17
|
+
browse import) runs inside `background()`: a copy of the model capped at half the cores, at
|
|
18
|
+
below-normal priority; a query never waits on the cap. Each model (the embedder, the capped
|
|
19
|
+
copy, the reranker) is dropped after IDLE_UNLOAD seconds unused and loaded again on its next
|
|
20
|
+
use, and runs without onnxruntime's CPU arena (ARENA), so an idle process gives its memory back
|
|
21
|
+
(docs/benchmarks/memory.md). Only a person's use keeps a model: background work loads nothing
|
|
22
|
+
until it embeds, drops the capped copy when it ends and never restarts the main model's idle
|
|
23
|
+
clock (`_Held.use(touch=False)`, `loaded_embedder`). When the last model goes (an idle drop or
|
|
24
|
+
a background run's end), the process empties its working set (TRIM, `_trim_if_none`).
|
|
25
|
+
|
|
26
|
+
An optional cross-encoder (`RERANK_MODEL`, same cache dir, same download rule) reorders the top
|
|
27
|
+
`RERANK_POOL` hits; it never changes a hit's `score` or `match`. `rerank: false` in
|
|
28
|
+
~/.keepfold/config.yaml turns it off. `fuse="rrf"` is an eval-only alternative to the weighted sum.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
from __future__ import annotations
|
|
32
|
+
|
|
33
|
+
import bisect
|
|
34
|
+
import json
|
|
35
|
+
import logging
|
|
36
|
+
import math
|
|
37
|
+
import os
|
|
38
|
+
import re
|
|
39
|
+
import sqlite3
|
|
40
|
+
import sys
|
|
41
|
+
import threading
|
|
42
|
+
import time
|
|
43
|
+
from contextlib import closing, contextmanager
|
|
44
|
+
from datetime import UTC, date, datetime
|
|
45
|
+
from pathlib import Path
|
|
46
|
+
|
|
47
|
+
import numpy as np
|
|
48
|
+
|
|
49
|
+
from keepfold import quarantine, vecstore
|
|
50
|
+
from keepfold.events import local_day
|
|
51
|
+
from keepfold.index import BM25, STOPWORDS, Index, _one_line, aliases
|
|
52
|
+
from keepfold.topics import is_hub, page_date, page_source
|
|
53
|
+
from keepfold.vault import VaultError
|
|
54
|
+
|
|
55
|
+
log = logging.getLogger(__name__)
|
|
56
|
+
|
|
57
|
+
MODEL = "BAAI/bge-small-en-v1.5"
|
|
58
|
+
RERANK_MODEL = "Xenova/ms-marco-MiniLM-L-6-v2"
|
|
59
|
+
RERANK_POOL = 30
|
|
60
|
+
RRF_K = 60
|
|
61
|
+
NOT_SET_UP = "semantic search not set up; run `keepfold model download`"
|
|
62
|
+
CACHE = ".keepfold/vectors.db" # the vector store (keepfold.vecstore)
|
|
63
|
+
# the cache before the store: read into it once; `prune` deletes it
|
|
64
|
+
NPZ = ".keepfold/vectors-v3.npz"
|
|
65
|
+
BODY_CHARS = 1500
|
|
66
|
+
CHUNK_CHARS, CHUNK_OVERLAP = 1000, 200 # ~250-300 tokens: well under bge-small's 512
|
|
67
|
+
TEXT_VERSION = 5 # bump when _text or _chunks change, so cached vectors are rebuilt
|
|
68
|
+
CHUNKING = [BODY_CHARS, CHUNK_CHARS, CHUNK_OVERLAP] # in the cache meta: a change rebuilds
|
|
69
|
+
RECALL_BUDGET = 1.0 # seconds of extra-chunk embedding per recall; `keepfold model build` the rest
|
|
70
|
+
HEAD_BUDGET = 1.0 # seconds of missing chunk-0 embedding per recall (a lost cache, an import)
|
|
71
|
+
TAIL_BATCH = 8 # chunks per embed call under a budget, so it overshoots by about one second
|
|
72
|
+
W_COS, W_KW = 0.7, 0.3
|
|
73
|
+
# With the query prefix, bge-small scores unrelated pages ~0.45-0.56 (median ~0.5) and real
|
|
74
|
+
# matches >= 0.7 (measured on a real vault): below this a page is not similar at all.
|
|
75
|
+
# One constant on purpose: tune it on real queries (RETR-1), never per call.
|
|
76
|
+
# A page's best of ~6 chunks sits higher than one head vector, so the floor went from 0.6 to
|
|
77
|
+
# 0.62: the quantile where the same share of (page, query) pairs passes as heads did at 0.6
|
|
78
|
+
# (3.6%, measured over 30 queries on a 5,214-page vault; labels unused).
|
|
79
|
+
MIN_COS = 0.62
|
|
80
|
+
MIN_KW_COVER = 0.5 # under MIN_COS, a keyword hit must match this share of the query's terms
|
|
81
|
+
QUERY_PREFIX = "Represent this sentence for searching relevant passages: " # bge, queries only
|
|
82
|
+
DECAY = 0.5 # score factor per graph hop
|
|
83
|
+
MAX_LIMIT = 20
|
|
84
|
+
CHAT_WEIGHT = 0.6 # imported chat transcripts are long and noisy: the user's own pages win ties
|
|
85
|
+
# a page whose status says it no longer holds, so an old decision never outranks its successor
|
|
86
|
+
STALE_WEIGHT = 0.5
|
|
87
|
+
STALE = {("decision", "superseded"), ("decision", "retired"), ("project", "archived"),
|
|
88
|
+
("loop", "dropped")}
|
|
89
|
+
RECENT_BOOST, RECENT_DAYS = 0.12, 180 # a dated journal or chat page: up to +12%, fading
|
|
90
|
+
# a query asking how things are now: any dated page, up to +30%, fading faster
|
|
91
|
+
CURRENT_BOOST, CURRENT_DAYS = 0.3, 90
|
|
92
|
+
_CURRENT = re.compile(r"\b(?:current|currently|now|still|latest|nowadays|anymore|these days"
|
|
93
|
+
r"|at the moment)\b", re.I)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def is_current(query: str) -> bool:
|
|
97
|
+
"""Whether `query` asks how things stand now (`_factors`' stronger recency)."""
|
|
98
|
+
return bool(_CURRENT.search(query or ""))
|
|
99
|
+
BATCH = 64
|
|
100
|
+
PROGRESS_S = 5.0 # a long embedding pass says how far it got
|
|
101
|
+
# vault root -> (the store's stamp as last seen, cache, stacked rows or None)
|
|
102
|
+
_MEM: dict[Path, tuple] = {}
|
|
103
|
+
_embedder = None
|
|
104
|
+
_EMBED_LOCK = threading.Lock()
|
|
105
|
+
_reranker = None
|
|
106
|
+
_RERANK_LOCK = threading.Lock() # not _EMBED_LOCK: a query embedding never waits for this load
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def models_dir() -> Path:
|
|
110
|
+
"""Beside ~/.keepfold/config.yaml (the vault pointer, cli._pointer)."""
|
|
111
|
+
return Path.home() / ".keepfold" / "models"
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def load_embedder(download: bool = False):
|
|
115
|
+
"""The model as `embed(texts) -> array`, or None when it is not downloaded. Only
|
|
116
|
+
`download=True` (the `keepfold model download` command) may fetch it. The function stays;
|
|
117
|
+
the model behind it is dropped when idle and loaded again by its next call (`_Held`).
|
|
118
|
+
Inside `background()` it loads nothing: the function, when the download is whole
|
|
119
|
+
(doctor.search_model_ready), and its first embed loads the capped copy; files that do
|
|
120
|
+
not load raise `NotLoaded` there. `_embedder` (what prime and review take as "this
|
|
121
|
+
process has it") is set only by a load outside `background()`."""
|
|
122
|
+
global _embedder
|
|
123
|
+
with _EMBED_LOCK: # the server's warm-up thread and a first tool call may race
|
|
124
|
+
if _embedder is not None:
|
|
125
|
+
return _embedder
|
|
126
|
+
if not download and not models_dir().is_dir():
|
|
127
|
+
return None
|
|
128
|
+
if not download and getattr(_bg, "on", False):
|
|
129
|
+
from keepfold import doctor # here: its imports cost 0.8 s (the app has it already)
|
|
130
|
+
|
|
131
|
+
return _embed_real if doctor.search_model_ready() else None
|
|
132
|
+
try:
|
|
133
|
+
model = _text_embedding(download)
|
|
134
|
+
except Exception:
|
|
135
|
+
if download:
|
|
136
|
+
raise
|
|
137
|
+
return None
|
|
138
|
+
_main.put(model)
|
|
139
|
+
_embedder = _embed_real
|
|
140
|
+
return _embedder
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def _text_embedding(download: bool = False, threads: int | None = None):
|
|
144
|
+
from fastembed import TextEmbedding # slow import: keep it off CLI and server start
|
|
145
|
+
|
|
146
|
+
return TextEmbedding(MODEL, cache_dir=str(models_dir()), local_files_only=not download,
|
|
147
|
+
threads=threads, enable_cpu_mem_arena=ARENA)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
class NotLoaded(VaultError):
|
|
151
|
+
"""Background work's first embed found the model's files whole but not loading (corrupt):
|
|
152
|
+
the caller goes on without the model, as when load_embedder returns None."""
|
|
153
|
+
|
|
154
|
+
def __init__(self):
|
|
155
|
+
super().__init__("not_set_up", NOT_SET_UP)
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def _embed_real(texts) -> np.ndarray:
|
|
159
|
+
"""The real model's embed: in `background()` the capped copy, when it loads."""
|
|
160
|
+
bg = getattr(_bg, "on", False)
|
|
161
|
+
if bg:
|
|
162
|
+
with _capped.use() as m:
|
|
163
|
+
if m:
|
|
164
|
+
return np.asarray(list(m.embed(list(texts))), dtype=np.float32)
|
|
165
|
+
try:
|
|
166
|
+
with _main.use(touch=not bg) as m:
|
|
167
|
+
return np.asarray(list(m.embed(list(texts))), dtype=np.float32)
|
|
168
|
+
except Exception as e:
|
|
169
|
+
if bg and _main.model is None: # its load failed, not an embed
|
|
170
|
+
raise NotLoaded() from e
|
|
171
|
+
raise
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def _embed_quiet(texts) -> np.ndarray:
|
|
175
|
+
"""The main model for background work that found it in memory (`loaded_embedder`): its use
|
|
176
|
+
does not restart the idle clock, so only a person's own use keeps the model loaded."""
|
|
177
|
+
with _main.use(touch=False) as m:
|
|
178
|
+
return np.asarray(list(m.embed(list(texts))), dtype=np.float32)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def loaded_embedder():
|
|
182
|
+
"""For work that embeds only with a model already in memory (the safety net, review's
|
|
183
|
+
scorer): `_embed_quiet` while the main model is loaded, else None; never a load. An
|
|
184
|
+
`_embedder` other than the real model's (a test's) is returned as it is.
|
|
185
|
+
shortcut: a drop between this check and the embed loads it again for that call (dropped at
|
|
186
|
+
the next idle check, as its clock was not restarted)."""
|
|
187
|
+
if _embedder is not None and _embedder is not _embed_real:
|
|
188
|
+
return _embedder
|
|
189
|
+
return _embed_quiet if _main.model else None
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
# ---- idle unload: a model unused for IDLE_UNLOAD seconds is dropped ---------------------------
|
|
193
|
+
|
|
194
|
+
IDLE_UNLOAD = 600.0 # seconds unused before a model is dropped; its next use loads it again
|
|
195
|
+
IDLE_CHECK = 60.0 # seconds between the idle thread's checks
|
|
196
|
+
# onnxruntime's CPU arena keeps the largest batch's buffers for the session's life (after an
|
|
197
|
+
# index build, 1.6 GB); without it a run frees them. A query is no slower; bulk embedding is
|
|
198
|
+
# 7-40% slower (docs/benchmarks/memory.md)
|
|
199
|
+
ARENA = False
|
|
200
|
+
# Windows: once the last model is dropped, the idle process empties its working set (`_trim`)
|
|
201
|
+
TRIM = True
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
class _Held:
|
|
205
|
+
"""A model made by `load()` on first use and dropped by `drop_idle` once unused for
|
|
206
|
+
IDLE_UNLOAD seconds; never while a call holds it (`use`). A load that returned a falsy
|
|
207
|
+
model (the capped copy that failed) stays as it is: never dropped, never tried again.
|
|
208
|
+
A use with `touch=False` (background work) leaves the idle clock where a person's last use
|
|
209
|
+
set it: background work never keeps a model, and one no person used goes at the next
|
|
210
|
+
check."""
|
|
211
|
+
|
|
212
|
+
def __init__(self, load):
|
|
213
|
+
self.load, self.lock = load, threading.Lock()
|
|
214
|
+
self.model, self.used, self.busy = None, 0.0, 0
|
|
215
|
+
|
|
216
|
+
def put(self, model) -> None:
|
|
217
|
+
with self.lock:
|
|
218
|
+
self.model, self.used = model, time.monotonic()
|
|
219
|
+
_watch()
|
|
220
|
+
|
|
221
|
+
@contextmanager
|
|
222
|
+
def use(self, touch: bool = True):
|
|
223
|
+
with self.lock: # one load, not two: a racing call waits for it
|
|
224
|
+
if self.model is None:
|
|
225
|
+
self.model = self.load()
|
|
226
|
+
_watch()
|
|
227
|
+
self.busy += 1
|
|
228
|
+
m = self.model
|
|
229
|
+
try:
|
|
230
|
+
yield m
|
|
231
|
+
finally:
|
|
232
|
+
with self.lock:
|
|
233
|
+
self.busy -= 1
|
|
234
|
+
if touch:
|
|
235
|
+
self.used = time.monotonic()
|
|
236
|
+
|
|
237
|
+
def drop(self, now: float) -> bool:
|
|
238
|
+
with self.lock:
|
|
239
|
+
if not self.model or self.busy or now - self.used < IDLE_UNLOAD:
|
|
240
|
+
return False
|
|
241
|
+
self.model = None
|
|
242
|
+
return True
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def drop_idle(now: float | None = None) -> list[str]:
|
|
246
|
+
"""Drop every model unused for IDLE_UNLOAD seconds (`_watch`'s thread calls it every
|
|
247
|
+
IDLE_CHECK); the names of those dropped."""
|
|
248
|
+
now = time.monotonic() if now is None else now
|
|
249
|
+
return [name for name, h in (("embedder", _main), ("background copy", _capped),
|
|
250
|
+
("reranker", _ranker)) if h.drop(now)]
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def idle_pass(now: float | None = None) -> list[str]:
|
|
254
|
+
"""One check of the idle thread: `drop_idle`, then, when that dropped the last model held,
|
|
255
|
+
`_trim`. The names of the models dropped."""
|
|
256
|
+
dropped = drop_idle(now)
|
|
257
|
+
if dropped:
|
|
258
|
+
_trim_if_none()
|
|
259
|
+
return dropped
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _trim_if_none() -> None:
|
|
263
|
+
"""`_trim` once no model is held (TRIM): after an idle drop or a background run's end."""
|
|
264
|
+
if TRIM and not any(h.model for h in (_main, _capped, _ranker)):
|
|
265
|
+
_trim()
|
|
266
|
+
|
|
267
|
+
|
|
268
|
+
def _trim() -> None:
|
|
269
|
+
"""Empty this process's working set (Windows; nothing elsewhere). Its pages go to the
|
|
270
|
+
standby list, where other programs may have them; the next call faults back only what it
|
|
271
|
+
touches. Private bytes do not change: what the process still holds is in them
|
|
272
|
+
(docs/benchmarks/memory.md, M3)."""
|
|
273
|
+
if sys.platform != "win32":
|
|
274
|
+
return
|
|
275
|
+
import ctypes
|
|
276
|
+
|
|
277
|
+
k = ctypes.WinDLL("kernel32") # its own instance: the argtypes below stay local
|
|
278
|
+
k.GetCurrentProcess.restype = ctypes.c_void_p
|
|
279
|
+
k.K32EmptyWorkingSet.argtypes = [ctypes.c_void_p]
|
|
280
|
+
k.K32EmptyWorkingSet(k.GetCurrentProcess())
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
_WATCH_LOCK = threading.Lock()
|
|
284
|
+
_watching = False
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def _watch() -> None:
|
|
288
|
+
"""Start the idle thread (once per process, on the first model load)."""
|
|
289
|
+
global _watching
|
|
290
|
+
with _WATCH_LOCK:
|
|
291
|
+
if _watching:
|
|
292
|
+
return
|
|
293
|
+
_watching = True
|
|
294
|
+
|
|
295
|
+
def loop():
|
|
296
|
+
while True:
|
|
297
|
+
time.sleep(IDLE_CHECK)
|
|
298
|
+
idle_pass()
|
|
299
|
+
|
|
300
|
+
threading.Thread(target=loop, name="keepfold-model-idle", daemon=True).start()
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
# ---- background embedding: half the cores, below-normal priority -----------------------------
|
|
304
|
+
|
|
305
|
+
BG_THREADS = max(1, (os.cpu_count() or 2) // 2) # a background build leaves the rest to the owner
|
|
306
|
+
_bg = threading.local()
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
@contextmanager
|
|
310
|
+
def background():
|
|
311
|
+
"""Embedding in this thread is background work while inside: the real model's calls go to
|
|
312
|
+
a second copy capped at BG_THREADS threads, all at below-normal priority (Windows), so the
|
|
313
|
+
PC stays quick. A query in another thread keeps the full model. Nests. The outermost exit
|
|
314
|
+
drops the copy (unless another thread's background work holds it): it served only this.
|
|
315
|
+
When that leaves no model, the working set is emptied too (`_trim_if_none`)."""
|
|
316
|
+
if getattr(_bg, "on", False):
|
|
317
|
+
yield
|
|
318
|
+
return
|
|
319
|
+
_bg.on = True
|
|
320
|
+
old = _priority(_BELOW_NORMAL)
|
|
321
|
+
try:
|
|
322
|
+
yield
|
|
323
|
+
finally:
|
|
324
|
+
_bg.on = False
|
|
325
|
+
if _capped.drop(math.inf):
|
|
326
|
+
_trim_if_none()
|
|
327
|
+
if old is not None:
|
|
328
|
+
_priority(old)
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _capped_load():
|
|
332
|
+
"""The capped copy of the model (made on first background use, again after an idle
|
|
333
|
+
drop), or False when it cannot be loaded: the full model does background work then."""
|
|
334
|
+
before = _threads()
|
|
335
|
+
try:
|
|
336
|
+
m = _text_embedding(threads=BG_THREADS)
|
|
337
|
+
list(m.embed(["keepfold"])) # onnxruntime has made its threads by now
|
|
338
|
+
except Exception as e:
|
|
339
|
+
log.warning("background embedding uses the full model: %s", type(e).__name__)
|
|
340
|
+
return False
|
|
341
|
+
# shortcut: a thread another part of the process made in this second is lowered
|
|
342
|
+
# too; harmless, as background work is all this process does then
|
|
343
|
+
_lower(_threads() - before)
|
|
344
|
+
return m
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
# the lambdas look the loaders up at load time, so tests can replace them
|
|
348
|
+
_main = _Held(lambda: _text_embedding())
|
|
349
|
+
_capped = _Held(lambda: _capped_load())
|
|
350
|
+
|
|
351
|
+
|
|
352
|
+
_BELOW_NORMAL = -1 # THREAD_PRIORITY_BELOW_NORMAL
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def _kernel32():
|
|
356
|
+
import ctypes
|
|
357
|
+
from ctypes import wintypes
|
|
358
|
+
|
|
359
|
+
k = ctypes.WinDLL("kernel32") # its own instance: the argtypes below stay local
|
|
360
|
+
H = wintypes.HANDLE
|
|
361
|
+
k.GetCurrentThread.restype = k.OpenThread.restype = H
|
|
362
|
+
k.CreateToolhelp32Snapshot.restype = H
|
|
363
|
+
k.SetThreadPriority.argtypes = [H, ctypes.c_int]
|
|
364
|
+
k.GetThreadPriority.argtypes = k.CloseHandle.argtypes = [H]
|
|
365
|
+
k.OpenThread.argtypes = [wintypes.DWORD, wintypes.BOOL, wintypes.DWORD]
|
|
366
|
+
k.Thread32First.argtypes = k.Thread32Next.argtypes = [H, ctypes.c_void_p]
|
|
367
|
+
return k
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _priority(p: int) -> int | None:
|
|
371
|
+
"""Set this thread's priority (Windows); the one it had, None elsewhere."""
|
|
372
|
+
if sys.platform != "win32":
|
|
373
|
+
return None
|
|
374
|
+
k = _kernel32()
|
|
375
|
+
h = k.GetCurrentThread()
|
|
376
|
+
old = k.GetThreadPriority(h)
|
|
377
|
+
k.SetThreadPriority(h, p)
|
|
378
|
+
return old
|
|
379
|
+
|
|
380
|
+
|
|
381
|
+
def _threads() -> set[int]:
|
|
382
|
+
"""The ids of this process's threads (Windows; empty elsewhere)."""
|
|
383
|
+
if sys.platform != "win32":
|
|
384
|
+
return set()
|
|
385
|
+
import ctypes
|
|
386
|
+
from ctypes import wintypes
|
|
387
|
+
|
|
388
|
+
class Entry(ctypes.Structure): # THREADENTRY32
|
|
389
|
+
_fields_ = [("size", wintypes.DWORD), ("usage", wintypes.DWORD),
|
|
390
|
+
("tid", wintypes.DWORD), ("pid", wintypes.DWORD),
|
|
391
|
+
("base", wintypes.LONG), ("delta", wintypes.LONG),
|
|
392
|
+
("flags", wintypes.DWORD)]
|
|
393
|
+
|
|
394
|
+
k = _kernel32()
|
|
395
|
+
snap = k.CreateToolhelp32Snapshot(4, 0) # TH32CS_SNAPTHREAD
|
|
396
|
+
if not snap or snap == ctypes.c_void_p(-1).value:
|
|
397
|
+
return set()
|
|
398
|
+
out, e, pid = set(), Entry(), k.GetCurrentProcessId()
|
|
399
|
+
e.size = ctypes.sizeof(Entry)
|
|
400
|
+
try:
|
|
401
|
+
ok = k.Thread32First(snap, ctypes.byref(e))
|
|
402
|
+
while ok:
|
|
403
|
+
if e.pid == pid:
|
|
404
|
+
out.add(e.tid)
|
|
405
|
+
ok = k.Thread32Next(snap, ctypes.byref(e))
|
|
406
|
+
finally:
|
|
407
|
+
k.CloseHandle(snap)
|
|
408
|
+
return out
|
|
409
|
+
|
|
410
|
+
|
|
411
|
+
def _lower(tids) -> None:
|
|
412
|
+
"""Below-normal priority for these threads of this process (Windows)."""
|
|
413
|
+
if not tids:
|
|
414
|
+
return
|
|
415
|
+
k = _kernel32()
|
|
416
|
+
for t in tids:
|
|
417
|
+
if h := k.OpenThread(0x0020, False, t): # THREAD_SET_INFORMATION
|
|
418
|
+
k.SetThreadPriority(h, _BELOW_NORMAL)
|
|
419
|
+
k.CloseHandle(h)
|
|
420
|
+
|
|
421
|
+
|
|
422
|
+
def rerank_on() -> bool:
|
|
423
|
+
"""The `rerank` switch in ~/.keepfold/config.yaml (default on)."""
|
|
424
|
+
from keepfold.taint import config
|
|
425
|
+
|
|
426
|
+
return config().get("rerank") is not False
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def load_reranker(download: bool = False, config: bool = True):
|
|
430
|
+
"""The cross-encoder as `score(query, texts) -> list[float]`, or None when it is not
|
|
431
|
+
downloaded, fails to load, or is switched off (`config=False` ignores the switch). Only
|
|
432
|
+
`download=True` may fetch it."""
|
|
433
|
+
global _reranker
|
|
434
|
+
if config and not download and not rerank_on():
|
|
435
|
+
return None
|
|
436
|
+
if _reranker is not None:
|
|
437
|
+
return _reranker
|
|
438
|
+
with _RERANK_LOCK: # warm-up and a first Chat turn may race: one load, not two
|
|
439
|
+
if _reranker is not None:
|
|
440
|
+
return _reranker
|
|
441
|
+
# fastembed's HF cache folder; checked first so an absent model logs no fastembed ERROR
|
|
442
|
+
if not download and not (models_dir()
|
|
443
|
+
/ f"models--{RERANK_MODEL.replace('/', '--')}").is_dir():
|
|
444
|
+
return None
|
|
445
|
+
try:
|
|
446
|
+
model = _cross_encoder(download)
|
|
447
|
+
except Exception:
|
|
448
|
+
if download:
|
|
449
|
+
raise
|
|
450
|
+
return None
|
|
451
|
+
_ranker.put(model)
|
|
452
|
+
_reranker = _score_real
|
|
453
|
+
return _reranker
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def _cross_encoder(download: bool = False):
|
|
457
|
+
from fastembed.rerank.cross_encoder import TextCrossEncoder
|
|
458
|
+
|
|
459
|
+
return TextCrossEncoder(RERANK_MODEL, cache_dir=str(models_dir()),
|
|
460
|
+
local_files_only=not download, enable_cpu_mem_arena=ARENA)
|
|
461
|
+
|
|
462
|
+
|
|
463
|
+
def _score_real(query, texts) -> list[float]:
|
|
464
|
+
with _ranker.use() as m:
|
|
465
|
+
return [float(x) for x in m.rerank(query, list(texts))]
|
|
466
|
+
|
|
467
|
+
|
|
468
|
+
_ranker = _Held(lambda: _cross_encoder())
|
|
469
|
+
|
|
470
|
+
|
|
471
|
+
def is_chat(n: dict) -> bool:
|
|
472
|
+
"""An imported chat page: a resource whose `Timeline:` line names its `Source:` app."""
|
|
473
|
+
return n["kind"] == "resource" and bool(page_source(n["body"]))
|
|
474
|
+
|
|
475
|
+
|
|
476
|
+
def _today() -> str:
|
|
477
|
+
"""The local day recency counts from (tests patch it)."""
|
|
478
|
+
return local_day(datetime.now(UTC))
|
|
479
|
+
|
|
480
|
+
|
|
481
|
+
def older_versions(index: Index) -> frozenset[str]:
|
|
482
|
+
"""RR-18: imported pages a newer import of the same file replaced: the same `Source:`
|
|
483
|
+
label, `From:` origin and title on the header line (sources.HEADER) and an older Date
|
|
484
|
+
(`x-2` is newer than `x` on the same day). A read-time fold; nothing is stored."""
|
|
485
|
+
from keepfold.sources import HEADER # lazy: sources pulls in the import machinery
|
|
486
|
+
groups: dict[tuple, list] = {}
|
|
487
|
+
for id, n in index._notes.items():
|
|
488
|
+
if n["kind"] == "resource" and (m := HEADER.search(n["body"][:2000])) and m.group(3):
|
|
489
|
+
groups.setdefault((m.group(1), m.group(3), n["title"]), []).append(
|
|
490
|
+
(m.group(2), len(id), id))
|
|
491
|
+
return frozenset(i for g in groups.values() for *_, i in sorted(g)[:-1])
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _factors(index: Index, id: str, chats: bool, quiet: dict[str, float] | None,
|
|
495
|
+
current: bool = False, older: frozenset[str] = frozenset()) -> dict:
|
|
496
|
+
"""A page's score factors other than 1 after the floors: `quiet`, its harvest.quiet weight
|
|
497
|
+
(0 hides a folded copy even with `chats`), else `chat`, CHAT_WEIGHT for a chat page (`chats`
|
|
498
|
+
lifts both but 0); `status`, STALE_WEIGHT for a STALE status; `older_version`, STALE_WEIGHT
|
|
499
|
+
for a page in `older` (`older_versions`); `recency`, up to
|
|
500
|
+
1 + RECENT_BOOST for a journal or chat page dated in the last months, or with `current`
|
|
501
|
+
(`is_current` query) up to 1 + CURRENT_BOOST for any dated page."""
|
|
502
|
+
q = (quiet or {}).get(id)
|
|
503
|
+
if q == 0:
|
|
504
|
+
return {"quiet": 0.0}
|
|
505
|
+
n = index._notes[id]
|
|
506
|
+
chat = is_chat(n)
|
|
507
|
+
f = {}
|
|
508
|
+
if q is not None:
|
|
509
|
+
if not chats:
|
|
510
|
+
f["quiet"] = q
|
|
511
|
+
elif chat and not chats:
|
|
512
|
+
f["chat"] = CHAT_WEIGHT
|
|
513
|
+
if (n["kind"], str(n["fields"].get("status"))) in STALE: # str: a YAML list is unhashable
|
|
514
|
+
f["status"] = STALE_WEIGHT
|
|
515
|
+
if id in older:
|
|
516
|
+
f["older_version"] = STALE_WEIGHT
|
|
517
|
+
if (current or chat or n["kind"] == "journal") \
|
|
518
|
+
and (d := page_date(id, n["fields"], n["body"])):
|
|
519
|
+
boost, days = (CURRENT_BOOST, CURRENT_DAYS) if current else (RECENT_BOOST, RECENT_DAYS)
|
|
520
|
+
try:
|
|
521
|
+
age = max(0, (date.fromisoformat(_today()) - date.fromisoformat(d)).days)
|
|
522
|
+
f["recency"] = 1 + boost * math.exp(-age / days)
|
|
523
|
+
except ValueError: # a malformed day (2026-13-45) gets no boost
|
|
524
|
+
pass
|
|
525
|
+
return f
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def _weight(index: Index, id: str, chats: bool, quiet: dict[str, float] | None,
|
|
529
|
+
current: bool = False, older: frozenset[str] = frozenset()) -> float:
|
|
530
|
+
"""The product of the page's `_factors`; 0 drops it."""
|
|
531
|
+
return math.prod(_factors(index, id, chats, quiet, current, older).values(), start=1.0)
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def rerank(index: Index, query: str, hits: list[dict], score, chats: bool = False,
|
|
535
|
+
quiet: dict[str, float] | None = None, out: dict | None = None) -> list[dict]:
|
|
536
|
+
"""`hits` reordered by the cross-encoder over each hit's best chunk (`at`; chunk 0 without
|
|
537
|
+
one), its sigmoid times the page's `_weight`, blended with the first-stage rank r (R3d,
|
|
538
|
+
QMD's rule: _blend(r) / r + (1 - _blend(r)) x that, so the top few stay unless the
|
|
539
|
+
cross-encoder is clearly surer); on any failure, as they were. Each hit's `score` and
|
|
540
|
+
`match` are untouched (the Honest Double check reads them)."""
|
|
541
|
+
if len(hits) < 2:
|
|
542
|
+
return hits
|
|
543
|
+
try:
|
|
544
|
+
s = score(query, [_chunk_text(index._notes[h["id"]], h.get("at", 0)) for h in hits])
|
|
545
|
+
except Exception as e: # a broken model must never break recall
|
|
546
|
+
log.warning("rerank skipped: %s", e)
|
|
547
|
+
return hits
|
|
548
|
+
# logits can be negative, so weight their sigmoid (same order) rather than the logit
|
|
549
|
+
now, older = is_current(query), older_versions(index)
|
|
550
|
+
s = [1 / (1 + np.exp(-x)) * _weight(index, h["id"], chats, quiet, now, older)
|
|
551
|
+
for x, h in zip(s, hits, strict=True)]
|
|
552
|
+
if out is not None: # `--explain` shows the weighted rerank score per page
|
|
553
|
+
out.update({h["id"]: float(x) for x, h in zip(s, hits, strict=True)})
|
|
554
|
+
b = [_blend(r) / r + (1 - _blend(r)) * x for r, x in enumerate(s, 1)]
|
|
555
|
+
return [h for _, h in sorted(zip(b, hits, strict=True), key=lambda p: -p[0])]
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def _blend(r: int) -> float:
|
|
559
|
+
"""The first stage's weight at rank r in the rerank blend (QMD's numbers)."""
|
|
560
|
+
return 0.75 if r <= 3 else 0.60 if r <= 10 else 0.40
|
|
561
|
+
|
|
562
|
+
|
|
563
|
+
def _unit(v: np.ndarray) -> np.ndarray:
|
|
564
|
+
return v / (np.linalg.norm(v) or 1.0)
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def _filled(body: str) -> str:
|
|
568
|
+
"""The body without headings of empty sections: template headings ("## How I write to
|
|
569
|
+
them" on a fresh people page) otherwise match queries they say nothing about."""
|
|
570
|
+
lines, out = body.splitlines(), []
|
|
571
|
+
for i, line in enumerate(lines):
|
|
572
|
+
if h := _HEAD.match(line):
|
|
573
|
+
nxt = next((x for x in lines[i + 1:] if x.strip()), "")
|
|
574
|
+
sub = _HEAD.match(nxt)
|
|
575
|
+
if not nxt or (sub and len(sub[1]) <= len(h[1])): # nothing under it
|
|
576
|
+
continue
|
|
577
|
+
out.append(line)
|
|
578
|
+
return "\n".join(out)
|
|
579
|
+
|
|
580
|
+
|
|
581
|
+
_HEAD = re.compile(r"^(#{1,6})\s")
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _text(n: dict) -> str:
|
|
585
|
+
summary = n["fields"].get("summary") or ""
|
|
586
|
+
return f"{n['title']}\n{summary}\n{_filled(n['body'].strip())[:BODY_CHARS]}"
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
HEADER_CHARS = 150
|
|
590
|
+
|
|
591
|
+
|
|
592
|
+
def _header(title: str, path: list[str], day: str, kind: str) -> str:
|
|
593
|
+
"""A deep chunk's first line, `title › heading path · day · kind`, at most HEADER_CHARS
|
|
594
|
+
(the title and path are cut first), so a chunk read alone says where it is from."""
|
|
595
|
+
tail = " · ".join(x for x in (day, kind) if x)
|
|
596
|
+
head = " › ".join([" ".join(title.split()), *path])
|
|
597
|
+
return f"{head[:HEADER_CHARS - len(tail) - 3]} · {tail}" if tail else head[:HEADER_CHARS]
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _heads(body: str, code: bool = False):
|
|
601
|
+
"""The heading lines of `body` outside fenced code blocks; with `code`, the heading-like
|
|
602
|
+
lines inside them instead (a "# install deps" comment: no heading, C13)."""
|
|
603
|
+
fences = [m.start() for m in _FENCE.finditer(body)] # inside one: an odd count before
|
|
604
|
+
return (h for h in _HEAD_LINE.finditer(body)
|
|
605
|
+
if bisect.bisect(fences, h.start()) % 2 == code)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def _chunks(n: dict) -> list[tuple[int, str]]:
|
|
609
|
+
"""(start in the filled body, text) per chunk. Chunk 0 is `_text` (start 0). The rest are
|
|
610
|
+
windows of about CHUNK_CHARS over the body from BODY_CHARS - CHUNK_OVERLAP on, each under
|
|
611
|
+
a `_header` line (the last 2 levels of headings above the window start), overlapping the
|
|
612
|
+
one before by CHUNK_OVERLAP and cut at the best boundary in the window's final
|
|
613
|
+
CHUNK_OVERLAP characters (`_cut`: turn, paragraph, line, sentence, then space)."""
|
|
614
|
+
body = _filled(n["body"].strip())
|
|
615
|
+
out = [(0, _text(n))]
|
|
616
|
+
if len(body) <= BODY_CHARS:
|
|
617
|
+
return out
|
|
618
|
+
day = page_date("", n["fields"], n["body"])
|
|
619
|
+
heads = _heads(body)
|
|
620
|
+
h, stack = next(heads, None), [] # [(level, "## heading")] open above the window start
|
|
621
|
+
|
|
622
|
+
def header(s: int) -> str:
|
|
623
|
+
nonlocal h
|
|
624
|
+
while h is not None and h.start() < s: # one pass: windows only move forward
|
|
625
|
+
stack[:] = [x for x in stack if x[0] < len(h[1])] + [(len(h[1]), h[0].strip())]
|
|
626
|
+
h = next(heads, None)
|
|
627
|
+
path = [t for _, t in stack if t.lstrip("#").strip() != n["title"]] # not "# Title"
|
|
628
|
+
return _header(n["title"], path[-2:], day, n["kind"])
|
|
629
|
+
|
|
630
|
+
s = BODY_CHARS - CHUNK_OVERLAP
|
|
631
|
+
while True:
|
|
632
|
+
end = s + CHUNK_CHARS
|
|
633
|
+
if end >= len(body) - CHUNK_OVERLAP: # the rest, rather than a short last window
|
|
634
|
+
out.append((s, f"{header(s)}\n{body[s:]}"))
|
|
635
|
+
break
|
|
636
|
+
cut = _cut(body[end - CHUNK_OVERLAP:end])
|
|
637
|
+
if cut > 0:
|
|
638
|
+
end += cut - CHUNK_OVERLAP
|
|
639
|
+
out.append((s, f"{header(s)}\n{body[s:end]}"))
|
|
640
|
+
s = end - CHUNK_OVERLAP
|
|
641
|
+
return out
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def _cut(seg: str) -> int:
|
|
645
|
+
"""Where in `seg` (a window's last CHUNK_OVERLAP characters) the window ends, by a ladder:
|
|
646
|
+
before the last turn, else at a paragraph break, a line end, after a sentence's end, a
|
|
647
|
+
space, so a word is never split; -1 (a hard cut) only when `seg` has none of them."""
|
|
648
|
+
turns = [m.start() for m in _TURN.finditer(seg)]
|
|
649
|
+
if turns:
|
|
650
|
+
return turns[-1]
|
|
651
|
+
for at in (seg.rfind("\n\n"), seg.rfind("\n"),
|
|
652
|
+
max((m.end() for m in _SENTENCE.finditer(seg)), default=-1), seg.rfind(" ")):
|
|
653
|
+
if at > 0:
|
|
654
|
+
return at
|
|
655
|
+
return -1
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
_SENTENCE = re.compile(r"[.!?][\"')\]]*(?=\s)")
|
|
659
|
+
_HEAD_LINE = re.compile(r"^(#{1,6})[ \t][^\n]*", re.M)
|
|
660
|
+
_FENCE = re.compile(r"^[ \t]*(?:```|~~~)", re.M)
|
|
661
|
+
# a turn starts at its `### <time>` line when it has one, else at `**Me:**`
|
|
662
|
+
_TURN = re.compile(r"\n(?:### [^\n]*\n)?\*\*Me:\*\*|\n### ")
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
PASSAGE = 300 # RR-12: characters of a recall hit's best passage
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def passage(n: dict, at: int, query: str) -> tuple[int, str]:
|
|
669
|
+
"""RR-12: (offset in the page body, at a line start; the best passage, one line of at
|
|
670
|
+
most PASSAGE characters) from the best chunk starting at `at` (an offset in the filled
|
|
671
|
+
body): its first line holding a query word, else its start; else the first line holding
|
|
672
|
+
a query word, else the body's start."""
|
|
673
|
+
body = n["body"]
|
|
674
|
+
words = [t for t in re.findall(r"\w+", query.lower()) if len(t) > 2 and t not in STOPWORDS]
|
|
675
|
+
# the matching line, not the chunk's first: a chunk starts up to CHUNK_CHARS before its
|
|
676
|
+
# match, and its first 60 characters may repeat earlier in the page (a log's same line)
|
|
677
|
+
chunk = _chunk_text(n, at).split("\n", 1)[-1] if at else "" # without the header line
|
|
678
|
+
line = next((ln.strip() for ln in chunk.splitlines()
|
|
679
|
+
if ln.strip() and any(w in ln.lower() for w in words)), "")
|
|
680
|
+
probe = line or (_filled(body.strip())[at:at + 60] if at else "")
|
|
681
|
+
pos = body.find(probe) if probe.strip() else -1
|
|
682
|
+
if pos < 0:
|
|
683
|
+
low = body.lower()
|
|
684
|
+
found = [i for t in words if (i := low.find(t)) >= 0]
|
|
685
|
+
pos = min(found) if found else len(body) - len(body.lstrip())
|
|
686
|
+
pos = body.rfind("\n", 0, pos) + 1
|
|
687
|
+
return pos, _one_line(body[pos:pos + 2 * PASSAGE], PASSAGE)
|
|
688
|
+
|
|
689
|
+
|
|
690
|
+
def _chunk_text(n: dict, at: int) -> str:
|
|
691
|
+
"""The text of the chunk starting at `at`, as embedded; chunk 0 when there is none."""
|
|
692
|
+
return next((t for s, t in _chunks(n) if s == at), _text(n)) if at else _text(n)
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
def _pages(index: Index) -> dict[str, tuple]:
|
|
696
|
+
return {id: (index._rel(p), *index._stats[p]) # not relative_to: most of a warm query
|
|
697
|
+
for p, id in index._ids.items() if id in index._notes}
|
|
698
|
+
|
|
699
|
+
|
|
700
|
+
# The cache: page id -> (manifest (path, mtime_ns, size), full (every chunk built), chunk
|
|
701
|
+
# starts int32 (k,), unit vectors (k, dim)); chunk 0 is always the first row. In memory the
|
|
702
|
+
# vectors are views of one float32 matrix (`vecstore.stack`); on disk, the rows of CACHE.
|
|
703
|
+
|
|
704
|
+
|
|
705
|
+
def _want(dim: int) -> dict:
|
|
706
|
+
return {"model": MODEL, "text": TEXT_VERSION, "chunk": CHUNKING, "dim": dim}
|
|
707
|
+
|
|
708
|
+
|
|
709
|
+
def _npz_read(root: Path) -> dict:
|
|
710
|
+
"""The .npz cache from before the store, or {} when it is missing, unreadable or built
|
|
711
|
+
with other settings."""
|
|
712
|
+
try:
|
|
713
|
+
with np.load(root / NPZ, allow_pickle=False) as z:
|
|
714
|
+
meta = json.loads(z["meta"].item())
|
|
715
|
+
if [meta.get("model"), meta.get("text"), meta.get("chunk")] == [
|
|
716
|
+
MODEL, TEXT_VERSION, CHUNKING]:
|
|
717
|
+
ids, full, page = [str(i) for i in z["ids"]], z["full"], z["page"]
|
|
718
|
+
start, vecs = z["start"], z["vecs"].astype(np.float32)
|
|
719
|
+
cut = np.searchsorted(page, np.arange(len(ids) + 1))
|
|
720
|
+
return {i: (tuple(meta["pages"][i]), bool(full[k]), start[cut[k]:cut[k + 1]],
|
|
721
|
+
vecs[cut[k]:cut[k + 1]]) for k, i in enumerate(ids)}
|
|
722
|
+
except (OSError, ValueError, KeyError) as e:
|
|
723
|
+
if not isinstance(e, FileNotFoundError):
|
|
724
|
+
log.warning("the old vector cache is unreadable: %s", e)
|
|
725
|
+
return {}
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def _connect(root: Path, dim: int, write: bool = True, vault=None):
|
|
729
|
+
"""The store, its settings checked (other ones empty it; a damaged one is moved aside
|
|
730
|
+
through `vault` and made again) and the .npz read into it once (never written again:
|
|
731
|
+
`prune` deletes it). With `write` False (a dry run) nothing is made, moved or changed:
|
|
732
|
+
None when there is no store or it holds other settings."""
|
|
733
|
+
p = root / CACHE
|
|
734
|
+
if not write:
|
|
735
|
+
if not p.is_file():
|
|
736
|
+
return None
|
|
737
|
+
con = vecstore.connect(p, create=False)
|
|
738
|
+
if vecstore.get_meta(con, "settings") != _want(dim):
|
|
739
|
+
con.close()
|
|
740
|
+
return None
|
|
741
|
+
return con
|
|
742
|
+
con = vecstore.connect(p, vault=vault)
|
|
743
|
+
try:
|
|
744
|
+
vecstore.prepare(con, _want(dim))
|
|
745
|
+
if not vecstore.get_meta(con, "migrated"): # idempotent: a rerun upserts the same rows
|
|
746
|
+
vecstore.put(con, {i: (json.dumps(list(e[0])), e[1], e[2], e[3])
|
|
747
|
+
for i, e in _npz_read(root).items() if e[3].shape[1] == dim})
|
|
748
|
+
with vecstore.tx(con):
|
|
749
|
+
vecstore.set_meta(con, "migrated", True)
|
|
750
|
+
except BaseException:
|
|
751
|
+
con.close()
|
|
752
|
+
raise
|
|
753
|
+
return con
|
|
754
|
+
|
|
755
|
+
|
|
756
|
+
def _code_heads_once(con, index: Index) -> None:
|
|
757
|
+
"""Once per store: delete the rows of pages with a "# line" in a fenced code block, whose
|
|
758
|
+
chunk headers C13 changed (the manifest key would keep their old vectors until an edit);
|
|
759
|
+
the refresh re-embeds just those. The "c13" meta flag makes it run once; the deletes bump
|
|
760
|
+
the store's stamp, so every process's `_sync` drops the rows from memory too."""
|
|
761
|
+
if vecstore.get_meta(con, "c13"):
|
|
762
|
+
return
|
|
763
|
+
vecstore.delete(con, [i for i in vecstore.manifests(con) if i in index._notes and next(
|
|
764
|
+
_heads(_filled(index._notes[i]["body"].strip()), code=True), None)])
|
|
765
|
+
with vecstore.tx(con):
|
|
766
|
+
vecstore.set_meta(con, "c13", True)
|
|
767
|
+
|
|
768
|
+
|
|
769
|
+
def _sync(con, dim: int, st0, cache: dict) -> tuple[tuple, bool]:
|
|
770
|
+
return vecstore.sync(con, dim, st0, cache, lambda m: tuple(json.loads(m)))
|
|
771
|
+
|
|
772
|
+
|
|
773
|
+
def _save(con, cache: dict, changed: set, gone) -> None:
|
|
774
|
+
"""Upsert the `changed` pages and delete the `gone` ones; a disposable cache, so a failure
|
|
775
|
+
is a warning (a later call embeds what is missing)."""
|
|
776
|
+
try:
|
|
777
|
+
vecstore.delete(con, [i for i in gone if i not in cache]) # a changed page: upserted
|
|
778
|
+
vecstore.put(con, {i: (json.dumps(list(cache[i][0])), *cache[i][1:])
|
|
779
|
+
for i in changed if i in cache})
|
|
780
|
+
except sqlite3.Error as e:
|
|
781
|
+
log.warning("vector cache not saved: %s", e)
|
|
782
|
+
|
|
783
|
+
|
|
784
|
+
def _read(root: Path) -> dict:
|
|
785
|
+
"""Every stored row: {id: (manifest, full, starts, float32 vectors)}; {} without a store."""
|
|
786
|
+
if not (root / CACHE).is_file():
|
|
787
|
+
return {}
|
|
788
|
+
with closing(vecstore.connect(root / CACHE, create=False)) as con:
|
|
789
|
+
dim = (vecstore.get_meta(con, "settings") or {}).get("dim")
|
|
790
|
+
return {i: (tuple(json.loads(m)), full, s, v.astype(np.float32))
|
|
791
|
+
for i, m, full, s, v in vecstore.rows(con, dim)} if dim else {}
|
|
792
|
+
|
|
793
|
+
|
|
794
|
+
def stamp(root: Path) -> tuple | None:
|
|
795
|
+
"""The store's change stamp, None when there is none or it is unreadable (the brain
|
|
796
|
+
map's cache key)."""
|
|
797
|
+
if not (root / CACHE).is_file():
|
|
798
|
+
return None
|
|
799
|
+
try:
|
|
800
|
+
with closing(vecstore.connect(root / CACHE, create=False)) as con:
|
|
801
|
+
return vecstore.stamp(con)
|
|
802
|
+
except sqlite3.Error:
|
|
803
|
+
return None
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
def heads(root: Path) -> tuple[list[str], np.ndarray]:
|
|
807
|
+
"""(ids, float32 chunk-0 vectors) of every stored page, read now (the brain map's input:
|
|
808
|
+
one row per page, not the whole matrix). FileNotFoundError without a store."""
|
|
809
|
+
if not (root / CACHE).is_file():
|
|
810
|
+
raise FileNotFoundError(root / CACHE)
|
|
811
|
+
with closing(vecstore.connect(root / CACHE, create=False)) as con:
|
|
812
|
+
dim = (vecstore.get_meta(con, "settings") or {}).get("dim")
|
|
813
|
+
return vecstore.heads(con, dim) if dim else ([], np.zeros((0, 0), np.float32))
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def prune(vault) -> int:
|
|
817
|
+
"""Delete the rows of pages that went or changed, with no model needed (a forget or a
|
|
818
|
+
settings change must not leave a page's vectors behind; a changed page is embedded again
|
|
819
|
+
later). The old .npz is deleted when it holds such a row: the store read it in, so it only
|
|
820
|
+
kept forgotten pages (G-5-5). Rows deleted from the store."""
|
|
821
|
+
from keepfold.catalog import Catalog
|
|
822
|
+
|
|
823
|
+
root = vault.root
|
|
824
|
+
if not ((root / CACHE).is_file() or (root / NPZ).is_file()):
|
|
825
|
+
return 0
|
|
826
|
+
pages = _pages(Index(vault, Catalog.load(vault)))
|
|
827
|
+
n = 0
|
|
828
|
+
if (root / CACHE).is_file():
|
|
829
|
+
with closing(vecstore.connect(root / CACHE, vault=vault)) as con:
|
|
830
|
+
n = vecstore.delete(con, [i for i, m in vecstore.manifests(con).items()
|
|
831
|
+
if pages.get(i) != tuple(json.loads(m))])
|
|
832
|
+
if any(pages.get(i) != e[0] for i, e in _npz_read(root).items()):
|
|
833
|
+
vault.remove(root / NPZ)
|
|
834
|
+
return n
|
|
835
|
+
|
|
836
|
+
|
|
837
|
+
def _embed(embed, texts: list[str]) -> np.ndarray:
|
|
838
|
+
v = np.asarray(embed(texts), dtype=np.float32)
|
|
839
|
+
return v / np.where((n := np.linalg.norm(v, axis=1, keepdims=True)) > 0, n, 1.0)
|
|
840
|
+
|
|
841
|
+
|
|
842
|
+
def embed_all(embed, texts: list[str], batch: int = BATCH, say=None,
|
|
843
|
+
what: str = "texts") -> np.ndarray:
|
|
844
|
+
"""`_embed` of many texts in batches, shortest first so a batch pads little (the vectors
|
|
845
|
+
are the same; 1.4x faster on titles), returned in input order. `say` gets a counts-only
|
|
846
|
+
line every PROGRESS_S seconds."""
|
|
847
|
+
order = sorted(range(len(texts)), key=lambda i: len(texts[i]))
|
|
848
|
+
parts, last = [], time.monotonic()
|
|
849
|
+
for s in range(0, len(order), batch):
|
|
850
|
+
parts.append(_embed(embed, [texts[i] for i in order[s:s + batch]]))
|
|
851
|
+
if say and time.monotonic() - last >= PROGRESS_S:
|
|
852
|
+
say(f"embedded {s + len(parts[-1])} of {len(texts)} {what}")
|
|
853
|
+
last = time.monotonic()
|
|
854
|
+
if not parts:
|
|
855
|
+
return np.zeros((0, 1), np.float32)
|
|
856
|
+
got = np.concatenate(parts)
|
|
857
|
+
out = np.empty_like(got)
|
|
858
|
+
out[order] = got
|
|
859
|
+
return out
|
|
860
|
+
|
|
861
|
+
|
|
862
|
+
def vectors(index: Index, embed, dim: int, budget: float | None = None,
|
|
863
|
+
save_every: float | None = None, progress=None, heads: float | None = None,
|
|
864
|
+
only: set[str] | None = None, save: bool = True):
|
|
865
|
+
"""Bring the vault's cache up to date and return (page ids, row -> page index, row chunk
|
|
866
|
+
start, unit row vectors), rows grouped by page.
|
|
867
|
+
|
|
868
|
+
Chunk 0 of new and changed pages gets at most `heads` seconds per call (None: all of
|
|
869
|
+
them); a page without it is left out of the rows until a later call or `keepfold model
|
|
870
|
+
build` embeds it. Gone pages are dropped. The other chunks get at most `budget` seconds
|
|
871
|
+
per call (None: no limit, for `keepfold model build`); until all of a page's chunks are
|
|
872
|
+
built it scores by those it has.
|
|
873
|
+
With `save_every` (seconds) the build saves as it goes, so an interrupted one resumes;
|
|
874
|
+
`progress(done, total)` counts the chunks built in this call. With `only` (page ids) the
|
|
875
|
+
missing chunk 0 of no other page is embedded in this call (the browse import needs the hub
|
|
876
|
+
members only; recall and `keepfold model build` embed the rest). With `save=False` (a dry
|
|
877
|
+
run) nothing is written and the in-memory cache is left as it was.
|
|
878
|
+
|
|
879
|
+
The store is read lazily: the whole of it on a process's first call, then only the rows
|
|
880
|
+
other processes saved since (its change stamp); a save writes the changed pages only."""
|
|
881
|
+
root = index.vault.root
|
|
882
|
+
pages = _pages(index)
|
|
883
|
+
st, cache, stack = _MEM.get(root, (None, {}, None))
|
|
884
|
+
cache = dict(cache)
|
|
885
|
+
con = None
|
|
886
|
+
try:
|
|
887
|
+
con = _connect(root, dim, save, index.vault)
|
|
888
|
+
if save and con is not None:
|
|
889
|
+
_code_heads_once(con, index)
|
|
890
|
+
if con is None: # a dry run with no usable store: nothing cached
|
|
891
|
+
st, cache, stack = None, {}, None
|
|
892
|
+
else:
|
|
893
|
+
st, moved = _sync(con, dim, st, cache)
|
|
894
|
+
stack = None if moved else stack
|
|
895
|
+
except (sqlite3.Error, OSError) as e: # a disposable cache: embed what this call can
|
|
896
|
+
log.warning("vector cache not read: %s", e)
|
|
897
|
+
if con is not None:
|
|
898
|
+
con.close()
|
|
899
|
+
con = None
|
|
900
|
+
if save and quarantine.torn(e): # damaged past the first open: the next call starts over
|
|
901
|
+
vecstore.heal(root / CACHE, e, index.vault)
|
|
902
|
+
try:
|
|
903
|
+
return _vectors(index, embed, dim, pages, st, cache, stack, con, budget, save_every,
|
|
904
|
+
progress, heads, only, save)
|
|
905
|
+
finally:
|
|
906
|
+
if con is not None:
|
|
907
|
+
con.close()
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
def _vectors(index: Index, embed, dim: int, pages: dict, st, cache: dict, stack, con, budget,
|
|
911
|
+
save_every, progress, heads, only, save: bool):
|
|
912
|
+
root = index.vault.root
|
|
913
|
+
save = save and con is not None
|
|
914
|
+
gone = [i for i, e in cache.items() if pages.get(i) != e[0]] # went, changed or private now
|
|
915
|
+
for i in gone:
|
|
916
|
+
del cache[i]
|
|
917
|
+
dirty, changed = bool(gone), set()
|
|
918
|
+
todo = [i for i in pages if i not in cache and (only is None or i in only)]
|
|
919
|
+
t0, step = time.monotonic(), (BATCH if heads is None else TAIL_BATCH)
|
|
920
|
+
for s in range(0, len(todo), step):
|
|
921
|
+
if heads is not None and time.monotonic() - t0 >= heads:
|
|
922
|
+
break
|
|
923
|
+
batch = todo[s:s + step]
|
|
924
|
+
vecs = _embed(embed, [_text(index._notes[i]) for i in batch])
|
|
925
|
+
for i, v in zip(batch, vecs, strict=True):
|
|
926
|
+
cache[i] = (pages[i], False, np.zeros(1, np.int32), v[None])
|
|
927
|
+
changed.update(batch)
|
|
928
|
+
dirty = True
|
|
929
|
+
pending = [i for i in pages if i in cache and not cache[i][1]]
|
|
930
|
+
work = {}
|
|
931
|
+
if progress: # counted up front only for the CLI build
|
|
932
|
+
work = {i: _chunks(index._notes[i]) for i in pending}
|
|
933
|
+
total = sum(len(c) for c in work.values()) - sum(len(cache[i][2]) for i in pending)
|
|
934
|
+
t0 = last = time.monotonic()
|
|
935
|
+
done, step = 0, (BATCH if budget is None else TAIL_BATCH)
|
|
936
|
+
for i in pending:
|
|
937
|
+
meta, _, have, vecs = cache[i]
|
|
938
|
+
built = set(have.tolist())
|
|
939
|
+
rest = [c for c in work.pop(i, None) or _chunks(index._notes[i]) if c[0] not in built]
|
|
940
|
+
if not rest: # short page: chunk 0 is all of it
|
|
941
|
+
cache[i], dirty = (meta, True, have, vecs), True
|
|
942
|
+
changed.add(i)
|
|
943
|
+
while rest and (budget is None or time.monotonic() - t0 < budget):
|
|
944
|
+
part, rest = rest[:step], rest[step:]
|
|
945
|
+
have = np.concatenate([have, np.array([s for s, _ in part], np.int32)])
|
|
946
|
+
vecs = np.concatenate([vecs, _embed(embed, [t for _, t in part])])
|
|
947
|
+
cache[i], dirty, done = (meta, not rest, have, vecs), True, done + len(part)
|
|
948
|
+
changed.add(i)
|
|
949
|
+
if progress:
|
|
950
|
+
progress(done, total)
|
|
951
|
+
if save and save_every is not None and time.monotonic() - last >= save_every:
|
|
952
|
+
_save(con, cache, changed, gone)
|
|
953
|
+
changed, gone = set(), []
|
|
954
|
+
last = time.monotonic()
|
|
955
|
+
if budget is not None and time.monotonic() - t0 >= budget:
|
|
956
|
+
break
|
|
957
|
+
if save and (changed or gone):
|
|
958
|
+
_save(con, cache, changed, gone)
|
|
959
|
+
if save and dirty: # read back what this call and any other process saved since
|
|
960
|
+
try:
|
|
961
|
+
st = _sync(con, dim, st, cache)[0]
|
|
962
|
+
except sqlite3.Error as e:
|
|
963
|
+
log.warning("vector cache not read back: %s", e)
|
|
964
|
+
for i in [i for i, e in cache.items() if pages.get(i) != e[0]]:
|
|
965
|
+
del cache[i] # another process's newer page: in the store, not in this index yet
|
|
966
|
+
if dirty or stack is None:
|
|
967
|
+
stack = vecstore.stack(cache, dim)
|
|
968
|
+
if save:
|
|
969
|
+
_MEM[root] = (st, cache, stack)
|
|
970
|
+
return stack
|
|
971
|
+
|
|
972
|
+
|
|
973
|
+
def best_chunks(page: np.ndarray, start: np.ndarray, sims: np.ndarray,
|
|
974
|
+
n: int) -> tuple[np.ndarray, np.ndarray]:
|
|
975
|
+
"""Per page (rows grouped by page; every page has chunk 0): the best chunk's cosine and
|
|
976
|
+
its start offset."""
|
|
977
|
+
if not n:
|
|
978
|
+
return np.zeros(0, np.float32), np.zeros(0, np.int32)
|
|
979
|
+
best = np.maximum.reduceat(sims, np.searchsorted(page, np.arange(n)))
|
|
980
|
+
rows = np.flatnonzero(sims == best[page])
|
|
981
|
+
_, first = np.unique(page[rows], return_index=True)
|
|
982
|
+
return best, start[rows[first]]
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def _terms(query: str) -> list[str]:
|
|
986
|
+
"""Distinct non-stopword FTS terms; short words match exactly: a prefix like "i"* would hit
|
|
987
|
+
most of the vault."""
|
|
988
|
+
return list(dict.fromkeys(f'"{t.lower()}"' + ("*" if len(t) > 3 else "")
|
|
989
|
+
for t in re.findall(r"\w+", query or "")
|
|
990
|
+
if t.lower() not in STOPWORDS))
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def _cover(index: Index, query: str) -> dict[str, float]:
|
|
994
|
+
"""Page id -> share of the query's terms it matches (pages matching none are absent)."""
|
|
995
|
+
terms = _terms(query)
|
|
996
|
+
n: dict[str, int] = {}
|
|
997
|
+
for t in terms:
|
|
998
|
+
for (i,) in index.db.execute("SELECT id FROM fts WHERE fts MATCH ?", (t,)):
|
|
999
|
+
n[i] = n.get(i, 0) + 1
|
|
1000
|
+
return {i: c / len(terms) for i, c in n.items()}
|
|
1001
|
+
|
|
1002
|
+
|
|
1003
|
+
def _keyword(index: Index, query: str) -> dict[str, float]:
|
|
1004
|
+
"""BM25 over the FTS index, any non-stopword term (OR), scaled so the best hit is 1."""
|
|
1005
|
+
terms = _terms(query)
|
|
1006
|
+
if not terms:
|
|
1007
|
+
return {}
|
|
1008
|
+
rows = index.db.execute(f"SELECT id, {BM25} FROM fts WHERE fts MATCH ?",
|
|
1009
|
+
(" OR ".join(terms),)).fetchall()
|
|
1010
|
+
s = {i: -b for i, b in rows}
|
|
1011
|
+
top = max(s.values(), default=0.0)
|
|
1012
|
+
return {i: v / top for i, v in s.items()} if top > 0 else {}
|
|
1013
|
+
|
|
1014
|
+
|
|
1015
|
+
def _neighbours(index: Index, id: str):
|
|
1016
|
+
return index.db.execute("SELECT dst, type FROM edges WHERE src = ?1 UNION "
|
|
1017
|
+
"SELECT src, type FROM edges WHERE dst = ?1", (id,)).fetchall()
|
|
1018
|
+
|
|
1019
|
+
|
|
1020
|
+
MENTIONED_BY = 8 # R3a: the pages saying a page's name that count as linked, best BM25 first
|
|
1021
|
+
_WORD = re.compile(r"[\w-]+") # a hyphenated id is one word: "dec-x" is not in "dec-x-v2"
|
|
1022
|
+
|
|
1023
|
+
|
|
1024
|
+
def _names(id: str, title: str, also: list[str] = ()) -> list[tuple[str, ...]]:
|
|
1025
|
+
"""The words a page is named by in other pages' text: its title without a trailing
|
|
1026
|
+
"(…)" ("Paper (PDF)" is said "Paper") and an id with a hyphen and a letter; a one-word
|
|
1027
|
+
name only of 5+ characters. R13d: `also` (its `aliases:`) are names too, of 2+ characters
|
|
1028
|
+
(an owner chose them: "DSA" names the page), matched as whole words like the rest."""
|
|
1029
|
+
out = []
|
|
1030
|
+
for name in (re.sub(r"\s*\([^)]*\)\s*$", "", title), id if "-" in id and re.search(
|
|
1031
|
+
r"[^\W\d_]", id) else ""):
|
|
1032
|
+
w = tuple(_WORD.findall(name.lower()))
|
|
1033
|
+
if (len(w) > 1 or (w and len(w[0]) >= 5)) and w not in out:
|
|
1034
|
+
out.append(w)
|
|
1035
|
+
for name in also:
|
|
1036
|
+
w = tuple(_WORD.findall(name.lower()))
|
|
1037
|
+
if len("".join(w)) >= 2 and w not in out:
|
|
1038
|
+
out.append(w)
|
|
1039
|
+
return out
|
|
1040
|
+
|
|
1041
|
+
|
|
1042
|
+
def _holds(words: list[str], name: tuple[str, ...]) -> bool:
|
|
1043
|
+
return any(tuple(words[k:k + len(name)]) == name for k, w in enumerate(words) if w == name[0])
|
|
1044
|
+
|
|
1045
|
+
|
|
1046
|
+
def _says(index: Index, name: tuple[str, ...]) -> list[str]:
|
|
1047
|
+
"""The MENTIONED_BY pages whose body says `name` most (an FTS phrase, BM25 order)."""
|
|
1048
|
+
phrase = " ".join(re.findall(r"\w+", " ".join(name))) # word characters only: no FTS syntax
|
|
1049
|
+
return [] if not phrase else [i for (i,) in index.db.execute(
|
|
1050
|
+
"SELECT id FROM fts WHERE fts MATCH ? ORDER BY rank LIMIT ?",
|
|
1051
|
+
(f'body : "{phrase}"', MENTIONED_BY))]
|
|
1052
|
+
|
|
1053
|
+
|
|
1054
|
+
def linked(index: Index, ids: list[str], quiet: dict[str, float] | None = None,
|
|
1055
|
+
rank: dict[str, float] | None = None) -> list[str]:
|
|
1056
|
+
"""R3a: the pages linked with those in `ids` by the most kinds of link (summed over
|
|
1057
|
+
`ids`), then by `rank` (higher first: how well each answers the question), then in the
|
|
1058
|
+
order of `ids`. The kinds: an edge either way (wiki links, front-matter keys), the page
|
|
1059
|
+
saying another's name (`_names`) and another saying the page's name (`_says`). `ids`,
|
|
1060
|
+
quiet pages (weight 0), pages the index lacks and the pages Keepfold builds over many
|
|
1061
|
+
others (rollups, topic hubs: they link everything) are left out."""
|
|
1062
|
+
def words(i: str) -> list[str]:
|
|
1063
|
+
return _WORD.findall(index._notes[i]["body"].lower())
|
|
1064
|
+
|
|
1065
|
+
def names(i: str) -> list[tuple[str, ...]]:
|
|
1066
|
+
return _names(i, index._notes[i]["title"], aliases(index._notes[i]["fields"]))
|
|
1067
|
+
|
|
1068
|
+
def first(text: str) -> str:
|
|
1069
|
+
return (m := _WORD.search(text.lower())) and m[0]
|
|
1070
|
+
|
|
1071
|
+
count: dict[str, list] = {} # id -> [links, first seed]
|
|
1072
|
+
for s, seed in enumerate(ids):
|
|
1073
|
+
if seed not in index._notes:
|
|
1074
|
+
continue
|
|
1075
|
+
w = words(seed)
|
|
1076
|
+
have = set(w) # a name's first word must be here: skips _names for most pages
|
|
1077
|
+
got = [{n for n, _ in _neighbours(index, seed)},
|
|
1078
|
+
{i for i, n in index._notes.items()
|
|
1079
|
+
if (i in have or first(n["title"]) in have
|
|
1080
|
+
or any(first(a) in have for a in aliases(n["fields"])))
|
|
1081
|
+
and any(_holds(w, name) for name in names(i))},
|
|
1082
|
+
{i for name in names(seed)
|
|
1083
|
+
for i in _says(index, name) if i in index._notes and _holds(words(i), name)}]
|
|
1084
|
+
for i in set().union(*got):
|
|
1085
|
+
if i not in ids and i in index._notes and (quiet or {}).get(i) != 0 \
|
|
1086
|
+
and index._notes[i]["kind"] != "rollup" and not is_hub(index._notes[i]):
|
|
1087
|
+
c = count.setdefault(i, [0, s])
|
|
1088
|
+
c[0] += sum(i in g for g in got)
|
|
1089
|
+
return sorted(count, key=lambda i: (-count[i][0], -(rank or {}).get(i, 0.0), count[i][1], i))
|
|
1090
|
+
|
|
1091
|
+
|
|
1092
|
+
def recall(index: Index, query: str, embed=None, limit: int = 8, hops: int = 1,
|
|
1093
|
+
rerank_with=None, fuse: str = "weighted", chats: bool = False,
|
|
1094
|
+
quiet: dict[str, float] | None = None, explain: dict | None = None,
|
|
1095
|
+
save: bool = True) -> list[dict]:
|
|
1096
|
+
"""Hybrid hits (0.7 cosine + 0.3 BM25; keyword only when `embed` is None; a cosine under
|
|
1097
|
+
MIN_COS counts as 0, and such a page is a hit only through a keyword match of at least
|
|
1098
|
+
MIN_KW_COVER of the query's terms), plus graph
|
|
1099
|
+
neighbours of the seeds within `hops` (score x0.5 per hop, `via` names the edge). Up to a
|
|
1100
|
+
quarter of the `limit` slots go to linked pages. Returns
|
|
1101
|
+
[{id, kind, title, summary, score, match: similar|keyword|linked, via?, at?}], best first;
|
|
1102
|
+
`at` is the start of the page's best chunk in its filled body (absent for chunk 0).
|
|
1103
|
+
Imported chat pages (`is_chat`) score x CHAT_WEIGHT after the floors, unless `chats`;
|
|
1104
|
+
`quiet` ({id: weight}, harvest.quiet) overrides that weight, and weight 0 drops the page,
|
|
1105
|
+
from the graph neighbours too, even with `chats`. A STALE page or an older version of an
|
|
1106
|
+
imported file (`older_versions`) scores x STALE_WEIGHT and a
|
|
1107
|
+
recent journal or chat page up to x(1 + RECENT_BOOST), or any recent dated page up to
|
|
1108
|
+
x(1 + CURRENT_BOOST) for an `is_current` query (`_factors`).
|
|
1109
|
+
With `rerank_with` (a `load_reranker` scorer) the top RERANK_POOL are reordered by it.
|
|
1110
|
+
`explain` (a dict) is filled with the score parts for `explained`. With `save` False (the
|
|
1111
|
+
app's dry run) the vector cache is read, never written (`vectors`)."""
|
|
1112
|
+
limit = max(1, min(MAX_LIMIT, int(limit)))
|
|
1113
|
+
hops = max(0, min(2, int(hops)))
|
|
1114
|
+
if rerank_with is not None:
|
|
1115
|
+
pool = _rank(index, query, embed, max(limit, RERANK_POOL), hops, fuse, chats, quiet,
|
|
1116
|
+
explain, save)
|
|
1117
|
+
out = None if explain is None else explain.setdefault("rerank", {})
|
|
1118
|
+
return rerank(index, query, pool, rerank_with, chats, quiet, out)[:limit]
|
|
1119
|
+
return _rank(index, query, embed, limit, hops, fuse, chats, quiet, explain, save)
|
|
1120
|
+
|
|
1121
|
+
|
|
1122
|
+
def _rank(index: Index, query: str, embed, limit: int, hops: int, fuse: str,
|
|
1123
|
+
chats: bool = False, quiet: dict[str, float] | None = None,
|
|
1124
|
+
explain: dict | None = None, save: bool = True) -> list[dict]:
|
|
1125
|
+
kw = raw_kw = _keyword(index, query)
|
|
1126
|
+
cos: dict[str, float] = {}
|
|
1127
|
+
raw_cos: dict[str, float] = {}
|
|
1128
|
+
cover: dict[str, float] = {}
|
|
1129
|
+
at: dict[str, int] = {} # page -> start of its best chunk, for the rerank
|
|
1130
|
+
use_cos = embed is not None and bool((query or "").strip())
|
|
1131
|
+
if use_cos:
|
|
1132
|
+
q = _unit(np.asarray(embed([QUERY_PREFIX + query])[0], dtype=np.float32))
|
|
1133
|
+
ids, page, start, m = vectors(index, embed, len(q), RECALL_BUDGET, heads=HEAD_BUDGET,
|
|
1134
|
+
save=save)
|
|
1135
|
+
best, where = best_chunks(page, start, m @ q, len(ids))
|
|
1136
|
+
at = dict(zip(ids, where.tolist(), strict=True))
|
|
1137
|
+
# under the floor a page is only a hit through a keyword match of most query terms,
|
|
1138
|
+
# so one shared common word ("best") is no hit, while an exact id or title still is
|
|
1139
|
+
raw_cos = dict(zip(ids, best.tolist(), strict=True))
|
|
1140
|
+
cos = {i: c for i, c in raw_cos.items() if c >= MIN_COS}
|
|
1141
|
+
cover = _cover(index, query) if kw else {}
|
|
1142
|
+
kw = {i: v for i, v in kw.items() if i in cos or cover.get(i, 0.0) >= MIN_KW_COVER}
|
|
1143
|
+
w_cos, w_kw = (W_COS, W_KW) if use_cos else (0.0, 1.0)
|
|
1144
|
+
score = {i: w_cos * cos.get(i, 0.0) + w_kw * kw.get(i, 0.0)
|
|
1145
|
+
for i in set(cos) | set(kw) if i in index._notes}
|
|
1146
|
+
if fuse == "rrf": # reciprocal rank fusion of the two lists (eval only)
|
|
1147
|
+
score = dict.fromkeys(score, 0.0)
|
|
1148
|
+
for d in (cos, kw):
|
|
1149
|
+
for r, i in enumerate(sorted(d, key=lambda i: (-d[i], i))):
|
|
1150
|
+
if i in score:
|
|
1151
|
+
score[i] += 1 / (RRF_K + r + 1)
|
|
1152
|
+
# after the floors, so a chat page that is the only match still shows
|
|
1153
|
+
now, older = is_current(query), older_versions(index)
|
|
1154
|
+
score = {i: sc * w for i, sc in score.items()
|
|
1155
|
+
if (w := _weight(index, i, chats, quiet, now, older))}
|
|
1156
|
+
if explain is not None:
|
|
1157
|
+
explain.update(cos=raw_cos, kw=raw_kw, cover=cover, at=at, score=score, chats=chats,
|
|
1158
|
+
quiet=quiet, current=now, w=(w_cos, w_kw), older=older)
|
|
1159
|
+
|
|
1160
|
+
def match(i):
|
|
1161
|
+
return "keyword" if w_kw * kw.get(i, 0.0) > w_cos * cos.get(i, 0.0) else "similar"
|
|
1162
|
+
|
|
1163
|
+
ranked = sorted((i for i in score if score[i] > 0), key=lambda i: (-score[i], i))[:limit]
|
|
1164
|
+
n_linked = min(max(1, limit // 4), limit - 1) if hops else 0
|
|
1165
|
+
kept, spare = ranked[:limit - n_linked], ranked[limit - n_linked:]
|
|
1166
|
+
hits = {i: (score[i], match(i), None) for i in kept}
|
|
1167
|
+
linked: dict[str, tuple[float, str]] = {}
|
|
1168
|
+
for seed in kept:
|
|
1169
|
+
seen, frontier = {seed}, [seed]
|
|
1170
|
+
for h in range(1, hops + 1):
|
|
1171
|
+
nxt = []
|
|
1172
|
+
for f in frontier:
|
|
1173
|
+
for n, typ in _neighbours(index, f):
|
|
1174
|
+
if n in seen or n not in index._notes or (quiet or {}).get(n) == 0:
|
|
1175
|
+
continue
|
|
1176
|
+
seen.add(n)
|
|
1177
|
+
nxt.append(n)
|
|
1178
|
+
sc = score[seed] * DECAY ** h
|
|
1179
|
+
if n not in hits and sc > linked.get(n, (0.0, ""))[0]:
|
|
1180
|
+
linked[n] = (sc, f"{f} ({typ})")
|
|
1181
|
+
frontier = nxt
|
|
1182
|
+
for i, (sc, via) in sorted(linked.items(), key=lambda kv: (-kv[1][0], kv[0]))[:n_linked]:
|
|
1183
|
+
hits[i] = (score[i], match(i), None) if score.get(i, 0.0) > sc else (sc, "linked", via)
|
|
1184
|
+
for i in spare:
|
|
1185
|
+
if len(hits) >= limit:
|
|
1186
|
+
break
|
|
1187
|
+
hits.setdefault(i, (score[i], match(i), None))
|
|
1188
|
+
out = []
|
|
1189
|
+
for i, (sc, how, via) in sorted(hits.items(), key=lambda kv: (-kv[1][0], kv[0])):
|
|
1190
|
+
n = index._notes[i]
|
|
1191
|
+
summary = n["fields"].get("summary")
|
|
1192
|
+
out.append({"id": i, "kind": n["kind"], "title": n["title"],
|
|
1193
|
+
"summary": _one_line(str(summary)) if summary else "",
|
|
1194
|
+
"score": round(sc, 3), "match": how, **({"via": via} if via else {}),
|
|
1195
|
+
**({"at": at[i]} if at.get(i) else {})})
|
|
1196
|
+
return out
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def search(index: Index, query: str, limit: int = 8, hops: int = 1,
|
|
1200
|
+
rerank: bool = True, chats: bool = False,
|
|
1201
|
+
quiet: dict[str, float] | None = None,
|
|
1202
|
+
explain: dict | None = None, save: bool = True) -> tuple[list[dict], str]:
|
|
1203
|
+
"""`recall` with the downloaded model (and the reranker when present, on and `rerank`);
|
|
1204
|
+
without the embedder, keyword + graph and the NOT_SET_UP notice (never a download)."""
|
|
1205
|
+
embed = load_embedder()
|
|
1206
|
+
ce = load_reranker() if rerank else None
|
|
1207
|
+
return recall(index, query, embed, limit, hops, ce, chats=chats, quiet=quiet,
|
|
1208
|
+
explain=explain, save=save), \
|
|
1209
|
+
"" if embed else NOT_SET_UP
|
|
1210
|
+
|
|
1211
|
+
|
|
1212
|
+
def explained(index: Index, explain: dict, hits: list[dict],
|
|
1213
|
+
misses: int = 0) -> tuple[list[dict], list[dict]]:
|
|
1214
|
+
"""The score parts of each hit, and of the `misses` best pages that missed the cut, from a
|
|
1215
|
+
`recall(explain=...)` dict: {id, cos (raw best-chunk cosine, None without the model), kw
|
|
1216
|
+
(BM25 scaled to the best hit), cover (share of query terms), weight, factors (`_factors`,
|
|
1217
|
+
whose product is the weight), score, rerank?, at,
|
|
1218
|
+
chunk (its text without the title line), via?, reason (misses only)}. Read-only."""
|
|
1219
|
+
raw_cos, kw, cover = explain["cos"], explain["kw"], explain["cover"]
|
|
1220
|
+
score, (w_cos, w_kw), rr = explain["score"], explain["w"], explain.get("rerank", {})
|
|
1221
|
+
|
|
1222
|
+
def weight(i: str) -> float:
|
|
1223
|
+
return _weight(index, i, explain["chats"], explain["quiet"],
|
|
1224
|
+
explain.get("current", False), explain.get("older", frozenset())) or 0.0
|
|
1225
|
+
|
|
1226
|
+
def parts(i: str, h: dict | None = None) -> dict:
|
|
1227
|
+
at = explain["at"].get(i, 0)
|
|
1228
|
+
chunk = _chunk_text(index._notes[i], at).split("\n", 1)[-1] if raw_cos else ""
|
|
1229
|
+
f = _factors(index, i, explain["chats"], explain["quiet"], explain.get("current", False),
|
|
1230
|
+
explain.get("older", frozenset()))
|
|
1231
|
+
return {"id": i, "cos": raw_cos.get(i), "kw": kw.get(i, 0.0), "cover": cover.get(i),
|
|
1232
|
+
"weight": weight(i), "factors": {k: round(v, 3) for k, v in f.items()},
|
|
1233
|
+
"score": h["score"] if h else round(score.get(i, 0.0), 3),
|
|
1234
|
+
**({"rerank": round(rr[i], 3)} if i in rr else {}), "at": at,
|
|
1235
|
+
"chunk": _one_line(chunk)[:80], **({"via": h["via"]} if h and "via" in h else {})}
|
|
1236
|
+
|
|
1237
|
+
def reason(p: dict) -> str:
|
|
1238
|
+
if not p["weight"]:
|
|
1239
|
+
return "hidden (harvest quiet weight 0)"
|
|
1240
|
+
if p["id"] in score:
|
|
1241
|
+
return "below limit" + (" after rerank" if rr else "")
|
|
1242
|
+
why = [] if p["cos"] is None else [f"cosine {p['cos']:.3f} < MIN_COS {MIN_COS}"]
|
|
1243
|
+
if p["kw"]:
|
|
1244
|
+
why.append(f"keyword cover {p['cover'] or 0.0:.2f} < MIN_KW_COVER {MIN_KW_COVER}")
|
|
1245
|
+
return ", ".join(why) or "no signal"
|
|
1246
|
+
|
|
1247
|
+
def would(i: str) -> float: # the fused score without the floors: the order of the misses
|
|
1248
|
+
return (w_cos * raw_cos.get(i, 0.0) + w_kw * kw.get(i, 0.0)) * weight(i)
|
|
1249
|
+
|
|
1250
|
+
shown = {h["id"] for h in hits}
|
|
1251
|
+
cand = sorted((i for i in set(raw_cos) | set(kw) if i in index._notes and i not in shown),
|
|
1252
|
+
key=lambda i: (-would(i), i))[:misses]
|
|
1253
|
+
return ([parts(h["id"], h) for h in hits],
|
|
1254
|
+
[{**(p := parts(i)), "reason": reason(p)} for i in cand])
|