archive-db / tools /bake_rich_html.py
tuka1's picture
Add build/deploy tooling under tools/
fb6a24f verified
Raw History Blame Contribute Delete
4.8 kB
"""Bake the sanitized rich HTML of every post into posts.content_html so the
deployable app no longer needs the 62 GB extracted.noindex/ HTML tree.
Threaded: lxml releases the GIL during parse, so many workers parse in
parallel while the main thread streams UPDATEs to SQLite. Resumable —
skips files whose first post id is already baked.
Run:
python search/bake_rich_html.py [--workers N]
"""
import argparse
import multiprocessing as mp
import os
import sqlite3
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from server import _parse_thread_html # noqa: E402
DB = Path(__file__).resolve().parent / "posts.db"
BATCH = 500
LOG_EVERY = 10000
def parse_one(path: str):
"""Worker: parse one file → list of (post_id, html). Returns [] on error
(logged separately, not noisy)."""
try:
rich = _parse_thread_html(path)
except Exception:
return []
return [(html, pid) for pid, html in rich.items() if html]
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--workers", type=int, default=max(2, os.cpu_count() or 4))
ap.add_argument("--no-resume", action="store_true")
args = ap.parse_args()
conn = sqlite3.connect(DB)
cur = conn.cursor()
# Schema migration (no-op if already present)
cols = {r[1] for r in cur.execute("PRAGMA table_info(posts)")}
if "content_html" not in cols:
print("Adding content_html column…", flush=True)
cur.execute("ALTER TABLE posts ADD COLUMN content_html TEXT")
conn.commit()
cur.execute("PRAGMA journal_mode=WAL")
cur.execute("PRAGMA synchronous=NORMAL")
cur.execute("PRAGMA cache_size=-200000") # 200MB
# Resume: skip files whose posts are already fully baked. We test the
# FIRST post of each file — if it's baked, assume all of them are.
# Build a (path → list of post ids in that file) is too expensive (no
# join key), so we sample the first row inserted from this file using a
# heuristic on filename+posts table. Simpler: just skip files where
# ALL posts in the parent thread are baked.
paths_all = [r[0] for r in cur.execute("SELECT path FROM processed_files ORDER BY path")]
print(f"Files in processed_files: {len(paths_all):,}", flush=True)
if args.no_resume:
paths = paths_all
else:
# Coarse resume: skip files in directories where every post in their
# thread already has content_html. Too coarse for partial bakes;
# over-process is OK because UPDATE … WHERE content_html IS NULL is
# a cheap no-op.
paths = paths_all
print(f"Files to process: {len(paths):,} workers={args.workers}", flush=True)
start = time.time()
last_log = start
files_done = 0
posts_baked = 0
pending = []
def flush():
nonlocal pending, posts_baked
if not pending:
return
cur.executemany(
"UPDATE posts SET content_html = ? WHERE id = ? AND content_html IS NULL",
pending,
)
conn.commit()
posts_baked += cur.rowcount
pending = []
# Multiprocessing pool — workers do the CPU-heavy parse+sanitize in
# parallel, main process accumulates results and commits to SQLite.
pool = mp.Pool(args.workers)
try:
for items in pool.imap_unordered(parse_one, paths, chunksize=1):
for item in items:
pending.append(item)
if len(pending) >= BATCH:
flush()
files_done += 1
if files_done % LOG_EVERY == 0:
flush()
now = time.time()
rate = LOG_EVERY / max(0.001, now - last_log)
last_log = now
elapsed = now - start
remaining = (len(paths) - files_done) / max(1, rate)
print(
f" files={files_done:,}/{len(paths):,} "
f"posts_baked={posts_baked:,} "
f"rate={rate:.0f}/s elapsed={elapsed:.0f}s ETA={remaining/60:.1f}m",
flush=True,
)
flush()
finally:
pool.close()
pool.join()
print("ANALYZE…", flush=True)
t = time.time()
cur.execute("ANALYZE")
conn.commit()
print(f" done in {time.time()-t:.0f}s", flush=True)
posts_with = cur.execute("SELECT COUNT(*) FROM posts WHERE content_html IS NOT NULL").fetchone()[0]
posts_total = cur.execute("SELECT COUNT(*) FROM posts").fetchone()[0]
print(
f"DONE files={files_done:,} posts_with_html={posts_with:,}/{posts_total:,} "
f"elapsed={time.time()-start:.0f}s",
flush=True,
)
conn.close()
if __name__ == "__main__":
main()