#!/usr/bin/env python3 """Batch generate cards for an entire tier+flavor from raw materials. Usage: python3 scripts/batch-generate.py --raw-dir raw-materials-3/Tier-4/Defense \ --output-dir "3 Master/Defense" --flavor Defense --tier 3 Reads all .txt items, selects template by rarity, generates SVGs, exports DM + Player PDFs, and assembles packs from PACKAGE_CONTENTS.txt. """ import argparse, os, sys, re, subprocess, glob from pathlib import Path # Template selection by rarity + price currency TEMPLATES = { "Common_silver_2": "0b Intermediate/Template Common 10-99 silver.svg", "Common_silver_3": "0b Intermediate/Template Common 100-999 silver.svg", "Common_silver_4": "0b Intermediate/Template Common 1000+ silver.svg", "Common_silver_5": "0b Intermediate/Template Common 1000+ silver.svg", "Uncommon_silver": "1 Capable/Uncommon Template (10k-99k silver).svg", "Uncommon_gold": "0c Specialist/Recovery/Vitality Tincture.svg", "Rare_gold": "1 Capable/Recovery/Rare Template.svg", "Rare_silver": "1 Capable/Recovery/Rare Template.svg", "Very Rare": "3 Master/Recovery/Very Rare Template.svg", "Legendary": "5 Exit/Legendary Template.svg", } def select_template(rarity, price_str): if rarity == "Very Rare": return TEMPLATES["Very Rare"] if rarity == "Legendary": return TEMPLATES["Legendary"] is_gold = "g" in price_str and "s" not in price_str.replace("g","") if rarity == "Rare": return TEMPLATES["Rare_gold"] if rarity == "Uncommon": return TEMPLATES["Uncommon_gold"] if is_gold else TEMPLATES["Uncommon_silver"] # Common if is_gold: return TEMPLATES["Common_silver_3"] # gold prices use 100-999s template as fallback # Count digits in silver price digits = len(re.sub(r'[,\s]', '', price_str.replace('s',''))) if digits <= 2: return TEMPLATES["Common_silver_2"] elif digits <= 3: return TEMPLATES["Common_silver_3"] else: return TEMPLATES["Common_silver_4"] def parse_price(filename): """Extract price string from filename like 'Item [Rarity] [1,200s].txt'""" m = re.findall(r'\[([^\]]+)\]', filename) if len(m) >= 2: return m[-1] # Last bracket is price return "" def parse_rarity(filename): m = re.findall(r'\[([^\]]+)\]', filename) if m: return m[0] return "Common" def find_image(raw_dir, item_name): """Find _1.png or _2.png for an item""" slug = item_name.replace(" ", "_").replace("'", "").replace("\u2019", "") for variant in ["_1.png", "_2.png"]: pattern = os.path.join(raw_dir, f"*{slug[:15]}*{variant}") matches = glob.glob(pattern) if matches: return matches[0] # Try with apostrophe variants slug2 = item_name.replace(" ", "_").replace("'", "s").replace("\u2019", "s") for variant in ["_1.png", "_2.png"]: for f in os.listdir(raw_dir): if f.endswith(variant) and slug[:12].lower() in f.lower().replace("'","").replace("\u2019",""): return os.path.join(raw_dir, f) return None def main(): parser = argparse.ArgumentParser() parser.add_argument("--raw-dir", required=True) parser.add_argument("--output-dir", required=True) parser.add_argument("--flavor", required=True) parser.add_argument("--tier", required=True) parser.add_argument("--dry-run", action="store_true") args = parser.parse_args() raw_dir = args.raw_dir output_dir = args.output_dir flavor = args.flavor tier = args.tier # Find all item .txt files items = [] for f in sorted(os.listdir(raw_dir)): if not f.endswith('.txt') or 'PACKAGE' in f: continue item_name = f.split(' [')[0] rarity = parse_rarity(f) price = parse_price(f) img = find_image(raw_dir, item_name) template = select_template(rarity, price) if not img: print(f" WARNING: No image for {item_name}") continue items.append({ 'name': item_name, 'rarity': rarity, 'price': price, 'txt_path': os.path.join(raw_dir, f), 'img_path': img, 'template': template, }) print(f"Found {len(items)} items in {raw_dir}") if args.dry_run: for item in items: print(f" {item['rarity']:10s} | {item['name']:40s} | {item['price']:12s} | tmpl={os.path.basename(item['template'])}") return # Generate SVGs for item in items: svg_out = os.path.join(output_dir, f"{item['name']}.svg") cmd = [ "python3", "scripts/generate-card.py", "--template", item['template'], "--item-text", item['txt_path'], "--image", item['img_path'], "--lore-choice", "main", "--output", svg_out, "--flavor", flavor, "--tier", tier, ] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode != 0: print(f" ERROR generating {item['name']}: {result.stderr[:200]}") else: print(f" Generated: {item['name']}") # Export PDFs for item in items: svg_path = os.path.join(output_dir, f"{item['name']}.svg") if not os.path.exists(svg_path): continue price = item['price'] dm_pdf = os.path.join(output_dir, "PDFs DM", f"{item['name']} ({price}).pdf") player_pdf = os.path.join(output_dir, "PDFs Players", "Singles", f"{item['name']} ({price}).pdf") # DM PDF subprocess.run([ "inkscape", svg_path, "--export-type=pdf", f"--export-filename=/tmp/dm-batch-", "--export-page=all" ], capture_output=True, timeout=30) subprocess.run([ "pdfunite", "/tmp/dm-batch-_p1.pdf", "/tmp/dm-batch-_p2.pdf", dm_pdf ], capture_output=True) # Player PDF result = subprocess.run([ "python3", "scripts/export-player-pdf.py", svg_path, "-o", player_pdf ], capture_output=True, text=True) print(f" Exported {len(items)} DM + Player PDFs") # Assemble packs pkg_path = os.path.join(raw_dir, "PACKAGE_CONTENTS.txt") if not os.path.exists(pkg_path): print(" No PACKAGE_CONTENTS.txt -- skipping pack assembly") return singles_dir = os.path.join(output_dir, "PDFs Players", "Singles") packs_dir = os.path.join(output_dir, "PDFs Players", "Packs") # Parse packs current_pack = None current_num = 0 packs = [] with open(pkg_path) as f: for line in f: line = line.rstrip() if re.match(r'\s+- Pack', line): m = re.search(r'"([^"]+)"', line) pack_name = m.group(1) if m else "Unknown" current_num += 1 current_pack = {"name": pack_name, "num": current_num, "items": []} packs.append(current_pack) elif line.startswith(" - ") and current_pack: item_line = line.strip().lstrip("- ") if any(item_line.startswith(x) for x in ["Notes", "Adjusted", "No total", "Pack"]): continue item_name = re.split(r' — | \(\d', item_line)[0].strip() item_name = re.sub(r'\s*\(x\d+\)$', '', item_name) if len(item_name) >= 3: current_pack["items"].append(item_name) # Build tier label tier_labels = {"3": "Master", "4": "Grandmaster", "5": "Exit"} tier_label = tier_labels.get(tier, f"Tier{tier}") for pack in packs: # Find matching PDFs for each item pdf_files = [] for item_name in pack["items"]: # Find the PDF by item name prefix matches = glob.glob(os.path.join(singles_dir, f"{item_name}*(*).pdf")) if not matches: # Try fuzzy for pdf in os.listdir(singles_dir): if pdf.startswith(item_name[:15]) and pdf.endswith('.pdf'): matches = [os.path.join(singles_dir, pdf)] break if matches: pdf_files.append(matches[0]) else: print(f" WARNING: No PDF for '{item_name}' in pack '{pack['name']}'") if not pdf_files: continue pack_filename = f"{pack['num']:02d} {tier_label} {flavor} - {pack['name']}.pdf" pack_path = os.path.join(packs_dir, pack_filename) cmd = ["pdfunite"] + pdf_files + [pack_path] subprocess.run(cmd, capture_output=True) pages = len(pdf_files) * 2 print(f" Pack {pack['num']}: {pack['name']} ({len(pdf_files)} cards, {pages} pages)") print(f"\nDone: {len(items)} items, {len(packs)} packs") if __name__ == "__main__": main()