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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
"""
|
| 4 |
+
Offline builder for single JSONL visit DB (SQLite offset index).
|
| 5 |
+
|
| 6 |
+
Input JSONL (one JSON object per line):
|
| 7 |
+
{"title": "...", "caption": "...", "text": "..."} # text required for visit
|
| 8 |
+
|
| 9 |
+
This builds a SQLite DB that maps:
|
| 10 |
+
title -> offset (byte offset of the line in the JSONL file)
|
| 11 |
+
|
| 12 |
+
Online visit can return the first match or top-k matches.
|
| 13 |
+
|
| 14 |
+
Usage:
|
| 15 |
+
python /data/workspace/tool/visit_bulid_sql.py \
|
| 16 |
+
--jsonl /data/workspace/wiki_simulator/wcx/wiki/output/wikiextractor_v1.jsonl \
|
| 17 |
+
--db /data/workspace/tool/visit_sqlite/visit_offsets.sqlite
|
| 18 |
+
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
import os
|
| 23 |
+
import sqlite3
|
| 24 |
+
import sys
|
| 25 |
+
from typing import Any, Dict, List, Optional, Tuple
|
| 26 |
+
|
| 27 |
+
# Fast JSON if available
|
| 28 |
+
try:
|
| 29 |
+
import orjson as _json # type: ignore
|
| 30 |
+
|
| 31 |
+
def json_loads(b: bytes):
|
| 32 |
+
return _json.loads(b)
|
| 33 |
+
except Exception:
|
| 34 |
+
import json as _json # type: ignore
|
| 35 |
+
|
| 36 |
+
def json_loads(b: bytes):
|
| 37 |
+
return _json.loads(b.decode("utf-8", errors="replace"))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _as_str(x: Any) -> str:
|
| 41 |
+
if x is None:
|
| 42 |
+
return ""
|
| 43 |
+
if isinstance(x, str):
|
| 44 |
+
return x
|
| 45 |
+
return str(x)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
SCHEMA_SQL = """
|
| 49 |
+
CREATE TABLE IF NOT EXISTS meta (
|
| 50 |
+
k TEXT PRIMARY KEY,
|
| 51 |
+
v TEXT NOT NULL
|
| 52 |
+
);
|
| 53 |
+
|
| 54 |
+
-- allow duplicates
|
| 55 |
+
CREATE TABLE IF NOT EXISTS offsets (
|
| 56 |
+
keyword TEXT NOT NULL,
|
| 57 |
+
offset INTEGER NOT NULL
|
| 58 |
+
);
|
| 59 |
+
|
| 60 |
+
CREATE INDEX IF NOT EXISTS idx_offsets_keyword ON offsets(keyword);
|
| 61 |
+
CREATE INDEX IF NOT EXISTS idx_offsets_offset ON offsets(offset);
|
| 62 |
+
"""
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def connect_db(db_path: str) -> sqlite3.Connection:
|
| 66 |
+
conn = sqlite3.connect(db_path)
|
| 67 |
+
conn.execute("PRAGMA journal_mode=WAL;")
|
| 68 |
+
conn.execute("PRAGMA synchronous=NORMAL;")
|
| 69 |
+
conn.execute("PRAGMA temp_store=MEMORY;")
|
| 70 |
+
conn.execute("PRAGMA cache_size=-200000;") # ~200MB best effort
|
| 71 |
+
return conn
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _file_fingerprint(path: str) -> Tuple[str, str]:
|
| 75 |
+
st = os.stat(path)
|
| 76 |
+
return (str(st.st_size), str(getattr(st, "st_mtime_ns", int(st.st_mtime * 1e9))))
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def set_meta(conn: sqlite3.Connection, k: str, v: str) -> None:
|
| 80 |
+
conn.execute("INSERT OR REPLACE INTO meta(k, v) VALUES (?, ?)", (k, v))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def main():
|
| 84 |
+
ap = argparse.ArgumentParser()
|
| 85 |
+
ap.add_argument("--jsonl", required=True, help="Single JSONL file path")
|
| 86 |
+
ap.add_argument("--db", required=True, help="Output sqlite DB path")
|
| 87 |
+
ap.add_argument("--keyword-field", default="title", help="Field name for keyword/title")
|
| 88 |
+
ap.add_argument("--require-text-field", default="text", help="Require this field to be non-null")
|
| 89 |
+
ap.add_argument("--batch-size", type=int, default=100000, help="SQLite insert batch size")
|
| 90 |
+
args = ap.parse_args()
|
| 91 |
+
|
| 92 |
+
jsonl_path = os.path.abspath(args.jsonl)
|
| 93 |
+
db_path = os.path.abspath(args.db)
|
| 94 |
+
|
| 95 |
+
if not os.path.exists(jsonl_path):
|
| 96 |
+
raise FileNotFoundError(jsonl_path)
|
| 97 |
+
|
| 98 |
+
os.makedirs(os.path.dirname(db_path) or ".", exist_ok=True)
|
| 99 |
+
|
| 100 |
+
conn = connect_db(db_path)
|
| 101 |
+
conn.executescript(SCHEMA_SQL)
|
| 102 |
+
|
| 103 |
+
# record fingerprint so online visit can detect mismatch
|
| 104 |
+
size, mtime_ns = _file_fingerprint(jsonl_path)
|
| 105 |
+
set_meta(conn, "jsonl_path", jsonl_path)
|
| 106 |
+
set_meta(conn, "jsonl_size", size)
|
| 107 |
+
set_meta(conn, "jsonl_mtime_ns", mtime_ns)
|
| 108 |
+
set_meta(conn, "keyword_field", args.keyword_field)
|
| 109 |
+
set_meta(conn, "text_field", args.require_text_field)
|
| 110 |
+
|
| 111 |
+
# rebuild offsets from scratch
|
| 112 |
+
conn.execute("DELETE FROM offsets;")
|
| 113 |
+
conn.commit()
|
| 114 |
+
|
| 115 |
+
insert_sql = "INSERT INTO offsets(keyword, offset) VALUES (?, ?)"
|
| 116 |
+
cur = conn.cursor()
|
| 117 |
+
|
| 118 |
+
total = 0
|
| 119 |
+
bad_json = 0
|
| 120 |
+
missing_kw = 0
|
| 121 |
+
missing_text = 0
|
| 122 |
+
|
| 123 |
+
buf: List[Tuple[str, int]] = []
|
| 124 |
+
|
| 125 |
+
with open(jsonl_path, "rb") as f:
|
| 126 |
+
while True:
|
| 127 |
+
offset = f.tell()
|
| 128 |
+
line = f.readline()
|
| 129 |
+
if not line:
|
| 130 |
+
break
|
| 131 |
+
line = line.strip()
|
| 132 |
+
if not line:
|
| 133 |
+
continue
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
obj: Dict[str, Any] = json_loads(line)
|
| 137 |
+
except Exception:
|
| 138 |
+
bad_json += 1
|
| 139 |
+
continue
|
| 140 |
+
|
| 141 |
+
kw = _as_str(obj.get(args.keyword_field)).strip()
|
| 142 |
+
if not kw:
|
| 143 |
+
missing_kw += 1
|
| 144 |
+
continue
|
| 145 |
+
|
| 146 |
+
if args.require_text_field:
|
| 147 |
+
if obj.get(args.require_text_field) is None:
|
| 148 |
+
missing_text += 1
|
| 149 |
+
continue
|
| 150 |
+
|
| 151 |
+
buf.append((kw, offset))
|
| 152 |
+
total += 1
|
| 153 |
+
|
| 154 |
+
if len(buf) >= args.batch_size:
|
| 155 |
+
cur.executemany(insert_sql, buf)
|
| 156 |
+
conn.commit()
|
| 157 |
+
buf.clear()
|
| 158 |
+
|
| 159 |
+
if buf:
|
| 160 |
+
cur.executemany(insert_sql, buf)
|
| 161 |
+
conn.commit()
|
| 162 |
+
buf.clear()
|
| 163 |
+
|
| 164 |
+
conn.execute("ANALYZE;")
|
| 165 |
+
conn.commit()
|
| 166 |
+
conn.close()
|
| 167 |
+
|
| 168 |
+
print(
|
| 169 |
+
"Build done.\n"
|
| 170 |
+
f" jsonl={jsonl_path}\n"
|
| 171 |
+
f" db={db_path}\n"
|
| 172 |
+
f" indexed={total}\n"
|
| 173 |
+
f" bad_json={bad_json}\n"
|
| 174 |
+
f" missing_keyword={missing_kw}\n"
|
| 175 |
+
f" missing_text={missing_text}",
|
| 176 |
+
file=sys.stderr,
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
if __name__ == "__main__":
|
| 181 |
+
main()
|