268 lines
9.7 KiB
Python
268 lines
9.7 KiB
Python
"""Extract semantic marker records from PSD layer metadata.
|
|
|
|
The PSD artwork is never composited. Visible leaf layers inside on-map marker
|
|
groups become normalized JSON records which the viewer renders with one shared
|
|
HTML/CSS style.
|
|
|
|
python tools/extract_markers.py
|
|
python tools/extract_markers.py customs woods
|
|
python tools/extract_markers.py --source-root C:/path/to/checkout
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from psd_tools import PSDImage
|
|
|
|
from common import DATA, ROOT, find_map, load_config
|
|
|
|
CONTEXT = ("overlay", "onmap", "on map", "map marker", "mapmarker", "extractinformation")
|
|
EXCLUDED = (
|
|
"legend", "credit", "title section", "raid detail", "compass", "coloredmarkers",
|
|
"colored markers", "mapinfo", "duration", "version",
|
|
)
|
|
LEAF_KINDS = {"type", "smartobject", "pixel"}
|
|
GENERIC = re.compile(
|
|
r"^(layer|group|shape|form|icon|marker|scav|boss|pmcspawn|player ?spawn|extractbg|"
|
|
r"cache|corpse|aiscav)(?:\s*\d+)?$",
|
|
re.IGNORECASE,
|
|
)
|
|
CATEGORY_LABELS = {
|
|
"extract-pmc": "PMC extract", "extract-scav": "Scav extract",
|
|
"extract-neutral": "Co-op extract", "extract-hidden": "Hidden extract",
|
|
"transit": "Transit", "spawn": "PMC spawn", "scav": "Scav area",
|
|
"boss": "Boss area", "cultist": "Cultist area", "sniper": "Sniper area",
|
|
"cache": "Cache", "key": "Key", "loot": "Loot", "hazard": "Hazard",
|
|
"quest": "Quest", "location": "Location", "poi": "Point of interest",
|
|
}
|
|
|
|
|
|
def clean_name(value: str) -> str:
|
|
value = "".join(char if char.isprintable() else " " for char in value)
|
|
value = re.sub(r"\s+(?:copy|kopiera)(?:\s+\d+)?$", "", value, flags=re.IGNORECASE)
|
|
value = re.sub(r"(?<=[a-z])(?=[A-Z])", " ", value)
|
|
value = value.replace("_", " ")
|
|
value = re.sub(r"\s+", " ", value).strip(" _-")
|
|
return value[:80]
|
|
|
|
|
|
def display_label(category: str, value: str) -> str:
|
|
value = clean_name(value)
|
|
lower = value.lower()
|
|
noisy = (not any(char.isalnum() for char in value)
|
|
or GENERIC.match(value)
|
|
or len(value) > 48
|
|
or lower.startswith(("layer ", "shape ", "form ", "ellipse ", "handpainted"))
|
|
or lower.startswith("read description")
|
|
or set(value) <= {".", " ", "•"})
|
|
if (category.startswith("extract-") or category == "transit") \
|
|
and 0 < len(value) <= 4 and any(c.isalnum() for c in value):
|
|
return value.upper()
|
|
if category in {"spawn", "cache", "loot"}:
|
|
return CATEGORY_LABELS[category]
|
|
if noisy:
|
|
return CATEGORY_LABELS.get(category, "Point of interest")
|
|
return value or CATEGORY_LABELS.get(category, "Point of interest")
|
|
|
|
|
|
def category_for(path: tuple[str, ...]) -> str | None:
|
|
text = " / ".join(path).lower().replace("_", " ")
|
|
if any(term in text for term in EXCLUDED):
|
|
return None
|
|
if not any(term in text for term in CONTEXT):
|
|
return None
|
|
|
|
if "extract" in text or "exfil" in text:
|
|
if "scav" in text:
|
|
return "extract-scav"
|
|
if "neutral" in text:
|
|
return "extract-neutral"
|
|
if "hidden" in text:
|
|
return "extract-hidden"
|
|
if "transit" in text:
|
|
return "transit"
|
|
return "extract-pmc"
|
|
if "overlay captions" in text:
|
|
if "scav" in text:
|
|
return "extract-scav"
|
|
if "hidden" in text:
|
|
return "extract-hidden"
|
|
if "neutral" in text:
|
|
return "extract-neutral"
|
|
if "pmc" in text:
|
|
return "extract-pmc"
|
|
if "overlay neutral" in text:
|
|
return "extract-neutral"
|
|
if "overlay hidden" in text:
|
|
return "extract-hidden"
|
|
if "transit" in text:
|
|
return "transit"
|
|
if "player spawn" in text or "playerspawn" in text or "pmcspawn" in text or "pmc spawn" in text:
|
|
return "spawn"
|
|
if "sniper" in text:
|
|
return "sniper"
|
|
if any(term in text for term in ("boss", "glukhar", "killa", "sanitar", "goons")):
|
|
return "boss"
|
|
if "cultist" in text:
|
|
return "cultist"
|
|
if "scav" in text:
|
|
return "scav"
|
|
if "cache" in text or "stash" in text:
|
|
return "cache"
|
|
if "key" in text:
|
|
return "key"
|
|
if any(term in text for term in ("corpse", "loot", "gun")):
|
|
return "loot"
|
|
if any(term in text for term in ("mine", "deathzone", "border")):
|
|
return "hazard"
|
|
if "quest" in text:
|
|
return "quest"
|
|
if any(term in text for term in ("location", "caption", "house name", "housename", "text")):
|
|
return "location"
|
|
return "poi"
|
|
|
|
|
|
def layer_text(layer) -> str:
|
|
if layer.kind == "type":
|
|
try:
|
|
text = clean_name(layer.text)
|
|
if text:
|
|
return text
|
|
except Exception: # noqa: BLE001 - malformed text engine data is common
|
|
pass
|
|
return clean_name(layer.name)
|
|
|
|
|
|
def marker_score(layer, label: str) -> int:
|
|
score = {"type": 4, "smartobject": 3, "pixel": 2}.get(layer.kind, 0)
|
|
if label and not GENERIC.match(label):
|
|
score += 3
|
|
if len(label) <= 30:
|
|
score += 1
|
|
return score
|
|
|
|
|
|
def source_path(m: dict, source_root: Path | None) -> Path:
|
|
local = ROOT / m["psd"]
|
|
if local.exists():
|
|
return local
|
|
if source_root:
|
|
fallback = source_root / m["psd"]
|
|
if fallback.exists():
|
|
return fallback
|
|
raise FileNotFoundError(f"{m['psd']} is unavailable")
|
|
|
|
|
|
def extract_map(m: dict, source_root: Path | None) -> list[dict]:
|
|
path = source_path(m, source_root)
|
|
print(f"[{m['id']}] reading marker metadata from {path.name}")
|
|
psd = PSDImage.open(path)
|
|
crop = m.get("crop") or [0, 0, psd.width, psd.height]
|
|
left, top, right, bottom = map(float, crop)
|
|
width, height = right - left, bottom - top
|
|
candidates: list[dict] = []
|
|
|
|
def walk(node, prefix: tuple[str, ...], ancestors_visible: bool) -> None:
|
|
for layer in node:
|
|
visible = ancestors_visible and layer.visible
|
|
layer_path = prefix + (layer.name,)
|
|
if layer.is_group():
|
|
walk(layer, layer_path, visible)
|
|
continue
|
|
if not visible or layer.kind not in LEAF_KINDS:
|
|
continue
|
|
category = category_for(layer_path)
|
|
if not category:
|
|
continue
|
|
x0, y0, x1, y1 = map(float, layer.bbox)
|
|
if x1 <= x0 or y1 <= y0:
|
|
continue
|
|
cx, cy = (x0 + x1) / 2, (y0 + y1) / 2
|
|
if not (left <= cx <= right and top <= cy <= bottom):
|
|
continue
|
|
# Very large leaves are region overlays or artwork, not point data.
|
|
if x1 - x0 > width * 0.16 or y1 - y0 > height * 0.16:
|
|
continue
|
|
label = layer_text(layer)
|
|
if label in {"☠", "☢"}:
|
|
category = "hazard"
|
|
label = display_label(category, label)
|
|
candidates.append({
|
|
"x": (cx - left) / width,
|
|
"y": (cy - top) / height,
|
|
"category": category,
|
|
"label": label,
|
|
"source": "/".join(layer_path),
|
|
"score": marker_score(layer, label),
|
|
})
|
|
|
|
walk(psd, (), True)
|
|
|
|
# A logical PSD marker is often two or three co-located leaves (background,
|
|
# icon and type). Keep the most semantic record within each small cluster.
|
|
kept: list[dict] = []
|
|
for candidate in sorted(candidates, key=lambda item: -item["score"]):
|
|
duplicate = next((item for item in kept if item["category"] == candidate["category"]
|
|
and (item["x"] - candidate["x"]) ** 2
|
|
+ (item["y"] - candidate["y"]) ** 2 < 0.0035 ** 2), None)
|
|
if duplicate:
|
|
continue
|
|
candidate.pop("score")
|
|
kept.append(candidate)
|
|
|
|
kept.sort(key=lambda item: (item["category"], item["y"], item["x"]))
|
|
for index, marker in enumerate(kept, 1):
|
|
marker["id"] = f"{m['id']}-{index}"
|
|
marker["mapId"] = m["id"]
|
|
print(f"[{m['id']}] extracted {len(kept)} marker(s)")
|
|
return kept
|
|
|
|
|
|
def main(argv: list[str]) -> None:
|
|
source_root = None
|
|
if "--source-root" in argv:
|
|
index = argv.index("--source-root")
|
|
try:
|
|
source_root = Path(argv[index + 1]).resolve()
|
|
except IndexError as exc:
|
|
raise SystemExit("--source-root needs a path") from exc
|
|
del argv[index:index + 2]
|
|
|
|
cfg = load_config()
|
|
targets = [find_map(cfg, map_id) for map_id in argv] if argv else cfg.maps
|
|
destination = DATA / "markers.json"
|
|
markers = []
|
|
successful: set[str] = set()
|
|
errors = []
|
|
for m in targets:
|
|
try:
|
|
markers.extend(extract_map(m, source_root))
|
|
successful.add(m["id"])
|
|
except Exception as exc: # noqa: BLE001
|
|
errors.append(f"{m['id']}: {exc}")
|
|
print(f"[{m['id']}] SKIPPED: {exc}")
|
|
|
|
# Targeted runs replace only the maps successfully extracted. This makes
|
|
# `extract_markers.py customs` safe after a complete build, and preserves
|
|
# the previous records for a PSD that is temporarily unavailable.
|
|
if destination.exists():
|
|
previous = json.loads(destination.read_text(encoding="utf-8")).get("markers", [])
|
|
markers = [item for item in previous if item.get("mapId") not in successful] + markers
|
|
for marker in markers:
|
|
marker["label"] = display_label(marker["category"], marker.get("label", ""))
|
|
markers.sort(key=lambda item: (item["mapId"], item["category"], item["id"]))
|
|
|
|
DATA.mkdir(parents=True, exist_ok=True)
|
|
destination.write_text(json.dumps({"version": 1, "markers": markers}, indent=2), encoding="utf-8")
|
|
print(f"wrote {destination.relative_to(ROOT)} with {len(markers)} marker(s)")
|
|
if errors:
|
|
print("skipped maps: " + "; ".join(errors))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main(sys.argv[1:])
|