Download visit_sqlite/visit_bulid_sql.py from Ornamentt/DeepSearch-World-Env: direct link, hf CLI and curl.
- Browser
- Download file 4.98 kB
-
https://huggingface.co/datasets/Ornamentt/DeepSearch-World-Env/resolve/main/visit_sqlite/visit_bulid_sql.py
- Command line
-
hf download hf://datasets/Ornamentt/DeepSearch-World-Env/visit_sqlite/visit_bulid_sql.py
-
curl -L -o visit_bulid_sql.py https://huggingface.co/datasets/Ornamentt/DeepSearch-World-Env/resolve/main/visit_sqlite/visit_bulid_sql.py
4.98 kB
| #!/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() | |