File size: 12,153 Bytes
e84f53b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 | """
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
# ---------------------------------------------------------------------------
# Database
# ---------------------------------------------------------------------------
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()
# Migrate old schema (crawl_id → run_id) if needed
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
# ---------------------------------------------------------------------------
# Utilities
# ---------------------------------------------------------------------------
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---"
# ---------------------------------------------------------------------------
# Stage 1: Discover
# ---------------------------------------------------------------------------
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()
# ---------------------------------------------------------------------------
# Stage 2: Download
# ---------------------------------------------------------------------------
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
# Fetch from Wayback Machine via cdx_toolkit
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.")
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
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()
|