Files
mtga/scripts/fetch_card_images.py
T
fukunee 58446ec562 Add TRK set preview and refresh draft analysis
Track the TRK preview package and the newest value artifacts for FRA20261007, move the 17lands API notes under data, and ignore downloaded 17lands, card image and live directories.
2026-11-15 11:37:16 +08:00

119 lines
4.2 KiB
Python

#!/usr/bin/env python3
"""Download a set's card images to data/card_images/<SET>/ for LOCAL reports.
New sets (e.g. TRK) have no images in `data/mtgch`, so the template pages fall
back to remote 17lands CDN URLs. This script caches them locally so the report
works offline and loads instantly.
Image source: `data/scryfall/<SET>.json` (see fetch_scryfall.py) `image_url`,
with a fallback to the 17lands `draft_picks.jsonl` image_url.
Filename: `<slugify(name)>.jpg|webp` — MUST match `render_templates_html.slugify`
(the renderer looks up `data/card_images/<SET>/<slug>.<ext>`).
Usage:
python scripts/fetch_card_images.py --set TRK
python scripts/fetch_card_images.py --set TRK --snapshot data/17lands/TRK20261114 -w 8
"""
from __future__ import annotations
import argparse
import http.client
import json
import sys
import time
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
from render_templates_html import slugify # noqa: E402
UA = {"User-Agent": "MtgaAnalysis/1.0"}
def _download(url: str, dest: Path, tries: int = 4) -> bool:
if dest.exists() and dest.stat().st_size > 1000:
return False
tmp = dest.with_suffix(dest.suffix + ".part")
last = None
for i in range(tries):
try:
req = urllib.request.Request(url, headers=UA)
with urllib.request.urlopen(req, timeout=60) as r:
data = r.read()
if len(data) < 500:
raise ValueError(f"too small ({len(data)} bytes)")
tmp.write_bytes(data)
tmp.replace(dest)
return True
except (urllib.error.HTTPError, http.client.IncompleteRead,
ConnectionError, TimeoutError, OSError, ValueError) as e:
last = e
time.sleep(1.5 * (i + 1))
print(f" [failed] {dest.name}: {last}", file=sys.stderr)
return False
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--set", required=True, help="17lands set code, e.g. TRK")
ap.add_argument("--snapshot", default=None,
help="可选:data/17lands/<snap>,用它补 draft_picks 的 image_url")
ap.add_argument("--out", default="data/card_images")
ap.add_argument("-w", "--workers", type=int, default=8)
a = ap.parse_args()
setcode = a.set.upper()
urls: dict[str, str] = {}
sf = ROOT / "data" / "scryfall" / f"{setcode}.json"
if sf.exists():
for name, rec in json.loads(sf.read_text(encoding="utf-8")).items():
u = (rec or {}).get("image_url")
if u:
urls.setdefault(name, u)
snap = Path(a.snapshot) if a.snapshot else None
dp = (snap / "drafts/draft_picks.jsonl") if snap else None
if dp and dp.exists():
for line in dp.open(encoding="utf-8"):
line = line.strip()
if not line:
continue
for m in (json.loads(line).get("cards") or {}).values():
nm, u = m.get("name"), m.get("image_url")
if nm and u:
urls.setdefault(nm, u)
if not urls:
raise SystemExit("no image urls: run scripts/fetch_scryfall.py first")
out_dir = ROOT / a.out / setcode
out_dir.mkdir(parents=True, exist_ok=True)
jobs = []
for name, u in urls.items():
sl = slugify(name).lower()
if not sl:
continue
ext = Path(u.split("?")[0]).suffix.lower() or ".jpg"
if ext not in (".jpg", ".jpeg", ".webp", ".png"):
ext = ".jpg"
jobs.append((u, out_dir / f"{sl}{ext}"))
print(f"[{setcode}] {len(urls)} cards -> {out_dir} (workers={a.workers})")
ok = 0
t0 = time.time()
with ThreadPoolExecutor(max_workers=a.workers) as pool:
futs = [pool.submit(_download, u, d) for u, d in jobs]
for i, f in enumerate(as_completed(futs), 1):
ok += 1 if f.result() else 0
if i % 50 == 0 or i == len(futs):
print(f" {i}/{len(futs)} new={ok} {i/(time.time()-t0):.1f}/s", flush=True)
print(f"done: {ok} new, {len(list(out_dir.iterdir()))} files in {out_dir}")
return 0
if __name__ == "__main__":
raise SystemExit(main())