| """ |
| MTG Corpus Fetcher — two-stage pipeline using Internet Archive. |
| |
| Stage 1 (discover): enumerate URLs from IA CDX into state.db |
| Stage 2 (download): fetch content for pending URLs from Wayback Machine |
| |
| Usage: |
| python fetch.py discover |
| python fetch.py discover --from-year 2024 --to-year 2025 |
| python fetch.py discover --dry-run |
| |
| python fetch.py download |
| python fetch.py download --workers 16 |
| python fetch.py download --limit 500 |
| python fetch.py download --retry fetch_error |
| python fetch.py download --dry-run |
| """ |
|
|
| import argparse |
| import hashlib |
| import sqlite3 |
| import threading |
| from concurrent.futures import ThreadPoolExecutor, as_completed |
| from datetime import datetime, timezone |
| from pathlib import Path |
|
|
| import cdx_toolkit |
| import trafilatura |
| import yaml |
|
|
| ROOT = Path(__file__).parent |
| DB_PATH = ROOT / "state.db" |
| CORPUS_DIR = ROOT / "corpus" |
| HTML_DIR = ROOT / "html" |
| SITES_FILE = ROOT / "sites.yaml" |
| MIN_LENGTH = 500 |
|
|
|
|
| |
| |
| |
|
|
| def open_db() -> sqlite3.Connection: |
| conn = sqlite3.connect(str(DB_PATH), check_same_thread=False) |
| conn.row_factory = sqlite3.Row |
| conn.execute("PRAGMA journal_mode=WAL") |
| conn.executescript(""" |
| CREATE TABLE IF NOT EXISTS crawl_runs ( |
| run_id TEXT, |
| site TEXT, |
| url_pattern TEXT, |
| status TEXT, |
| url_count INTEGER, |
| started_at TEXT, |
| completed_at TEXT, |
| PRIMARY KEY (run_id, site) |
| ); |
| CREATE TABLE IF NOT EXISTS pages ( |
| url TEXT PRIMARY KEY, |
| run_id TEXT, |
| site TEXT, |
| http_code INTEGER, |
| discovered_at TEXT, |
| download_status TEXT, |
| archive TEXT, |
| filename TEXT, |
| char_count INTEGER, |
| downloaded_at TEXT |
| ); |
| CREATE INDEX IF NOT EXISTS idx_pages_status ON pages(download_status); |
| """) |
| conn.commit() |
| |
| for table in ("crawl_runs", "pages"): |
| try: |
| conn.execute(f"ALTER TABLE {table} RENAME COLUMN crawl_id TO run_id") |
| conn.commit() |
| except Exception: |
| pass |
| return conn |
|
|
|
|
| |
| |
| |
|
|
| def now_iso() -> str: |
| return datetime.now(timezone.utc).isoformat() |
|
|
|
|
| def url_to_filename(url: str) -> str: |
| slug = url.rstrip("/").split("/")[-1][:60] or "index" |
| uid = hashlib.md5(url.encode()).hexdigest()[:8] |
| return f"{slug}-{uid}.md" |
|
|
|
|
| def load_sites() -> list[dict]: |
| with open(SITES_FILE, encoding="utf-8") as f: |
| return yaml.safe_load(f)["sites"] |
|
|
|
|
| def make_run_id(from_year: int | None, to_year: int | None) -> str: |
| if from_year and to_year: |
| return f"ia-{from_year}-{to_year}" |
| if from_year: |
| return f"ia-from{from_year}" |
| if to_year: |
| return f"ia-to{to_year}" |
| return "ia" |
|
|
|
|
| def year_to_ts(year: int, end: bool = False) -> str: |
| return f"{year}1231235959" if end else f"{year}0101000000" |
|
|
|
|
| def extract_text_and_meta(html: bytes, url: str) -> tuple[str | None, object]: |
| text = trafilatura.extract( |
| html, |
| url=url, |
| output_format="markdown", |
| include_comments=False, |
| include_tables=True, |
| ) |
| try: |
| meta = trafilatura.extract_metadata(html.decode("utf-8", errors="replace"), default_url=url) |
| except Exception: |
| meta = None |
| return text, meta |
|
|
|
|
| def build_frontmatter(url: str, site: str, run_id: str, meta=None) -> str: |
| fields: dict = { |
| "source": url, |
| "site": site, |
| "archive": "ia", |
| "run": run_id, |
| "fetched": datetime.now(timezone.utc).date().isoformat(), |
| } |
| if meta: |
| if getattr(meta, "title", None): |
| fields["title"] = meta.title |
| if getattr(meta, "date", None): |
| fields["date"] = meta.date |
| if getattr(meta, "author", None): |
| fields["author"] = meta.author |
| body = yaml.dump(fields, allow_unicode=True, default_flow_style=False, sort_keys=False).rstrip() |
| return f"---\n{body}\n---" |
|
|
|
|
| |
| |
| |
|
|
| def cmd_discover(args: argparse.Namespace) -> None: |
| sites = load_sites() |
| run_id = make_run_id(args.from_year, args.to_year) |
|
|
| cdx_kwargs: dict = {"collapse": "urlkey"} |
| if args.from_year: |
| cdx_kwargs["from_ts"] = year_to_ts(args.from_year) |
| if args.to_year: |
| cdx_kwargs["to"] = year_to_ts(args.to_year, end=True) |
|
|
| if args.dry_run: |
| print(f"Run: {run_id}") |
| for s in sites: |
| print(f" {s['site']:20s} {s['url']}") |
| return |
|
|
| db = open_db() |
| print(f"Run: {run_id}") |
|
|
| for s in sites: |
| site, pattern = s["site"], s["url"].rstrip("/*") + "/*" |
|
|
| print(f"Searching {site} with {pattern}") |
|
|
| row = db.execute( |
| "SELECT status FROM crawl_runs WHERE run_id=? AND site=?", |
| (run_id, site), |
| ).fetchone() |
| if row and row["status"] == "complete": |
| print(f" [skip] {site}") |
| continue |
|
|
| db.execute( |
| "INSERT OR REPLACE INTO crawl_runs " |
| "(run_id, site, url_pattern, status, started_at) VALUES (?,?,?,?,?)", |
| (run_id, site, pattern, "in_progress", now_iso()), |
| ) |
| db.commit() |
| print(f" {site}: {pattern}") |
| print(f" querying IA CDX... (may pause on retries)", flush=True) |
|
|
| cdx = cdx_toolkit.CDXFetcher(source="ia") |
| count = 0 |
| last_url = "" |
| try: |
| for obj in cdx.iter(pattern, **cdx_kwargs): |
| url = obj["url"] |
| last_url = url |
| try: |
| http_code = int(obj.get("status") or 0) |
| except (ValueError, TypeError): |
| http_code = 0 |
| db.execute( |
| "INSERT OR IGNORE INTO pages " |
| "(url, run_id, site, http_code, discovered_at) VALUES (?,?,?,?,?)", |
| (url, run_id, site, http_code, now_iso()), |
| ) |
| count += 1 |
| if count % 100 == 0: |
| db.commit() |
| ts = datetime.now(timezone.utc).strftime("%H:%M:%S") |
| print(f" [{ts}] {count:,} URLs last: {last_url}", flush=True) |
| except Exception as e: |
| db.execute( |
| "UPDATE crawl_runs SET status='error', completed_at=? WHERE run_id=? AND site=?", |
| (now_iso(), run_id, site), |
| ) |
| db.commit() |
| print(f" ERROR {site}: {e}") |
| continue |
|
|
| db.commit() |
| db.execute( |
| "UPDATE crawl_runs SET status='complete', url_count=?, completed_at=? " |
| "WHERE run_id=? AND site=?", |
| (count, now_iso(), run_id, site), |
| ) |
| db.commit() |
| print(f" {site}: {count:,} URLs discovered") |
|
|
| db.close() |
|
|
|
|
| |
| |
| |
|
|
| def process_page(row: sqlite3.Row, db: sqlite3.Connection, db_lock: threading.Lock) -> str: |
| url = row["url"] |
| run_id = row["run_id"] |
| site = row["site"] |
| http_code = row["http_code"] |
|
|
| def update(status: str, filename=None, char_count=None) -> None: |
| with db_lock: |
| db.execute( |
| "UPDATE pages SET download_status=?, archive=?, filename=?, char_count=?, " |
| "downloaded_at=? WHERE url=?", |
| (status, "ia" if filename else None, filename, char_count, now_iso(), url), |
| ) |
| db.commit() |
|
|
| def save_file(text: str, meta, html: bytes) -> str: |
| filename = url_to_filename(url) |
| out_dir = CORPUS_DIR / site |
| out_dir.mkdir(parents=True, exist_ok=True) |
| fm = build_frontmatter(url, site, run_id, meta) |
| (out_dir / filename).write_text(f"{fm}\n\n{text}", encoding="utf-8") |
| html_dir = HTML_DIR / site |
| html_dir.mkdir(parents=True, exist_ok=True) |
| (html_dir / filename).with_suffix(".html").write_bytes(html) |
| return filename |
|
|
| |
| html: bytes | None = None |
| fetch_err: str | None = None |
|
|
| if http_code not in (0, 200): |
| fetch_err = "http_error" |
| else: |
| try: |
| cdx = cdx_toolkit.CDXFetcher(source="ia") |
| for obj in cdx.iter(url, limit=1): |
| html = obj.content |
| break |
| if html is None: |
| fetch_err = "not_found" |
| except Exception: |
| fetch_err = "fetch_error" |
|
|
| if html is None: |
| update(fetch_err or "not_found") |
| return f"[{fetch_err or 'not_found'}] {url}" |
|
|
| text, meta = extract_text_and_meta(html, url) |
|
|
| if text and len(text) >= MIN_LENGTH: |
| fn = save_file(text, meta, html) |
| update("saved", fn, len(text)) |
| return f"[saved] {fn} ({len(text):,})" |
|
|
| if text: |
| fn = save_file(text, meta, html) |
| update("too_short", fn, len(text)) |
| return f"[too_short] {fn} ({len(text):,})" |
|
|
| update("no_text") |
| return f"[no_text] {url}" |
|
|
|
|
| def cmd_download(args: argparse.Namespace) -> None: |
| db = open_db() |
| db_lock = threading.Lock() |
|
|
| limit_clause = f" LIMIT {args.limit}" if args.limit else "" |
| if args.retry: |
| rows = db.execute( |
| f"SELECT url, run_id, site, http_code FROM pages WHERE download_status=?{limit_clause}", |
| (args.retry,), |
| ).fetchall() |
| else: |
| rows = db.execute( |
| f"SELECT url, run_id, site, http_code FROM pages WHERE download_status IS NULL{limit_clause}" |
| ).fetchall() |
|
|
| if args.dry_run: |
| print(f"Pending: {len(rows):,} URLs") |
| db.close() |
| return |
|
|
| CORPUS_DIR.mkdir(exist_ok=True) |
| HTML_DIR.mkdir(exist_ok=True) |
| total = len(rows) |
| done = 0 |
| print(f"Downloading {total:,} URLs ({args.workers} workers)...") |
|
|
| with ThreadPoolExecutor(max_workers=args.workers) as pool: |
| futures = {pool.submit(process_page, row, db, db_lock): row["url"] for row in rows} |
| for future in as_completed(futures): |
| done += 1 |
| try: |
| result = future.result() |
| print(f" [{done}/{total}] {result}") |
| except Exception as e: |
| print(f" [{done}/{total}] ERROR {futures[future]}: {e}") |
|
|
| db.close() |
| print(f"\nDone. {done:,} URLs processed.") |
|
|
|
|
| |
| |
| |
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser(prog="fetch.py", description="MTG corpus fetcher") |
| sub = parser.add_subparsers(dest="command", required=True) |
|
|
| disc = sub.add_parser("discover", help="Enumerate URLs from IA CDX into state.db") |
| disc.add_argument("--from-year", type=int, dest="from_year", help="Only captures from this year onwards") |
| disc.add_argument("--to-year", type=int, dest="to_year", help="Only captures up to end of this year") |
| disc.add_argument("--dry-run", action="store_true") |
|
|
| dl = sub.add_parser("download", help="Fetch content for pending URLs from Wayback Machine") |
| dl.add_argument("--workers", type=int, default=8) |
| dl.add_argument("--limit", type=int) |
| dl.add_argument("--retry", metavar="STATUS") |
| dl.add_argument("--dry-run", action="store_true") |
|
|
| args = parser.parse_args() |
| {"discover": cmd_discover, "download": cmd_download}[args.command](args) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|