#!/usr/bin/env python """Build a DuckDB dataset of SCP Foundation Wiki content pages, one year at a time. Downloads every content page (the `_default` Wikidot category: SCPs, tales, hubs, GOI formats, essays, art) created in a given year on the English SCP wiki (`scp-wiki.wikidot.com`), through the Crom GraphQL API via the `thaumiel` client. Captured per page: url, wikidot id, title, rating, vote count, category, created_at (UTC), revision count, comment count, thumbnail url, parent url, created_by (crom id / display name / unix name / wikidot id), source (raw Wikidot text), summary, tags, alternate titles, and attributions (a JSON array of {type, user_display_name, date, order}). Only the rendered text content is skipped; hidden pages and user/author pages are filtered out server-side. The DuckDB file is the checkpoint: re-running a year resumes from the last saved page (a `created_at` watermark) and re-fetched rows upsert in place, so interruptions and Ctrl+C are safe. A `pages` table (with an `attributions` JSON column) plus normalized `page_tags` and `page_alternate_titles` child tables. Usage (run from the src/ directory): python scp_dataset.py 2008 python scp_dataset.py 2023 --page-size 100 python scp_dataset.py 2023 --restart # re-crawl a year from January 1 Publish to Parquet (one file per table) with the companion script: python export_parquet.py """ from __future__ import annotations import argparse import asyncio import contextlib import json import logging import signal import sys import time from datetime import UTC, datetime, timedelta from functools import partial from typing import TYPE_CHECKING import duckdb import httpx from thaumiel import AsyncClient, F, RetryPolicy, Sort, SortKey, estimate_pages if TYPE_CHECKING: from thaumiel import Page, Predicate # --- Constants ------------------------------------------------------------------------ EN_WIKI_URL_PREFIX = "http://scp-wiki.wikidot.com" CONTENT_CATEGORY = "_default" QUOTA_CEILING = 300_000 # Crom's per-window point budget (resets every 5 minutes). WIKI_FIRST_YEAR = 2008 MAX_PAGE_SIZE = 100 # Crom's per-request ceiling for `first`. DEFAULT_DB = "../data/scp_dataset.duckdb" DEFAULT_PAGE_SIZE = 100 DEFAULT_MIN_POINTS = 2_000 DEFAULT_USER_AGENT = "thaumiel-scp-dataset/1.0 (contact: hi@efe.cv)" logger = logging.getLogger("scp_dataset") # --- Time helpers --------------------------------------------------------------------- def to_utc_naive(value: datetime) -> datetime: """Normalize an aware datetime to naive UTC for DuckDB TIMESTAMP storage.""" return value.astimezone(UTC).replace(tzinfo=None) def year_bounds(year: int) -> tuple[datetime, datetime]: """Return the aware-UTC `[start, end)` bounds of a calendar year.""" return datetime(year, 1, 1, tzinfo=UTC), datetime(year + 1, 1, 1, tzinfo=UTC) # --- Quota tracking ------------------------------------------------------------------- class Quota: """Tracks Crom's fixed-window rate-limit budget from response headers. Crom bills points against a 300,000-point budget that resets to full at the wall-clock time in `x-ratelimit-reset` (no gradual refill). An httpx response hook keeps this current after every API call. """ def __init__(self) -> None: self.remaining: int | None = None self.limit: int | None = None self.reset_at: float | None = None self.spent: int = 0 self._last: int | None = None async def hook(self, response: httpx.Response) -> None: """Record the latest rate-limit headers (an httpx response hook).""" remaining = response.headers.get("x-ratelimit-remaining") limit = response.headers.get("x-ratelimit-limit") reset = response.headers.get("x-ratelimit-reset") if remaining is not None: value = int(remaining) # Count only decreases as spend; an increase means the window reset. if self._last is not None and value < self._last: self.spent += self._last - value self._last = value self.remaining = value if limit is not None: self.limit = int(limit) if reset is not None: self.reset_at = float(reset) def seconds_until_reset(self) -> float: """Seconds until the current window resets, per the last seen header.""" if self.reset_at is None: return 0.0 return max(0.0, self.reset_at - time.time()) # --- Filter --------------------------------------------------------------------------- def content_filter(year: int, *, since: datetime | None = None) -> Predicate: """Build the server-side filter for EN-wiki content pages created in `year`. `since` (aware UTC) overrides the lower bound when resuming; it is inclusive (`>=`) so no page is skipped, and re-fetched boundary pages upsert harmlessly. """ start, end = year_bounds(year) lower = since if since is not None else start return ( F.url.starts_with(EN_WIKI_URL_PREFIX) & (F.is_hidden == False) # noqa: E712 # DSL overloads `==`; `is False` won't build a predicate & (F.is_user_page == False) # noqa: E712 & (F.category == CONTENT_CATEGORY) & (F.created_at >= lower) & (F.created_at < end) ) # --- Database layer ------------------------------------------------------------------- _SCHEMA = """ CREATE TABLE IF NOT EXISTS pages ( url VARCHAR PRIMARY KEY, wikidot_id VARCHAR, title VARCHAR NOT NULL, rating DOUBLE, -- nullable; net votes on EN vote_count INTEGER NOT NULL, category VARCHAR NOT NULL, created_at TIMESTAMP NOT NULL, -- UTC (naive) revision_count INTEGER NOT NULL, comment_count INTEGER NOT NULL, thumbnail_url VARCHAR, parent_url VARCHAR, created_by_crom_id VARCHAR, -- null if author account deleted created_by_display_name VARCHAR, created_by_unix_name VARCHAR, created_by_wikidot_id VARCHAR, source VARCHAR, -- raw Wikidot source text summary VARCHAR, -- author summary, often null attributions JSON, -- [{type, user_display_name, ...}] fetched_at TIMESTAMP NOT NULL -- UTC (naive); when saved ); CREATE TABLE IF NOT EXISTS page_tags ( page_url VARCHAR NOT NULL, position INTEGER NOT NULL, -- preserves Crom's tag order tag VARCHAR NOT NULL, PRIMARY KEY (page_url, tag) ); CREATE TABLE IF NOT EXISTS page_alternate_titles ( page_url VARCHAR NOT NULL, idx INTEGER NOT NULL, title VARCHAR NOT NULL, source VARCHAR NOT NULL, PRIMARY KEY (page_url, idx) ); """ # Page columns, kept in lockstep with the tuple built by `_page_row`. _PAGE_COLUMNS = ( "url", "wikidot_id", "title", "rating", "vote_count", "category", "created_at", "revision_count", "comment_count", "thumbnail_url", "parent_url", "created_by_crom_id", "created_by_display_name", "created_by_unix_name", "created_by_wikidot_id", "source", "summary", "attributions", "fetched_at", ) # Built from internal constants only, so the f-string is injection-safe. _INSERT_PAGE = ( f"INSERT OR REPLACE INTO pages ({', '.join(_PAGE_COLUMNS)}) " # noqa: S608 f"VALUES ({', '.join(['?'] * len(_PAGE_COLUMNS))})" ) def connect(db_path: str) -> duckdb.DuckDBPyConnection: """Open the DuckDB database and ensure the schema (with migrations) exists.""" con = duckdb.connect(db_path) con.execute(_SCHEMA) # Migration: add `attributions` to databases created before the column existed. con.execute("ALTER TABLE pages ADD COLUMN IF NOT EXISTS attributions JSON") return con def _attributions_json(page: Page) -> str: """Serialize a page's attributions to a JSON array string for the JSON column.""" return json.dumps( [ { "type": a.type.value, "user_display_name": a.user_display_name, "date": a.date.isoformat() if a.date is not None else None, "order": a.order, } for a in page.attributions or () ], ensure_ascii=False, ) def _page_row(page: Page, fetched_at: datetime) -> tuple[object, ...]: """Flatten a page into a row tuple matching `_PAGE_COLUMNS`.""" author = page.created_by return ( page.url, page.wikidot_id, page.title, page.rating, page.vote_count, page.category, to_utc_naive(page.created_at), page.revision_count, page.comment_count, page.thumbnail_url, page.parent_url, author.id if author else None, author.display_name if author else None, author.unix_name if author else None, author.wikidot_id if author else None, page.source, page.summary, _attributions_json(page), fetched_at, ) def save_batch( con: duckdb.DuckDBPyConnection, pages: tuple[Page, ...], fetched_at: datetime, ) -> None: """Upsert a batch of pages and their child rows in one transaction. Pages are replaced by URL and child rows are delete-then-insert, so re-saving a page (on resume or `--restart`) is idempotent. """ page_rows = [_page_row(p, fetched_at) for p in pages] urls = [(p.url,) for p in pages] tag_rows: list[tuple[str, int, str]] = [] alt_rows: list[tuple[str, int, str, str]] = [] for p in pages: # Tags are unique per page already; dedupe defensively, preserving order. for i, tag in enumerate(dict.fromkeys(p.tags)): tag_rows.append((p.url, i, tag)) for i, alt in enumerate(p.alternate_titles or ()): alt_rows.append((p.url, i, alt.title, alt.source)) con.execute("BEGIN TRANSACTION") try: con.executemany(_INSERT_PAGE, page_rows) con.executemany("DELETE FROM page_tags WHERE page_url = ?", urls) con.executemany("DELETE FROM page_alternate_titles WHERE page_url = ?", urls) if tag_rows: con.executemany("INSERT INTO page_tags VALUES (?, ?, ?)", tag_rows) if alt_rows: con.executemany( "INSERT INTO page_alternate_titles VALUES (?, ?, ?, ?)", alt_rows ) except Exception: con.execute("ROLLBACK") raise con.execute("COMMIT") def year_saved_count(con: duckdb.DuckDBPyConnection, year: int) -> int: """Count pages already saved for `year`.""" start, end = year_bounds(year) row = con.execute( "SELECT count(*) FROM pages WHERE created_at >= ? AND created_at < ?", [to_utc_naive(start), to_utc_naive(end)], ).fetchone() return int(row[0]) if row else 0 def year_watermark(con: duckdb.DuckDBPyConnection, year: int) -> datetime | None: """Latest `created_at` saved for `year` (the resume point), or None.""" start, end = year_bounds(year) row = con.execute( "SELECT max(created_at) FROM pages WHERE created_at >= ? AND created_at < ?", [to_utc_naive(start), to_utc_naive(end)], ).fetchone() return row[0] if row and row[0] is not None else None # --- Crawl ---------------------------------------------------------------------------- async def ensure_budget( quota: Quota, batch_cost: int, min_points: int, stop: asyncio.Event, ) -> None: """Pause until the rate-limit window resets if the next batch would dip too low.""" if quota.remaining is None or quota.remaining - batch_cost >= min_points: return wait = quota.seconds_until_reset() + 2.0 logger.warning( "Low quota (%s left); pausing %.0fs for the window reset.", f"{quota.remaining:,}", wait, ) # Returns early if a stop is requested mid-wait; otherwise waits the full window. with contextlib.suppress(TimeoutError): await asyncio.wait_for(stop.wait(), timeout=wait) def _install_signal_handlers(stop: asyncio.Event, task: asyncio.Task[int]) -> None: """First Ctrl+C stops after the current batch; a second cancels at once.""" def handle() -> None: if not stop.is_set(): stop.set() logger.warning( "Interrupt received -- finishing the current batch, then stopping. " "Press Ctrl+C again to force-quit." ) else: logger.warning("Second interrupt -- cancelling now.") task.cancel() loop = asyncio.get_running_loop() for sig in (signal.SIGINT, signal.SIGTERM): with contextlib.suppress(NotImplementedError): # not supported on Windows loop.add_signal_handler(sig, handle) def _log_plan( args: argparse.Namespace, expected: int, already: int, quota: Quota, ) -> None: """Log the crawl banner: scope, sizing, and current quota.""" per_page = estimate_pages( page_size=1, source=True, summary=True, alternate_titles=True, attributions=True, ) remaining = max(0, expected - already) est = remaining * per_page logger.info("=" * 72) logger.info( "SCP dataset crawl -- English wiki, _default content, year %d", args.year, ) logger.info("Database: %s", args.db) logger.info( "Pages this year: %s expected | %s already saved | ~%s to fetch", f"{expected:,}", f"{already:,}", f"{remaining:,}", ) logger.info( "Cost: %d pts/page | est. ~%s pts for the rest (%.1f%% of a %s-pt window)", per_page, f"{est:,}", est / QUOTA_CEILING * 100, f"{QUOTA_CEILING:,}", ) if quota.remaining is not None: logger.info( "Quota now: %s / %s points, window resets in %.0fs", f"{quota.remaining:,}", f"{quota.limit or QUOTA_CEILING:,}", quota.seconds_until_reset(), ) logger.info("=" * 72) async def crawl_year(args: argparse.Namespace) -> int: # noqa: C901, PLR0915 — linear orchestration """Crawl one year into the database; return a process exit code.""" con = connect(args.db) quota = Quota() http = httpx.AsyncClient( headers={"User-Agent": args.user_agent}, timeout=args.timeout, event_hooks={"response": [quota.hook]}, ) client = AsyncClient(http_client=http) retry = RetryPolicy( max_attempts=args.max_attempts, backoff=args.backoff, retry_server_errors=True, ) stop = asyncio.Event() task = asyncio.current_task() if task is not None: _install_signal_handlers(stop, task) year: int = args.year batch_cost = estimate_pages( page_size=args.page_size, source=True, summary=True, alternate_titles=True, attributions=True, ) try: # Count first: sizes the job and primes the quota headers. expected = await retry.run(lambda: client.count_pages(content_filter(year))) already = year_saved_count(con, year) watermark = None if args.restart else year_watermark(con, year) _log_plan(args, expected, already, quota) if args.restart: logger.info("Restart: re-crawling from January 1 (rows updated in place).") if expected == 0: logger.info("No content pages found for %d. Nothing to do.", year) return 0 if already >= expected and not args.restart: logger.info("Year %d already complete (%s saved).", year, f"{already:,}") return 0 since = watermark.replace(tzinfo=UTC) if watermark is not None else None if since is not None: logger.info( "Resuming from %s UTC (boundary re-fetched; duplicates upsert).", watermark, ) crawl = content_filter(year, since=since) sort = Sort.by(SortKey.CREATED_AT, descending=False) after: str | None = None batch_no = 0 saved_this_run = 0 run_start = time.monotonic() fetched_at = to_utc_naive(datetime.now(UTC)) while not stop.is_set(): await ensure_budget(quota, batch_cost, args.min_points, stop) if stop.is_set(): break t0 = time.monotonic() batch = await retry.run( partial( client.fetch_page_batch, filter=crawl, sort=sort, page_size=args.page_size, after=after, source=True, summary=True, alternate_titles=True, attributions=True, ) ) if batch.pages: save_batch(con, batch.pages, fetched_at) saved_this_run += len(batch.pages) batch_no += 1 total = year_saved_count(con, year) rate = saved_this_run / max(1e-9, time.monotonic() - run_start) eta = ( timedelta(seconds=int((expected - total) / rate)) if rate > 0 else timedelta() ) logger.info( "batch %-4d +%-3d | %s/%s (%.1f%%) | %.1f pg/s | " "%s pts left, %s spent | %.2fs | ETA %s", batch_no, len(batch.pages), f"{total:,}", f"{expected:,}", total / expected * 100 if expected else 100.0, rate, f"{quota.remaining:,}" if quota.remaining is not None else "?", f"{quota.spent:,}", time.monotonic() - t0, eta, ) if not batch.has_next_page or batch.end_cursor is None: logger.info("Reached the end of %d.", year) break after = batch.end_cursor total = year_saved_count(con, year) interrupted = stop.is_set() and total < expected logger.info("-" * 72) logger.info( "%s year %d: %s/%s saved (this run %s) | run cost %s pts | %s left | %.1fs", "INTERRUPTED" if interrupted else "DONE", year, f"{total:,}", f"{expected:,}", f"{saved_this_run:,}", f"{quota.spent:,}", f"{quota.remaining:,}" if quota.remaining is not None else "?", time.monotonic() - run_start, ) if interrupted: logger.info("Re-run the same command to continue where you left off.") logger.info("-" * 72) finally: await http.aclose() con.close() return 0 # --- CLI ------------------------------------------------------------------------------ def setup_logging(log_file: str | None, *, verbose: bool) -> None: """Configure the package logger to write to stderr (and optionally a file).""" logger.setLevel(logging.DEBUG if verbose else logging.INFO) logger.propagate = False console = logging.StreamHandler(sys.stderr) console.setFormatter( logging.Formatter("%(asctime)s %(levelname)-7s %(message)s", "%H:%M:%S") ) logger.addHandler(console) if log_file: file_handler = logging.FileHandler(log_file) file_handler.setFormatter( logging.Formatter("%(asctime)s %(levelname)-7s %(message)s") ) logger.addHandler(file_handler) def parse_args(argv: list[str] | None = None) -> argparse.Namespace: """Parse and validate command-line arguments.""" parser = argparse.ArgumentParser( description="Download SCP wiki content pages for one year into DuckDB.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument("year", type=int, help="Calendar year to crawl, e.g. 2008") parser.add_argument("--db", default=DEFAULT_DB, help="DuckDB database path") parser.add_argument( "--page-size", type=int, default=DEFAULT_PAGE_SIZE, help="Pages per API round trip", ) parser.add_argument( "--restart", action="store_true", help="Re-crawl the year from January 1 instead of resuming", ) parser.add_argument( "--min-points", type=int, default=DEFAULT_MIN_POINTS, help="Pause for the window reset when points dip below this", ) parser.add_argument( "--user-agent", default=DEFAULT_USER_AGENT, help="HTTP User-Agent" ) parser.add_argument( "--timeout", type=float, default=30.0, help="HTTP timeout (seconds)" ) parser.add_argument( "--max-attempts", type=int, default=5, help="Max attempts per API call (retry/backoff)", ) parser.add_argument( "--backoff", type=float, default=1.0, help="Base seconds for exponential backoff", ) parser.add_argument( "--log-file", default=None, help="Also append logs to this file" ) parser.add_argument("--verbose", action="store_true", help="Debug-level logging") args = parser.parse_args(argv) if not WIKI_FIRST_YEAR <= args.year <= datetime.now(UTC).year: parser.error(f"year must be between {WIKI_FIRST_YEAR} and now") if not 1 <= args.page_size <= MAX_PAGE_SIZE: parser.error(f"page-size must be between 1 and {MAX_PAGE_SIZE}") return args def main(argv: list[str] | None = None) -> int: """Entry point: parse arguments, set up logging, and run the crawl.""" args = parse_args(argv) setup_logging(args.log_file, verbose=args.verbose) try: return asyncio.run(crawl_year(args)) except KeyboardInterrupt, asyncio.CancelledError: logger.warning("Cancelled. Progress through the last committed batch is saved.") return 130 if __name__ == "__main__": raise SystemExit(main())