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.
This commit is contained in:
2026-11-15 11:37:16 +08:00
parent 4984b1f756
commit 58446ec562
1131 changed files with 1430660 additions and 189314 deletions
+120
View File
@@ -0,0 +1,120 @@
#!/usr/bin/env python3
"""Fetch a set's card data from Scryfall into data/scryfall/<SET>.json.
The local `data/mtgch` card library is often incomplete for a brand-new set
(e.g. TRK: 117/336 cards), which starves `mech_tags` / `types` in
`build_templates_contract.py`. Scryfall has every card's Oracle text, so we
cache it here and let the build merge it in for names mtgch doesn't cover.
Output: {"<SET>": {"<card name>": {oracle, keywords, mana_cost, cmc,
types, color_identity, rarity, image_url, layout}}}
Usage:
python scripts/fetch_scryfall.py --set TRK # scryfall set code = trk
python scripts/fetch_scryfall.py --set TRK --scryfall-set trk
"""
from __future__ import annotations
import argparse
import http.client
import json
import re
import time
import urllib.error
import urllib.request
from pathlib import Path
API = "https://api.scryfall.com/cards/search"
UA = {"User-Agent": "MtgaAnalysis/1.0", "Accept": "application/json"}
def _get(url: str, tries: int = 6) -> dict:
last = None
for i in range(tries):
try:
req = urllib.request.Request(url, headers=UA)
with urllib.request.urlopen(req, timeout=60) as r:
return json.loads(r.read().decode("utf-8"))
except urllib.error.HTTPError as e:
if e.code == 404:
raise SystemExit(f"not found: {url}")
last = e
time.sleep(2 * (i + 1))
except (http.client.IncompleteRead, ConnectionError, TimeoutError, OSError) as e:
last = e
time.sleep(2 * (i + 1))
raise SystemExit(f"gave up after {tries}: {url} ({last})")
def _types(type_line: str) -> list[str]:
left = (type_line or "").split("—")[0]
return [w for w in re.split(r"[\s/]+", left) if w]
def _record(c: dict) -> dict:
faces = c.get("card_faces") or []
oracle = c.get("oracle_text") or " ".join(f.get("oracle_text", "") for f in faces)
mc = c.get("mana_cost") or (faces[0].get("mana_cost") if faces else "") or ""
img = (c.get("image_uris") or {}).get("normal")
if not img and faces:
img = (faces[0].get("image_uris") or {}).get("normal")
return {
"oracle": oracle,
"keywords": c.get("keywords") or [],
"mana_cost": mc,
"cmc": c.get("cmc"),
"types": _types(c.get("type_line", "")),
"color_identity": c.get("color_identity") or [],
"rarity": c.get("rarity"),
"image_url": img,
"layout": c.get("layout"),
}
def fetch(set_code: str, scryfall_set: str) -> dict:
out: dict = {}
url = f"{API}?q=set:{scryfall_set}&unique=cards&order=set"
n_pages = 0
while url:
d = _get(url)
for c in d.get("data") or []:
rec = _record(c)
out[c["name"]] = rec
# also index each face name so "A" resolves to "A // B"
for f in c.get("card_faces") or []:
if f.get("name"):
out.setdefault(f["name"], rec)
n_pages += 1
url = d.get("next_page")
print(f" page {n_pages}: +{len(d.get('data') or [])} (total {len(out)})", flush=True)
if url:
time.sleep(0.1) # be polite (<10 req/s)
return out
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--set", required=True, help="17lands set code, e.g. TRK")
ap.add_argument("--scryfall-set", default=None,
help="scryfall set code (default: --set lowercased)")
ap.add_argument("--out", default="data/scryfall")
ap.add_argument("--merge", action="store_true",
help="merge into existing <SET>.json instead of overwriting")
a = ap.parse_args()
setcode = a.set.upper()
sf = (a.scryfall_set or setcode).lower()
data = fetch(setcode, sf)
out = Path(a.out)
out.mkdir(parents=True, exist_ok=True)
p = out / f"{setcode}.json"
if a.merge and p.exists():
old = json.loads(p.read_text(encoding="utf-8"))
old.update(data)
data = old
p.write_text(json.dumps(data, ensure_ascii=False, indent=1), encoding="utf-8")
print(f"\nwrote {len(data)} cards -> {p} (scryfall set '{sf}')")
return 0
if __name__ == "__main__":
raise SystemExit(main())