Files

285 lines
9.2 KiB
Python

#!/usr/bin/env python3
"""Generate 5etools Homebrew JSON from ITEMS.md source of truth.
Usage:
python3 scripts/generate-5etools-json.py --tier "3 Master"
python3 scripts/generate-5etools-json.py --all
"""
import argparse
import json
import os
import re
from pathlib import Path
REPO = Path(__file__).resolve().parent.parent
os.chdir(REPO)
TIER_META = {
"0a Novice": {"json": "N-GIL-0a", "abbr": "NGIL0a", "full": "Northlands Guild Item Lootboxes - Novice"},
"0b Intermediate": {"json": "N-GIL-0b", "abbr": "NGIL0b", "full": "Northlands Guild Item Lootboxes - Intermediate"},
"0c Specialist": {"json": "N-GIL-0c", "abbr": "NGIL0c", "full": "Northlands Guild Item Lootboxes - Specialist"},
"1 Capable": {"json": "N-GIL-1", "abbr": "NGIL1", "full": "Northlands Guild Item Lootboxes - Capable"},
"2 Expert": {"json": "N-GIL-2", "abbr": "NGIL2", "full": "Northlands Guild Item Lootboxes - Expert"},
"3 Master": {"json": "N-GIL-3", "abbr": "NGIL3", "full": "Northlands Guild Item Lootboxes - Master"},
"4 Grandmaster": {"json": "N-GIL-4", "abbr": "NGIL4", "full": "Northlands Guild Item Lootboxes - Grandmaster"},
"5 Exit": {"json": "N-GIL-5", "abbr": "NGIL5", "full": "Northlands Guild Item Lootboxes - Exit"},
}
DND_CONDITIONS = [
"blinded", "charmed", "deafened", "exhaustion", "frightened",
"grappled", "incapacitated", "invisible", "paralyzed", "petrified",
"poisoned", "prone", "restrained", "stunned", "unconscious",
]
POTION_SUBHEADS = {"potion", "oil", "elixir", "tonic", "draught", "tincture", "brew", "serum"}
SCROLL_SUBHEADS = {"scroll"}
def parse_items_md(path):
"""Parse ITEMS.md into a list of item dicts."""
text = Path(path).read_text(encoding="utf-8")
raw_items = text.split("\n### ")[1:]
items = []
for raw in raw_items:
lines = raw.strip().split("\n")
item = {"name": lines[0].strip()}
fields = {}
current_block = None
block_lines = []
for line in lines[1:]:
if line.startswith("- **") and "**:" in line:
m = re.match(r"- \*\*(.+?)\*\*:\s*(.*)", line)
if m:
fields[m.group(1).strip()] = m.group(2).strip()
continue
if line.startswith("**Front (mechanics):**"):
current_block = "mechanics"
block_lines = []
continue
elif line.startswith("**Lore:**"):
if current_block == "mechanics":
fields["_mechanics"] = "\n".join(block_lines).strip()
current_block = "lore"
block_lines = []
continue
elif line.startswith("---"):
if current_block == "lore":
fields["_lore"] = "\n".join(block_lines).strip()
current_block = "consensus"
block_lines = []
continue
elif line.startswith("> **Consensus negotiation**"):
current_block = "consensus"
block_lines = []
continue
if current_block:
if current_block == "consensus":
block_lines.append(line.lstrip("> ").rstrip())
else:
block_lines.append(line)
if current_block == "lore" and block_lines:
fields["_lore"] = "\n".join(block_lines).strip()
if current_block == "consensus" and block_lines:
fields["_consensus"] = "\n".join(block_lines).strip()
item["fields"] = fields
items.append(item)
return items
def extract_raw_gp(consensus_text):
"""Extract the 5e RAW gp price from consensus negotiation text."""
if not consensus_text:
return None
m = re.search(r"Final consensus:.*?(\d[\d,]*)\s*gp", consensus_text)
if m:
return int(m.group(1).replace(",", ""))
return None
def subhead_to_type(subhead):
"""Map our subhead to a 5etools item type code."""
sub_lower = subhead.lower().strip()
if sub_lower in POTION_SUBHEADS:
return "P", False
if sub_lower in SCROLL_SUBHEADS:
return "SC", False
return "OTH", True
def convert_mechanics_to_entries(mechanics_text):
"""Convert ITEMS.md mechanics (with markdown bold/italic) to 5etools entry strings."""
if not mechanics_text:
return []
text = mechanics_text
text = re.sub(
r"\*\*(\d+d\d+(?:\s*[+\u2212]\s*\d+)?(?:\s+(?:hit points?|temporary hit points?|(?:fire|cold|lightning|thunder|acid|poison|radiant|necrotic|force|psychic|bludgeoning|piercing|slashing)\s+damage)))\*\*",
lambda m: convert_dice_phrase(m.group(1)),
text
)
text = re.sub(
r"\*\*(\d+d\d+(?:\s*[+\u2212]\s*\d+)?)\*\*",
lambda m: "{@dice " + m.group(1).replace("\u2212", "-") + "}",
text
)
for cond in DND_CONDITIONS:
text = re.sub(
rf"\*{cond}\*",
"{@condition " + cond + "}",
text,
flags=re.IGNORECASE
)
text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
text = re.sub(r"\*(.+?)\*", r"\1", text)
text = text.replace("\u2212", "-")
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
if not paragraphs:
paragraphs = [text.strip()]
return paragraphs
def convert_dice_phrase(phrase):
"""Convert a bold dice+descriptor phrase to 5etools tags."""
m = re.match(r"(\d+d\d+(?:\s*[+\u2212]\s*\d+)?)\s+(.*)", phrase)
if m:
dice = m.group(1).replace("\u2212", "-")
rest = m.group(2)
return "{@dice " + dice + "} " + rest
return "{@dice " + phrase.replace("\u2212", "-") + "}"
def convert_lore_to_fluff(lore_text):
"""Convert lore text to 5etools entries as separate paragraphs."""
if not lore_text:
return []
text = lore_text.strip()
text = re.sub(r"\*\*(.+?)\*\*", r"\1", text)
text = re.sub(r"\*(.+?)\*", r"\1", text)
paragraphs = [p.strip() for p in text.split("\n\n") if p.strip()]
if not paragraphs:
paragraphs = [text]
return paragraphs
def build_5etools_item(item, source_json, northlands_price):
"""Build a single 5etools item object."""
fields = item["fields"]
subhead = fields.get("Subhead", "wondrous item")
rarity = fields.get("Rarity", "unknown").lower()
type_code, is_wondrous = subhead_to_type(subhead)
consensus = fields.get("_consensus", "")
raw_gp = extract_raw_gp(consensus)
entry_obj = {
"name": item["name"],
"source": source_json,
"page": 0,
"type": type_code,
"rarity": rarity if rarity in ("common", "uncommon", "rare", "very rare", "legendary") else "unknown (magic)",
}
if is_wondrous:
entry_obj["wondrous"] = True
if raw_gp is not None:
entry_obj["value"] = raw_gp * 100
mechanics = fields.get("_mechanics", "")
entries = convert_mechanics_to_entries(mechanics)
if northlands_price:
currency = "Gold" if northlands_price.endswith("g") else "Silver"
price_num = northlands_price.rstrip("gs")
entries.append(f"{{@bold List Price: {price_num} {currency}}}")
lore = fields.get("_lore", "")
if lore:
entries.append({"type": "hr"})
fluff_paragraphs = convert_lore_to_fluff(lore)
for p in fluff_paragraphs:
entries.append(p)
entry_obj["entries"] = entries
return entry_obj
def generate_tier(tier_name):
"""Generate 5etools homebrew JSON for a tier."""
meta = TIER_META.get(tier_name)
if not meta:
print(f"Unknown tier: {tier_name}")
return
items_path = os.path.join(tier_name, "ITEMS.md")
if not os.path.exists(items_path):
print(f"No ITEMS.md found at {items_path}")
return
parsed = parse_items_md(items_path)
print(f"Parsed {len(parsed)} items from {items_path}")
five_items = []
for item in parsed:
price = item["fields"].get("Price", "")
obj = build_5etools_item(item, meta["json"], price)
five_items.append(obj)
brew = {
"$schema": "https://raw.githubusercontent.com/TheGiddyLimit/5etools-utils/master/schema/brew-fast/homebrew.json",
"_meta": {
"sources": [{
"json": meta["json"],
"abbreviation": meta["abbr"],
"full": meta["full"],
"authors": ["Northlands Campaign"],
"version": "1.0.0",
}],
},
"item": five_items,
}
tier_slug = tier_name.split(" ", 1)[1].lower() if " " in tier_name else tier_name.lower()
out_path = os.path.join(tier_name, f"5etools-northlands-guildpacks-{tier_slug}.json")
with open(out_path, "w", encoding="utf-8") as f:
json.dump(brew, f, indent=2, ensure_ascii=False)
print(f"Wrote {out_path} ({len(five_items)} items)")
def main():
parser = argparse.ArgumentParser(description="Generate 5etools Homebrew JSON")
parser.add_argument("--tier", help="Tier folder name, e.g. '3 Master'")
parser.add_argument("--all", action="store_true", help="Generate for all tiers")
args = parser.parse_args()
if args.all:
for tier in TIER_META:
generate_tier(tier)
elif args.tier:
generate_tier(args.tier)
else:
parser.print_help()
if __name__ == "__main__":
main()