Files
northlands-guild-packs/scripts/generate-source-of-truth.py

920 lines
34 KiB
Python

#!/usr/bin/env python3
"""Generate ITEMS.md, PACKS.md, and BALANCE.md for each tier.
Extracts normative data from current SVGs and informative data from raw materials.
"""
import glob
import os
import re
import statistics
import xml.etree.ElementTree as ET
from collections import defaultdict
from pathlib import Path
SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
INKSCAPE_NS = "http://www.inkscape.org/namespaces/inkscape"
REPO = Path(__file__).resolve().parent.parent
os.chdir(REPO)
RARITY_GRADIENT_MARKERS = {
"#c3b8a2": "Common", "#c2baa3": "Common", "#fff9e5": "Common",
"#c7ff99": "Uncommon", "#eeffe5": "Uncommon", "#edffe5": "Uncommon",
"#66b2ff": "Rare", "#9beeff": "Rare",
"#bb99ff": "Very Rare", "#f7ccff": "Very Rare",
"#ff9966": "Legendary", "#ffc59b": "Legendary",
}
FLAVOR_COLORS = {
"#ff0000": "Offense",
"#0066ff": "Defense",
"#44aa00": "Recovery",
"#c87137": "Stealth",
"#4d4d4d": "Strike",
"#ffcc00": "Utility",
"#c34cff": "Magic",
}
TIER_CONFIG = {
"0a Novice": {
"tier_code": "0a",
"raw_tier": None,
"raw_base": None,
"raw_base_alt": None,
"flavors": None,
},
"0b Intermediate": {
"tier_code": "0b",
"raw_tier": None,
"raw_base": None,
"raw_base_alt": None,
"flavors": None,
},
"0c Specialist": {
"tier_code": "0c",
"raw_tier": "Tier-1",
"raw_base": "raw-materials/Packages, Images, Prices, and Text",
"raw_base_alt": None,
"flavors": ["Defense", "Magic", "Offense", "Recovery", "Stealth", "Strike", "Utility"],
},
"1 Capable": {
"tier_code": "1",
"raw_tier": "Tier-2",
"raw_base": "raw-materials/Packages, Images, Prices, and Text",
"raw_base_alt": None,
"flavors": ["Defense", "Magic", "Offense", "Recovery", "Stealth", "Strike", "Utility"],
},
"2 Expert": {
"tier_code": "2",
"raw_tier": "Tier-3",
"raw_base": "raw-materials/Packages, Images, Prices, and Text",
"raw_base_alt": None,
"flavors": ["Defense", "Magic", "Offense", "Recovery", "Stealth", "Strike", "Utility"],
},
"3 Master": {
"tier_code": "3",
"raw_tier": "Tier-4",
"raw_base": "raw-materials-3",
"raw_base_alt": "raw-materials/Packages, Images, Prices, and Text",
"flavors": ["Defense", "Magic", "Offense", "Recovery", "Stealth", "Strike", "Utility"],
},
"4 Grandmaster": {
"tier_code": "4",
"raw_tier": "Tier-5",
"raw_base": "raw-materials-3",
"raw_base_alt": None,
"flavors": ["Defense", "Magic", "Offense", "Recovery", "Stealth", "Strike", "Utility"],
},
"5 Exit": {
"tier_code": "5",
"raw_tier": "Tier-6",
"raw_base": "raw-materials-3",
"raw_base_alt": "raw-materials/Packages, Images, Prices, and Text",
"flavors": None,
},
}
# ---------------------------------------------------------------------------
# SVG extraction
# ---------------------------------------------------------------------------
def extract_text_from_tspans(text_elem):
tspans = text_elem.findall(f"{{{SVG_NS}}}tspan")
full = ""
for ts in tspans:
txt = ts.text or ""
for inner in ts.findall(f"{{{SVG_NS}}}tspan"):
txt += (inner.text or "") + (inner.tail or "")
full += txt
return full.strip()
def extract_rich_text_from_tspans(text_elem):
"""Extract text preserving **bold** and *italic* markup from tspan styles.
Merges adjacent same-style inner tspans into single markup spans.
"""
tspans = text_elem.findall(f"{{{SVG_NS}}}tspan")
all_lines = []
for ts in tspans:
if ts.text and ts.text.strip() == "" and "\n" in ts.text:
all_lines.append("")
continue
segments = []
if ts.text:
segments.append(("normal", ts.text))
for inner in ts.findall(f"{{{SVG_NS}}}tspan"):
inner_style = inner.get("style", "")
inner_text = inner.text or ""
if "font-weight:bold" in inner_style:
segments.append(("bold", inner_text))
elif "font-style:italic" in inner_style:
segments.append(("italic", inner_text))
else:
segments.append(("normal", inner_text))
if inner.tail:
segments.append(("normal", inner.tail))
merged = []
for style, text in segments:
if merged and merged[-1][0] == style:
merged[-1] = (style, merged[-1][1] + text)
else:
merged.append((style, text))
parts = []
for style, text in merged:
t = text.strip()
if not t:
if text and parts:
parts.append(" ")
continue
leading = " " if text and text[0] == " " and parts else ""
trailing = " " if text and text[-1] == " " else ""
if style == "bold":
parts.append(f"{leading}**{t}**{trailing}")
elif style == "italic":
parts.append(f"{leading}*{t}*{trailing}")
else:
parts.append(f"{leading}{t}{trailing}")
line = "".join(parts).rstrip()
if line:
all_lines.append(line)
return all_lines
def reflow_rich_lines(lines, paragraph_mode=False):
"""Join rich text lines into flowing prose.
paragraph_mode=False: join all lines with spaces (mechanics).
paragraph_mode=True: empty lines become paragraph breaks (lore).
"""
if not lines:
return ""
if not paragraph_mode:
return " ".join(l for l in lines if l)
paragraphs = []
current = []
for line in lines:
if line == "":
if current:
paragraphs.append(" ".join(current))
current = []
else:
current.append(line)
if current:
paragraphs.append(" ".join(current))
return "\n\n".join(paragraphs)
def extract_from_svg(svg_path):
"""Extract all card data from an SVG file."""
tree = ET.parse(svg_path)
root = tree.getroot()
data = {
"svg_path": svg_path,
"title_raw": "",
"title_lines": [],
"subhead": "",
"price_text": "",
"mechanics_rich": "",
"mechanics_plain": "",
"lore_rich": "",
"lore_plain": "",
"rarity_from_gradient": "",
"flavor_colors": [],
}
layer = root.find(f".//{{{SVG_NS}}}g[@id='layer1']")
if layer is None:
for g in root.iter(f"{{{SVG_NS}}}g"):
if g.get(f"{{{INKSCAPE_NS}}}groupmode") == "layer":
layer = g
break
if layer is None:
return data
texts = []
rects = []
for child in layer:
tag = child.tag.split("}")[-1] if "}" in child.tag else child.tag
if tag == "text":
texts.append(child)
elif tag == "rect":
rects.append(child)
elif tag == "g":
for sub in child:
sub_tag = sub.tag.split("}")[-1] if "}" in sub.tag else sub.tag
if sub_tag == "text":
texts.append(sub)
for t in texts:
tspans = t.findall(f"{{{SVG_NS}}}tspan")
first_text = ""
for ts in tspans:
if ts.text:
first_text = ts.text
break
inner = ts.findall(f"{{{SVG_NS}}}tspan")
if inner and inner[0].text:
first_text = inner[0].text
break
style = t.get("style", "")
transform = t.get("transform", "")
if "DUNGEON MASTER" in first_text:
continue
elif "rotate" in transform:
data["price_text"] = extract_text_from_tspans(t)
elif "shape-inside" in style and "matrix" in transform:
m = re.search(r"matrix\([^,]+,[^,]+,[^,]+,[^,]+,([^,]+)", transform)
x_offset = float(m.group(1)) if m else 0
if x_offset > 50:
lines = extract_rich_text_from_tspans(t)
data["lore_rich"] = reflow_rich_lines(lines, paragraph_mode=True)
data["lore_plain"] = extract_text_from_tspans(t)
else:
lines = extract_rich_text_from_tspans(t)
data["mechanics_rich"] = reflow_rich_lines(lines, paragraph_mode=False)
data["mechanics_plain"] = extract_text_from_tspans(t)
elif re.search(r"font-size:[45]\.\d+", style) and first_text.isupper() and "DUNGEON" not in first_text and "SILVER" not in first_text and "GOLD" not in first_text:
title_tspans = t.findall(f"{{{SVG_NS}}}tspan")
lines = []
for ts in title_tspans:
txt = ts.text or ""
for inner in ts.findall(f"{{{SVG_NS}}}tspan"):
txt += (inner.text or "") + (inner.tail or "")
txt = txt.strip()
if txt and txt.isupper():
lines.append(txt)
data["title_lines"] = lines
data["title_raw"] = " ".join(lines) if len(lines) > 1 else (lines[0] if lines else "")
elif re.search(r"font-size:3\.5", style):
data["subhead"] = extract_text_from_tspans(t)
elif "attunement" in first_text.lower() or "attune" in first_text.lower():
pass
for r in rects:
style = r.get("style", "")
ry = r.get("ry", "")
if ry:
try:
ry_val = float(ry)
except ValueError:
continue
if 0.3 < ry_val < 0.5:
fill_m = re.search(r"fill:([^;]+)", style)
if fill_m:
data["flavor_colors"].append(fill_m.group(1).strip())
gradient_colors = set()
for lg in root.iter(f"{{{SVG_NS}}}linearGradient"):
for stop in lg.findall(f"{{{SVG_NS}}}stop"):
m = re.search(r"stop-color:(#[0-9a-fA-F]+)", stop.get("style", ""))
if m:
gradient_colors.add(m.group(1).lower())
rarity_votes = {}
for c in gradient_colors:
r = RARITY_GRADIENT_MARKERS.get(c)
if r:
rarity_votes[r] = rarity_votes.get(r, 0) + 1
if rarity_votes:
data["rarity_from_gradient"] = max(rarity_votes, key=rarity_votes.get)
return data
# ---------------------------------------------------------------------------
# Raw material extraction
# ---------------------------------------------------------------------------
def find_raw_txt(item_name, raw_dirs):
"""Find the raw material .txt file for an item across possible directories."""
for raw_dir in raw_dirs:
if not os.path.isdir(raw_dir):
continue
for f in os.listdir(raw_dir):
if not f.endswith(".txt") or "PACKAGE" in f:
continue
fname_item = f.split(" [")[0]
if normalize_name(fname_item) == normalize_name(item_name):
return os.path.join(raw_dir, f)
return None
def normalize_name(name):
return name.replace("\u2019", "'").replace("\u2018", "'").lower().strip()
def parse_raw_material(path):
"""Extract informative fields from a raw material .txt file."""
if not path or not os.path.exists(path):
return {}
text = Path(path).read_text(encoding="utf-8")
info = {}
m = re.search(r"^Rarity:\s*(.+)$", text, re.MULTILINE)
if m:
info["rarity"] = m.group(1).strip()
m = re.search(r"^Price:\s*(.+)$", text, re.MULTILINE)
if m:
info["price_raw"] = m.group(1).strip()
m = re.search(r"^Lore \((\d+) words; source=([^;]+);?\s*replaced=(\w+)\)", text, re.MULTILINE)
if m:
info["lore_source"] = m.group(2).strip()
info["lore_replaced"] = m.group(3).strip()
consensus_m = re.search(
r"--- Consensus Negotiation Update.*?---\n(.+?)\n--- End Consensus",
text, re.DOTALL)
if consensus_m:
info["consensus"] = consensus_m.group(1).strip()
all_lores = []
for lm in re.finditer(
r"(?:^Lore[^:]*:\s*\n|^Lore alt \d[^:]*:\s*\n)(.+?)(?=\n(?:---|Lore|\Z))",
text, re.MULTILINE | re.DOTALL):
all_lores.append(lm.group(1).strip())
info["all_lores"] = all_lores
return info
def find_image_file(item_name, raw_dirs):
"""Find which image variant was used (best guess: _1.png first)."""
slug = item_name.replace(" ", "_").replace("'", "").replace("\u2019", "").replace("(", "").replace(")", "")
slug_lower = slug.lower()
for raw_dir in raw_dirs:
if not os.path.isdir(raw_dir):
continue
for variant in ["_1.png", "_2.png", "_3.png"]:
for f in os.listdir(raw_dir):
if not f.endswith(variant):
continue
f_base = f.lower().replace("'", "").replace("\u2019", "")
if f_base.startswith(slug_lower[:20].rstrip("_")):
return f
if slug_lower.replace("_", "") in f_base.replace("_", ""):
return f
return None
def parse_price_value(price_text):
"""Parse a price string like '36,000 GOLD' or '550 SILVER' into numeric + currency."""
if not price_text:
return 0, ""
price_text = price_text.strip()
m = re.match(r"([\d,]+)\s*(GOLD|SILVER)", price_text, re.IGNORECASE)
if m:
val = int(m.group(1).replace(",", ""))
currency = "g" if m.group(2).upper() == "GOLD" else "s"
return val, currency
return 0, ""
def format_price(val, currency):
if val == 0:
return "?"
return f"{val:,}{currency}"
# ---------------------------------------------------------------------------
# PACKAGE_CONTENTS parsing
# ---------------------------------------------------------------------------
def find_package_contents(tier_name, config, flavor=None):
"""Find PACKAGE_CONTENTS.txt for a tier+flavor combination."""
raw_tier = config["raw_tier"]
if not raw_tier:
return []
if tier_name == "5 Exit":
paths = []
for pack_dir in ["Exit Pack A", "Exit Pack B", "Exit Pack C", "Exit Pack D"]:
for base in [config["raw_base"], config.get("raw_base_alt", "")]:
if not base:
continue
p = os.path.join(base, raw_tier, pack_dir, "PACKAGE_CONTENTS.txt")
if os.path.exists(p):
paths.append(p)
break
return paths
search_dirs = [config["raw_base"]]
if config.get("raw_base_alt"):
search_dirs.append(config["raw_base_alt"])
for base in search_dirs:
p = os.path.join(base, raw_tier, flavor, "PACKAGE_CONTENTS.txt")
if os.path.exists(p):
return [p]
return []
def parse_package_contents(path):
"""Parse a PACKAGE_CONTENTS.txt into list of packs."""
text = Path(path).read_text(encoding="utf-8")
packs = []
current_pack = None
current_items = []
for line in text.splitlines():
pm = re.search(r'["\u201c]([^"\u201d]+)["\u201d]', line)
if pm and re.match(r'\s*-\s+(?:Pack|Exit Pack|Defense Pack|Magic Pack|Offense Pack|Recovery Pack|Stealth Pack|Strike Pack|Utility Pack)', line):
if current_pack is not None:
packs.append((current_pack, current_items))
current_pack = pm.group(1)
current_items = []
continue
if re.match(r'\s{4,}-\s+', line) and current_pack is not None:
item_line = line.strip().lstrip("- ").strip()
if item_line.startswith("Note") or item_line.startswith("Adjust") or item_line.startswith("No total"):
continue
item_name = re.split(r'\s+\(|\s+[\u2014]\s+', item_line)[0].strip()
item_name = re.sub(r'\s*\(x\d+\)$', '', item_name)
item_name = re.sub(r'^Parry option:\s*', '', item_name)
if len(item_name) >= 3:
current_items.append(item_name)
if current_pack is not None:
packs.append((current_pack, current_items))
return packs
# ---------------------------------------------------------------------------
# Markdown generation
# ---------------------------------------------------------------------------
def get_raw_dirs(config, flavor=None):
"""Get list of raw material directories to search for an item."""
raw_tier = config["raw_tier"]
if not raw_tier:
return []
dirs = []
if config["raw_base"]:
if flavor:
dirs.append(os.path.join(config["raw_base"], raw_tier, flavor))
else:
for sub in os.listdir(os.path.join(config["raw_base"], raw_tier)):
d = os.path.join(config["raw_base"], raw_tier, sub)
if os.path.isdir(d):
dirs.append(d)
if config.get("raw_base_alt"):
if flavor:
dirs.append(os.path.join(config["raw_base_alt"], raw_tier, flavor))
else:
alt_path = os.path.join(config["raw_base_alt"], raw_tier)
if os.path.isdir(alt_path):
for sub in os.listdir(alt_path):
d = os.path.join(alt_path, sub)
if os.path.isdir(d):
dirs.append(d)
return dirs
def detect_lore_source(raw_info, lore_plain, all_raw_lores=None):
"""Determine lore provenance.
Compares SVG lore against all raw material lore variants.
If SVG lore doesn't match any OpenClaw text, it was written by Claude.
"""
if not raw_info:
word_count = len(lore_plain.split()) if lore_plain else 0
if word_count >= 80:
return "claude-opus"
return "unknown"
if all_raw_lores:
svg_start = lore_plain.strip()[:80].lower().replace(" ", "")
for raw_lore in all_raw_lores:
raw_norm = raw_lore.strip()[:80].lower().replace(" ", "")
if raw_norm and svg_start[:40] in raw_norm:
src = raw_info.get("lore_source", "unknown")
return src if src != "unknown" else "openclaw"
return "claude-opus"
src = raw_info.get("lore_source", "unknown")
replaced = raw_info.get("lore_replaced", "false")
if replaced == "true":
return "rewritten"
return src
def generate_items_md(tier_name, config, all_items):
"""Generate ITEMS.md for a tier."""
lines = []
display_name = tier_name.split(" ", 1)[1] if " " in tier_name else tier_name
lines.append(f"# {display_name} Items")
lines.append("")
lines.append("> **Source of truth** for card content in this tier. Raw material `.txt` files in `raw-materials/`")
lines.append("> and `raw-materials-3/` are historical and may contain outdated mechanics, lore, or prices.")
lines.append(">")
lines.append(f"> Generated from SVGs on {__import__('datetime').date.today().isoformat()}.")
lines.append("")
if config["flavors"]:
for flavor in config["flavors"]:
flavor_items = [i for i in all_items if i["flavor"] == flavor]
if not flavor_items:
continue
lines.append(f"## {flavor}")
lines.append("")
for item in sorted(flavor_items, key=lambda x: x["name"]):
lines.extend(format_item_block(item))
else:
for item in sorted(all_items, key=lambda x: x["name"]):
lines.extend(format_item_block(item))
return "\n".join(lines)
def format_item_block(item):
lines = []
lines.append(f"### {item['name']}")
lines.append("")
lines.append(f"- **Title**: {item['title_display']}")
if len(item["title_lines"]) > 1:
split = " / ".join(f'"{l}"' for l in item["title_lines"])
lines.append(f"- **Title layout**: two-line: {split}")
else:
lines.append(f"- **Title layout**: single-line")
lines.append(f"- **Subhead**: {item['subhead']}")
lines.append(f"- **Rarity**: {item['rarity']}")
lines.append(f"- **Price**: {item['price']}")
if item.get("flavors_display"):
lines.append(f"- **Flavor**: {item['flavors_display']}")
if item.get("image"):
lines.append(f"- **Image**: {item['image']}")
lines.append(f"- **Lore source**: {item['lore_source']}")
lines.append("")
lines.append("**Front (mechanics):**")
lines.append("")
lines.append(item["mechanics_rich"])
lines.append("")
lines.append("**Lore:**")
lines.append("")
lines.append(item["lore_rich"])
lines.append("")
if item.get("consensus"):
lines.append("---")
lines.append("")
lines.append("> **Consensus negotiation** (informative, non-normative)")
for cline in item["consensus"].splitlines():
lines.append(f"> {cline}")
lines.append("")
lines.append("")
return lines
def generate_packs_md(tier_name, config, all_items, all_packs):
"""Generate PACKS.md for a tier."""
lines = []
display_name = tier_name.split(" ", 1)[1] if " " in tier_name else tier_name
lines.append(f"# {display_name} Packs")
lines.append("")
item_lookup = {}
for item in all_items:
item_lookup[normalize_name(item["name"])] = item
if config["flavors"]:
for flavor in config["flavors"]:
flavor_packs = all_packs.get(flavor, [])
if not flavor_packs:
continue
lines.append(f"## {flavor}")
lines.append("")
for i, (pack_name, items) in enumerate(flavor_packs, 1):
lines.append(f'### Pack {i} \u2014 "{pack_name}"')
lines.append("")
lines.append("| Item | Rarity | Price |")
lines.append("|------|--------|-------|")
for item_name in items:
idata = item_lookup.get(normalize_name(item_name), {})
rarity = idata.get("rarity", "?")
price = idata.get("price", "?")
lines.append(f"| {item_name} | {rarity} | {price} |")
lines.append("")
else:
for pack_group_name, pack_list in all_packs.items():
for i, (pack_name, items) in enumerate(pack_list, 1):
lines.append(f'### {pack_group_name} \u2014 "{pack_name}"')
lines.append("")
lines.append("| Item | Rarity | Price |")
lines.append("|------|--------|-------|")
for item_name in items:
idata = item_lookup.get(normalize_name(item_name), {})
rarity = idata.get("rarity", "?")
price = idata.get("price", "?")
lines.append(f"| {item_name} | {rarity} | {price} |")
lines.append("")
return "\n".join(lines)
def generate_balance_md(tier_name, config, all_items, all_packs):
"""Generate BALANCE.md for a tier."""
lines = []
display_name = tier_name.split(" ", 1)[1] if " " in tier_name else tier_name
lines.append(f"# {display_name} Balance")
lines.append("")
lines.append(f"> Generated from SVGs on {__import__('datetime').date.today().isoformat()}.")
lines.append("")
rarities_seen = sorted(set(i["rarity"] for i in all_items if i["rarity"]))
rarity_order = ["Common", "Uncommon", "Rare", "Very Rare", "Legendary"]
rarities_seen = [r for r in rarity_order if r in rarities_seen]
if config["flavors"]:
flavor_groups = {f: [i for i in all_items if i["flavor"] == f] for f in config["flavors"]}
else:
flavor_groups = {"All": all_items}
lines.append("## Rarity distribution by flavor")
lines.append("")
hdr = "| Flavor | " + " | ".join(rarities_seen) + " | Total |"
sep = "|--------|" + "|".join("------" for _ in rarities_seen) + "|-------|"
lines.append(hdr)
lines.append(sep)
for flavor, items in flavor_groups.items():
counts = {r: sum(1 for i in items if i["rarity"] == r) for r in rarities_seen}
row = f"| {flavor} | " + " | ".join(str(counts.get(r, 0)) for r in rarities_seen) + f" | {len(items)} |"
lines.append(row)
lines.append("")
lines.append("## Price statistics by flavor")
lines.append("")
lines.append("| Flavor | Items | Min | Max | Median | Mean | Total |")
lines.append("|--------|-------|-----|-----|--------|------|-------|")
for flavor, items in flavor_groups.items():
prices = [i["price_num"] for i in items if i["price_num"] > 0]
if not prices:
continue
curr = items[0].get("price_currency", "g")
mn = min(prices)
mx = max(prices)
med = int(statistics.median(prices))
mean = int(statistics.mean(prices))
total = sum(prices)
lines.append(f"| {flavor} | {len(prices)} | {format_price(mn,curr)} | {format_price(mx,curr)} | {format_price(med,curr)} | {format_price(mean,curr)} | {format_price(total,curr)} |")
lines.append("")
if all_packs:
lines.append("## Pack balance")
lines.append("")
pack_hdr = "| Pack | Items | " + " | ".join(rarities_seen) + " | Total price |"
pack_sep = "|------|-------|" + "|".join("------" for _ in rarities_seen) + "|-------------|"
lines.append(pack_hdr)
lines.append(pack_sep)
item_lookup = {}
for item in all_items:
item_lookup[normalize_name(item["name"])] = item
for flavor_or_group, pack_list in all_packs.items():
for pack_name, items in pack_list:
label = f'{flavor_or_group} \u2014 "{pack_name}"' if config["flavors"] else f'"{pack_name}"'
pack_items = [item_lookup.get(normalize_name(n), {}) for n in items]
rarity_counts = {r: sum(1 for pi in pack_items if pi.get("rarity") == r) for r in rarities_seen}
total_price = sum(pi.get("price_num", 0) for pi in pack_items)
curr = pack_items[0].get("price_currency", "g") if pack_items else "g"
row = f"| {label} | {len(items)} | " + " | ".join(str(rarity_counts.get(r, 0)) for r in rarities_seen) + f" | {format_price(total_price, curr)} |"
lines.append(row)
lines.append("")
lines.append("## Cross-flavor comparison")
lines.append("")
if config["flavors"] and len(flavor_groups) > 1:
mean_prices = {}
for flavor, items in flavor_groups.items():
prices = [i["price_num"] for i in items if i["price_num"] > 0]
if prices:
mean_prices[flavor] = int(statistics.mean(prices))
if mean_prices:
overall_mean = int(statistics.mean(mean_prices.values()))
lines.append(f"Overall mean item price across flavors: {format_price(overall_mean, items[0].get('price_currency', 'g'))}")
lines.append("")
sorted_flavors = sorted(mean_prices.items(), key=lambda x: x[1], reverse=True)
for flavor, mp in sorted_flavors:
delta_pct = ((mp - overall_mean) / overall_mean * 100) if overall_mean else 0
direction = "above" if delta_pct > 0 else "below"
lines.append(f"- **{flavor}**: mean {format_price(mp, items[0].get('price_currency','g'))} ({abs(delta_pct):.0f}% {direction} average)")
else:
lines.append("Single-flavor tier; no cross-flavor comparison applicable.")
lines.append("")
return "\n".join(lines)
# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------
def process_tier(tier_name, config):
print(f"\n{'='*60}")
print(f"Processing: {tier_name}")
print(f"{'='*60}")
all_items = []
if config["flavors"]:
for flavor in config["flavors"]:
svg_dir = os.path.join(tier_name, flavor)
if not os.path.isdir(svg_dir):
continue
raw_dirs = get_raw_dirs(config, flavor)
for svg_path in sorted(glob.glob(os.path.join(svg_dir, "*.svg"))):
if "Template" in svg_path:
continue
item_name = os.path.basename(svg_path).replace(".svg", "")
svg_data = extract_from_svg(svg_path)
raw_txt = find_raw_txt(item_name, raw_dirs)
raw_info = parse_raw_material(raw_txt)
image_file = find_image_file(item_name, raw_dirs)
price_val, price_curr = parse_price_value(svg_data["price_text"])
detected_flavors = []
for c in svg_data["flavor_colors"]:
fname = FLAVOR_COLORS.get(c)
if fname and fname not in detected_flavors:
detected_flavors.append(fname)
lore_source = detect_lore_source(
raw_info, svg_data["lore_plain"],
all_raw_lores=raw_info.get("all_lores"))
item = {
"name": item_name,
"title_display": svg_data["title_raw"],
"title_lines": svg_data["title_lines"],
"subhead": svg_data["subhead"],
"rarity": raw_info.get("rarity") or svg_data["rarity_from_gradient"] or "?",
"price": format_price(price_val, price_curr),
"price_num": price_val,
"price_currency": price_curr,
"flavor": flavor,
"flavors_display": ", ".join(detected_flavors) if detected_flavors else flavor,
"image": image_file or "?",
"lore_source": lore_source,
"mechanics_rich": svg_data["mechanics_rich"],
"mechanics_plain": svg_data["mechanics_plain"],
"lore_rich": svg_data["lore_rich"],
"lore_plain": svg_data["lore_plain"],
"consensus": raw_info.get("consensus", ""),
}
all_items.append(item)
else:
svg_dir = tier_name
raw_dirs = get_raw_dirs(config)
for svg_path in sorted(glob.glob(os.path.join(svg_dir, "*.svg"))):
if "Template" in svg_path or "Legendary Template" in svg_path:
continue
item_name = os.path.basename(svg_path).replace(".svg", "")
svg_data = extract_from_svg(svg_path)
raw_txt = find_raw_txt(item_name, raw_dirs)
raw_info = parse_raw_material(raw_txt)
image_file = find_image_file(item_name, raw_dirs)
price_val, price_curr = parse_price_value(svg_data["price_text"])
lore_source = detect_lore_source(
raw_info, svg_data["lore_plain"],
all_raw_lores=raw_info.get("all_lores"))
item = {
"name": item_name,
"title_display": svg_data["title_raw"],
"title_lines": svg_data["title_lines"],
"subhead": svg_data["subhead"],
"rarity": raw_info.get("rarity") or svg_data["rarity_from_gradient"] or "?",
"price": format_price(price_val, price_curr),
"price_num": price_val,
"price_currency": price_curr,
"flavor": "Exit",
"flavors_display": "",
"image": image_file or "?",
"lore_source": lore_source,
"mechanics_rich": svg_data["mechanics_rich"],
"mechanics_plain": svg_data["mechanics_plain"],
"lore_rich": svg_data["lore_rich"],
"lore_plain": svg_data["lore_plain"],
"consensus": raw_info.get("consensus", ""),
}
all_items.append(item)
print(f" Extracted {len(all_items)} items")
# Packs
all_packs = {}
if config["flavors"]:
for flavor in config["flavors"]:
pkg_paths = find_package_contents(tier_name, config, flavor)
for pkg_path in pkg_paths:
packs = parse_package_contents(pkg_path)
if packs:
all_packs[flavor] = packs
else:
pkg_paths = find_package_contents(tier_name, config)
for pkg_path in pkg_paths:
packs = parse_package_contents(pkg_path)
if packs:
pack_label = os.path.basename(os.path.dirname(pkg_path))
all_packs[pack_label] = packs
pack_count = sum(len(v) for v in all_packs.values())
print(f" Found {pack_count} packs")
# Write files
items_md = generate_items_md(tier_name, config, all_items)
packs_md = generate_packs_md(tier_name, config, all_items, all_packs)
balance_md = generate_balance_md(tier_name, config, all_items, all_packs)
items_path = os.path.join(tier_name, "ITEMS.md")
packs_path = os.path.join(tier_name, "PACKS.md")
balance_path = os.path.join(tier_name, "BALANCE.md")
Path(items_path).write_text(items_md, encoding="utf-8")
if pack_count > 0:
Path(packs_path).write_text(packs_md, encoding="utf-8")
else:
print(f" Skipped: {packs_path} (no packs found; preserving hand-written file)")
Path(balance_path).write_text(balance_md, encoding="utf-8")
print(f" Wrote: {items_path} ({len(all_items)} items)")
print(f" Wrote: {packs_path} ({pack_count} packs)")
print(f" Wrote: {balance_path}")
def main():
import argparse
parser = argparse.ArgumentParser(description="Generate ITEMS.md, PACKS.md, BALANCE.md")
parser.add_argument("--tier", help="Tier folder name, e.g. '3 Master'")
parser.add_argument("--all", action="store_true", help="Process all tiers (default if no --tier)")
args = parser.parse_args()
if args.tier:
if args.tier not in TIER_CONFIG:
print(f"Unknown tier: {args.tier}")
print(f"Available: {', '.join(TIER_CONFIG.keys())}")
return
process_tier(args.tier, TIER_CONFIG[args.tier])
else:
for tier_name, config in TIER_CONFIG.items():
process_tier(tier_name, config)
print("\nDone.")
if __name__ == "__main__":
main()