File size: 4,977 Bytes
3ecfdc7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Offline builder for single JSONL visit DB (SQLite offset index).

Input JSONL (one JSON object per line):
  {"title": "...", "caption": "...", "text": "..."}  # text required for visit

This builds a SQLite DB that maps:
  title -> offset (byte offset of the line in the JSONL file)

Online visit can return the first match or top-k matches.

Usage:
python /data/workspace/tool/visit_bulid_sql.py \
  --jsonl /data/workspace/wiki_simulator/wcx/wiki/output/wikiextractor_v1.jsonl \
  --db /data/workspace/tool/visit_sqlite/visit_offsets.sqlite

"""

import argparse
import os
import sqlite3
import sys
from typing import Any, Dict, List, Optional, Tuple

# Fast JSON if available
try:
    import orjson as _json  # type: ignore

    def json_loads(b: bytes):
        return _json.loads(b)
except Exception:
    import json as _json  # type: ignore

    def json_loads(b: bytes):
        return _json.loads(b.decode("utf-8", errors="replace"))


def _as_str(x: Any) -> str:
    if x is None:
        return ""
    if isinstance(x, str):
        return x
    return str(x)


SCHEMA_SQL = """
CREATE TABLE IF NOT EXISTS meta (
  k TEXT PRIMARY KEY,
  v TEXT NOT NULL
);

-- allow duplicates
CREATE TABLE IF NOT EXISTS offsets (
  keyword TEXT NOT NULL,
  offset  INTEGER NOT NULL
);

CREATE INDEX IF NOT EXISTS idx_offsets_keyword ON offsets(keyword);
CREATE INDEX IF NOT EXISTS idx_offsets_offset ON offsets(offset);
"""


def connect_db(db_path: str) -> sqlite3.Connection:
    conn = sqlite3.connect(db_path)
    conn.execute("PRAGMA journal_mode=WAL;")
    conn.execute("PRAGMA synchronous=NORMAL;")
    conn.execute("PRAGMA temp_store=MEMORY;")
    conn.execute("PRAGMA cache_size=-200000;")  # ~200MB best effort
    return conn


def _file_fingerprint(path: str) -> Tuple[str, str]:
    st = os.stat(path)
    return (str(st.st_size), str(getattr(st, "st_mtime_ns", int(st.st_mtime * 1e9))))


def set_meta(conn: sqlite3.Connection, k: str, v: str) -> None:
    conn.execute("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)", (k, v))


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--jsonl", required=True, help="Single JSONL file path")
    ap.add_argument("--db", required=True, help="Output sqlite DB path")
    ap.add_argument("--keyword-field", default="title", help="Field name for keyword/title")
    ap.add_argument("--require-text-field", default="text", help="Require this field to be non-null")
    ap.add_argument("--batch-size", type=int, default=100000, help="SQLite insert batch size")
    args = ap.parse_args()

    jsonl_path = os.path.abspath(args.jsonl)
    db_path = os.path.abspath(args.db)

    if not os.path.exists(jsonl_path):
        raise FileNotFoundError(jsonl_path)

    os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)

    conn = connect_db(db_path)
    conn.executescript(SCHEMA_SQL)

    # record fingerprint so online visit can detect mismatch
    size, mtime_ns = _file_fingerprint(jsonl_path)
    set_meta(conn, "jsonl_path", jsonl_path)
    set_meta(conn, "jsonl_size", size)
    set_meta(conn, "jsonl_mtime_ns", mtime_ns)
    set_meta(conn, "keyword_field", args.keyword_field)
    set_meta(conn, "text_field", args.require_text_field)

    # rebuild offsets from scratch
    conn.execute("DELETE FROM offsets;")
    conn.commit()

    insert_sql = "INSERT INTO offsets(keyword, offset) VALUES (?, ?)"
    cur = conn.cursor()

    total = 0
    bad_json = 0
    missing_kw = 0
    missing_text = 0

    buf: List[Tuple[str, int]] = []

    with open(jsonl_path, "rb") as f:
        while True:
            offset = f.tell()
            line = f.readline()
            if not line:
                break
            line = line.strip()
            if not line:
                continue

            try:
                obj: Dict[str, Any] = json_loads(line)
            except Exception:
                bad_json += 1
                continue

            kw = _as_str(obj.get(args.keyword_field)).strip()
            if not kw:
                missing_kw += 1
                continue

            if args.require_text_field:
                if obj.get(args.require_text_field) is None:
                    missing_text += 1
                    continue

            buf.append((kw, offset))
            total += 1

            if len(buf) >= args.batch_size:
                cur.executemany(insert_sql, buf)
                conn.commit()
                buf.clear()

    if buf:
        cur.executemany(insert_sql, buf)
        conn.commit()
        buf.clear()

    conn.execute("ANALYZE;")
    conn.commit()
    conn.close()

    print(
        "Build done.\n"
        f"  jsonl={jsonl_path}\n"
        f"  db={db_path}\n"
        f"  indexed={total}\n"
        f"  bad_json={bad_json}\n"
        f"  missing_keyword={missing_kw}\n"
        f"  missing_text={missing_text}",
        file=sys.stderr,
    )


if __name__ == "__main__":
    main()