Add build/deploy tooling under tools/
Browse filesFiles changed (16)
- tools/.dockerignoreAdded+30
- tools/BUILD.mdAdded+81
- tools/DEPLOY.mdAdded+135
- tools/DockerfileAdded+67
- tools/README.mdAdded+53
- tools/bake_rich_html.pyAdded+140
- tools/build_index.pyAdded+538
- tools/deploy.shAdded+175
- tools/populate_forum_names.pyAdded+66
- tools/predeploy.shAdded+121
- tools/requirements.txtAdded+7
- tools/static/favicon.icoAdded
- tools/static/index.htmlAdded
- tools/static/logo.pngAdded
- tools/tests/smoke.pyAdded+227
- tools/tests/test_parsers.pyAdded+326
123456789101112131415161718192021222324252627282930# Secrets โ never bake into image.env*.env
# Build / parse logsbuild.logbake.logserver.logserver_test.log
# Local test artifactsposts_test.db*posts.db-walposts.db-shm
# Python noise__pycache__/*.pyc*.pyo
# OS.DS_Store
# Indexer / maintenance scripts not needed at runtimebuild_index.pybake_rich_html.pypopulate_forum_names.py
# NotesREADME.local.md123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081# gamer2 archive โ search
Fast full-text search over the ~246K forum threads archived in`../gamer2/static/gamer2/archive/extracted.noindex/`.
* **Indexer** โ `build_index.py` parses every thread HTML into a SQLite FTS5 database (`posts.db`).* **API** โ `server.py` (FastAPI) exposes `/api/search`, `/api/thread/{id}`, `/api/forums`, `/api/users/search`, `/api/stats`.* **UI** โ `static/index.html` is a single-page Tailwind app served at `/`. Live search, snippet highlighting, RTL Hebrew, dark theme, thread drawer.
## Setup
```shpip install fastapi 'uvicorn[standard]' beautifulsoup4 html5lib python-dateutil```
## Build the index
```sh# small test runpython search/build_index.py --limit 500 --db search/posts_test.db
# full run (~2 hours on M1, 9 workers, ~2-3 GB DB)python search/build_index.py```
Re-runnable โ `INSERT OR REPLACE` lets you re-index a subset without rebuilding.
## Backfill forum names (only needed if you indexed with an old build)
```shpython search/populate_forum_names.py```
The current `build_index.py` already extracts forum names from the pagebreadcrumb, so this script is only needed for DBs built before that change.
## Run the UI
```shpython -m uvicorn search.server:app --host 127.0.0.1 --port 8765open http://127.0.0.1:8765/```
Override the DB path with `GAMER_DB=/path/to/posts.db`.
## Search syntax
FTS5 โ each whitespace-separated token is wrapped in `"โฆ"` server-side soarbitrary punctuation (Hebrew, apostrophes, etc.) is safe. Effective behavior:
* `ืงืืื ืืจ ืกืืจืืืง` โ matches posts containing both phrases* `Counter Strike` โ same, English* Single word โ straight token match
Boolean operators (`OR`, `NOT`, `*`, `^`) are *not* exposed because user inputis quoted; this is a deliberate tradeoff for safety. Drop the quoting in`server.py:escape_fts` if you want raw FTS5.
## Schema
```threads(id, name, forum_id, archive, file_path)forums(id, name)users(id, nick, location)posts(id, thread_id, author_id, idx, created_at, content)posts_fts USING fts5(content, author_nick UNINDEXED, thread_name, tokenize='unicode61 remove_diacritics 2')```
Three indexes on `posts` (thread+idx, author, created_at) keep filter queriesfast even without the FTS path.
## Performance notes
* FTS5 queries return in <5 ms over 1-2M posts.* Initial parse is CPU-bound โ the indexer uses a multiprocessing pool sized to `cpu_count - 1` and commits in batches of 200 threads.* DB uses WAL so the UI can serve reads while you re-index.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135# Deploy runbook
This Space is `gamer-forums/archive` on HF, served at**https://gamer-forums-archive.hf.space**. The DB (24 GB) lives inthe dataset repo `gamer-forums/archive-db` as 11 zstd chunks; theDockerfile fetches + reassembles them at image-build time.
## TL;DR โ the one command
```bashcd search && set -a && source .env && set +a && ./deploy.sh push gamer-forums/archive```
That runs the full deploy pipeline:
1. **Predeploy gate** โ `predeploy.sh`: - syntax + import check on `server.py` - `tests/test_parsers.py` โ 54 unit assertions on the parsers - chmod-0444 `posts.db`, boot test server on :8799, `tests/smoke.py` โ 19 endpoint smoke tests against the RO DB2. **Stage** โ copies the slim bundle (~37 MB) into `_deploy/`3. **Upload with retry+verify** โ retries up to 3ร on HF flake; between retries it checks the git-log API to detect whether a "client 500" actually committed server-side (HF's commit API loses the ack but persists the commit; we skip the retry in that case)4. **Post-deploy verification** โ polls `hf spaces info` until the new sha is in stage `RUNNING`, then curls `/api/stats` to confirm it's truly serving. 12-minute timeout.
You see one report at the end: `โ Live: https://โฆ (sha XXX)`.If anything between predeploy and post-deploy verify fails, thescript aborts with a clear message; nothing is half-shipped.
## Symptoms โ causes โ fixes
### "500 Internal Server Error" from `hf upload`HF's commit API flakes intermittently. **The commit usually succeededserver-side anyway** โ check:```bashcurl -s -H "Authorization: Bearer $HF_TOKEN" \ https://huggingface.co/api/spaces/gamer-forums/archive/commits/main?limit=3 \ | python3 -m json.tool```If the latest commit title matches what you tried to push, you're done.Otherwise re-run the upload โ `hf upload` is idempotent (skips unchangedfiles, no harm in re-running).
### `hf spaces restart` reused the OLD image**Restart != rebuild.** Restart restarts the *currently deployed* image.If you want HF to pull the latest commit and rebuild, you need either:- a fresh push with a real diff, **or**- `hf spaces restart gamer-forums/archive --factory-reboot` (clean rebuild from latest commit, takes ~5-10 min)
### `stage: RUNNING_APP_STARTING` for >10 minHF infra being slow. Old container is still serving in the meantime(no user-visible downtime unless old code is broken). Patience usuallywins; if not, `--factory-reboot` forces it.
### `"No space_sdk provided"` from upload-large-folderKnown HF CLI bug โ `hf upload-large-folder` calls `create_repo`without `space_sdk` even when the Space exists. **`deploy.sh` usesplain `hf upload` instead**; if you ever call upload-large-foldermanually for a Space, swap to `hf upload`.
### `sqlite3.OperationalError: attempt to write a readonly database`Anything that needs to write to the DB file (PRAGMA cache_size,WAL lock files, journal mode change) fails in prod where posts.dbis owned by root and the app runs as user.- DB is opened with `?immutable=1` (skips locking entirely)- Best-effort PRAGMAs are wrapped in `try/except sqlite3.OperationalError`- **The predeploy gate** runs the server against a `chmod 0444` posts.db, so any new "attempt to write" bug shows up locally before we push.
### "Everything is broken on the Space right after I pushed"Could be the 5-30 s window where HF stopped the old container andthe new one isn't healthchecked yet. Frontend already has aretry-on-5xx wrapper around `fetch('/api/*')` that backs off0.5/1.5/3.5 s โ usually invisible to the user. If a 500 persistspast 30 s, the new code probably crashes on startup โ check`hf spaces logs gamer-forums/archive --tail 30`.
## Layer caching โ DO NOT bust the 24 GB DB layerThe Dockerfile is ordered so `RUN snapshot_download โฆ` (the slow24 GB step) comes BEFORE the small app COPYs. As long as you don'tchange `DB_REPO` / `DB_REVISION` or re-upload the dataset chunks,that layer stays cached and rebuilds take ~3 min instead of ~15.
Things that WILL invalidate the DB layer (avoid casually):- changing `DB_REPO` ARG in Dockerfile- changing `DB_REVISION` ARG- re-uploading any `posts.db.zst.*` chunk to the dataset repo- `apt-get install` line above the RUN- `pip install` from a changed `requirements.txt`
## Architecture cheat sheet
```Space (gamer-forums/archive) โโโโโโโโโโโโ app + static assets, 37 MB โโ Dockerfile RUN snapshot_download(โฆ) โ fetches posts.db.zst.* โ at IMAGE-BUILD time, not runtimeDataset (gamer-forums/archive-db) โโโโโโโโ 11 ร ~500 MB zstd chunks posts.db.zst.aa, .ab, โฆ, .ak (~5.1 GB total compressed, 24 GB decompressed)```
Why split into chunks: single-PUT LFS uploads of multi-GB fileswere timing out at the S3 layer over the residential upstream;500 MB pieces upload reliably and the Dockerfile reassembles themwith `cat | zstd -d`.
## Authentication
- `search/.env` has `HF_TOKEN=hf_โฆ` (chmod 600, gitignored)- Token needs **Write** scope, including write access to the `gamer-forums` org (fine-grained tokens with only personal-namespace write will 403 on org repo operations)- `set -a && source .env && set +a` exports HF_TOKEN so subprocesses (including `hf` CLI) see it. Plain `source .env` only sets shell variables, not environment, and the CLI won't see them.
## Smoke tests
`tests/smoke.py` hits every API endpoint and asserts 200 + valid JSON.`predeploy.sh` runs it against a chmod-0444 posts.db on port 8799.Add new endpoint tests there when you add new routes โ the gate isonly as good as its coverage.
Skip the gate (for a quick frontend-only change you trust):```bashPREDEPLOY_SKIP=1 ./deploy.sh push gamer-forums/archive```But really, don't.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# gamer.co.il archive search โ Hugging Face Spaces (Docker SDK)## Layout at runtime:# - server.py + static/ (app, shipped in the Space repo)# - avatars/ (~36 MB, shipped in the Space repo)# - forum_emojis/ (~120 KB, shipped in the Space repo)# - posts.db (~24 GB, fetched from a separate HF Dataset# repo at image-build time โ the Space repo# free-tier cap is 1 GB so the DB cannot live# alongside the app)## Layer order is tuned for HF's build cache: everything stable comes first,# small volatile things (app code) last. Editing server.py only re-runs# the COPY layer, not the 24 GB DB fetch or the chown.## Read-only at request time; no writes happen at runtime.
FROM python:3.11-slim
ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PIP_DISABLE_PIP_VERSION_CHECK=1 \ PIP_NO_CACHE_DIR=1
# zstd: <1 MB, used to decompress the chunked DB.RUN apt-get update && apt-get install -y --no-install-recommends zstd \ && rm -rf /var/lib/apt/lists/*
WORKDIR /app
# 1. Dependencies โ cached unless requirements.txt changes.COPY requirements.txt .RUN pip install -r requirements.txt
# 2. The big DB layer โ cached unless DB_REPO / DB_REVISION changes.# Pull the chunked, zstd-compressed posts.db from the dataset repo and# reassemble. Files end up readable by everyone (default 0644) so the# non-root user added below doesn't need them chowned.ARG DB_REPO=gamer-forums/archive-dbARG DB_REVISION=mainRUN python -c "from huggingface_hub import snapshot_download; \snapshot_download(repo_id='${DB_REPO}', repo_type='dataset', revision='${DB_REVISION}', \ local_dir='/tmp/db-chunks', allow_patterns=['posts.db.zst.*'])" \ && cat /tmp/db-chunks/posts.db.zst.* | zstd -d -o /app/posts.db \ && rm -rf /tmp/db-chunks \ && chmod 0644 /app/posts.db \ && ls -lh /app/posts.db
# 3. Non-root user โ created BEFORE the small app COPYs so chown is fast.RUN useradd -m -u 1000 user
# 4. Small static assets โ only re-copied if the dirs change.COPY --chown=user:user avatars/ ./avatars/COPY --chown=user:user forum_emojis/ ./forum_emojis/
# 5. App code last โ frequent edits only re-run these tiny COPYs.COPY --chown=user:user static/ ./static/COPY --chown=user:user server.py .
ENV GAMER_DB=/app/posts.db \ GAMER_AVATARS=/app/avatars \ GAMER_EMOJIS=/app/forum_emojis
EXPOSE 7860USER user
CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253---title: gamer.co.il archiveemoji: ๐colorFrom: purplecolorTo: indigosdk: dockerapp_port: 7860pinned: falselicense: mitshort_description: Searchable archive of forums.gamer.co.il (2004-2014)---
# gamer.co.il forum archive
Full-text search over **10 million posts** from the[forums.gamer.co.il](https://archive.org/details/forums.gamer.co.il) gamingforums (2004 โ 2014), pulled from the[archive.org dump](https://archive.org/details/forums.gamer.co.il) and re-indexedinto a single self-contained SQLite FTS5 database.
## What's in here
- **546K threads** across **173 forums**- **49K distinct users** with avatars, locations, post counts, and per-post ranks- Original rich-HTML rendering: quotes, formatting, smileys, spoilers- Click-to-jump-to-quoted-message, click-to-filter-by-author, etc.
## Special search syntax
Combine free-text search with structured filters:
| Token | Meaning || --- | --- || `ืืืจืื>80` / `ืืืจืื<10` / `ืืืจืื=100` | Filter by post star rating % || `ืืื:ืืืืืื` / `ืืื:ืฉื ืืืื` | Sort by best- / worst-rated || `ืฉื ื:2014` | Posts from one year || `ืคืืจืื:13` | Posts in one forum || `ืืืืขื:1` | First post in each thread only |
Examples:- `ืืื:ืืืืืื ืฉื ื:2010` โ best-rated posts of 2010- `ืืืจืื=100 ืืืืขื:1` โ opening posts that got a perfect rating- `ืืืฉื ืคืืจืื:11` โ anything about computers in the hardware forum
## Tech
- FastAPI + SQLite FTS5 + a Tailwind single-page UI (no build step)- Indexer + bake scripts in `BUILD.md` for re-building from raw HTML
## Credits
Archive content ยฉ original posters, scraped + preserved by the Internet Archive.This project is non-commercial and offered as a community resource.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140"""Bake the sanitized rich HTML of every post into posts.content_html so thedeployable app no longer needs the 62 GB extracted.noindex/ HTML tree.
Threaded: lxml releases the GIL during parse, so many workers parse inparallel 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 argparseimport multiprocessing as mpimport osimport sqlite3import sysimport timefrom 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 = 500LOG_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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538"""Parse gamer2 thread HTMLs into a SQLite FTS5 database.
Usage: python build_index.py [--limit N] [--workers N] [--db PATH] [--archive-root PATH]
Streams files through a multiprocessing pool. Main process commits in batches."""
import argparseimport multiprocessing as mpimport osimport reimport sqlite3import sysimport timefrom pathlib import Path
from bs4 import BeautifulSoupfrom dateutil import parser as dtparser
ARCHIVE_ROOT_DEFAULT = Path( "/Users/hadar/Projects/gamer2-archive/gamer2/static/gamer2/archive/extracted.noindex")DB_DEFAULT = Path("/Users/hadar/Projects/gamer2-archive/search/posts.db")
TOPIC_RE = re.compile(r"TopicID=(\d+)")FORUM_RE = re.compile(r"ForumID=(\d+)")REPLY_RE = re.compile(r"ReplyAnchor(\d+)")USERID_RE = re.compile(r"userid=(\d+)")BG_COLOR_RE = re.compile(r"background-color:\s*#([0-9A-Fa-f]{3,6})")WIDTH_PCT_RE = re.compile(r"width:\s*(\d+)%")NO_RATINGS_TEXT = "ืืื ืฉืืืืฉ ืืืขืจืืช ืืืืจืื"
def _parse_bar(div): """Return (color_int, width_pct) from a colored progress bar div, or (None, None).""" if div is None: return None, None style = div.get("style", "") color = None width = None cm = BG_COLOR_RE.search(style) if cm: try: color = int(cm.group(1), 16) except ValueError: pass wm = WIDTH_PCT_RE.search(style) if wm: try: width = int(wm.group(1)) except ValueError: pass return color, width
def iter_files(root: Path): """Yield all thread HTML file paths under root. Handles both archive layouts: early batches (39-69) place files in `{batch}/php/`, later batches (70-100) put them directly in `{batch}/`.""" for entry in sorted(os.scandir(root), key=lambda e: int(e.name) if e.name.isdigit() else 0): if not entry.is_dir() or not entry.name.isdigit(): continue batch_dir = Path(entry.path) # Prefer php/ subdir if present, else walk the batch dir itself. search_dirs = [batch_dir / "php"] if (batch_dir / "php").is_dir() else [batch_dir] for d in search_dirs: for f in os.scandir(d): if f.is_file() and "TopicID=" in f.name: yield Path(f.path)
def parse_file(path_str: str): """Parse one HTML file โ (thread_dict, forum_dict|None, [user_dicts], [post_dicts]) or None.""" path = Path(path_str) try: m = TOPIC_RE.search(path.name) if not m: return None thread_id = int(m.group(1))
# Decode explicitly โ files are windows-1255; this lets lxml skip # encoding detection and avoids a 4-5x slowdown on huge threads. with open(path, "rb") as f: text = f.read().decode("windows-1255", errors="replace") soup = BeautifulSoup(text, "lxml")
title_el = soup.find("span", "forumNameBlank") if not title_el: return None thread_name = title_el.get_text(strip=True)
archive_el = soup.find("td", "ForumChannelHeaderBar PrettyBoxHeadline") archive = bool(archive_el and "ืืจืืืื" in archive_el.get_text())
forum_id = None forum_name = None forum_links = soup.find_all("a", "forum1") if len(forum_links) >= 2: fm = FORUM_RE.search(forum_links[1].get("href", "")) if fm: forum_id = int(fm.group(1)) # Breadcrumb text: "ืืืืจ ืืคืืจืื <name>" txt = forum_links[1].get_text(strip=True) if txt.startswith("ืืืืจ ืืคืืจืื"): cand = txt[len("ืืืืจ ืืคืืจืื"):].strip() forum_name = cand or None
posts = [] users = {} post_anchors = soup.find_all("a", id=REPLY_RE)
# Thread-level: is the star-rating system on in this forum? The original # code checks the first post's toolbar cell adjacent to the index link; # if it says "ืืื ืฉืืืืฉ ืืืขืจืืช ืืืืจืื" then ratings are off. ratings_on = False if post_anchors: try: first_tb = post_anchors[0].parent.parent.find( "table", "Structural AlignVerticalMiddle ToolBarPadding" ) if first_tb: sib = first_tb.find("a").parent.find_next_sibling() if sib is not None and NO_RATINGS_TEXT not in sib.get_text(): ratings_on = True except Exception: pass
for a in post_anchors: pid_match = REPLY_RE.match(a["id"]) if not pid_match: continue post_id = int(pid_match.group(1))
# Created time created = None try: ts = a.parent.get_text(" ", strip=True).replace("[", "").replace("]", "") created = dtparser.parse(ts + " +0300").isoformat() except Exception: pass
# Post index + per-post rating idx = None post_color = None post_dsize = None try: toolbar = a.parent.parent.find( "table", "Structural AlignVerticalMiddle ToolBarPadding" ) if toolbar: idx_el = toolbar.find("a") if idx_el: idx = int(idx_el.get_text().replace("#", "")) if ratings_on: rate_cell = toolbar.find("a").parent.find_next_sibling() if rate_cell is not None and rate_cell.get_text(strip=True) == "": inner = rate_cell.find("div") if inner: bar = inner.find("div") post_color, post_dsize = _parse_bar(bar) except Exception: pass
# Author author_id = 0 author_nick = "ืื ืื ืืื" author_location = None author_messagecount = None author_rank_desc = None author_rank_color = None author_rank_dsize = None userspace = a.parent.parent.find_next_sibling() if userspace is not None: ua = userspace.find("a", href=USERID_RE) if ua: um = USERID_RE.search(ua.get("href", "")) if um: author_id = int(um.group(1)) nick_el = userspace.find("div", "boldText") if nick_el: author_nick = nick_el.get_text(strip=True) # Location: "ื: location" โ split by newline so the field doesn't # bleed into the adjacent "ืืืืขืืช: N" cell. try: txt_el = userspace.find("td") if txt_el: txt = txt_el.get_text(separator="\n") loc_match = re.search(r"ื:\s*([^\n]+)", txt) if loc_match: author_location = loc_match.group(1).strip() or None cnt_match = re.search(r"ืืืืขืืช:\s*([0-9]+)", txt) if cnt_match: author_messagecount = int(cnt_match.group(1)) except Exception: pass
# User rank: sibling of nick is the desc div; its next sibling # holds the bar div. if ratings_on and nick_el is not None: try: desc_div = nick_el.find_next_sibling() if desc_div is not None and desc_div.name == "div": txt = desc_div.get_text(strip=True) if txt: author_rank_desc = txt bar_holder = desc_div.find_next_sibling() if bar_holder is not None: inner = bar_holder.find("div") if inner: bar = inner.find("div") author_rank_color, author_rank_dsize = _parse_bar(bar) except Exception: pass
# Merge user data โ keep richer values when seen across posts existing = users.get(author_id) new_user = { "id": author_id, "nick": author_nick, "location": author_location, "messagecount": author_messagecount, } if existing is None: users[author_id] = new_user else: for k, v in new_user.items(): if existing.get(k) is None and v is not None: existing[k] = v
# Content content_text = "" if userspace is not None: reply_div = userspace.find("div", id=f"Reply{post_id}") if reply_div: for br in reply_div.find_all("br"): br.replace_with("\n") content_text = reply_div.get_text("\n", strip=True) # Strip the "Eliran Pe'er ืืืืจื ืคืืจ" link spammed across every post content_text = content_text.replace("Eliran Pe'er ืืืืจื ืคืืจ", "").strip()
posts.append( { "id": post_id, "thread_id": thread_id, "author_id": author_id, "idx": idx, "created_at": created, "content": content_text, "color": post_color, "dsize": post_dsize, "rank_desc": author_rank_desc, "rank_color": author_rank_color, "rank_dsize": author_rank_dsize, } )
forum = {"id": forum_id, "name": forum_name} if forum_id is not None else None thread = { "id": thread_id, "name": thread_name, "forum_id": forum_id, "archive": int(archive), "ratings": int(ratings_on), "file_path": str(path), } return (thread, forum, list(users.values()), posts) except Exception as e: return ("__error__", str(path), repr(e))
def init_db(db_path: Path): db_path.parent.mkdir(parents=True, exist_ok=True) conn = sqlite3.connect(db_path) cur = conn.cursor() cur.executescript( """ PRAGMA journal_mode=WAL; PRAGMA synchronous=OFF; PRAGMA temp_store=MEMORY; PRAGMA cache_size=-200000;
CREATE TABLE IF NOT EXISTS forums ( id INTEGER PRIMARY KEY, name TEXT ); CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY, nick TEXT, location TEXT, messagecount INTEGER ); CREATE TABLE IF NOT EXISTS threads ( id INTEGER PRIMARY KEY, name TEXT, forum_id INTEGER, archive INTEGER, ratings INTEGER, file_path TEXT ); CREATE TABLE IF NOT EXISTS posts ( id INTEGER PRIMARY KEY, thread_id INTEGER, author_id INTEGER, idx INTEGER, created_at TEXT, content TEXT, color INTEGER, dsize INTEGER, rank_desc TEXT, rank_color INTEGER, rank_dsize INTEGER ); CREATE INDEX IF NOT EXISTS posts_thread_idx ON posts(thread_id, idx); CREATE INDEX IF NOT EXISTS posts_author ON posts(author_id); CREATE INDEX IF NOT EXISTS posts_created ON posts(created_at); CREATE INDEX IF NOT EXISTS threads_forum ON threads(forum_id);
CREATE VIRTUAL TABLE IF NOT EXISTS posts_fts USING fts5( content, author_nick UNINDEXED, thread_name, tokenize='unicode61 remove_diacritics 2' ); CREATE TABLE IF NOT EXISTS processed_files ( path TEXT PRIMARY KEY ); """ ) # Backfill: anything already in threads.file_path counts as processed. # This preserves prior --skip-existing work when the tracking table is # introduced on an existing DB. conn.execute( "INSERT OR IGNORE INTO processed_files(path) " "SELECT DISTINCT file_path FROM threads WHERE file_path IS NOT NULL" ) conn.commit() return conn
def upsert_batch(conn, batch): """Insert results from worker into DB. batch is list of parse_file results.""" forums, users, threads, posts, fts_rows = {}, {}, [], [], [] errors = [] for r in batch: if r is None: continue if isinstance(r, tuple) and r and r[0] == "__error__": errors.append(r) continue thread, forum, ulist, plist = r threads.append(thread) if forum: forums[forum["id"]] = forum for u in ulist: users[u["id"]] = u for p in plist: posts.append(p) nick = users.get(p["author_id"], {}).get("nick", "") fts_rows.append((p["id"], p["content"] or "", nick or "", thread["name"] or ""))
cur = conn.cursor() if forums: cur.executemany( """ INSERT INTO forums(id, name) VALUES (?, ?) ON CONFLICT(id) DO UPDATE SET name = COALESCE(forums.name, excluded.name) """, [(f["id"], f["name"]) for f in forums.values()], ) if users: cur.executemany( """ INSERT INTO users(id, nick, location, messagecount) VALUES (?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET nick = COALESCE(excluded.nick, users.nick), location = COALESCE(excluded.location, users.location), messagecount = COALESCE(excluded.messagecount, users.messagecount) """, [(u["id"], u["nick"], u["location"], u["messagecount"]) for u in users.values()], ) if threads: cur.executemany( "INSERT OR REPLACE INTO threads(id, name, forum_id, archive, ratings, file_path) VALUES (?, ?, ?, ?, ?, ?)", [(t["id"], t["name"], t["forum_id"], t["archive"], t["ratings"], t["file_path"]) for t in threads], ) cur.executemany( "INSERT OR IGNORE INTO processed_files(path) VALUES (?)", [(t["file_path"],) for t in threads], ) if posts: # Dedupe by post id (last write wins) โ archive duplicates within one # batch otherwise yield the same post_id twice and trip the FTS rowid # uniqueness constraint downstream. posts_dedup = {p["id"]: p for p in posts}.values() cur.executemany( """ INSERT OR REPLACE INTO posts (id, thread_id, author_id, idx, created_at, content, color, dsize, rank_desc, rank_color, rank_dsize) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) """, [ (p["id"], p["thread_id"], p["author_id"], p["idx"], p["created_at"], p["content"], p["color"], p["dsize"], p["rank_desc"], p["rank_color"], p["rank_dsize"]) for p in posts_dedup ], ) # Refresh FTS rows for these post ids. Dedupe by rowid (last write wins) # so a duplicate row in the same batch can't violate the implicit # rowid uniqueness constraint of the FTS table. fts_dedup = {r[0]: r for r in fts_rows} cur.executemany("DELETE FROM posts_fts WHERE rowid = ?", [(rid,) for rid in fts_dedup]) cur.executemany( "INSERT INTO posts_fts(rowid, content, author_nick, thread_name) VALUES (?, ?, ?, ?)", list(fts_dedup.values()), ) return len(threads), len(posts), errors
def main(): ap = argparse.ArgumentParser() ap.add_argument("--archive-root", type=Path, default=ARCHIVE_ROOT_DEFAULT) ap.add_argument("--db", type=Path, default=DB_DEFAULT) ap.add_argument("--limit", type=int, default=None, help="Process only first N files") ap.add_argument("--workers", type=int, default=max(2, mp.cpu_count() - 1)) ap.add_argument("--batch", type=int, default=200, help="DB commit batch size") ap.add_argument("--progress-every", type=int, default=2000) ap.add_argument( "--skip-existing", action="store_true", help="Skip files whose TopicID is already in the threads table (resume)", ) args = ap.parse_args()
conn = init_db(args.db) print(f"DB: {args.db}", flush=True) print(f"Archive: {args.archive_root}", flush=True) print(f"Workers: {args.workers}", flush=True)
processed_paths: set = set() if args.skip_existing: for (p,) in conn.execute("SELECT path FROM processed_files"): processed_paths.add(p) print(f"Skip-existing: {len(processed_paths):,} files already processed", flush=True)
print("Enumerating filesโฆ", flush=True) files_list: list = [] for f in iter_files(args.archive_root): fp = str(f) if fp in processed_paths: continue files_list.append(fp) print(f" {len(files_list):,} files to process", flush=True) if args.limit: files_list = files_list[: args.limit] # sort by size ascending so we get steady throughput and the huge outliers # all run at the end (where they can chew in parallel without blocking # commits for early-batch progress) files_list.sort(key=lambda p: os.path.getsize(p)) print(f" smallest: {os.path.getsize(files_list[0])} B, largest: {os.path.getsize(files_list[-1])/1e6:.1f} MB", flush=True)
total_threads = 0 total_posts = 0 total_errors = 0 start = time.time() last_log = start processed = 0
batch = [] # Threading: lxml releases the GIL during parsing so multiple Python threads # can parse in parallel. The main thread drains results and commits to # SQLite (a single shared connection โ SQLite write is fast and serializes # naturally). Avoids the multiprocessing.Pool deadlock seen earlier on # macOS while still getting most of the parallel parse benefit. from concurrent.futures import ThreadPoolExecutor in_flight = max(args.workers * 4, 32) # cap queued futures to bound memory try: with ThreadPoolExecutor(max_workers=args.workers) as ex: it = iter(files_list) pending = [] # prime the pump for _ in range(in_flight): try: pending.append(ex.submit(parse_file, next(it))) except StopIteration: break while pending: # Always drain the head future (preserves no order requirement) fut = pending.pop(0) r = fut.result() batch.append(r) processed += 1 # submit a replacement to keep the window full try: pending.append(ex.submit(parse_file, next(it))) except StopIteration: pass if len(batch) >= args.batch: th, po, errs = upsert_batch(conn, batch) conn.commit() total_threads += th total_posts += po total_errors += len(errs) batch = [] if processed % args.progress_every == 0: now = time.time() rate = args.progress_every / max(0.001, now - last_log) last_log = now elapsed = now - start print( f" processed={processed:,} threads={total_threads:,} posts={total_posts:,} errors={total_errors} rate={rate:.0f}/s elapsed={elapsed:.0f}s", flush=True, ) if batch: th, po, errs = upsert_batch(conn, batch) conn.commit() total_threads += th total_posts += po total_errors += len(errs) finally: conn.commit()
print("Optimizing FTS indexโฆ", flush=True) conn.execute("INSERT INTO posts_fts(posts_fts) VALUES('optimize')") conn.commit() conn.execute("PRAGMA optimize") conn.close()
elapsed = time.time() - start print( f"DONE processed={processed:,} threads={total_threads:,} posts={total_posts:,} errors={total_errors} elapsed={elapsed:.0f}s", flush=True, )
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175#!/usr/bin/env bash# Stage the deploy bundle under search/_deploy/ and (optionally) push to HF.## Usage:# ./deploy.sh stage # just prep the bundle for inspection# ./deploy.sh push <user>/<repo> # stage + create-if-missing + upload## After `push` the Space rebuilds itself.
set -euo pipefailcd "$(dirname "$0")"
STAGE=_deploySRC_AVATARS="../gamer2/static/user_avatar"SRC_EMOJIS="../gamer2/static/gamer/forum_images"
# Color helpers (used by the push pipeline's final report).red() { printf '\033[31m%s\033[0m\n' "$*"; }green() { printf '\033[32m%s\033[0m\n' "$*"; }yellow() { printf '\033[33m%s\033[0m\n' "$*"; }
stage() { echo "โ Staging $STAGE/" rm -rf "$STAGE" mkdir -p "$STAGE"
# App cp server.py "$STAGE/" cp requirements.txt "$STAGE/" cp Dockerfile "$STAGE/" cp README.md "$STAGE/" cp -R static "$STAGE/static"
# Data โ posts.db lives in a separate dataset repo (Space free-tier is # capped at 1 GB; the Dockerfile pulls posts.db from the dataset at # image-build time). Only the small static assets ride along. cp -R "$SRC_AVATARS" "$STAGE/avatars" cp -R "$SRC_EMOJIS" "$STAGE/forum_emojis"
# Sanity echo echo "โ Bundle contents:" du -sh "$STAGE"/* | sort -h echo echo "โ Total bundle size:" du -sh "$STAGE"}
push() { local repo="$1" : "${HF_TOKEN:?Set HF_TOKEN env var or `source search/.env`}"
# Gate: refuse to push if smoke tests fail. predeploy.sh chmods posts.db # to 0444 (true read-only), boots a test server on port 8799, and hits # every endpoint โ catches the "works on dev, breaks in prod" class # of bug (PRAGMA writes on RO mounts, WAL lock files, etc) that has # bitten us twice. Skip with PREDEPLOY_SKIP=1 only when truly needed. if [ "${PREDEPLOY_SKIP:-}" != "1" ]; then echo "โ Running predeploy smoke testsโฆ" if ! "$(dirname "$0")/predeploy.sh"; then echo echo "โ Predeploy gate FAILED โ push aborted." echo " Set PREDEPLOY_SKIP=1 to override (only when you really know)." exit 1 fi echo else echo "โ Skipping predeploy gate (PREDEPLOY_SKIP=1)" fi
stage
echo "โ Creating Space if it doesn't exist: $repo" hf repos create "$repo" --type space --space-sdk docker --exist-ok
# `hf upload-large-folder` has a bug where it always calls create_repo # without space_sdk, even when --type space is passed and the Space # already exists. Use plain `hf upload` instead; our slim bundle is # ~37MB so chunked uploads aren't needed. The big posts.db lives in # a dataset repo and is fetched at image-build time. local commit_msg="${COMMIT_MSG:-deploy}" local last_known_sha last_known_sha=$( curl -s -H "Authorization: Bearer $HF_TOKEN" \ "https://huggingface.co/api/spaces/$repo/commits/main?limit=1" \ | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])" 2>/dev/null \ || echo "" )
# Retry the upload up to 3ร on HF flake (their commit API 500s # intermittently). After each attempt โ failure or otherwise โ # check the git log to see if the commit actually landed; sometimes # the client gets a 500 but the server-side commit succeeded, and # blindly retrying creates a no-op (or wastes time). local attempt local success=0 for attempt in 1 2 3; do echo "โ Uploading bundle (attempt $attempt/3)โฆ" if hf upload "$repo" "$STAGE" . --type space --commit-message "$commit_msg"; then success=1 break fi echo " upload exit was non-zero โ checking if the commit actually landedโฆ" sleep 3 local current_sha current_sha=$( curl -s -H "Authorization: Bearer $HF_TOKEN" \ "https://huggingface.co/api/spaces/$repo/commits/main?limit=1" \ | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])" 2>/dev/null \ || echo "" ) if [ -n "$current_sha" ] && [ "$current_sha" != "$last_known_sha" ]; then echo " commit landed despite client error: $current_sha" success=1 break fi if [ "$attempt" -lt 3 ]; then local wait=$((attempt * 10)) echo " no new commit โ retrying in ${wait}sโฆ" sleep "$wait" fi done
if [ "$success" -ne 1 ]; then red "โ Upload failed after 3 attempts." echo " Check https://status.huggingface.co/ โ their commit API" echo " has intermittent 5xx episodes." exit 1 fi
# Confirm the new commit and wait for HF to actually serve it. local new_sha new_sha=$( curl -s -H "Authorization: Bearer $HF_TOKEN" \ "https://huggingface.co/api/spaces/$repo/commits/main?limit=1" \ | python3 -c "import json,sys; print(json.load(sys.stdin)[0]['id'])" ) echo "โ Latest commit: $new_sha"
echo "โ Waiting for Space to build + serve this sha (timeout 12 min)โฆ" local space_host="${repo//\//-}.hf.space" local deadline=$(( $(date +%s) + 720 )) local last_stage="" while [ "$(date +%s)" -lt "$deadline" ]; do local info_json info_json=$(curl -s -H "Authorization: Bearer $HF_TOKEN" \ "https://huggingface.co/api/spaces/$repo" 2>/dev/null) local live_sha stage live_sha=$(echo "$info_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('sha',''))" 2>/dev/null || echo "") stage=$(echo "$info_json" | python3 -c "import json,sys; print(json.load(sys.stdin).get('runtime',{}).get('stage',''))" 2>/dev/null || echo "") if [ "$stage" != "$last_stage" ]; then echo " stage: $stage sha: ${live_sha:0:12}" last_stage="$stage" fi if [ "$stage" = "RUNNING" ] && [ "$live_sha" = "$new_sha" ]; then # Final liveness check: hit /api/stats and confirm JSON if curl -fs -m 10 "https://$space_host/api/stats" >/dev/null 2>&1; then green "โ Live: https://$space_host (sha ${new_sha:0:12})" return 0 fi echo " stage RUNNING but /api/stats not answering yet โ waitingโฆ" fi sleep 10 done
red "โ Timed out waiting for Space to flip to RUNNING on the new sha." echo " Build may still finish โ check 'hf spaces info $repo' and runtime logs." exit 1}
case "${1:-}" in stage) stage ;; push) shift; push "${1:?Usage: ./deploy.sh push <user>/<repo>}" ;; *) echo "Usage: $0 stage | push <user>/<repo>"; exit 1 ;;esac123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566"""Backfill forum names by parsing one HTML per forum and extracting thebreadcrumb link text ("ืืืืจ ืืคืืจืื <name>").
Run after build_index.py โ safe to re-run."""
import reimport sqlite3import sysfrom pathlib import Path
from bs4 import BeautifulSoup
DB = Path(__file__).resolve().parent / "posts.db"BREADCRUMB_PREFIX = "ืืืืจ ืืคืืจืื"
def name_from_file(path: Path): try: with open(path, "rb") as f: soup = BeautifulSoup(f, "html5lib") except Exception: return None for a in soup.find_all("a", "forum1"): txt = a.get_text(strip=True) if txt.startswith(BREADCRUMB_PREFIX): name = txt[len(BREADCRUMB_PREFIX):].strip() return name or None return None
def main(): conn = sqlite3.connect(DB) cur = conn.cursor()
rows = cur.execute( """ SELECT f.id, MIN(t.file_path) AS file_path FROM forums f JOIN threads t ON t.forum_id = f.id WHERE f.name IS NULL GROUP BY f.id """ ).fetchall() print(f"forums missing name: {len(rows)}", flush=True)
updates = [] for forum_id, fp in rows: if not fp: continue name = name_from_file(Path(fp)) if name: updates.append((name, forum_id)) print(f" forum {forum_id:>4} โ {name}", flush=True) else: print(f" forum {forum_id:>4} โ (no name found in {fp})", flush=True)
if updates: cur.executemany("UPDATE forums SET name=? WHERE id=?", updates) conn.commit() print(f"updated {len(updates)} forums", flush=True) conn.close()
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121#!/usr/bin/env bash# predeploy.sh โ gate that runs before every push to the Space.## Catches the classes of bugs we've actually hit in production:# 1. Syntax / import errors in server.py# 2. SQLite "attempt to write a readonly database" โ PRAGMA writes,# WAL lock file creation, anything that needs a writable mount# 3. 500s on common endpoints (top_hated + year filter was our worst)## How: chmod the local posts.db to 0444 (true read-only), spin up uvicorn# on a private test port (8799), run tests/smoke.py, then restore perms.# trap ensures perms are restored even if the test suite errors out.## Usage:# ./predeploy.sh # run gates, exit 0 on success# ./predeploy.sh --skip-perms # skip the chmod step (DB already RO)## deploy.sh push calls this automatically.
set -uo pipefailcd "$(dirname "$0")"
DB="$(pwd)/posts.db"PORT=8799TEST_BASE="http://127.0.0.1:${PORT}"SERVER_LOG="/tmp/predeploy_server.log"SERVER_PID=""ORIG_PERMS=""
red() { printf '\033[31m%s\033[0m\n' "$*"; }green() { printf '\033[32m%s\033[0m\n' "$*"; }yellow() { printf '\033[33m%s\033[0m\n' "$*"; }
cleanup() { local status=$? if [ -n "$SERVER_PID" ] && kill -0 "$SERVER_PID" 2>/dev/null; then kill "$SERVER_PID" 2>/dev/null || true wait "$SERVER_PID" 2>/dev/null || true fi if [ -n "$ORIG_PERMS" ] && [ -f "$DB" ]; then chmod "$ORIG_PERMS" "$DB" fi exit $status}trap cleanup EXIT INT TERM
# ---- gate 1: syntax / import ----echo "โถ syntax check"if ! python3 -m py_compile server.py 2>&1; then red "โ server.py syntax check FAILED" exit 1figreen "โ server.py compiles"
echo "โถ import check (catches top-level errors)"if ! (cd .. && python3 -c "import search.server" 2>&1); then red "โ server.py import FAILED" exit 1figreen "โ server.py imports cleanly"
# ---- gate 1b: parser unit tests (fast, no server needed) ----echo "โถ parser unit tests"if ! python3 tests/test_parsers.py 2>&1 | tail -5; then red "โ parser unit tests FAILED" exit 1figreen "โ parser unit tests pass"
# ---- gate 2: smoke tests against RO DB ----if [ ! -f "$DB" ]; then yellow "โ posts.db not present, skipping runtime smoke tests" exit 0fi
if [ "${1:-}" != "--skip-perms" ]; then ORIG_PERMS=$(stat -f "%Lp" "$DB" 2>/dev/null || stat -c "%a" "$DB") echo "โถ chmod 0444 posts.db (orig perms: $ORIG_PERMS โ will restore on exit)" chmod 0444 "$DB"fi
echo "โถ booting test server on port $PORT"# Use a fresh process group so cleanup can kill the whole tree if needed.(cd .. && python3 -m uvicorn search.server:app --host 127.0.0.1 --port "$PORT" --log-level warning) \ > "$SERVER_LOG" 2>&1 &SERVER_PID=$!
# Wait up to 15s for the server to come up.for i in $(seq 1 30); do if curl -s -o /dev/null -m 1 "$TEST_BASE/api/stats"; then break fi if ! kill -0 "$SERVER_PID" 2>/dev/null; then red "โ test server died during startup" echo "--- server log:" tail -30 "$SERVER_LOG" exit 1 fi sleep 0.5done
if ! curl -s -o /dev/null -m 2 "$TEST_BASE/api/stats"; then red "โ test server never came up" echo "--- server log:" tail -30 "$SERVER_LOG" exit 1figreen "โ test server up"
echo "โถ running smoke tests"if ! TEST_BASE="$TEST_BASE" python3 tests/smoke.py; then red "โ smoke tests FAILED" echo "--- server log:" tail -50 "$SERVER_LOG" exit 1figreen "โ all smoke tests passed"
echogreen "PREDEPLOY โ safe to push"exit 01234567fastapi>=0.115,<1.0uvicorn[standard]>=0.32,<1.0beautifulsoup4>=4.12,<5.0lxml>=5.1,<6.0python-dateutil>=2.9,<3.0slowapi>=0.1.9,<1.0huggingface_hub>=0.27,<2.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227#!/usr/bin/env python3"""End-to-end smoke tests for the search server.
Hits every public API endpoint and asserts each: - returns HTTP 2xx - returns valid JSON - has the expected shape
Run via predeploy.sh, which spins up uvicorn against a read-onlycopy of posts.db (chmod 0444) โ that's how we catch SQLite "attemptto write a readonly database" failures (PRAGMA cache_size, WAL lockfiles, etc.) BEFORE pushing to production where the DB is RO.
The base URL comes from $TEST_BASE (default http://127.0.0.1:8799).Exits 0 on success, 1 on any failure with a one-line per-test summary."""
from __future__ import annotationsimport jsonimport osimport sysimport urllib.errorimport urllib.request
BASE = os.environ.get("TEST_BASE", "http://127.0.0.1:8799").rstrip("/")TIMEOUT = 30
# -------- tiny test framework --------
passed: list[str] = []failed: list[tuple[str, str]] = []
def get(path: str) -> tuple[int, dict | list | str]: """GET {BASE}{path}, return (status, body-as-json-or-text).""" url = BASE + path try: req = urllib.request.Request(url) with urllib.request.urlopen(req, timeout=TIMEOUT) as resp: body = resp.read().decode("utf-8", errors="replace") try: return resp.status, json.loads(body) except json.JSONDecodeError: return resp.status, body except urllib.error.HTTPError as e: body = e.read().decode("utf-8", errors="replace") return e.code, body
def check(name: str, ok: bool, detail: str = "") -> None: if ok: passed.append(name) print(f" โ {name}") else: failed.append((name, detail)) print(f" โ {name} {detail}")
# -------- the tests --------
def test_stats(): code, body = get("/api/stats") check("GET /api/stats โ 200 + JSON", code == 200 and isinstance(body, dict), f"got {code} body={body!r:.200}") if isinstance(body, dict): for key in ("threads", "posts", "users", "forums"): check(f" stats has key {key!r}", key in body, f"missing {key}")
def test_forums(): code, body = get("/api/forums") check("GET /api/forums โ 200 + JSON", code == 200 and isinstance(body, dict), f"got {code} body={body!r:.200}")
def test_search_empty_with_filter(): # Empty text + a filter (forum) โ a fast cursor-paginated path. # We don't test the unbounded "empty + browse=1" path because that # walks the whole 10M-row table cold and can take 30+ s; the frontend # shows the welcome card for that state instead of querying. code, body = get("/api/search?scope=posts&sort=newest&forum=13&limit=5") check("GET /api/search (empty + forum filter) โ 200", code == 200 and isinstance(body, dict) and "results" in body, f"got {code} body={body!r:.200}")
def test_search_text(): # An everyday Hebrew word that will produce hits across the corpus. code, body = get("/api/search?q=%D7%9E%D7%97%D7%A9%D7%91&scope=posts&limit=5") check("GET /api/search (text query) โ 200 + results", code == 200 and isinstance(body, dict) and "results" in body and len(body["results"]) > 0, f"got {code} body={body!r:.200}")
def test_search_top_hated_with_year(): # This was the exact query that broke in production โ RO-mode + WAL # lock files. Tests both the SELECT and the COUNT-skip path. code, body = get("/api/search?sort=top_hated&date_from=2010-01-01&date_to=2011-01-01&limit=5") check("GET /api/search (top_hated + ืฉื ื:2010) โ 200 + results", code == 200 and isinstance(body, dict) and "results" in body and len(body["results"]) > 0, f"got {code} body={body!r:.200}")
def test_search_top_rated_with_year(): code, body = get("/api/search?sort=top_rated&date_from=2010-01-01&date_to=2011-01-01&limit=5") check("GET /api/search (top_rated + ืฉื ื:2010) โ 200 + results", code == 200 and isinstance(body, dict) and "results" in body and len(body["results"]) > 0, f"got {code} body={body!r:.200}")
def test_search_threads_scope(): code, body = get("/api/search?q=%D7%9E%D7%97%D7%A9%D7%91&scope=threads&limit=5") check("GET /api/search (threads scope) โ 200 + results", code == 200 and isinstance(body, dict) and "results" in body, f"got {code} body={body!r:.200}")
def test_post_endpoint(): # Pick a post id known to exist (16607070 was our reference TomerCBR post). code, body = get("/api/post/16607070?bare=1") check("GET /api/post/{id}?bare=1 โ 200 + dict", code == 200 and isinstance(body, dict), f"got {code} body={body!r:.200}")
def test_thread_endpoint(): # Thread id from the same reference (969063 was the XBOX one). code, body = get("/api/thread/969063?page=0&page_size=5") check("GET /api/thread/{id} โ 200 + posts list", code == 200 and isinstance(body, dict) and isinstance(body.get("posts"), list), f"got {code} body={body!r:.200}")
def test_discovery_random_thread(): code, body = get("/api/discovery/random_thread") check("GET /api/discovery/random_thread โ 200 + thread dict", code == 200 and isinstance(body, dict), f"got {code} body={body!r:.200}")
def test_discovery_hot_threads(): code, body = get("/api/discovery/hot_threads?limit=5") check("GET /api/discovery/hot_threads โ 200 + list", code == 200 and isinstance(body, (dict, list)), f"got {code} body={body!r:.200}")
def test_discovery_top_users(): code, body = get("/api/discovery/top_users?by=messages&limit=5") check("GET /api/discovery/top_users โ 200", code == 200 and isinstance(body, (dict, list)), f"got {code} body={body!r:.200}")
def test_user_endpoint(): code, body = get("/api/user/1") check("GET /api/user/{id} โ 200 or 404 (no 500)", code in (200, 404), f"got {code} body={body!r:.200}")
def test_users_search(): code, body = get("/api/users/search?q=a&limit=5") check("GET /api/users/search โ 200", code == 200 and isinstance(body, (dict, list)), f"got {code} body={body!r:.200}")
def test_static_html(): # The SPA root must serve the HTML file (mounted as StaticFiles). code, body = get("/") check("GET / โ 200 + HTML", code == 200 and isinstance(body, str) and "<html" in body.lower(), f"got {code} body={body!r:.200}")
# -------- runner --------
ALL_TESTS = [ test_stats, test_forums, test_search_empty_with_filter, test_search_text, test_search_top_hated_with_year, test_search_top_rated_with_year, test_search_threads_scope, test_post_endpoint, test_thread_endpoint, test_discovery_random_thread, test_discovery_hot_threads, test_discovery_top_users, test_user_endpoint, test_users_search, test_static_html,]
def main() -> int: print(f"Smoke testing {BASE}") print("=" * 60) for t in ALL_TESTS: try: t() except Exception as e: check(t.__name__, False, f"raised: {type(e).__name__}: {e}") print("=" * 60) print(f"PASSED: {len(passed)} FAILED: {len(failed)}") if failed: print() print("FAILURES:") for name, detail in failed: print(f" - {name}: {detail}") return 1 return 0
if __name__ == "__main__": sys.exit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326#!/usr/bin/env python3"""Unit tests for the Python parsers in server.py.
These are deterministic, fast (<1s total), and exercise the specificbug classes we've actually hit in production:
- escape_fts: Hebrew prefix expansion, exact-phrase quoting, stopword drop, special-token filtering, empty-input safety- _strip_quotes_from_html: depth-aware nested blockquote removal- _query_terms: bare-token extraction including from quoted phrases- _build_snippet: window around first matching term, including with Hebrew prefix variants- _strip_quote_headers_text: heuristic plain-text quote-header strip for unbaked posts- _term_present_in_body: case-insensitive prefix-aware presence check
Wired into predeploy.sh โ runs BEFORE the smoke tests (which need abooted server). A failure here aborts the deploy with a clear message."""
from __future__ import annotationsimport osimport sys
# Make `import server` work whether we're run from project root or search/._THIS = os.path.dirname(os.path.abspath(__file__))_SEARCH = os.path.dirname(_THIS)_ROOT = os.path.dirname(_SEARCH)if _ROOT not in sys.path: sys.path.insert(0, _ROOT)if _SEARCH not in sys.path: sys.path.insert(0, _SEARCH)
# Prefer the package import (matches production layout) and fall back# to direct import for ad-hoc runs.try: from search import server # type: ignoreexcept ImportError: import server # type: ignore
# -------- tiny test framework --------
passed: list[str] = []failed: list[tuple[str, str]] = []
def check(name: str, ok: bool, detail: str = "") -> None: if ok: passed.append(name) else: failed.append((name, detail)) print(f" โ {name} {detail}")
def eq(name: str, got, want) -> None: check(name, got == want, f"got {got!r} want {want!r}")
def contains(name: str, haystack: str, needle: str) -> None: check(name, needle in haystack, f"{needle!r} not in {haystack!r}")
def not_contains(name: str, haystack: str, needle: str) -> None: check(name, needle not in haystack, f"{needle!r} should NOT be in {haystack!r}")
# -------- escape_fts --------
def test_escape_fts_empty(): eq("escape_fts('') is empty", server.escape_fts(""), "") eq("escape_fts(' ') is empty", server.escape_fts(" "), "")
def test_escape_fts_hebrew_prefix_expansion(): out = server.escape_fts("ืืืฉื") # Single Hebrew token โ OR of prefix variants, each with * wildcard contains("escape_fts: bare token", out, '"ืืืฉื"*') contains("escape_fts: ื-prefix variant", out, '"ืืืืฉื"*') contains("escape_fts: ื-prefix variant", out, '"ืืืืฉื"*') contains("escape_fts: OR connector", out, " OR ")
def test_escape_fts_skip_prefix_for_word_already_starting_with_it(): # The word "ืืืืฉื" already starts with ื, so we shouldn't double-add out = server.escape_fts("ืืืืฉื") not_contains("escape_fts: no ื+ื double-prefix", out, '"ืืืืืฉื"*') # But other prefixes should still be added contains("escape_fts: ื-prefix added for ื-starting word", out, '"ืืืืืฉื"*')
def test_escape_fts_stopword_dropped_when_other_tokens_present(): # "ืื ื" is a stopword; with other tokens, it should be dropped entirely out = server.escape_fts("ืื ื ืงืืคืฅ") not_contains("escape_fts: stopword ืื ื dropped", out, "ืื ื") contains("escape_fts: non-stopword survives", out, "ืงืืคืฅ")
def test_escape_fts_stopword_kept_when_alone(): # "ืื ื" alone should NOT be dropped โ otherwise the user gets nothing out = server.escape_fts("ืื ื") contains("escape_fts: lone stopword kept", out, "ืื ื")
def test_escape_fts_quoted_phrase_exact(): # Quoted phrases get no prefix expansion and no * suffix out = server.escape_fts('"red dead"') eq("escape_fts: quoted phrase exact", out, '"red dead"')
def test_escape_fts_quoted_keeps_stopword(): # Stopword inside a quoted phrase isn't dropped โ user explicitly asked out = server.escape_fts('"ืื ื ืงืืคืฅ"') eq("escape_fts: quoted phrase keeps stopword", out, '"ืื ื ืงืืคืฅ"')
def test_escape_fts_mixed_quoted_and_bare(): out = server.escape_fts('"red dead" redemption') contains("escape_fts: quoted part exact", out, '"red dead"') contains("escape_fts: bare part has wildcard", out, '"redemption"*') contains("escape_fts: AND-ed", out, " AND ")
def test_escape_fts_nonhebrew_no_prefix_expansion(): out = server.escape_fts("redemption") eq("escape_fts: non-Hebrew gets only * wildcard", out, '"redemption"*')
# -------- _is_stopword --------
def test_is_stopword_known_words(): eq("stopword: ืื ื", server._is_stopword("ืื ื"), True) eq("stopword: ืฉื", server._is_stopword("ืฉื"), True) eq("stopword: ืขื", server._is_stopword("ืขื"), True) eq("non-stopword: ืืืฉื", server._is_stopword("ืืืฉื"), False) eq("non-stopword: ืงืืคืฅ", server._is_stopword("ืงืืคืฅ"), False)
# -------- _strip_quotes_from_html --------
def test_strip_quotes_simple(): html = "before <blockquote>quoted</blockquote> after" out = server._strip_quotes_from_html(html) contains("strip_quotes: keeps text before", out, "before") contains("strip_quotes: keeps text after", out, "after") not_contains("strip_quotes: drops quoted text", out, "quoted")
def test_strip_quotes_nested(): # Nested blockquotes โ depth counter, not non-greedy regex html = ( "outer-pre <blockquote>L1-pre " "<blockquote>L2-content</blockquote>" " L1-post</blockquote> outer-post" ) out = server._strip_quotes_from_html(html) contains("strip_quotes nested: keeps outer-pre", out, "outer-pre") contains("strip_quotes nested: keeps outer-post", out, "outer-post") not_contains("strip_quotes nested: drops L1 content", out, "L1-pre") not_contains("strip_quotes nested: drops L1 post", out, "L1-post") not_contains("strip_quotes nested: drops L2 content", out, "L2-content")
def test_strip_quotes_deeply_nested(): # Three levels deep โ the case that originally broke the regex version html = ( "TOP <blockquote>A " "<blockquote>B " "<blockquote>C-deep</blockquote>" " B-end</blockquote>" " A-end</blockquote> BOTTOM" ) out = server._strip_quotes_from_html(html) contains("strip_quotes 3-deep: keeps TOP", out, "TOP") contains("strip_quotes 3-deep: keeps BOTTOM", out, "BOTTOM") not_contains("strip_quotes 3-deep: drops level-1 (A)", out, "A-end") not_contains("strip_quotes 3-deep: drops level-2 (B)", out, "B-end") not_contains("strip_quotes 3-deep: drops level-3 (C)", out, "C-deep")
def test_strip_quotes_no_blockquote(): html = "<p>just <b>some</b> text</p>" out = server._strip_quotes_from_html(html) contains("strip_quotes: keeps plain content", out, "just") contains("strip_quotes: keeps plain content (more)", out, "some") contains("strip_quotes: keeps plain content (end)", out, "text") not_contains("strip_quotes: strips html tags", out, "<p>")
# -------- _query_terms --------
def test_query_terms_bare_tokens(): eq("query_terms: bare tokens", server._query_terms("ืืืฉื ื ืืื"), ["ืืืฉื", "ื ืืื"])
def test_query_terms_quoted_phrase(): eq("query_terms: quoted phrase", server._query_terms('"red dead"'), ["red dead"])
def test_query_terms_mixed(): out = server._query_terms('"red dead" redemption') eq("query_terms: mixed quoted + bare", sorted(out), sorted(["red dead", "redemption"]))
def test_query_terms_drops_special_tokens(): # Special tokens (ืืืจืื>80, ืฉื ื:2014, ืคืืจืื:13, ืืืืขื:1, ืืื:ืืืืืื) are # consumed by parseSpecialQuery client-side, but server-side _query_terms # also defensively filters them out = server._query_terms("ืืืฉื ืฉื ื:2014 ืืื:ืืืืืื") eq("query_terms: drops special tokens", out, ["ืืืฉื"])
# -------- _term_present_in_body --------
def test_term_present_simple(): eq("term_present: exact match", server._term_present_in_body("hello world", "hello"), True) eq("term_present: case-insensitive", server._term_present_in_body("Hello World".lower(), "hello"), True) eq("term_present: not found", server._term_present_in_body("hello world", "foo"), False)
def test_term_present_hebrew_prefix(): # "ืืืฉื" should match a body that has "ืืืืฉื" (with ื- prefix) eq("term_present: matches Hebrew prefix variant", server._term_present_in_body("ืื ื ืืืื ืืช ืืืืฉื ืฉืื", "ืืืฉื"), True)
# -------- _build_snippet --------
def test_build_snippet_no_terms_returns_start(): body = "a" * 1000 out = server._build_snippet(body, terms=[]) check("build_snippet: no terms truncates with ellipsis", out.endswith("โฆ") and len(out) <= 400, f"got len={len(out)}, suffix={out[-3:]!r}")
def test_build_snippet_centers_on_match(): body = "before " * 50 + " TARGET " + "after " * 50 out = server._build_snippet(body, terms=["TARGET"]) contains("build_snippet: includes the match", out, "TARGET") check("build_snippet: has ellipsis at both ends (windowed)", out.startswith("โฆ") and out.endswith("โฆ"), f"got {out[:30]!r} ... {out[-30:]!r}")
# -------- _strip_quote_headers_text --------
def test_strip_quote_headers_plaintext(): # The serialized quote header pattern from the indexer (fallback for # unbaked posts) text = ( 'ื ืืชื ืข"ื\n' 'someuser\n' 'ืืชืืจืื 2010-01-01 12:34:56\n' 'this is the quoted body\n' 'and the real reply here' ) out = server._strip_quote_headers_text(text) not_contains("strip_quote_headers: drops header marker", out, 'ื ืืชื ืข"ื') not_contains("strip_quote_headers: drops username line", out, "someuser") not_contains("strip_quote_headers: drops date line", out, "ืืชืืจืื") contains("strip_quote_headers: keeps body content", out, "real reply")
# -------- runner --------
ALL_TESTS = [ test_escape_fts_empty, test_escape_fts_hebrew_prefix_expansion, test_escape_fts_skip_prefix_for_word_already_starting_with_it, test_escape_fts_stopword_dropped_when_other_tokens_present, test_escape_fts_stopword_kept_when_alone, test_escape_fts_quoted_phrase_exact, test_escape_fts_quoted_keeps_stopword, test_escape_fts_mixed_quoted_and_bare, test_escape_fts_nonhebrew_no_prefix_expansion, test_is_stopword_known_words, test_strip_quotes_simple, test_strip_quotes_nested, test_strip_quotes_deeply_nested, test_strip_quotes_no_blockquote, test_query_terms_bare_tokens, test_query_terms_quoted_phrase, test_query_terms_mixed, test_query_terms_drops_special_tokens, test_term_present_simple, test_term_present_hebrew_prefix, test_build_snippet_no_terms_returns_start, test_build_snippet_centers_on_match, test_strip_quote_headers_plaintext,]
def main() -> int: print(f"Running {len(ALL_TESTS)} parser test groups") print("=" * 60) for t in ALL_TESTS: try: t() except Exception as e: failed.append((t.__name__, f"raised: {type(e).__name__}: {e}")) print(f" โ {t.__name__} raised: {type(e).__name__}: {e}") print("=" * 60) print(f"PASSED: {len(passed)} FAILED: {len(failed)}") if failed: print() print("FAILURES:") for name, detail in failed: print(f" - {name}: {detail}") return 1 return 0
if __name__ == "__main__": sys.exit(main())tools/.dockerignoreAdded+30
tools/BUILD.mdAdded+81
tools/DEPLOY.mdAdded+135
tools/DockerfileAdded+67
tools/README.mdAdded+53
tools/bake_rich_html.pyAdded+140
tools/build_index.pyAdded+538
tools/deploy.shAdded+175
tools/populate_forum_names.pyAdded+66
tools/predeploy.shAdded+121
tools/requirements.txtAdded+7
tools/static/favicon.icoAdded
tools/static/index.htmlAdded
tools/static/logo.pngAdded

Large File Pointer Details
- SHA256: 644daf5e08fcab41d746de5d91e04f6e8495f932ea47ffd109f8436d2277bfa2
- Pointer size: 131 Bytes
- Size of remote file: 106 kB
tools/tests/smoke.pyAdded+227
tools/tests/test_parsers.pyAdded+326