Files
rick d784005f77 regen(1 Capable): regenerate ITEMS.md after lore rewrites
- ITEMS.md regenerated from SVGs via generate-source-of-truth.py
- Added "Second Wind Salts" → "Second-Wind Salts" alias to
  assemble-packs.py (PACKS.md uses space, SVG uses hyphen)
- Cleaned up stale PDFs from prior exports (old prices)
- All 28 packs assembled, 0 warnings, QA passed

Made-with: Cursor
2026-04-16 20:56:47 +02:00

205 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""Assemble player pack PDFs from singles, with cross-flavor lookup and name aliasing.
Usage:
python3 scripts/assemble-packs.py "0c Specialist"
Reads PACKS.md, finds matching singles PDFs across all flavor directories,
assembles pack PDFs via pdfunite, and builds the All-Packs grand PDF.
Includes QA verification of page counts.
"""
import os, re, sys, subprocess, glob
ALIASES = {
"Shieldfoam Ampoule": "Shieldfoam Vial",
"Frostbite Trap Resin": "Frostbite Trap",
"Rest-Easing Draught": "Resting Draught",
"Elixir of Fire Breath": "Elixir of Lesser Fire Breath",
"Mire-Walk Oil": "Mirewalk Oil",
"Acid Flask": "Acid Flask (Improved)",
"Rune of Warding": "Rune of Warding (Absorb)",
"Second Wind Salts": "Second-Wind Salts",
}
def invert_name(name):
"""'Oil of X' → 'X (oil of)', 'Potion of X' → 'X (potion of)'."""
m = re.match(r'^(Oil|Potion|Elixir|Scroll) of (.+)$', name)
if m:
return f"{m.group(2)} ({m.group(1).lower()} of)"
return None
def normalize_name(name):
"""Normalize curly quotes/apostrophes to straight for matching."""
return name.replace("\u2019", "'").replace("\u2018", "'").replace("\u201c", '"').replace("\u201d", '"')
def build_singles_index(tier_dir):
"""Build a lookup: normalized item name → PDF path, across all flavors."""
index = {}
for flavor_dir in sorted(glob.glob(os.path.join(tier_dir, "*/PDFs Players/Singles"))):
for pdf in sorted(glob.glob(os.path.join(flavor_dir, "*.pdf"))):
basename = os.path.basename(pdf).replace(".pdf", "")
name_no_price = re.sub(r'\s*\([^)]*\)$', '', basename)
index[normalize_name(name_no_price)] = pdf
return index
def find_pdf(item_name, index):
"""Find a PDF for an item name, trying aliases and inversions."""
candidates = [item_name]
inv = invert_name(item_name)
if inv:
candidates.append(inv)
alias = ALIASES.get(item_name)
if alias:
candidates.append(alias)
inv2 = invert_name(alias)
if inv2:
candidates.append(inv2)
for c in candidates:
nc = normalize_name(c)
if nc in index:
return index[nc]
return None
def parse_packs(packs_md):
"""Parse PACKS.md into [(flavor, pack_num, pack_name, [item_names])]."""
packs = []
current_flavor = None
current_num = 0
current_name = None
current_items = []
with open(packs_md) as f:
for line in f:
line = line.rstrip()
m = re.match(r'^## (\w+)', line)
if m and not line.startswith("###"):
if current_name and current_items:
packs.append((current_flavor, current_num, current_name, current_items))
current_flavor = m.group(1)
current_num = 0
current_name = None
current_items = []
continue
m = re.match(r'^### Pack \d+.*"([^"]+)"', line)
if m:
if current_name and current_items:
packs.append((current_flavor, current_num, current_name, current_items))
current_num += 1
current_name = m.group(1)
current_items = []
continue
m = re.match(r'^\|\s+([A-Z][^|]+?)\s+\|', line)
if m and current_name:
item = m.group(1).strip()
if item != "Item":
current_items.append(item)
if current_name and current_items:
packs.append((current_flavor, current_num, current_name, current_items))
return packs
def get_page_count(pdf_path):
try:
r = subprocess.run(["pdfinfo", pdf_path], capture_output=True, text=True, timeout=10)
for line in r.stdout.splitlines():
if line.startswith("Pages:"):
return int(line.split(":")[1].strip())
except Exception:
pass
return 0
def main():
tier_dir = sys.argv[1] if len(sys.argv) > 1 else "0c Specialist"
packs_md = os.path.join(tier_dir, "PACKS.md")
if not os.path.isfile(packs_md):
print(f"ERROR: {packs_md} not found", file=sys.stderr)
sys.exit(1)
tier_label = tier_dir.split()[-1] if " " in tier_dir else tier_dir
print(f"Building singles index from {tier_dir}...")
index = build_singles_index(tier_dir)
print(f" Indexed {len(index)} singles\n")
packs = parse_packs(packs_md)
print(f"=== Assembling {len(packs)} packs ===\n")
all_pack_pdfs = []
warnings = []
for flavor, num, name, items in packs:
packs_dir = os.path.join(tier_dir, flavor, "PDFs Players", "Packs")
os.makedirs(packs_dir, exist_ok=True)
pack_pdf = os.path.join(packs_dir, f"{num:02d} {tier_label} {flavor} - {name}.pdf")
pdf_list = []
for item in items:
found = find_pdf(item, index)
if found:
pdf_list.append(found)
else:
w = f" WARN: [{flavor} Pack {num} '{name}'] missing '{item}'"
print(w)
warnings.append(w)
if len(pdf_list) >= 2:
subprocess.run(["pdfunite"] + pdf_list + [pack_pdf],
capture_output=True, timeout=30)
elif len(pdf_list) == 1:
subprocess.run(["cp", pdf_list[0], pack_pdf], capture_output=True)
expected = len(items)
actual = len(pdf_list)
status = "OK" if actual == expected else "INCOMPLETE"
print(f" {status}: {os.path.basename(pack_pdf)} — {actual}/{expected} cards")
all_pack_pdfs.append(pack_pdf)
# Grand all-packs PDF
print(f"\n=== Building All {tier_label} Player Packs.pdf ===")
existing_packs = [p for p in all_pack_pdfs if os.path.isfile(p)]
grand_pdf = os.path.join(tier_dir, f"All {tier_label} Player Packs.pdf")
if len(existing_packs) >= 2:
subprocess.run(["pdfunite"] + existing_packs + [grand_pdf],
capture_output=True, timeout=120)
print(f" Created: {grand_pdf} ({len(existing_packs)} packs)")
# QA: page counts
print(f"\n=== QA: Pack page counts ===")
qa_fail = False
for pack_pdf in existing_packs:
pages = get_page_count(pack_pdf)
pname = os.path.basename(pack_pdf)
if pages < 4:
print(f" FAIL: {pname} — {pages} pages (expected >=4)")
qa_fail = True
else:
print(f" OK: {pname} — {pages} pages")
print(f"\n=== QA: Singles count per flavor ===")
for flavor in sorted(set(f for f, _, _, _ in packs)):
singles_dir = os.path.join(tier_dir, flavor, "PDFs Players", "Singles")
svg_dir = os.path.join(tier_dir, flavor)
n_pdfs = len(glob.glob(os.path.join(singles_dir, "*.pdf")))
n_svgs = len([s for s in glob.glob(os.path.join(svg_dir, "*.svg"))
if "Template" not in os.path.basename(s)])
status = "OK" if n_pdfs == n_svgs else "MISMATCH"
print(f" {status}: {flavor} — {n_pdfs} PDFs, {n_svgs} SVGs")
if warnings:
print(f"\n=== {len(warnings)} warnings (items not found) ===")
for w in warnings:
print(w)
if qa_fail:
print("\nFAIL: Some packs have fewer pages than expected.")
sys.exit(1)
elif warnings:
print(f"\nWARN: {len(warnings)} items could not be matched. Packs may be incomplete.")
else:
print("\nAll packs assembled successfully. No warnings.")
if __name__ == "__main__":
main()