Datasets:
Passages database job script
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165"""Build the phone's passages database for the v2 library (one CPU pod, no embedding).
Input: combined/apoc-combined-v1/ text shards + metadata (unchanged chunk ids).Output: combined/apoc-combined-v2/passages/passages.sqlite.gz + manifest.json.
Schema is the one the Android reader (LibraryDatabase) reads: chunks(id, source_id, unit_path, title, section, text, part) + index (source_id, unit_path, part) sources(id, path, format, digest, native_fts, namespace) settings(key, value JSON) -- fts_mode = "none": keyword search is the v2 Tantivy packWikipedia source ids get the same +1,000,000,000 offset as their chunk ids.Checks: row count, unique ids, every chunk's source present, every v2 vector id present, quick_check.Authorized by Manny on 2026-11-11 ("you can build the app").
python build_passages.py WORK (env HF_TOKEN, DEADLINE_EPOCH)"""import gzip, hashlib, json, os, shutil, sqlite3, subprocess, sys, threading, time, urllib.requestfrom pathlib import Pathimport numpy as np, orjsonfrom huggingface_hub import HfApi
R = 'MannyMorningstar/APOC-embedding'BASE = f'https://huggingface.co/datasets/{R}/resolve/main/'V1, V2 = 'combined/apoc-combined-v1/', 'combined/apoc-combined-v2/'OUT = V2 + 'passages/'STATUS = 'builds/passages-20261111/status.json'WIKI = 1_000_000_000W = Path(sys.argv[1]); W.mkdir(parents=True, exist_ok=True)api = HfApi(token=os.environ.get('HF_TOKEN'))STATE = dict(stage='start', started=time.time(), rows=0)
def publish(): STATE['updated'] = time.time() try: api.upload_file(path_or_fileobj=json.dumps(STATE, indent=1).encode(), path_in_repo=STATUS, repo_id=R, repo_type='dataset', commit_message=f"passages build: {STATE['stage']}") except Exception as e: print('status upload failed', type(e).__name__, flush=True)
def heartbeat(): while STATE['stage'] not in ('done', 'failed'): time.sleep(300) if time.time() > float(os.environ.get('DEADLINE_EPOCH', 'inf')): STATE['stage'] = 'failed'; STATE['error'] = 'deadline'; publish(); os._exit(3) publish()
def url(path): return urllib.request.urlopen(urllib.request.Request(BASE + path, headers={'User-Agent': 'apoc-passages/1.0'}), timeout=900)
def sha256(path): h = hashlib.sha256() with open(path, 'rb') as f: for b in iter(lambda: f.read(1 << 24), b''): h.update(b) return h.hexdigest()
def main(): threading.Thread(target=heartbeat, daemon=True).start() man = json.load(url(V1 + 'manifest.json')); files = {f['path']: f for f in man['files']} db_path = W / 'passages.sqlite' if db_path.exists(): db_path.unlink() db = sqlite3.connect(db_path) for p in ('page_size=8192', 'journal_mode=OFF', 'synchronous=OFF', 'cache_size=-1000000', 'temp_store=MEMORY'): db.execute('PRAGMA ' + p) db.executescript(''' CREATE TABLE sources(id INTEGER PRIMARY KEY, path TEXT NOT NULL, format TEXT NOT NULL, digest TEXT NOT NULL, native_fts INTEGER NOT NULL, namespace TEXT NOT NULL); CREATE TABLE chunks(id INTEGER PRIMARY KEY, source_id INTEGER NOT NULL, unit_path TEXT NOT NULL, title TEXT NOT NULL, section TEXT NOT NULL, text TEXT NOT NULL, part INTEGER NOT NULL); CREATE TABLE settings(key TEXT PRIMARY KEY, value TEXT NOT NULL);''')
STATE['stage'] = 'metadata'; publish() meta = W / 'metadata.jsonl.gz' with url(V1 + 'metadata.jsonl.gz') as r, open(meta, 'wb') as f: shutil.copyfileobj(r, f, 1 << 24) assert sha256(meta) == files['metadata.jsonl.gz']['sha256'], 'metadata checksum' n_src = 0 for line in gzip.open(meta, 'rt'): d = json.loads(line) if d['table'] != 'sources': continue s = d['row']; off = WIKI if d['namespace'] == 'wikipedia' else 0 db.execute('INSERT INTO sources VALUES(?,?,?,?,?,?)', (s['id'] + off, os.path.basename(s['path']), s['format'], s['digest'], int(s.get('native_fts') or 0), d['namespace'])) n_src += 1 STATE['sources'] = n_src
STATE['stage'] = 'chunks'; publish() shards = sorted(p for p in files if p.startswith('chunks-')) for sh in shards: h = hashlib.sha256(); rows = [] class Tee: # hash the compressed bytes while gunzip reads them def __init__(s, r): s.r = r def read(s, n=-1): b = s.r.read(n); h.update(b); return b with url(V1 + sh) as r: for line in gzip.GzipFile(fileobj=Tee(r)): c = orjson.loads(line) sid = c['source_id'] + (WIKI if c.get('namespace') == 'wikipedia' else 0) rows.append((c['id'], sid, c['unit_path'], c['title'], c['section'], c['text'], c['part'])) if len(rows) >= 200_000: db.executemany('INSERT INTO chunks VALUES(?,?,?,?,?,?,?)', rows); STATE['rows'] += len(rows); rows = [] rest = r.read() h.update(rest) if rows: db.executemany('INSERT INTO chunks VALUES(?,?,?,?,?,?,?)', rows); STATE['rows'] += len(rows) db.commit() assert h.hexdigest() == files[sh]['sha256'], f'{sh} checksum' STATE.setdefault('shards_done', []).append(sh); print(sh, STATE['rows'], flush=True); publish()
STATE['stage'] = 'index'; publish() db.execute('CREATE INDEX chunks_unit ON chunks(source_id, unit_path, part)') total = db.execute('SELECT count(*) FROM chunks').fetchone()[0] assert total == man['chunk_count'] == int(os.environ.get('EXPECT_ROWS', '24825562')), total orphans = db.execute('SELECT count(*) FROM chunks c LEFT JOIN sources s ON s.id=c.source_id WHERE s.id IS NULL').fetchone()[0] assert orphans == 0, f'{orphans} chunks without a source' STATE['stage'] = 'check_v2_ids'; publish() ids_path = W / 'ids.npy' with url(V2 + 'ann/ids.npy') as r, open(ids_path, 'wb') as f: shutil.copyfileobj(r, f, 1 << 24) ids = np.load(ids_path) assert len(ids) == total and len(np.unique(ids)) == total db.execute('CREATE TEMP TABLE v2(id INTEGER PRIMARY KEY)') db.executemany('INSERT INTO v2 VALUES(?)', ((int(i),) for i in ids)) missing = db.execute('SELECT count(*) FROM v2 LEFT JOIN chunks c ON c.id=v2.id WHERE c.id IS NULL').fetchone()[0] assert missing == 0, f'{missing} v2 ids not in passages' db.execute('DROP TABLE v2') settings = dict(fts_mode='none', format='apoc-passages-v1', library='combined/apoc-combined-v2', chunk_count=total, text_source=V1, text_manifest_sha256=hashlib.sha256(json.dumps(man, sort_keys=True).encode()).hexdigest(), id_namespaces=dict(library=0, wikipedia=WIKI), built=time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())) db.executemany('INSERT INTO settings VALUES(?,?)', ((k, json.dumps(v)) for k, v in settings.items())) db.commit(); db.execute('ANALYZE'); db.commit() assert db.execute('PRAGMA quick_check').fetchone()[0] == 'ok' db.execute('PRAGMA journal_mode=DELETE'); db.close() STATE.update(stage='compress', unpacked_bytes=db_path.stat().st_size); publish() unpacked_sha = sha256(db_path) gz = W / 'passages.sqlite.gz' if shutil.which('pigz'): subprocess.run(f'pigz -6 -p {os.environ.get("THREADS", "8")} -c {db_path} > {gz}', shell=True, check=True) else: with open(db_path, 'rb') as src, gzip.open(gz, 'wb', 6) as dst: shutil.copyfileobj(src, dst, 1 << 24) STATE['stage'] = 'upload'; publish() manifest = dict(format='apoc-passages-v1', chunk_count=total, sources=n_src, schema='chunks/sources/settings, index chunks_unit; fts_mode none', files=[dict(path='passages.sqlite.gz', bytes=gz.stat().st_size, sha256=sha256(gz), unpacked_bytes=db_path.stat().st_size, unpacked_sha256=unpacked_sha)], checks=dict(rows=total, orphan_chunks=0, v2_ids_missing=0, quick_check='ok'), settings=settings) (W / 'manifest.json').write_text(json.dumps(manifest, indent=1)) api.upload_file(path_or_fileobj=str(gz), path_in_repo=OUT + 'passages.sqlite.gz', repo_id=R, repo_type='dataset', commit_message='Passages database for the phone (v2 library)') api.upload_file(path_or_fileobj=str(W / 'manifest.json'), path_in_repo=OUT + 'manifest.json', repo_id=R, repo_type='dataset', commit_message='Passages database manifest') remote = {x.path: x for x in api.get_paths_info(R, [OUT + 'passages.sqlite.gz'], repo_type='dataset')} assert remote[OUT + 'passages.sqlite.gz'].lfs.sha256 == manifest['files'][0]['sha256'], 'remote checksum' STATE.update(stage='done', manifest=manifest); publish(); print('done', json.dumps(manifest), flush=True)
if __name__ == '__main__': try: main() except Exception as e: STATE.update(stage='failed', error=f'{type(e).__name__}: {e}'); publish(); raisebuilds/passages-20261111/build_passages.pyAdded+165