# -*- coding: utf-8 -*- """Download the English card images for the 311 TRK cards and cache them as JPEG.""" import json, os, sys, urllib.request, time from concurrent.futures import ThreadPoolExecutor, as_completed from PIL import Image import io BASE = os.path.dirname(os.path.abspath(__file__)) OUT = os.path.join(BASE, 'images_en') os.makedirs(OUT, exist_ok=True) cards = json.load(open(os.path.join(BASE, 'data', 'cards_scored.json'), encoding='utf-8')) v1 = {c['name']: c for c in json.load(open(r'C:/Code/Mtga/.tmp/trk_view1.json', encoding='utf-8'))['items']} def one(c): idx = c['idx'] path = os.path.join(OUT, f'{idx:03d}.jpg') if os.path.exists(path) and os.path.getsize(path) > 8000: return idx, 'cached' url = v1[c['name']].get('image_url') if not url: url = v1[c['name']]['image_uris']['normal'] last = None 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 = 360 h = round(im.size[1] * w / im.size[0]) bg = bg.resize((w, h), Image.LANCZOS) bg.save(path, 'JPEG', quality=88, optimize=True) return idx, f'ok {os.path.getsize(path)}' except Exception as e: last = e time.sleep(1.5 * (attempt + 1)) return idx, f'FAIL {last}' def main(): todo = [c for c in cards if not (os.path.exists(os.path.join(OUT, f"{c['idx']:03d}.jpg")) and os.path.getsize(os.path.join(OUT, f"{c['idx']:03d}.jpg")) > 8000)] print('to fetch', len(todo)) fails = [] with ThreadPoolExecutor(max_workers=8) as ex: futs = {ex.submit(one, c): c for c in todo} for n, fut in enumerate(as_completed(futs), 1): idx, msg = fut.result() if msg.startswith('FAIL'): fails.append((idx, msg)) if n % 25 == 0 or msg.startswith('FAIL'): print(n, idx, msg, flush=True) print('fails', fails) ok = sum(1 for c in cards if os.path.exists(os.path.join(OUT, f"{c['idx']:03d}.jpg"))) print('images present', ok, '/', len(cards)) if __name__ == '__main__': main()