File size: 6,025 Bytes
860fd4c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
"""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()