Files
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

106 lines
3.8 KiB
Python

# -*- coding: utf-8 -*-
"""Download images for every card referenced in the comparison comments."""
import json, os, re, sys, gzip, io, time, urllib.request
from concurrent.futures import ThreadPoolExecutor, as_completed
from PIL import Image
BASE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(BASE, 'images_ref')
os.makedirs(OUT, exist_ok=True)
ZH = r'C:/Code/Mtga/data/mtgch/cardnames-zh-CN.txt'
ORACLE = r'C:/Code/Mtga/.tmp/oracle.jsonl.gz'
def load_zh():
d = {}
for line in open(ZH, encoding='utf-8'):
p = line.rstrip('\r\n').split('|')
if len(p) >= 4:
d[p[0].lower()] = p[1]
return d
def main():
cards = json.load(open(os.path.join(BASE, 'data', 'cards_scored.json'), encoding='utf-8'))
names = []
seen = set()
for c in cards:
for m in re.findall(r'\[\[([^\]]+)\]\]', c['comment']):
n = m.split('|')[0].strip()
if n.lower() not in seen:
seen.add(n.lower())
names.append(n)
print('unique refs', len(names))
oracle = {}
with gzip.open(ORACLE, 'rt', encoding='utf-8') as f:
for line in f:
c = json.loads(line)
if c['name'].lower() not in oracle:
oracle[c['name'].lower()] = c
zh = load_zh()
meta = {}
jobs = []
for n in names:
c = oracle.get(n.lower())
if not c:
print('MISSING oracle', n)
continue
uris = c.get('image_uris')
if not uris and c.get('card_faces'):
uris = c['card_faces'][0].get('image_uris')
url = (uris or {}).get('normal') or (uris or {}).get('large') or (uris or {}).get('small')
if not url:
print('MISSING image', n)
continue
oid = c.get('oracle_id') or c.get('id')
path = os.path.join(OUT, f'{oid}.jpg')
meta[n.lower()] = {
'name': c['name'],
'zh_name': zh.get(n.lower(), c['name']),
'rarity': c.get('rarity'),
'mana_cost': c.get('mana_cost') or '',
'type_line': c.get('type_line', ''),
'image': f'images_ref/{oid}.jpg',
}
jobs.append((n, url, path))
def fetch(job):
n, url, path = job
if os.path.exists(path) and os.path.getsize(path) > 4000:
return n, 'cached'
for attempt in range(4):
try:
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
raw = urllib.request.urlopen(req, timeout=45).read()
im = Image.open(io.BytesIO(raw)).convert('RGBA')
bg = Image.new('RGB', im.size, (255, 255, 255))
bg.paste(im, mask=im.split()[-1])
w = 220
h = round(im.size[1] * w / im.size[0])
bg = bg.resize((w, h), Image.LANCZOS)
bg.save(path, 'JPEG', quality=86, optimize=True)
return n, 'ok'
except Exception as e:
if attempt == 3:
return n, f'FAIL {e}'
time.sleep(1.5 * (attempt + 1))
fails = []
with ThreadPoolExecutor(max_workers=8) as ex:
futs = [ex.submit(fetch, j) for j in jobs]
for k, fut in enumerate(as_completed(futs), 1):
n, msg = fut.result()
if msg.startswith('FAIL'):
fails.append((n, msg))
print('FAIL', n, msg)
elif k % 40 == 0:
print(k, msg, flush=True)
print('fails', fails)
with open(os.path.join(BASE, 'data', 'ref_cards.json'), 'w', encoding='utf-8') as f:
json.dump(meta, f, ensure_ascii=False, indent=1)
ok = sum(1 for m in meta.values() if os.path.exists(os.path.join(BASE, m['image'])))
print('ref cards', len(meta), 'images', ok)
if __name__ == '__main__':
main()