budgetdex 0.0.1__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.
- budgetdex/__init__.py +21 -0
- budgetdex/_name.py +16 -0
- budgetdex/api.py +257 -0
- budgetdex/bench.py +437 -0
- budgetdex/cards.py +303 -0
- budgetdex/cli.py +317 -0
- budgetdex/configs.py +434 -0
- budgetdex/excerpt.py +184 -0
- budgetdex/ingest/__init__.py +320 -0
- budgetdex/ingest/formats.py +226 -0
- budgetdex/ingest/glossary.py +139 -0
- budgetdex/ingest/notion_api.py +438 -0
- budgetdex/ingest/notion_zip.py +385 -0
- budgetdex/ingest/postgres.py +674 -0
- budgetdex/ingest/secrets.py +44 -0
- budgetdex/ingest/table.py +785 -0
- budgetdex/ingest/text.py +264 -0
- budgetdex/ingest/walk.py +304 -0
- budgetdex/mcp_server.py +100 -0
- budgetdex/pack.py +341 -0
- budgetdex/rank.py +176 -0
- budgetdex/render.py +283 -0
- budgetdex/rerank.py +249 -0
- budgetdex/search.py +191 -0
- budgetdex/secretstore.py +60 -0
- budgetdex/spm.py +247 -0
- budgetdex/sqltool.py +445 -0
- budgetdex/store.py +191 -0
- budgetdex/textindex.py +276 -0
- budgetdex/tokens.py +91 -0
- budgetdex/vec.py +467 -0
- budgetdex/weak.py +567 -0
- budgetdex-0.0.1.dist-info/METADATA +192 -0
- budgetdex-0.0.1.dist-info/RECORD +38 -0
- budgetdex-0.0.1.dist-info/WHEEL +4 -0
- budgetdex-0.0.1.dist-info/entry_points.txt +2 -0
- budgetdex-0.0.1.dist-info/licenses/LICENSE +202 -0
- budgetdex-0.0.1.dist-info/licenses/NOTICE +16 -0
budgetdex/__init__.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Local, LLM-free index that returns search results packed into a token budget."""
|
|
2
|
+
|
|
3
|
+
from ._name import NAME
|
|
4
|
+
|
|
5
|
+
__version__ = "0.0.1"
|
|
6
|
+
__all__ = ["NAME", "open", "DB"]
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def open(path=None): # noqa: A001 - public SDK entry point, mirrors design doc
|
|
10
|
+
"""Open (or create) an index. ``path`` defaults to $BUDGETDEX_HOME/default.db."""
|
|
11
|
+
from .api import DB
|
|
12
|
+
|
|
13
|
+
return DB(path)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def __getattr__(name):
|
|
17
|
+
if name == "DB":
|
|
18
|
+
from .api import DB
|
|
19
|
+
|
|
20
|
+
return DB
|
|
21
|
+
raise AttributeError(name)
|
budgetdex/_name.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
"""The package's public name, defined in one place so it can be renamed.
|
|
2
|
+
|
|
3
|
+
Everything user-visible (CLI program name, MCP server name, home directory,
|
|
4
|
+
environment variable) is derived from NAME. Internal imports are relative.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
NAME = "budgetdex"
|
|
8
|
+
HOME_ENV = NAME.upper() + "_HOME" # e.g. BUDGETDEX_HOME overrides ~/.budgetdex
|
|
9
|
+
DEFAULT_HOME_DIRNAME = "." + NAME
|
|
10
|
+
|
|
11
|
+
# Former working name (renamed 2026-11-19). Compatibility only: AKDB_HOME is
|
|
12
|
+
# honoured when BUDGETDEX_HOME is unset; ~/.akdb is never used automatically,
|
|
13
|
+
# but the walker still skips a folder of that name (an old index home).
|
|
14
|
+
LEGACY_NAME = "akdb"
|
|
15
|
+
LEGACY_HOME_ENV = LEGACY_NAME.upper() + "_HOME"
|
|
16
|
+
LEGACY_HOME_DIRNAME = "." + LEGACY_NAME
|
budgetdex/api.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""SDK entry point: DB with add / sync / search / get / status."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import sqlite3
|
|
5
|
+
import time
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
from . import configs, ingest, render, search as searchmod, store
|
|
9
|
+
from .ingest import walk
|
|
10
|
+
from .tokens import estimate
|
|
11
|
+
|
|
12
|
+
DEFAULT_BUDGET = 1500
|
|
13
|
+
GET_DEFAULT_BUDGET = 2000
|
|
14
|
+
SQL_DEFAULT_BUDGET = 1000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Session:
|
|
18
|
+
"""What one MCP connection has already been given (design 5節 既出の省略).
|
|
19
|
+
|
|
20
|
+
Chunks returned as snippet or full text, or fetched with get, come back
|
|
21
|
+
from later searches of the same session as a title line marked ※既出."""
|
|
22
|
+
|
|
23
|
+
def __init__(self):
|
|
24
|
+
self.seen = set()
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class DB:
|
|
28
|
+
def __init__(self, path=None):
|
|
29
|
+
self.path = Path(path).expanduser() if path else store.default_path()
|
|
30
|
+
self.con = store.connect(self.path)
|
|
31
|
+
from .ingest import table
|
|
32
|
+
|
|
33
|
+
table.upgrade_storage(self.con) # older local tables stored every column as TEXT
|
|
34
|
+
table.upgrade_cards(self.con) # older cards carried cell values (AUDIT_P2 中#1)
|
|
35
|
+
|
|
36
|
+
# -- context manager --
|
|
37
|
+
def __enter__(self):
|
|
38
|
+
return self
|
|
39
|
+
|
|
40
|
+
def __exit__(self, *exc):
|
|
41
|
+
self.close()
|
|
42
|
+
|
|
43
|
+
def close(self):
|
|
44
|
+
if getattr(self, "_sql", None) is not None:
|
|
45
|
+
self._sql.close()
|
|
46
|
+
self._sql = None
|
|
47
|
+
if self.con:
|
|
48
|
+
self.con.close()
|
|
49
|
+
self.con = None
|
|
50
|
+
|
|
51
|
+
# -- ingestion --
|
|
52
|
+
def add(self, *paths, table_values: bool | None = None) -> dict:
|
|
53
|
+
"""Add folders / files / Notion export zips. table_values=True lets the table
|
|
54
|
+
cards of these paths (a folder, or one table file) list repeated category
|
|
55
|
+
values and numeric / date ranges (personal-looking columns still excluded);
|
|
56
|
+
False switches that off again; None (default) leaves the setting as it is.
|
|
57
|
+
By default cards hold no cell value."""
|
|
58
|
+
from pathlib import Path
|
|
59
|
+
|
|
60
|
+
from .ingest import table
|
|
61
|
+
|
|
62
|
+
total = {}
|
|
63
|
+
for p in paths:
|
|
64
|
+
if table_values is not None:
|
|
65
|
+
table.set_values(self.con, Path(p).expanduser().resolve(), table_values)
|
|
66
|
+
for k, v in ingest.add_source(self.con, p).items():
|
|
67
|
+
total[k] = total.get(k, 0) + v
|
|
68
|
+
if table_values is not None: # unchanged files are not re-read: re-render their cards
|
|
69
|
+
table.refresh_cards(self.con)
|
|
70
|
+
self.con.commit()
|
|
71
|
+
return total
|
|
72
|
+
|
|
73
|
+
def add_postgres(self, name="default", env=None, keychain=None, schemas=("public",),
|
|
74
|
+
table_values: bool | None = None) -> dict:
|
|
75
|
+
"""Index a Postgres / Supabase database's schema and statistics (no rows).
|
|
76
|
+
The connection string is read from `env` (default BUDGETDEX_POSTGRES_URL) or the
|
|
77
|
+
macOS keychain item `keychain` whenever needed; it is never stored.
|
|
78
|
+
table_values: as in add() (planner statistics' common values and ranges)."""
|
|
79
|
+
from .ingest import postgres
|
|
80
|
+
|
|
81
|
+
return postgres.add(self.con, name, env, keychain, schemas, table_values)
|
|
82
|
+
|
|
83
|
+
def add_notion(self, name="default", env=None, keychain=None, transport=None) -> dict:
|
|
84
|
+
"""Sync Notion pages through the API (token from `env`, default NOTION_TOKEN, or the keychain)."""
|
|
85
|
+
from .ingest import notion_api
|
|
86
|
+
|
|
87
|
+
return notion_api.add(self.con, name, env, keychain, transport)
|
|
88
|
+
|
|
89
|
+
def allow(self, *globs) -> list:
|
|
90
|
+
"""Let file/folder names matching these globs past the default ignores."""
|
|
91
|
+
return ingest.allow(self.con, *globs)
|
|
92
|
+
|
|
93
|
+
def sync(self) -> dict:
|
|
94
|
+
return ingest.sync_all(self.con)
|
|
95
|
+
|
|
96
|
+
def last_sync(self):
|
|
97
|
+
r = self.con.execute("SELECT MAX(last_sync) FROM sources").fetchone()
|
|
98
|
+
return r[0] if r else None
|
|
99
|
+
|
|
100
|
+
# -- reading --
|
|
101
|
+
def config(self) -> configs.Config:
|
|
102
|
+
"""The search configuration stored in the index (bench --write-config / profile),
|
|
103
|
+
else the default. A stored configuration that does not keep to the token
|
|
104
|
+
budget (the plain_* baselines) is never used: the default replaces it."""
|
|
105
|
+
try:
|
|
106
|
+
cfg = configs.get(store.get_meta(self.con, configs.META_KEY))
|
|
107
|
+
except KeyError:
|
|
108
|
+
return configs.get(None)
|
|
109
|
+
return cfg if cfg.budgeted else configs.get(None)
|
|
110
|
+
|
|
111
|
+
def search(self, query: str, budget: int = DEFAULT_BUDGET, where: str | None = None,
|
|
112
|
+
session: Session | None = None, config: str | None = None, log: bool = True) -> str:
|
|
113
|
+
cfg = configs.get(config) if config else self.config()
|
|
114
|
+
synced = self.last_sync()
|
|
115
|
+
cands, capped = configs.retrieve(cfg, self.con, query, where=where)
|
|
116
|
+
seen = frozenset(session.seen) if session else frozenset()
|
|
117
|
+
text, shown = configs.pack(cfg, cands, budget, capped, synced, seen)
|
|
118
|
+
if session:
|
|
119
|
+
session.seen.update(i for i, lv in shown.items() if lv >= 2)
|
|
120
|
+
if log:
|
|
121
|
+
self._log_saving(estimate(text), estimate(render.topk_full(cands, capped=capped, synced=synced)))
|
|
122
|
+
return text
|
|
123
|
+
|
|
124
|
+
def _log_saving(self, returned: int, baseline: int) -> None:
|
|
125
|
+
"""Savings log: tokens returned vs. the plain-RAG baseline (top-10 in full) for the
|
|
126
|
+
same query. Both are this package's estimates; a failure never breaks a search."""
|
|
127
|
+
try:
|
|
128
|
+
self.con.execute("INSERT INTO savings(at, returned, baseline) VALUES (?,?,?)", (time.time(), returned, baseline))
|
|
129
|
+
self.con.commit()
|
|
130
|
+
except sqlite3.Error:
|
|
131
|
+
pass
|
|
132
|
+
|
|
133
|
+
def savings(self) -> list:
|
|
134
|
+
"""[(YYYY-MM, searches, returned, baseline)] newest month first (local time)."""
|
|
135
|
+
return self.con.execute(
|
|
136
|
+
"SELECT strftime('%Y-%m', at, 'unixepoch', 'localtime') m, COUNT(*), SUM(returned), SUM(baseline)"
|
|
137
|
+
" FROM savings GROUP BY m ORDER BY m DESC"
|
|
138
|
+
).fetchall()
|
|
139
|
+
|
|
140
|
+
def local_sql(self):
|
|
141
|
+
from . import sqltool
|
|
142
|
+
|
|
143
|
+
if getattr(self, "_sql", None) is None:
|
|
144
|
+
self._sql = sqltool.LocalSQL(self.path)
|
|
145
|
+
return self._sql
|
|
146
|
+
|
|
147
|
+
def sql(self, query: str, budget: int = SQL_DEFAULT_BUDGET) -> str:
|
|
148
|
+
"""Read-only SQL over the indexed tables (and Postgres sources), as tab-separated
|
|
149
|
+
text within `budget` tokens."""
|
|
150
|
+
from . import sqltool
|
|
151
|
+
|
|
152
|
+
return sqltool.run(self, query, budget)
|
|
153
|
+
|
|
154
|
+
def get(self, id: str, budget: int | None = None, start: int = 0, session: Session | None = None) -> str: # noqa: A002
|
|
155
|
+
"""One item's full text (see get_text)."""
|
|
156
|
+
return get_text(self.con, id, budget, start, session)
|
|
157
|
+
|
|
158
|
+
def status(self) -> dict:
|
|
159
|
+
q = lambda sql: self.con.execute(sql).fetchone()[0] # noqa: E731
|
|
160
|
+
size = sum(os.path.getsize(p) for p in [self.path, Path(str(self.path) + "-wal")] if os.path.exists(p))
|
|
161
|
+
return {
|
|
162
|
+
"path": str(self.path),
|
|
163
|
+
"sources": [r[0] for r in self.con.execute("SELECT location FROM sources ORDER BY id")],
|
|
164
|
+
"documents": q("SELECT COUNT(*) FROM documents"),
|
|
165
|
+
"tables": q("SELECT COUNT(*) FROM tables"),
|
|
166
|
+
"chunks": q("SELECT COUNT(*) FROM chunks"),
|
|
167
|
+
"skipped": [(u, r) for u, r in self.con.execute(
|
|
168
|
+
"SELECT uri, reason FROM skipped WHERE reason NOT IN (?,?,?) ORDER BY uri", walk.IGNORE_REASONS)],
|
|
169
|
+
"ignored": dict(self.con.execute(
|
|
170
|
+
"SELECT reason, COUNT(*) FROM skipped WHERE reason IN (?,?,?) GROUP BY reason", walk.IGNORE_REASONS)),
|
|
171
|
+
"connectors": [(k, loc) for k, loc in self.con.execute(
|
|
172
|
+
"SELECT kind, location FROM sources WHERE kind NOT IN ('dir','file') ORDER BY id")],
|
|
173
|
+
"index_bytes": size,
|
|
174
|
+
"last_sync": self.last_sync(),
|
|
175
|
+
"savings": self.savings(),
|
|
176
|
+
"config": self.config().name,
|
|
177
|
+
"vectors": self.vector_progress(),
|
|
178
|
+
"rls": self._rls_tables(),
|
|
179
|
+
"tables_untyped": self._untyped_tables(),
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
def _untyped_tables(self):
|
|
183
|
+
"""Local tables still stored all-TEXT by an older version (retyped at the next
|
|
184
|
+
writable open; 0 normally)."""
|
|
185
|
+
from .ingest import table
|
|
186
|
+
|
|
187
|
+
return table.storage_pending(self.con)
|
|
188
|
+
|
|
189
|
+
def _rls_tables(self):
|
|
190
|
+
from .ingest import postgres
|
|
191
|
+
|
|
192
|
+
return postgres.rls_tables(self.con)
|
|
193
|
+
|
|
194
|
+
def vector_progress(self):
|
|
195
|
+
from . import vec
|
|
196
|
+
|
|
197
|
+
done, total = vec.progress(self.con)
|
|
198
|
+
return {"embedded": done, "chunks": total} if done or vec.model_present() else None
|
|
199
|
+
|
|
200
|
+
def embed(self, embedder=None, **kw) -> dict:
|
|
201
|
+
"""Add vectors for chunks without one (optional extra). Returns embed_pending's counts."""
|
|
202
|
+
from . import vec
|
|
203
|
+
|
|
204
|
+
return vec.embed_pending(self.con, embedder, **kw)
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def get_text(con, id: str, budget: int | None = None, start: int = 0, session: Session | None = None) -> str: # noqa: A002
|
|
208
|
+
"""One item's full text, from character offset `start`, within `budget`
|
|
209
|
+
tokens (default GET_DEFAULT_BUDGET; 0 or less returns ""). When the text
|
|
210
|
+
does not fit, the last line says how to fetch the rest (start=N).
|
|
211
|
+
Always the full text, even for items marked ※既出 in this session."""
|
|
212
|
+
budget = GET_DEFAULT_BUDGET if budget is None else int(budget)
|
|
213
|
+
if budget <= 0:
|
|
214
|
+
return ""
|
|
215
|
+
row = con.execute(
|
|
216
|
+
"SELECT c.id, c.path, c.body, c.ord, c.document_id, d.title, d.rel, d.mtime, d.kind FROM chunks c"
|
|
217
|
+
" JOIN documents d ON d.id=c.document_id WHERE c.id=?",
|
|
218
|
+
(id.strip().strip("[]"),),
|
|
219
|
+
).fetchone()
|
|
220
|
+
if not row:
|
|
221
|
+
return render._fit([f"見つかりません: {render._oneline(id)[:40]}", "見つかりません"], budget)
|
|
222
|
+
cid, path, body, ord_, doc_id, title, rel, mtime, kind = row
|
|
223
|
+
if session:
|
|
224
|
+
session.seen.add(cid)
|
|
225
|
+
cand = searchmod.Candidate(cid, 1.0, title, path, rel, mtime, kind, "", body)
|
|
226
|
+
head = render.title_line(cand)
|
|
227
|
+
nb = con.execute(
|
|
228
|
+
"SELECT ord, id FROM chunks WHERE document_id=? AND ord IN (?, ?)", (doc_id, ord_ - 1, ord_ + 1)
|
|
229
|
+
).fetchall()
|
|
230
|
+
nav = " ".join(("前" if o < ord_ else "次") + f" [{i}]" for o, i in sorted(nb))
|
|
231
|
+
full = render.full_lines(body)
|
|
232
|
+
start = max(0, min(int(start), len(full)))
|
|
233
|
+
rest = full[start:]
|
|
234
|
+
lead = [f" …({start}文字目から)"] if start else []
|
|
235
|
+
tail = [nav] if nav else []
|
|
236
|
+
text = "\n".join([head] + lead + ([rest] if rest else []) + tail)
|
|
237
|
+
if estimate(text) <= budget:
|
|
238
|
+
return text
|
|
239
|
+
|
|
240
|
+
def page(n):
|
|
241
|
+
nxt = start + n
|
|
242
|
+
more = f"…続きは get(id={cid}, start={nxt})"
|
|
243
|
+
return "\n".join([head] + lead + [rest[:n].rstrip("\n"), more] + tail)
|
|
244
|
+
|
|
245
|
+
lo, hi = 0, len(rest)
|
|
246
|
+
while lo < hi: # longest prefix of the rest that fits
|
|
247
|
+
mid = (lo + hi + 1) // 2
|
|
248
|
+
if estimate(page(mid)) <= budget:
|
|
249
|
+
lo = mid
|
|
250
|
+
else:
|
|
251
|
+
hi = mid - 1
|
|
252
|
+
nl = rest.rfind("\n", 0, lo)
|
|
253
|
+
if nl > lo // 2: # prefer ending the page at a line break
|
|
254
|
+
lo = nl + 1
|
|
255
|
+
if lo == 0:
|
|
256
|
+
return render._fit([head, "予算不足", ""], budget)
|
|
257
|
+
return page(lo)
|