Download api/library_query.py from Einsia/LitGraph: direct link, hf CLI and curl.
- Browser
- Download file 6.03 kB
-
https://huggingface.co/datasets/Einsia/LitGraph/resolve/main/api/library_query.py
- Command line
-
hf download hf://datasets/Einsia/LitGraph/api/library_query.py
-
curl -L -o library_query.py https://huggingface.co/datasets/Einsia/LitGraph/resolve/main/api/library_query.py
6.03 kB
| """Search and inspect the domain problem/insight snapshot used by ideaX. | |
| library_query.py build --source <insight_lib> --db <library.db> | |
| library_query.py search <words> [--kind problem|insight] [--unit <id>] [-k 12] | |
| library_query.py show <entry-id> | paper <numeric-paper-id> | |
| Entry IDs belong to insight_lib; numeric paper IDs are NOT lit.db W IDs. | |
| """ | |
| import argparse | |
| import json | |
| import os | |
| import re | |
| import sqlite3 | |
| from pathlib import Path | |
| def tokens(text): | |
| parts = re.findall(r'[a-z0-9]+|[\u4e00-\u9fff]+', text.lower()) | |
| return list(dict.fromkeys(t for p in parts for t in | |
| ([p] if not re.search(r'[\u4e00-\u9fff]', p) else | |
| [p[i:i + 2] for i in range(max(1, len(p) - 1))]))) | |
| def build(source, output): | |
| source, output = Path(source), Path(output) | |
| output.parent.mkdir(parents=True, exist_ok=True) | |
| temp = output.with_suffix('.building.db') | |
| if temp.exists(): | |
| temp.unlink() | |
| con = sqlite3.connect(temp) | |
| con.executescript(''' | |
| create table entries(id text primary key, kind text, unit text, data text); | |
| create virtual table search using fts5(id UNINDEXED, words); | |
| create table papers(id text primary key, data text); | |
| create index entries_kind_unit on entries(kind, unit); | |
| ''') | |
| names = {d['id']: d['name'] for d in json.loads((source / 'domains.json').read_text())['domains']} | |
| paper_ids = set() | |
| count = 0 | |
| for unit in sorted((source / 'domains').iterdir()): | |
| if not unit.is_dir(): | |
| continue | |
| for kind in ('problem', 'insight'): | |
| path = unit / (kind + '.json') | |
| if not path.exists(): | |
| continue | |
| for entry in json.loads(path.read_text()).get('entries', []): | |
| entry = dict(entry, unit=unit.name, unit_name=names.get(unit.name, unit.name), kind=kind) | |
| text = ' '.join(str(entry.get(k) or '') for k in ('unit', 'unit_name', 'statement', 'mechanism', 'scope', 'techniques')) | |
| con.execute('insert into entries values(?,?,?,?)', | |
| (entry['id'], kind, unit.name, json.dumps(entry, ensure_ascii=False))) | |
| con.execute('insert into search values(?,?)', (entry['id'], ' '.join(tokens(text)))) | |
| for e in [entry] + entry.get('members', []): | |
| paper_ids.update(str(p) for p in e.get('supporting_papers', [])) | |
| count += 1 | |
| for pid in sorted(paper_ids): | |
| path = source / 'cards' / (pid + '.json') | |
| if path.exists(): | |
| card = json.loads(path.read_text()) | |
| # Keep source evidence and metadata; generation traces are unnecessary. | |
| card = {k: v for k, v in card.items() if k not in ('raw', 'usage', 'response', 'prompt')} | |
| con.execute('insert into papers values(?,?)', (pid, json.dumps(card, ensure_ascii=False))) | |
| con.commit() | |
| papers = con.execute('select count(*) from papers').fetchone()[0] | |
| con.close() | |
| os.replace(temp, output) | |
| return {'entries': count, 'papers': papers, 'db': str(output)} | |
| def main(): | |
| ap = argparse.ArgumentParser(description=__doc__) | |
| ap.add_argument('--db', default=os.environ.get('LITGRAPH_LIBRARY_DB', '/work/library.db')) | |
| sub = ap.add_subparsers(dest='cmd', required=True) | |
| b = sub.add_parser('build') | |
| b.add_argument('--source', required=True) | |
| s = sub.add_parser('search') | |
| s.add_argument('query', nargs='+') | |
| s.add_argument('--kind', choices=['problem', 'insight']) | |
| s.add_argument('--unit') | |
| s.add_argument('-k', type=int, default=12) | |
| for name in ('show', 'paper'): | |
| sub.add_parser(name).add_argument('id') | |
| args = ap.parse_args() | |
| if args.cmd == 'build': | |
| print(json.dumps(build(args.source, args.db), ensure_ascii=False)) | |
| return | |
| from library_client import LibraryClient, LibraryAPIError, run_config | |
| # A run opts into HTTP explicitly; reconstruction and older runs stay on their snapshot. | |
| if run_config().get('base_url'): | |
| try: | |
| client = LibraryClient() | |
| if args.cmd in ('show', 'paper'): | |
| data = client.entry(args.id) if args.cmd == 'show' else client.paper(args.id) | |
| print(json.dumps(data, ensure_ascii=False, indent=2)) | |
| else: | |
| result = client.request('/api/v1/search', dict(q=' '.join(args.query), kind=args.kind, | |
| unit=args.unit, limit=args.k, mode='any')) | |
| # Preserve page metadata rather than silently dropping unfetched results. | |
| print(json.dumps(result, ensure_ascii=False, indent=2)) | |
| return | |
| except LibraryAPIError as exc: | |
| raise SystemExit(str(exc)) from exc | |
| con = sqlite3.connect('file:' + str(Path(args.db).absolute()) + '?mode=ro', uri=True) | |
| if args.cmd in ('show', 'paper'): | |
| table = 'entries' if args.cmd == 'show' else 'papers' | |
| row = con.execute(f'select data from {table} where id=?', (args.id,)).fetchone() | |
| if not row: | |
| raise SystemExit(f'No {args.cmd} ID {args.id}') | |
| print(json.dumps(json.loads(row[0]), ensure_ascii=False, indent=2)) | |
| else: | |
| terms = tokens(' '.join(args.query)) | |
| if not terms: | |
| raise SystemExit('Search needs a nonempty term') | |
| sql = 'select e.data from search join entries e on e.id=search.id where search match ?' | |
| params = [' OR '.join('"' + t + '"' for t in terms)] | |
| for k in ('kind', 'unit'): | |
| if getattr(args, k): | |
| sql += f' and e.{k}=?' | |
| params.append(getattr(args, k)) | |
| sql += ' order by bm25(search) limit ?' | |
| params.append(args.k) | |
| for (data,) in con.execute(sql, params): | |
| d = json.loads(data) | |
| print(json.dumps({k: d.get(k) for k in ('id', 'kind', 'unit', 'unit_name', 'statement', 'mechanism', 'scope', 'supporting_papers')}, ensure_ascii=False)) | |
| if __name__ == '__main__': | |
| main() | |