Files
rick 8d03e3da28 Fix _bold_fmt() regex for resistance/immunity phrases; fix 21 items
Root cause: regex \b(resistance to [\w,]+)\b stopped at spaces,
capturing only "resistance to nonmagical" instead of the full
"resistance to nonmagical bludgeoning, piercing, and slashing damage".

Fixed generate-card.py _bold_fmt():
- Resistance regex now captures multi-word damage type phrases
- Immunity regex handles *italic* conditions inside the phrase
- Both handle "damage type" suffix

21 items patched across 5 tiers (Specialist 4, Expert 4, Master 3,
Grandmaster 7, Exit 2). Also fixed HP abbreviations and double-to typo.

Master Lore Replacements.pdf updated (now 30 cards).
All ITEMS.md and 5etools JSON regenerated.

Made-with: Cursor
2026-04-16 15:59:23 +02:00

975 lines
33 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""
Generate guild pack item card SVGs from raw material text files and templates.
Usage:
python3 scripts/generate-card.py \
--template "0c Specialist/Recovery/Cleanse Draught.svg" \
--item-text "raw-materials/.../Burn Salve [Common] [450s].txt" \
--image "raw-materials/.../Burn_Salve_2.png" \
--lore-choice alt1 \
--output "0c Specialist/Recovery/Burn Salve.svg"
The script clones a template SVG and replaces:
- Title text
- Type/subhead text
- Front mechanics text (page 1 body)
- Back lore text (page 2 body)
- Price tag text
- Embedded image
- Flavor mark color and count
"""
import argparse
import base64
import copy
import re
import sys
import textwrap
from pathlib import Path
import xml.etree.ElementTree as ET
SVG_NS = "http://www.w3.org/2000/svg"
XLINK_NS = "http://www.w3.org/1999/xlink"
INKSCAPE_NS = "http://www.inkscape.org/namespaces/inkscape"
SODIPODI_NS = "http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
ET.register_namespace("", SVG_NS)
ET.register_namespace("svg", SVG_NS)
ET.register_namespace("inkscape", INKSCAPE_NS)
ET.register_namespace("sodipodi", SODIPODI_NS)
ET.register_namespace("xlink", XLINK_NS)
FLAVOR_COLORS = {
"Offense": "#ff0000",
"Defense": "#0066ff",
"Recovery": "#44aa00",
"Stealth": "#c87137",
"Strike": "#4d4d4d",
"Utility": "#ffcc00",
"Magic": "#c34cff",
}
TIER_MARKS = {
"0c": 1,
"1": 2,
"2": 3,
"3": 4,
"4": 5,
"5": 0,
}
def parse_item_file(path):
"""Parse a raw material .txt file into structured fields."""
text = Path(path).read_text(encoding="utf-8")
def field(name):
m = re.search(rf"^{name}:\s*(.+)$", text, re.MULTILINE)
return m.group(1).strip() if m else ""
item = field("Item")
tier = field("Tier")
category = field("Category")
rarity = field("Rarity")
price_raw = field("Price")
m = re.search(r"^Front \(mechanics\):\s*\n(.+?)(?:\n\n|\nLore)", text, re.MULTILINE | re.DOTALL)
front = m.group(1).strip() if m else ""
lore_main_m = re.search(
r"^Lore \([^)]+\):\s*\n(.+?)(?:\n---|\Z)",
text, re.MULTILINE | re.DOTALL,
)
lore_main = lore_main_m.group(1).strip() if lore_main_m else ""
lore_alts = {}
for alt_m in re.finditer(
r"Lore alt (\d+)[^:]*:\s*\n(.+?)(?=\nLore alt |\n--- End Lore|\Z)",
text, re.DOTALL,
):
lore_alts[f"alt{alt_m.group(1)}"] = alt_m.group(2).strip()
price_m = re.search(r"([\d,]+)\s*([sg])", price_raw)
if price_m:
price_num = price_m.group(1)
price_unit = "SILVER" if price_m.group(2) == "s" else "GOLD"
price_display = f"{price_num} {price_unit}"
else:
price_display = price_raw
return {
"item": item,
"tier": tier,
"category": category,
"rarity": rarity,
"price_raw": price_raw,
"price_display": price_display,
"price_num": price_m.group(1) if price_m else "",
"price_unit": price_m.group(2) if price_m else "",
"front": front,
"lore_main": lore_main,
"lore_alts": lore_alts,
}
def find_layer(root):
"""Find the main layer group."""
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
return layer
def find_elements(layer):
"""Categorize layer children into semantic roles."""
elements = {}
texts = []
rects = []
images = []
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 == "image":
images.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:
elements.setdefault("dm_marks", []).append(t)
elif "rotate" in transform:
elements["price_text"] = t
elif "shape-inside" in style and "matrix" in transform:
x_offset = 0
m = re.search(r"matrix\([^,]+,[^,]+,[^,]+,[^,]+,([^,]+)", transform)
if m:
x_offset = float(m.group(1))
if x_offset > 50:
elements["lore_text"] = t
else:
elements["front_text"] = 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:
elements["title_text"] = t
elif re.search(r"font-size:3\.5", style):
elements["subhead_text"] = t
elif "attunement" in first_text.lower() or "attune" in first_text.lower():
elements["attunement_text"] = t
for r in rects:
style = r.get("style", "")
ry = r.get("ry", "")
transform = r.get("transform", "")
fill_m = re.search(r"fill:([^;]+)", style)
fill = fill_m.group(1) if fill_m else ""
if ry and float(ry) > 0.3 and float(ry) < 0.5:
elements.setdefault("flavor_marks", []).append(r)
elif "d40000" in fill and "rotate" in transform:
elements.setdefault("bottom_bars", []).append(r)
elif "url(" in fill:
elements.setdefault("bg_rects", []).append(r)
elif float(r.get("width", "0")) > 5 and float(r.get("height", "0")) > 15:
elements["price_tag_rect"] = r
if images:
elements["image"] = images[0]
return elements
def set_text_content(text_elem, content, wrap_width=40):
"""Replace tspan content in a text element with new content.
For positioned text (title, subhead, price), replaces inline.
For shape-inside body text, delegates to set_rich_text.
"""
style = text_elem.get("style", "")
tspans = text_elem.findall(f"{{{SVG_NS}}}tspan")
if "shape-inside" in style:
set_rich_text(text_elem, content, wrap_width)
else:
if tspans:
first = tspans[0]
first.text = content
for inner in first.findall(f"{{{SVG_NS}}}tspan"):
first.remove(inner)
for ts in tspans[1:]:
text_elem.remove(ts)
def _parse_markup(text):
"""Parse **bold** and *italic* markup into (text, style) segments."""
segments = []
parts = re.split(r"(\*\*[^*]+\*\*|\*[^*]+\*)", text)
for part in parts:
if not part:
continue
if part.startswith("**") and part.endswith("**"):
segments.append((part[2:-2], "bold"))
elif part.startswith("*") and part.endswith("*"):
segments.append((part[1:-1], "italic"))
else:
segments.append((part, None))
return segments
def _wrap_segments(segments, wrap_width):
"""Wrap parsed segments into visual lines, preserving formatting.
Each non-final line gets a trailing space appended to prevent
word-joining when Inkscape renders sequential tspans.
"""
tokens = []
prev_had_trailing_space = False
for seg_text, seg_style in segments:
leading_space = seg_text.startswith(" ") or seg_text.startswith("\u201c")
words = seg_text.split()
for i, word in enumerate(words):
add_space_before = (i > 0) or (leading_space and tokens) or (i == 0 and prev_had_trailing_space)
tokens.append((word, seg_style, add_space_before))
prev_had_trailing_space = seg_text.endswith(" ")
lines = [[]]
col = 0
for word, style, space_before in tokens:
sep = " " if space_before and col > 0 else ""
total = len(sep) + len(word)
if col > 0 and col + total > wrap_width:
last_line = lines[-1]
if last_line:
lt, ls = last_line[-1]
last_line[-1] = (lt + " ", ls)
lines.append([])
col = 0
sep = ""
total = len(word)
lines[-1].append((sep + word, style))
col += total
if lines and lines[-1]:
lt, ls = lines[-1][-1]
lines[-1][-1] = (lt, ls)
return lines
def set_rich_text(text_elem, content, wrap_width=40):
"""Set body text with rich formatting: **bold**, *italic*, paragraph breaks.
Parses markup first, then wraps preserving formatting spans.
Produces Inkscape-native tspan layout with explicit x/y coordinates.
"""
tspans = text_elem.findall(f"{{{SVG_NS}}}tspan")
base_x = "12.65625"
base_y = 93.108
line_spacing = 11.6667
if tspans:
base_x = tspans[0].get("x", base_x)
y_str = tspans[0].get("y", "")
if y_str:
base_y = float(y_str)
for ts in list(tspans):
text_elem.remove(ts)
text_elem.text = None
text_elem.tail = None
paragraphs = re.split(r"\n\n+", content)
all_lines = []
for p_idx, para in enumerate(paragraphs):
if p_idx > 0:
all_lines.append(None)
segments = _parse_markup(para.strip())
wrapped = _wrap_segments(segments, wrap_width)
all_lines.extend(wrapped)
for i, line in enumerate(all_lines):
ts = ET.SubElement(text_elem, f"{{{SVG_NS}}}tspan")
ts.set("x", base_x)
ts.set("y", f"{base_y + i * line_spacing:.5f}")
ts.set("id", f"tspan_gen_{i}")
if line is None:
ts.text = "\n"
continue
is_last_in_para = (i + 1 >= len(all_lines) or all_lines[i + 1] is None)
_build_segments_into_tspan(ts, line, i)
if is_last_in_para:
children = list(ts)
if children:
children[-1].tail = (children[-1].tail or "") + "\n"
elif ts.text:
ts.text += "\n"
def _build_segments_into_tspan(parent_tspan, segments, line_idx):
"""Build tspan children from pre-parsed (text, style) segments."""
first = True
for text, style in segments:
if not text:
continue
if style == "bold":
inner = ET.SubElement(parent_tspan, f"{{{SVG_NS}}}tspan")
inner.set("id", f"tspan_fmt_{line_idx}_{id(text) % 10000}")
inner.set(
"style",
"font-style:normal;font-variant:normal;font-weight:bold;"
"font-stretch:normal;font-family:Ubuntu;"
"-inkscape-font-specification:'Ubuntu Bold'",
)
if first:
parent_tspan.text = ""
inner.text = text
inner.tail = ""
first = False
elif style == "italic":
inner = ET.SubElement(parent_tspan, f"{{{SVG_NS}}}tspan")
inner.set("id", f"tspan_fmt_{line_idx}_{id(text) % 10000}")
inner.set(
"style",
"font-style:italic;font-variant:normal;font-weight:normal;"
"font-stretch:normal;font-family:Ubuntu;"
"-inkscape-font-specification:'Ubuntu Italic'",
)
if first:
parent_tspan.text = ""
inner.text = text
inner.tail = ""
first = False
else:
if first:
parent_tspan.text = text
first = False
else:
children = list(parent_tspan)
if children:
children[-1].tail = (children[-1].tail or "") + text
else:
parent_tspan.text = (parent_tspan.text or "") + text
FONT_LARGE = 4.93889
FONT_SMALL = 4.58611
MAX_SINGLE_LINE_CHARS_LARGE = 15
MAX_SINGLE_LINE_CHARS_SMALL = 16
MAX_TWO_LINE_CHARS = 24
TITLE_Y_SINGLE = 8.2095
TITLE_Y_TWO_LINE1 = 7.151
TITLE_Y_TWO_LINE2 = 11.508
BOLD_TITLE_STYLE = (
"font-style:normal;font-variant:normal;font-weight:bold;"
"font-stretch:normal;font-size:{fs}px;line-height:0.95;"
"font-family:Ubuntu;-inkscape-font-specification:'Ubuntu Bold';"
"stroke-width:0.264583"
)
def set_title(text_elem, title):
"""Set title with smart fitting: large single -> small single -> small two-line.
Returns True if two-line layout was used."""
tspans = text_elem.findall(f"{{{SVG_NS}}}tspan")
upper = title.upper()
char_count = len(upper)
for ts in tspans:
for inner in ts.findall(f"{{{SVG_NS}}}tspan"):
ts.remove(inner)
for ts in tspans[1:]:
text_elem.remove(ts)
if char_count <= MAX_SINGLE_LINE_CHARS_LARGE:
_set_title_single(text_elem, tspans[0], upper, FONT_LARGE, TITLE_Y_SINGLE)
return False
elif char_count <= MAX_SINGLE_LINE_CHARS_SMALL:
_set_title_single(text_elem, tspans[0], upper, FONT_SMALL, TITLE_Y_SINGLE)
return False
elif " " in upper:
_set_title_two_line(text_elem, tspans[0], upper)
return True
else:
_set_title_single(text_elem, tspans[0], upper, FONT_SMALL, TITLE_Y_SINGLE)
return False
def _set_title_single(text_elem, tspan, text, font_size, y_pos):
"""Set a single-line title at the given font size."""
tspan.text = text
tspan.set("y", str(y_pos))
style = tspan.get("style", "")
style = re.sub(r"font-size:[^;]+", f"font-size:{font_size}px", style)
tspan.set("style", style)
parent_style = text_elem.get("style", "")
parent_style = re.sub(r"font-size:[^;]+", f"font-size:{font_size}px", parent_style)
text_elem.set("style", parent_style)
SUBHEAD_Y_SINGLE = 12.370
SUBHEAD_Y_TWO_LINE = 17.0
def _set_title_two_line(text_elem, first_tspan, text):
"""Set a two-line title at the smaller font size with tight line-height.
Splits at the point that most evenly balances line lengths,
with preference for a shorter second line (to avoid mark overlap).
"""
words = text.split()
best_split = len(words) // 2
best_diff = float("inf")
for i in range(1, len(words)):
l1 = " ".join(words[:i])
l2 = " ".join(words[i:])
diff = abs(len(l1) - len(l2))
if len(l2) <= MAX_SINGLE_LINE_CHARS_SMALL and (diff < best_diff or (diff == best_diff and len(l2) < len(l1))):
best_diff = diff
best_split = i
line1 = " ".join(words[:best_split])
line2 = " ".join(words[best_split:])
first_tspan.text = line1
first_tspan.set("y", str(TITLE_Y_TWO_LINE1))
style = first_tspan.get("style", "")
style = re.sub(r"font-size:[^;]+", f"font-size:{FONT_SMALL}px", style)
style = re.sub(r"line-height:[^;]+", "line-height:0.95", style)
first_tspan.set("style", style)
ts2 = copy.deepcopy(first_tspan)
ts2.text = line2
ts2.set("y", str(TITLE_Y_TWO_LINE2))
ts2.set("id", "tspan_title_2")
text_elem.append(ts2)
parent_style = text_elem.get("style", "")
parent_style = re.sub(r"font-size:[^;]+", f"font-size:{FONT_SMALL}px", parent_style)
parent_style = re.sub(r"line-height:[^;]+", "line-height:0.95", parent_style)
text_elem.set("style", parent_style)
return True
DND_CONDITIONS = [
"frightened", "charmed", "blinded", "deafened", "grappled",
"incapacitated", "invisible", "paralyzed", "petrified",
"poisoned", "prone", "restrained", "stunned", "unconscious",
"exhaustion", "exhausted", "confused", "confusion",
"paralysis",
]
def _bold_fmt(mechanics):
"""Apply bold formatting to mechanics text. Order matters -- specific first."""
t = mechanics
t = re.sub(r"\breduced to 0\s*(?:hp|HP)\b", "reduced to **zero hit points**", t)
t = re.sub(r"\b0\s*(?:hp|HP)\b", "**zero hit points**", t)
t = re.sub(r"\b(\d+)\s+temp(?:orary)?\s+(?:HP|hp)\b",
lambda m: f"**{m.group(1)} temporary hit points**", t)
t = re.sub(
r"(\d+d\d+(?:\s*[+\u2212]\s*\d+)?)\s*((?:fire|cold|lightning|thunder|acid|poison|radiant|necrotic|force|psychic|bludgeoning|piercing|slashing)\s+damage)",
r"**\1 \2**", t, flags=re.IGNORECASE)
t = re.sub(
r"(\d+d\d+(?:\s*[+\u2212]\s*\d+)?)\s*(damage)",
r"**\1 \2**", t, flags=re.IGNORECASE)
t = re.sub(
r"\b(\d+d\d+\s*[+\u2212]\s*\d+)\s*(?:HP|hp)\b",
lambda m: f"**{m.group(1)} hit points**", t)
t = re.sub(
r"\b(\d+d\d+)\s*(?:HP|hp)\b",
lambda m: f"**{m.group(1)} hit points**", t)
t = re.sub(r"\b1 hit points\b", "1 hit point", t)
t = re.sub(
r"\b(\d+)\s*(?:HP|hp)\b",
lambda m: f"**{m.group(1)} hit point{'s' if m.group(1) != '1' else ''}**", t)
t = re.sub(
r"(?<!\*\*)(\b\d+d\d+(?:\s*[+\u2212]\s*\d+)?\b)(?! hit)",
r"**\1**", t)
t = re.sub(r"\b(\d+)\s*(ft|feet)\b", r"**\1 \2**", t)
def _bold_resistance(m):
return f"**{m.group(0)}**"
t = re.sub(
r"\bresistance to (?:nonmagical |magical )?(?:\w+(?:,\s*\w+)*(?:,?\s+and\s+\w+)?\s+)?damage(?:\s+type)?",
_bold_resistance, t, flags=re.IGNORECASE)
t = re.sub(
r"(?<!\*\*)\bresistance to \w+(?:\s+\w+)?\b",
_bold_resistance, t, flags=re.IGNORECASE)
t = re.sub(
r"\bimmunity to (?:being )?(?:the )?\*?\w+\*?(?:(?:,\s*\*?\w+\*?)*(?:,?\s+and\s+\*?\w+\*?))?\s*(?:condition|damage(?:\s+type)?)?",
_bold_resistance, t, flags=re.IGNORECASE)
t = re.sub(
r"\b(advantage on (?:saving throws?|saves?) vs\.? [\w/\-]+(?:\s+(?!for\b|and\b|until\b|during\b|while\b)[\w/\-]+)?)",
r"**\1**", t, flags=re.IGNORECASE)
t = re.sub(
r"\b(advantage on (?:death|concentration|initiative) (?:saving throws?|saves?))\b",
r"**\1**", t, flags=re.IGNORECASE)
t = re.sub(
r"\b(advantage on (?:checks?|saves?) (?:to \w+(?:\s+\w+(?:\s+\w+)?)?))",
r"**\1**", t, flags=re.IGNORECASE)
if "**advantage" not in t:
t = re.sub(r"\b(advantage)\b", r"**\1**", t, flags=re.IGNORECASE)
t = re.sub(
r"\b(disadvantage on \w+(?:\s+\w+)?)",
r"**\1**", t, flags=re.IGNORECASE)
if "**disadvantage" not in t:
t = re.sub(r"\b(disadvantage)\b", r"**\1**", t, flags=re.IGNORECASE)
t = re.sub(r"\*\*\*\*", "", t)
return t
def format_front_text(mechanics):
"""Format front mechanics with bold dramatics and italic conditions.
Rules:
- HP/hp → 'hit points' spelled out, bolded with the number
- GM/gm → DM
- Minus signs in dice notation → mathematical minus (−)
- D&D conditions → italic
- Key dramatic phrases → bold
- 'advantage on saving throws vs X' → bold as a phrase
"""
text = mechanics
text = re.sub(r"\(GM\)", "(DM)", text)
text = re.sub(r"\bGM\b", "DM", text)
text = re.sub(r"(\d+d\d+(?:\s*)\-\s*\d+)", lambda m: m.group(0).replace("-", "\u2212"), text)
for condition in DND_CONDITIONS:
text = re.sub(
rf"\b({condition})\b",
rf"*\1*",
text,
flags=re.IGNORECASE,
)
text = _bold_fmt(text)
return text
QUOTE_PATTERNS = [
(r'(?:once said|always say|used to say|often say|remarked|declared|wrote|noted|yelled|shouted|whispered|muttered),\s+"([^"]+)"', True),
(r'(?:once said|always say|used to say|often say|remarked|declared|wrote|noted|yelled|shouted|whispered|muttered),\s+([^.!?]+[.!?])', False),
]
def format_lore_text(lore, max_chars=900):
"""Format lore text with natural paragraph breaks and italic quotes.
Inserts paragraph breaks at sentence boundaries, aiming for
3-5 roughly equal paragraphs that fill the card back evenly.
Detects inline speech/quotes and wraps them in italic markup.
"""
if len(lore) > max_chars:
lore = lore[:max_chars].rsplit(" ", 1)[0] + "..."
for pattern, already_quoted in QUOTE_PATTERNS:
def _quote_repl(m):
quote = m.group(1)
full = m.group(0)
if already_quoted:
return full.replace(f'"{quote}"', f'*"\u201c{quote}\u201d"*')
else:
return full.replace(quote, f'*\u201c{quote}\u201d*')
lore = re.sub(pattern, _quote_repl, lore, flags=re.IGNORECASE)
sentences = re.split(r"(?<=[.!?])\s+", lore)
if len(sentences) <= 3:
return lore
total_chars = sum(len(s) for s in sentences)
target_paras = 4 if total_chars > 400 else 3
if total_chars > 550:
target_paras = 5
target_chars_per_para = total_chars / target_paras
paragraphs = []
current = []
current_chars = 0
for sent in sentences:
current.append(sent)
current_chars += len(sent)
if current_chars >= target_chars_per_para and len(paragraphs) < target_paras - 1:
paragraphs.append(" ".join(current))
current = []
current_chars = 0
if current:
paragraphs.append(" ".join(current))
return "\n\n".join(paragraphs)
PRICE_TAG_DIMS = {
("SILVER", 2): (24.621, 1.1608), # "75 SILVER" (template measured)
("SILVER", 3): (26.263, 1.2382), # "250 SILVER" (template measured)
("SILVER", 4): (29.890, 1.4093), # "1,150 SILVER" (template measured)
("SILVER", 5): (31.812, 1.4998), # "21,500 SILVER" (template measured)
("GOLD", 2): (21.948, 1.0348), # "10 GOLD" (template measured)
("GOLD", 3): (24.198, 1.1410), # "600 GOLD" (interpolated, flag for review)
("GOLD", 4): (28.697, 1.3530), # "1,100 GOLD" (interpolated, flag for review)
("GOLD", 5): (30.947, 1.4590), # "XX,XXX GOLD" (interpolated, looks good in practice)
("GOLD", 6): (33.197, 1.5650), # "280,000 GOLD" (interpolated, flag for review)
("GOLD", 7): (37.696, 1.7770), # "X,XXX,XXX GOLD" (extrapolated: 6d + 3→4d delta, flag for review)
}
def _price_tag_dims(price_display):
"""Look up price tag (height, ry) by (currency, digit_count).
Only height and ry vary; x, y, w stay as inherited from the template.
"""
parts = price_display.split()
if len(parts) != 2:
return None
num_str, currency = parts
digit_count = sum(1 for c in num_str if c.isdigit())
return PRICE_TAG_DIMS.get((currency, digit_count))
def _flag_missing_price_tag(price_display):
"""Return a warning if no template exists for this price tag size."""
dims = _price_tag_dims(price_display)
if dims is None:
return f"WARNING: No price tag template for '{price_display}'. Manual check needed."
return None
def embed_image(image_elem, png_path):
"""Replace embedded image data with a new PNG."""
with open(png_path, "rb") as f:
data = base64.b64encode(f.read()).decode("ascii")
image_elem.set(f"{{{XLINK_NS}}}href", f"data:image/png;base64,{data}")
if "transform" in image_elem.attrib:
del image_elem.attrib["transform"]
MARK_WIDTH = 0.76626754
MARK_GAP = 0.292
MARK_X_RIGHT = 52.253643
MARK_Y_START = 2.5394216
MARK_Y_SPACING = 6.88
def set_flavor_marks(layer, elements, flavors, tier_code):
"""Set mark colors and count for the tier. Supports multi-flavor.
Args:
flavors: single flavor string or comma-separated list (e.g. "Recovery,Defense")
"""
if isinstance(flavors, str):
flavor_list = [f.strip() for f in flavors.split(",")]
else:
flavor_list = list(flavors)
target_count = TIER_MARKS.get(tier_code, 1)
if target_count == 0:
for m in elements.get("flavor_marks", []):
layer.remove(m)
return
marks = elements.get("flavor_marks", [])
if marks:
template_mark = marks[0]
for m in marks:
layer.remove(m)
else:
template_mark = ET.SubElement(layer, f"{{{SVG_NS}}}rect")
template_mark.set("width", str(MARK_WIDTH))
template_mark.set("height", "5.2916665")
template_mark.set("ry", "0.38320225")
template_mark.set("style", "fill:#44aa00;stroke-width:0.264583")
layer.remove(template_mark)
for tier_i in range(target_count):
y = MARK_Y_START + tier_i * MARK_Y_SPACING
for flavor_i, flavor in enumerate(flavor_list):
color = FLAVOR_COLORS.get(flavor, "#44aa00")
new_mark = copy.deepcopy(template_mark)
new_mark.set("id", f"rect_mark_{tier_i}_{flavor_i}")
new_mark.set("y", str(y))
x = MARK_X_RIGHT - flavor_i * (MARK_WIDTH + MARK_GAP)
new_mark.set("x", str(x))
style = new_mark.get("style", "")
style = re.sub(r"fill:#[0-9a-fA-F]{6}", f"fill:{color}", style)
new_mark.set("style", style)
layer.append(new_mark)
def determine_subhead(item_data):
"""Determine the type/subhead line from item data."""
name_lower = item_data["item"].lower()
front_lower = item_data["front"].lower()
if "potion" in name_lower or "draught" in name_lower or "tonic" in name_lower or "tincture" in name_lower or "elixir" in name_lower or "antitoxin" in name_lower or "brew" in name_lower or "broth" in name_lower or "cordial" in name_lower or "surge" in name_lower or "pick-me-up" in name_lower or "phial" in name_lower or "draft" in name_lower or "dew" in name_lower or "serum" in name_lower:
return "potion"
if "drink" in front_lower or "sip" in front_lower:
return "potion"
if "flask" in name_lower and ("drink" in front_lower or "sip" in front_lower or "pour" in front_lower):
return "potion"
if "oil" in name_lower:
return "oil"
if "salve" in name_lower or "wrap" in name_lower or "poultice" in name_lower or "balm" in name_lower or "ointment" in name_lower or "unguent" in name_lower or "resin" in name_lower:
return "salve / poultice"
if "suture" in name_lower or ("thread" in name_lower and "spell" not in name_lower) or "bandage" in name_lower or "splint" in name_lower or "weave" in name_lower or "compress" in name_lower or "lattice" in name_lower:
return "medical supply"
if "salt" in name_lower or "salts" in name_lower or "tabs" in name_lower or "tab" in name_lower or "biscuit" in name_lower or "tea" in name_lower or "cup" in name_lower or ("capsule" in name_lower and "armor" not in name_lower and "mage" not in name_lower) or "taffy" in name_lower:
return "consumable (ingest)"
if "vapor" in name_lower or "fume" in name_lower or "ampoule" in name_lower or "censer" in name_lower or "snuff" in name_lower or "incense" in name_lower:
return "consumable (inhale)"
if "powder" in name_lower or "dust" in name_lower:
return "consumable (apply)"
if "pearl" in name_lower or "bead" in name_lower:
return "consumable (crush)"
if "scroll" in name_lower:
return "scroll"
if "ammo" in front_lower or "ammunition" in front_lower:
return "ammunition"
if "trap" in name_lower:
return "trap"
if "anchor" in name_lower or "charm" in name_lower or "patch" in name_lower:
return "consumable (apply)"
if "grenade" in name_lower or "bomb" in name_lower:
return "thrown weapon"
return "wondrous item"
SCALE = 0.26458333
RECT_Y_SCALED = 84.18 * SCALE
LINE_HEIGHT_MM = 3.1
DM_BAR_Y = 80.1
CARD_BOTTOM = 85.6
SIDE_MARGIN = 4.3
TITLE_BOTTOM = 14.0
TARGET_IMAGE_SIZE = 58.0
BOLD_WIDTH_FACTOR = 1.05
MECHANICS_WRAP_WIDTH = 42
def estimate_text_lines(text, wrap_width=MECHANICS_WRAP_WIDTH):
"""Estimate how many visual lines the mechanics text will occupy.
Accounts for bold text being ~10% wider than normal weight.
Default wrap width is calibrated to the mechanics text area on the card.
"""
parts = re.split(r"(\*\*[^*]+\*\*|\*[^*]+\*)", text)
words_with_width = []
for part in parts:
if not part:
continue
is_bold = part.startswith("**") and part.endswith("**")
clean = re.sub(r"\*+", "", part)
for word in clean.split():
effective_len = len(word) * BOLD_WIDTH_FACTOR if is_bold else len(word)
words_with_width.append(effective_len)
lines = 1
current_len = 0.0
for w_len in words_with_width:
needed = w_len + (1 if current_len > 0 else 0)
if current_len + needed > wrap_width:
lines += 1
current_len = w_len
else:
current_len += needed
return lines
def adjust_front_layout(elems, front_text, is_player=False, is_two_line_title=False):
"""Adjust front text and image for visual balance.
DM version: mechanics text ends flush with the DM bar.
Player version: mechanics text ends with side-margin gap to card bottom.
Image is scaled and centered between title and mechanics.
"""
n_lines = estimate_text_lines(front_text)
text_height = n_lines * LINE_HEIGHT_MM
DM_BOTTOM_GAP = 3.5
if is_player:
text_end = CARD_BOTTOM - SIDE_MARGIN
else:
text_end = DM_BAR_Y - DM_BOTTOM_GAP
text_start = text_end - text_height
y_offset = text_start - RECT_Y_SCALED
title_bottom = 19.0 if is_two_line_title else TITLE_BOTTOM
image_size = 53.0 if is_two_line_title else TARGET_IMAGE_SIZE
if "front_text" in elems:
transform = elems["front_text"].get("transform", "")
transform = re.sub(
r"(matrix\([^,]+,[^,]+,[^,]+,[^,]+,[^,]+,)([^)]+)\)",
rf"\g<1>{y_offset})",
transform,
)
elems["front_text"].set("transform", transform)
if "image" in elems:
img = elems["image"]
old_w = float(img.get("width", "65"))
old_h = float(img.get("height", "65"))
avail = text_start - title_bottom
IMAGE_BUFFER = 5.0
effective_size = min(image_size, avail - IMAGE_BUFFER)
effective_size = max(effective_size, 30.0)
scale = effective_size / max(old_w, old_h)
new_w = old_w * scale
new_h = old_h * scale
img.set("width", str(new_w))
img.set("height", str(new_h))
img_y = title_bottom + (avail - new_h) / 2
card_width = 53.98
img_x = (card_width - new_w) / 2
img.set("y", str(img_y))
img.set("x", str(img_x))
def generate_card(template_path, item_text_path, image_path, lore_choice,
output_path, flavor, tier_code):
"""Generate a card SVG from template + raw material."""
tree = ET.parse(template_path)
root = tree.getroot()
root.set(f"{{{INKSCAPE_NS}}}export-filename", "")
root.set(f"{{{SODIPODI_NS}}}docname", Path(output_path).name)
layer = find_layer(root)
elems = find_elements(layer)
item = parse_item_file(item_text_path)
display_name = re.sub(r"\s*\(.*?\)\s*$", "", item["item"]).strip()
is_two_line = False
if "title_text" in elems:
is_two_line = set_title(elems["title_text"], display_name)
if "subhead_text" in elems:
subhead = determine_subhead(item)
set_text_content(elems["subhead_text"], subhead)
if is_two_line:
elems["subhead_text"].set("y", str(SUBHEAD_Y_TWO_LINE))
tspans = elems["subhead_text"].findall(f"{{{SVG_NS}}}tspan")
if tspans:
tspans[0].set("y", str(SUBHEAD_Y_TWO_LINE))
if "attunement_text" in elems:
set_text_content(elems["attunement_text"], "")
front = format_front_text(item["front"])
if "front_text" in elems:
set_text_content(elems["front_text"], front, wrap_width=42)
lore = item["lore_main"]
if lore_choice in item["lore_alts"]:
lore = item["lore_alts"][lore_choice]
if "lore_text" in elems:
formatted_lore = format_lore_text(lore)
set_text_content(elems["lore_text"], formatted_lore, wrap_width=42)
if "price_text" in elems:
set_text_content(elems["price_text"], item["price_display"])
if "price_tag_rect" in elems:
warning = _flag_missing_price_tag(item["price_display"])
if warning:
print(f" {warning}")
tag_dims = _price_tag_dims(item["price_display"])
if tag_dims is not None:
h, ry = tag_dims
elems["price_tag_rect"].set("height", str(h))
elems["price_tag_rect"].set("ry", str(ry))
if "image" in elems and image_path:
embed_image(elems["image"], image_path)
set_flavor_marks(layer, elems, flavor, tier_code)
adjust_front_layout(elems, front, is_player=False, is_two_line_title=is_two_line)
tree.write(output_path, xml_declaration=True, encoding="unicode")
print(f"Generated: {output_path}")
def main():
parser = argparse.ArgumentParser(description="Generate guild pack item card SVG")
parser.add_argument("--template", required=True, help="Path to template SVG")
parser.add_argument("--item-text", required=True, help="Path to raw material .txt file")
parser.add_argument("--image", required=True, help="Path to PNG art file")
parser.add_argument("--lore-choice", default="alt1",
help="Which lore to use: main, alt1, alt2, etc.")
parser.add_argument("--output", required=True, help="Output SVG path")
parser.add_argument("--flavor", default="Recovery", help="Flavor category")
parser.add_argument("--tier", default="0c", help="Output tier code (0c, 1, 2, 3, 4)")
args = parser.parse_args()
generate_card(
template_path=args.template,
item_text_path=args.item_text,
image_path=args.image,
lore_choice=args.lore_choice,
output_path=args.output,
flavor=args.flavor,
tier_code=args.tier,
)
if __name__ == "__main__":
main()