File size: 7,445 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
"""Build a separate field-search/arXiv index without changing library.db."""
import argparse
import json
import os
from pathlib import Path
import re
import sqlite3
import time

from library_query import tokens


FIELDS = ('statement', 'mechanism', 'scope', 'techniques')
INDEX_VERSION = '3'


def supporting_paper_count(entry):
    """Count distinct numeric source-paper IDs, not external citation counts."""
    return len({int(value) for value in (entry.get('supporting_papers') or [])
                if not isinstance(value, bool) and re.fullmatch(r'[0-9]{1,20}', str(value))})


def arxiv_id(value):
    match = re.search(r'(\d{4}\.\d{4,5}|[a-z][a-z.\-]+/\d{7})(?:v\d+)?', str(value or ''), re.I)
    return match.group(1).lower() if match else None


def fingerprint(path):
    stat = Path(path).stat()
    return {'size': stat.st_size, 'mtime_ns': stat.st_mtime_ns}


def build(database, output, domains_file=None, papers_file=None):
    source, output = Path(database).resolve(strict=True), Path(output).resolve()
    if source == output:
        raise ValueError('Search index must be a separate file')
    output.parent.mkdir(parents=True, exist_ok=True)
    temp = output.with_name(output.name + f'.{os.getpid()}.building')
    before = fingerprint(source)
    domains_file = Path(domains_file) if domains_file else source.parent / 'domains.json'
    papers_file = Path(papers_file) if papers_file else source.parent.parent / 'papers.jsonl'
    catalog = json.loads(domains_file.read_text())['domains'] if domains_file.exists() else None
    start = time.monotonic()
    with sqlite3.connect(source.as_uri() + '?mode=ro', uri=True) as src, sqlite3.connect(temp) as dst:
        dst.executescript('''
            CREATE TABLE metadata(key TEXT PRIMARY KEY, value TEXT);
            CREATE TABLE entries(id TEXT PRIMARY KEY, kind TEXT, unit TEXT, paper_count INTEGER NOT NULL);
            CREATE INDEX entries_kind_unit ON entries(kind,unit);
            CREATE INDEX entries_domain_paper_count ON entries(unit,kind,paper_count DESC,id);
            CREATE INDEX entries_paper_count ON entries(paper_count DESC,id);
            CREATE VIRTUAL TABLE entry_fts USING fts5(id UNINDEXED, statement, mechanism, scope, techniques);
            CREATE TABLE papers(id TEXT PRIMARY KEY, arxiv TEXT, data TEXT, has_source_card INTEGER NOT NULL);
            CREATE INDEX papers_arxiv ON papers(arxiv);
            CREATE TABLE domains(id TEXT PRIMARY KEY, data TEXT);
            CREATE TABLE domain_papers(domain_id TEXT, paper_id TEXT, PRIMARY KEY(domain_id,paper_id));
            CREATE INDEX domain_papers_paper ON domain_papers(paper_id);
        ''')
        count = 0
        inferred_domains = {}
        for identifier, kind, unit, data in src.execute('SELECT id,kind,unit,data FROM entries'):
            entry = json.loads(data)
            values = []
            for field in FIELDS:
                value = entry.get(field, '')
                if field == 'techniques' and isinstance(value, list):
                    value = ' '.join(x.get('name', '') if isinstance(x, dict) else str(x) for x in value)
                if entry.get('summary_policy') == 'first_three_eligible_source_card_excerpts':
                    member_field = 'scope_tag' if field == 'scope' else field
                    member_values = [m.get(member_field) or '' for m in entry.get('members', [])]
                    value = str(value or '') + ' ' + ' '.join(
                        json.dumps(v, ensure_ascii=False) if not isinstance(v, str) else v for v in member_values)
                values.append(' '.join(tokens(str(value or ''))))
            dst.execute('INSERT INTO entries VALUES(?,?,?,?)', (identifier, kind, unit, supporting_paper_count(entry)))
            dst.execute('INSERT INTO entry_fts VALUES(?,?,?,?,?)', (identifier, *values))
            inferred = inferred_domains.setdefault(unit, {'id': unit, 'name': entry.get('unit_name', unit), 'papers': set()})
            inferred['papers'].update(str(x) for x in (entry.get('supporting_papers') or []))
            count += 1
        catalog = catalog if catalog is not None else list(inferred_domains.values())
        wanted = set()
        for domain in catalog:
            info = {k: domain[k] for k in ('id', 'name', 'lines', 'directions') if k in domain}
            dst.execute('INSERT INTO domains VALUES(?,?)', (domain['id'], json.dumps(info, ensure_ascii=False)))
            for pid in set(str(x) for x in domain.get('papers', [])):
                wanted.add(pid)
                dst.execute('INSERT INTO domain_papers VALUES(?,?)', (domain['id'], pid))
        paper_count = 0
        for identifier, data in src.execute('SELECT id,data FROM papers'):
            entry = json.loads(data)
            metadata = {k: entry.get(k) for k in ('title', 'arxiv', 'year', 'venue')}
            metadata.update(id=identifier, paper_id=int(identifier), source_card_available=True)
            dst.execute('INSERT INTO papers VALUES(?,?,?,1)', (identifier, arxiv_id(entry.get('arxiv')), json.dumps(metadata, ensure_ascii=False)))
            paper_count += 1
        if papers_file.exists():
            source_ids = {row[0] for row in dst.execute('SELECT id FROM papers')}
            with papers_file.open() as stream:
                for line in stream:
                    entry = json.loads(line)
                    identifier = str(entry['id'])
                    if identifier not in wanted:
                        continue
                    metadata = {k: entry.get(k) for k in ('title', 'arxiv', 'year', 'abstract')}
                    metadata.update(id=identifier, paper_id=int(identifier), venue=entry.get('conference'), source_card_available=identifier in source_ids)
                    dst.execute('INSERT INTO papers VALUES(?,?,?,0) ON CONFLICT(id) DO UPDATE SET arxiv=excluded.arxiv,data=excluded.data',
                                (identifier, arxiv_id(entry.get('arxiv')), json.dumps(metadata, ensure_ascii=False)))
        # Keep every declared domain member visible, even if the upstream metadata is missing.
        for (identifier,) in dst.execute('SELECT DISTINCT paper_id FROM domain_papers WHERE paper_id NOT IN (SELECT id FROM papers)').fetchall():
            metadata = {'id': identifier, 'paper_id': int(identifier), 'source_card_available': False, 'metadata_available': False}
            dst.execute('INSERT INTO papers VALUES(?,NULL,?,0)', (identifier, json.dumps(metadata)))
        dst.execute('INSERT INTO metadata VALUES(?,?)', ('source', json.dumps(before)))
        dst.execute('INSERT INTO metadata VALUES(?,?)', ('version', INDEX_VERSION))
        dst.commit()
    if before != fingerprint(source):
        temp.unlink()
        raise RuntimeError('Library changed during indexing; retry against a stable snapshot')
    os.replace(temp, output)
    return {'entries': count, 'source_cards': paper_count, 'domain_papers': len(wanted), 'domains': len(catalog),
            'seconds': round(time.monotonic() - start, 2), 'index': str(output)}


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--db', required=True)
    parser.add_argument('--output', required=True)
    parser.add_argument('--domains')
    parser.add_argument('--papers')
    args = parser.parse_args()
    print(json.dumps(build(args.db, args.output, args.domains, args.papers), ensure_ascii=False))