Add per-map editable markers and backups
This commit is contained in:
1 parent
e71447da5d
commit
bbb4cadddd
23 files changed
+11090
-129
No files matched your search
@@ -0,0 +1,58 @@
|
||||
"""Create an immutable snapshot of generated per-map marker defaults.
|
||||
|
||||
Existing backups are never overwritten. If a generated file differs from its
|
||||
backup, the script stops and reports it so replacing the snapshot is always an
|
||||
explicit manual decision.
|
||||
|
||||
python tools/backup_markers.py
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import stat
|
||||
from pathlib import Path
|
||||
|
||||
from common import DATA, ROOT
|
||||
|
||||
|
||||
SOURCE_DIR = DATA / "markers"
|
||||
BACKUP_DIR = DATA / "marker-defaults"
|
||||
|
||||
|
||||
def make_read_only(path: Path) -> None:
|
||||
path.chmod(stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
sources = sorted(SOURCE_DIR.glob("*.json"))
|
||||
if not sources:
|
||||
raise SystemExit("no generated marker files found; run extract_markers.py first")
|
||||
BACKUP_DIR.mkdir(parents=True, exist_ok=True)
|
||||
created = 0
|
||||
for source in sources:
|
||||
raw = json.loads(source.read_text(encoding="utf-8"))
|
||||
if raw.get("mapId") != source.stem or not isinstance(raw.get("markers"), list):
|
||||
raise SystemExit(f"invalid per-map marker file: {source.relative_to(ROOT)}")
|
||||
destination = BACKUP_DIR / source.name
|
||||
if destination.exists():
|
||||
if destination.read_bytes() != source.read_bytes():
|
||||
raise SystemExit(
|
||||
f"backup differs and was not replaced: {destination.relative_to(ROOT)}"
|
||||
)
|
||||
make_read_only(destination)
|
||||
print(f"kept {destination.relative_to(ROOT)}")
|
||||
continue
|
||||
temporary = destination.with_suffix(".json.tmp")
|
||||
shutil.copyfile(source, temporary)
|
||||
os.replace(temporary, destination)
|
||||
make_read_only(destination)
|
||||
created += 1
|
||||
print(f"created read-only {destination.relative_to(ROOT)}")
|
||||
print(f"backup ready: {len(sources)} map file(s), {created} newly created")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+320
-45
@@ -11,6 +11,8 @@ HTML/CSS style.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
@@ -20,10 +22,15 @@ from psd_tools import PSDImage
|
||||
|
||||
from common import DATA, ROOT, find_map, load_config
|
||||
|
||||
CONTEXT = ("overlay", "onmap", "on map", "map marker", "mapmarker", "extractinformation")
|
||||
CONTEXT = (
|
||||
"overlay", "onmap", "on map", "map marker", "mapmarker",
|
||||
"extractinformation", "extractnames", "extractmarkers",
|
||||
)
|
||||
EXCLUDED = (
|
||||
"legend", "credit", "title section", "raid detail", "compass", "coloredmarkers",
|
||||
"colored markers", "mapinfo", "duration", "version",
|
||||
"colored markers", "mapinfo", "duration", "sideindicator",
|
||||
"side indicator", "extract letter overlay", "description", "requirement",
|
||||
"only for bw", "onlyforbw",
|
||||
)
|
||||
LEAF_KINDS = {"type", "smartobject", "pixel"}
|
||||
GENERIC = re.compile(
|
||||
@@ -39,6 +46,38 @@ CATEGORY_LABELS = {
|
||||
"cache": "Cache", "key": "Key", "loot": "Loot", "hazard": "Hazard",
|
||||
"quest": "Quest", "location": "Location", "poi": "Point of interest",
|
||||
}
|
||||
LABEL_CORRECTIONS = {
|
||||
"holeinthefence": "HOLE IN THE FENCE",
|
||||
"powerstation v-ex": "POWER STATION V-EX",
|
||||
"pier boat": "PIER BOAT",
|
||||
}
|
||||
MAP_CATEGORY_OVERRIDES = {
|
||||
("reserve", "sewer manhole"): "extract-pmc",
|
||||
}
|
||||
EXTRACT_CATEGORIES = {
|
||||
"extract-pmc", "extract-scav", "extract-neutral", "extract-hidden", "transit",
|
||||
}
|
||||
EXTRACT_LABEL_PATHS = (
|
||||
"overlay captions", "extract name text / extract text pmc",
|
||||
"extract name text / extract text scav", "extract name text / extract text neutral",
|
||||
"extract name text / transit text", "onmap exfil names / text",
|
||||
"new onmap / exfil names", "on map extract text", "extract names / pmc",
|
||||
"extract names / scav", "extract names / neutral", "extract names / transit",
|
||||
"on map overlay / extracts / text",
|
||||
)
|
||||
EXTRACT_LABEL_NOISE = (
|
||||
"requires ", "req. ", "warning", "not always", "this extract",
|
||||
"check legend", "approach exfil", "located in the sniper zone",
|
||||
)
|
||||
EXTRACT_ANCHOR_PATHS = (
|
||||
"overlay pmc extracts", "overlay scav extracts", "overlay neutral",
|
||||
"overlay transit", "overlay hidden", "extract dots", "onmap exfil icons",
|
||||
"map markers / pmc extracts", "map markers / scav extracts",
|
||||
"map markers / neutral extracts", "running man markers", "hidden exfil onmap",
|
||||
"transit onmap", "on map overlay / extracts / pmc",
|
||||
"on map overlay / extracts / scav", "on map overlay / extracts / transit",
|
||||
"extract markers for bw",
|
||||
)
|
||||
|
||||
|
||||
def clean_name(value: str) -> str:
|
||||
@@ -53,6 +92,7 @@ def clean_name(value: str) -> str:
|
||||
def display_label(category: str, value: str) -> str:
|
||||
value = clean_name(value)
|
||||
lower = value.lower()
|
||||
value = LABEL_CORRECTIONS.get(lower, value)
|
||||
noisy = (not any(char.isalnum() for char in value)
|
||||
or GENERIC.match(value)
|
||||
or len(value) > 48
|
||||
@@ -66,25 +106,34 @@ def display_label(category: str, value: str) -> str:
|
||||
return CATEGORY_LABELS[category]
|
||||
if noisy:
|
||||
return CATEGORY_LABELS.get(category, "Point of interest")
|
||||
if category in EXTRACT_CATEGORIES:
|
||||
return value.upper()
|
||||
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):
|
||||
excluded = [term for term in EXCLUDED if term != "legend" and not (
|
||||
term in {"only for bw", "onlyforbw"} and "extractmarkersforbw" in text.replace(" ", "")
|
||||
)]
|
||||
if any(term in text for term in excluded):
|
||||
return None
|
||||
# Several real on-map icons retain source names such as PMCLegend copy.
|
||||
# Exclude legend artwork by location, not merely by a leaf-name fragment.
|
||||
if "legend" in text and not any(term in text for term in EXTRACT_ANCHOR_PATHS):
|
||||
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:
|
||||
if "transit" in text:
|
||||
return "transit"
|
||||
if "co-op" in text or "coop" in text or "neutral" in text:
|
||||
return "extract-neutral"
|
||||
if "hidden" in text:
|
||||
return "extract-hidden"
|
||||
if "transit" in text:
|
||||
return "transit"
|
||||
if "scav" in text:
|
||||
return "extract-scav"
|
||||
return "extract-pmc"
|
||||
if "overlay captions" in text:
|
||||
if "scav" in text:
|
||||
@@ -121,9 +170,130 @@ def category_for(path: tuple[str, ...]) -> str | None:
|
||||
return "hazard"
|
||||
if "quest" in text:
|
||||
return "quest"
|
||||
if any(term in text for term in ("location", "caption", "house name", "housename", "text")):
|
||||
if any(term in text for term in ("location", "caption", "house name", "housename", "room")):
|
||||
return "location"
|
||||
return "poi"
|
||||
if any(term in text for term in ("poi", "point of interest", "note", "address")):
|
||||
return "poi"
|
||||
return None
|
||||
|
||||
|
||||
def normalized_path(path: tuple[str, ...]) -> str:
|
||||
return " / ".join(clean_name(part).lower().replace("_", " ") for part in path)
|
||||
|
||||
|
||||
def is_extract_label_path(path: tuple[str, ...], label: str) -> bool:
|
||||
text = normalized_path(path)
|
||||
return (any(term in text for term in EXTRACT_LABEL_PATHS)
|
||||
and not label.lower().startswith(EXTRACT_LABEL_NOISE))
|
||||
|
||||
|
||||
def explicit_extract_category(path: tuple[str, ...], label: str) -> str | None:
|
||||
lower_label = label.lower()
|
||||
if ("smuggler" in lower_label and "basement" in lower_label) \
|
||||
or "passage by the lake" in lower_label:
|
||||
return "extract-hidden"
|
||||
if any(term in lower_label for term in ("co-op", "coop")) \
|
||||
or any(term in lower_label for term in (
|
||||
"scav camp", "factory gate", "scav lands", "emercom checkpoint",
|
||||
"railway exfil", "armored train", "bunker hermetic door",
|
||||
"road to customs", "smuggler’s path", "smuggler's path",
|
||||
)):
|
||||
return "extract-neutral"
|
||||
# Walk from the leaf upward so a direct PMC/SCAV subgroup wins over a
|
||||
# broad ancestor such as Shoreline's "Hidden + Transit" container.
|
||||
for raw_part in reversed(path):
|
||||
part = clean_name(raw_part).lower().replace("_", " ")
|
||||
words = set(re.findall(r"[a-z]+", part))
|
||||
if "neutral" in words or ("pmc" in words and "scav" in words):
|
||||
return "extract-neutral"
|
||||
if part in {"scav", "scav extracts", "extract dots scav", "extract dot scav"}:
|
||||
return "extract-scav"
|
||||
if part in {"pmc", "pmc extracts", "extract dots pmc", "extract dot pmc"}:
|
||||
return "extract-pmc"
|
||||
if part in {"hidden", "hidden exfil", "hidden exfil onmap"}:
|
||||
return "extract-hidden"
|
||||
if part in {"transit", "transits", "transit dots", "transit onmap"}:
|
||||
return "transit"
|
||||
return None
|
||||
|
||||
|
||||
def semantic_path_label(path: tuple[str, ...], category: str) -> str:
|
||||
ignored = {
|
||||
"icons", "main", "letters", "text", "pmc", "scav", "neutral", "hidden",
|
||||
"transit", "extracts", "extract dots", "extract dot pmc", "extract dots scav",
|
||||
"extract dots neutral", "transit dots", "onmap", "overlay", "overlays",
|
||||
"markers", "running man markers", "on map extract information",
|
||||
"neutral extracts", "pmc extracts", "scav extracts",
|
||||
"transit letters", "transit onmap", "hidden+transit", "re3mr.com",
|
||||
}
|
||||
for part in reversed(path[:-1]):
|
||||
label = clean_name(part)
|
||||
normalized = label.lower().replace("_", " ")
|
||||
if normalized in ignored or any(term in normalized for term in ("copy", "background")):
|
||||
continue
|
||||
if normalized.startswith(("overlay ", "onmap ", "extract", "map marker")):
|
||||
continue
|
||||
if len(label) > 2:
|
||||
return display_label(category, label)
|
||||
return CATEGORY_LABELS[category]
|
||||
|
||||
|
||||
def point_segment_distance(px: float, py: float, ax: float, ay: float,
|
||||
bx: float, by: float) -> float:
|
||||
dx, dy = bx - ax, by - ay
|
||||
if dx == 0 and dy == 0:
|
||||
return ((px - ax) ** 2 + (py - ay) ** 2) ** 0.5
|
||||
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / (dx * dx + dy * dy)))
|
||||
qx, qy = ax + t * dx, ay + t * dy
|
||||
return ((px - qx) ** 2 + (py - qy) ** 2) ** 0.5
|
||||
|
||||
|
||||
def inside_playable(m: dict, x: float, y: float, margin: float = 0.018) -> bool:
|
||||
points = m.get("trim", {}).get("points", [])
|
||||
if len(points) < 3:
|
||||
return True
|
||||
inside = False
|
||||
for index, (xi, yi) in enumerate(points):
|
||||
xj, yj = points[index - 1]
|
||||
if (yi > y) != (yj > y) and x < (xj - xi) * (y - yi) / (yj - yi) + xi:
|
||||
inside = not inside
|
||||
if point_segment_distance(x, y, xi, yi, xj, yj) <= margin:
|
||||
return True
|
||||
return inside
|
||||
|
||||
|
||||
def cluster_candidates(candidates: list[dict], radius: float) -> list[dict]:
|
||||
clusters: list[list[dict]] = []
|
||||
for candidate in sorted(candidates, key=lambda item: -item["score"]):
|
||||
cluster = next((items for items in clusters
|
||||
if items[0]["category"] == candidate["category"]
|
||||
and (sum(item["x"] for item in items) / len(items) - candidate["x"]) ** 2
|
||||
+ (sum(item["y"] for item in items) / len(items) - candidate["y"]) ** 2
|
||||
< radius ** 2), None)
|
||||
if cluster is None:
|
||||
clusters.append([candidate])
|
||||
else:
|
||||
cluster.append(candidate)
|
||||
result = []
|
||||
for items in clusters:
|
||||
best = max(items, key=lambda item: item["score"])
|
||||
result.append({
|
||||
**best,
|
||||
"x": sum(item["x"] for item in items) / len(items),
|
||||
"y": sum(item["y"] for item in items) / len(items),
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
def anchor_matches_label(anchor_label: str, label: str) -> bool:
|
||||
ignored = {"extract", "exfil", "transit", "to", "of", "tarkov", "v", "ex"}
|
||||
anchor_words = set(re.findall(r"[a-z0-9]+", anchor_label.lower())) - ignored
|
||||
label_words = set(re.findall(r"[a-z0-9]+", label.lower())) - ignored
|
||||
if anchor_words and anchor_words <= label_words:
|
||||
return True
|
||||
compact_anchor = re.sub(r"[^a-z0-9]", "", anchor_label.lower())
|
||||
compact_label = re.sub(r"[^a-z0-9]", "", label.lower())
|
||||
return len(compact_anchor) >= 5 and compact_anchor in compact_label
|
||||
|
||||
|
||||
def layer_text(layer) -> str:
|
||||
@@ -165,6 +335,8 @@ def extract_map(m: dict, source_root: Path | None) -> list[dict]:
|
||||
left, top, right, bottom = map(float, crop)
|
||||
width, height = right - left, bottom - top
|
||||
candidates: list[dict] = []
|
||||
extract_labels: list[dict] = []
|
||||
extract_anchors: list[dict] = []
|
||||
|
||||
def walk(node, prefix: tuple[str, ...], ancestors_visible: bool) -> None:
|
||||
for layer in node:
|
||||
@@ -190,33 +362,139 @@ def extract_map(m: dict, source_root: Path | None) -> list[dict]:
|
||||
label = layer_text(layer)
|
||||
if label in {"☠", "☢"}:
|
||||
category = "hazard"
|
||||
label = display_label(category, label)
|
||||
candidates.append({
|
||||
record = {
|
||||
"x": (cx - left) / width,
|
||||
"y": (cy - top) / height,
|
||||
"category": category,
|
||||
"label": label,
|
||||
"label": display_label(category, label),
|
||||
"source": "/".join(layer_path),
|
||||
"score": marker_score(layer, label),
|
||||
})
|
||||
}
|
||||
if category in EXTRACT_CATEGORIES:
|
||||
path_text = normalized_path(layer_path)
|
||||
label_context = any(term in path_text for term in EXTRACT_LABEL_PATHS)
|
||||
if label_context:
|
||||
if layer.kind != "type" or not is_extract_label_path(layer_path, label):
|
||||
continue
|
||||
explicit = explicit_extract_category(layer_path, label)
|
||||
explicit = MAP_CATEGORY_OVERRIDES.get(
|
||||
(m["id"], clean_name(label).lower()), explicit,
|
||||
)
|
||||
record["explicitCategory"] = explicit
|
||||
if explicit:
|
||||
record["category"] = explicit
|
||||
record["label"] = display_label(record["category"], label)
|
||||
extract_labels.append(record)
|
||||
else:
|
||||
if not any(term in path_text for term in EXTRACT_ANCHOR_PATHS):
|
||||
continue
|
||||
# Some PSDs place PMC and Scav marker groups inside a broad
|
||||
# "Hidden + Transit" parent. Prefer the closest semantic
|
||||
# group over that inherited parent-folder wording.
|
||||
explicit = explicit_extract_category(layer_path, label)
|
||||
if explicit:
|
||||
record["category"] = explicit
|
||||
leaf_label = display_label(record["category"], label)
|
||||
if layer.kind == "type" and len(clean_name(label)) > 4 \
|
||||
and not GENERIC.match(clean_name(label)):
|
||||
record["label"] = leaf_label
|
||||
else:
|
||||
record["label"] = semantic_path_label(layer_path, record["category"])
|
||||
extract_anchors.append(record)
|
||||
else:
|
||||
candidates.append(record)
|
||||
|
||||
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:
|
||||
# PSD extracts are usually represented twice: a semantic text label and a
|
||||
# nearby icon made from several leaves. Cluster the icon components, then
|
||||
# pair each visible on-map name with its nearest compatible icon. This
|
||||
# keeps the exact extract position and readable name without duplicating
|
||||
# the background, letter, caption and side-indicator layers.
|
||||
anchors = cluster_candidates(extract_anchors, 0.01)
|
||||
used_anchors: set[int] = set()
|
||||
extracts: list[dict] = []
|
||||
unmatched_labels = set(range(len(extract_labels)))
|
||||
|
||||
# Assign globally closest pairs first. A top-to-bottom greedy pass can
|
||||
# steal a nearby icon from the correct label on dense maps such as Shoreline.
|
||||
pairs = []
|
||||
for label_index, label in enumerate(extract_labels):
|
||||
explicit = label.get("explicitCategory")
|
||||
special_neutral = explicit == "extract-neutral" and any(
|
||||
term in label["label"].lower() for term in ("co-op", "coop", "scav camp", "factory gate", "scav lands")
|
||||
)
|
||||
for anchor_index, anchor in enumerate(anchors):
|
||||
if explicit is not None and not special_neutral and anchor["category"] != explicit:
|
||||
continue
|
||||
distance = ((anchor["x"] - label["x"]) ** 2
|
||||
+ (anchor["y"] - label["y"]) ** 2)
|
||||
if distance <= 0.12 ** 2:
|
||||
pairs.append((distance, label_index, anchor_index))
|
||||
|
||||
for _, label_index, anchor_index in sorted(pairs):
|
||||
if label_index not in unmatched_labels or anchor_index in used_anchors:
|
||||
continue
|
||||
candidate.pop("score")
|
||||
kept.append(candidate)
|
||||
label = extract_labels[label_index]
|
||||
anchor = anchors[anchor_index]
|
||||
explicit = label.get("explicitCategory")
|
||||
unmatched_labels.remove(label_index)
|
||||
used_anchors.add(anchor_index)
|
||||
anchor_is_playable = inside_playable(m, anchor["x"], anchor["y"])
|
||||
extracts.append({
|
||||
**label,
|
||||
"x": anchor["x"] if anchor_is_playable else label["x"],
|
||||
"y": anchor["y"] if anchor_is_playable else label["y"],
|
||||
"category": explicit or anchor["category"],
|
||||
})
|
||||
|
||||
for label_index in sorted(unmatched_labels):
|
||||
extracts.append(extract_labels[label_index])
|
||||
unmatched = [anchor for index, anchor in enumerate(anchors) if index not in used_anchors]
|
||||
unmatched_by_name: dict[tuple[str, str], dict] = {}
|
||||
for anchor in unmatched:
|
||||
if anchor["label"] == CATEGORY_LABELS[anchor["category"]]:
|
||||
continue
|
||||
if any(anchor_matches_label(anchor["label"], label["label"])
|
||||
for label in extract_labels):
|
||||
continue
|
||||
key = (anchor["category"], anchor["label"].lower())
|
||||
existing = unmatched_by_name.get(key)
|
||||
if existing is None or anchor["source"].lower().count("copy") \
|
||||
< existing["source"].lower().count("copy"):
|
||||
unmatched_by_name[key] = anchor
|
||||
extracts.extend(unmatched_by_name.values())
|
||||
icon_summary = ", ".join(
|
||||
f"{category}={count}" for category, count in sorted(Counter(
|
||||
anchor["category"] for anchor in anchors
|
||||
).items())
|
||||
)
|
||||
print(f"[{m['id']}] reconciled {len(extract_labels)} extract label(s) "
|
||||
f"with {len(anchors)} icon cluster(s) ({icon_summary or 'none'}) "
|
||||
f"into {len(extracts)} marker(s)")
|
||||
|
||||
# Non-extract icons still commonly contain a background, glyph and label.
|
||||
# A slightly larger visual cluster removes those redundant leaves.
|
||||
if m.get("parent"):
|
||||
extracts = []
|
||||
kept = cluster_candidates(candidates, 0.006) + extracts
|
||||
kept = [item for item in kept if inside_playable(m, item["x"], item["y"])]
|
||||
for marker in kept:
|
||||
marker.pop("score", None)
|
||||
marker.pop("explicitCategory", None)
|
||||
|
||||
kept.sort(key=lambda item: (item["category"], item["y"], item["x"]))
|
||||
for index, marker in enumerate(kept, 1):
|
||||
marker["id"] = f"{m['id']}-{index}"
|
||||
used_ids: set[str] = set()
|
||||
for marker in kept:
|
||||
seed = f"{marker['source']}|{marker['category']}|{marker['x']:.5f}|{marker['y']:.5f}"
|
||||
digest = hashlib.sha1(seed.encode("utf-8")).hexdigest()[:12]
|
||||
marker_id = f"{m['id']}-{digest}"
|
||||
suffix = 2
|
||||
while marker_id in used_ids:
|
||||
marker_id = f"{m['id']}-{digest}-{suffix}"
|
||||
suffix += 1
|
||||
used_ids.add(marker_id)
|
||||
marker["id"] = marker_id
|
||||
marker["mapId"] = m["id"]
|
||||
print(f"[{m['id']}] extracted {len(kept)} marker(s)")
|
||||
return kept
|
||||
@@ -234,31 +512,28 @@ def main(argv: list[str]) -> None:
|
||||
|
||||
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()
|
||||
destination_dir = DATA / "markers"
|
||||
destination_dir.mkdir(parents=True, exist_ok=True)
|
||||
written = 0
|
||||
errors = []
|
||||
for m in targets:
|
||||
try:
|
||||
markers.extend(extract_map(m, source_root))
|
||||
successful.add(m["id"])
|
||||
markers = extract_map(m, source_root)
|
||||
for marker in markers:
|
||||
marker["label"] = display_label(marker["category"], marker.get("label", ""))
|
||||
markers.sort(key=lambda item: (item["category"], item["id"]))
|
||||
destination = destination_dir / f"{m['id']}.json"
|
||||
destination.write_text(json.dumps({
|
||||
"version": 2,
|
||||
"mapId": m["id"],
|
||||
"markers": markers,
|
||||
}, indent=2) + "\n", encoding="utf-8")
|
||||
written += len(markers)
|
||||
print(f"wrote {destination.relative_to(ROOT)} with {len(markers)} marker(s)")
|
||||
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)")
|
||||
print(f"wrote {written} marker(s) across {len(targets) - len(errors)} map file(s)")
|
||||
if errors:
|
||||
print("skipped maps: " + "; ".join(errors))
|
||||
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
"""Render flattened PSD references beside the semantic marker layer.
|
||||
|
||||
The PSD merged preview is the saved composite of every visible layer. The
|
||||
right-hand audit image uses the marker-free base raster plus the extracted
|
||||
semantic markers, making missing, duplicated and off-map records easy to spot.
|
||||
|
||||
python tools/render_marker_audit.py --source-root C:/path/to/checkout
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from PIL import Image, ImageDraw, ImageFont
|
||||
from psd_tools import PSDImage
|
||||
|
||||
from common import DATA, ROOT, find_map, load_config
|
||||
|
||||
MAX_PANEL = (1500, 1050)
|
||||
EXTRACT_CATEGORIES = {
|
||||
"extract-pmc", "extract-scav", "extract-neutral", "extract-hidden", "transit",
|
||||
}
|
||||
|
||||
|
||||
def font(size: int, bold: bool = False):
|
||||
choices = [
|
||||
Path("C:/Windows/Fonts/seguisb.ttf" if bold else "C:/Windows/Fonts/segoeui.ttf"),
|
||||
Path("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf" if bold
|
||||
else "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"),
|
||||
]
|
||||
for path in choices:
|
||||
if path.exists():
|
||||
return ImageFont.truetype(str(path), size)
|
||||
return ImageFont.load_default()
|
||||
|
||||
|
||||
def flattened(psd: PSDImage) -> Image.Image:
|
||||
image = psd.topil()
|
||||
if image is None:
|
||||
image = psd.composite()
|
||||
if image is None:
|
||||
raise RuntimeError("PSD has neither a merged preview nor a compositable image")
|
||||
return image.convert("RGBA")
|
||||
|
||||
|
||||
def on_dark(image: Image.Image) -> Image.Image:
|
||||
result = Image.new("RGB", image.size, "#171a1f")
|
||||
if image.mode != "RGBA":
|
||||
image = image.convert("RGBA")
|
||||
result.paste(image, mask=image.getchannel("A"))
|
||||
return result
|
||||
|
||||
|
||||
def fit(image: Image.Image, size=MAX_PANEL) -> Image.Image:
|
||||
image = image.copy()
|
||||
image.thumbnail(size, Image.Resampling.LANCZOS)
|
||||
return image
|
||||
|
||||
|
||||
def merged_markers() -> list[dict]:
|
||||
markers = []
|
||||
marker_dir = DATA / "markers"
|
||||
edit_dir = DATA / "marker-edits"
|
||||
for marker_path in sorted(marker_dir.glob("*.json")):
|
||||
raw = json.loads(marker_path.read_text(encoding="utf-8"))
|
||||
edits_path = edit_dir / marker_path.name
|
||||
edits = json.loads(edits_path.read_text(encoding="utf-8")) \
|
||||
if edits_path.exists() else {}
|
||||
overrides = edits.get("overrides", {})
|
||||
deleted = set(edits.get("deleted", []))
|
||||
selected = [{**item, **overrides.get(item["id"], {})}
|
||||
for item in raw.get("markers", []) if item["id"] not in deleted]
|
||||
ids = {item["id"] for item in selected}
|
||||
selected.extend(item for item in edits.get("added", []) if item.get("id") not in ids)
|
||||
markers.extend(selected)
|
||||
return markers
|
||||
|
||||
|
||||
def marker_overlay(base: Image.Image, markers: list[dict], config: dict) -> Image.Image:
|
||||
image = fit(on_dark(base.convert("RGBA")))
|
||||
draw = ImageDraw.Draw(image)
|
||||
sx, sy = image.width / base.width, image.height / base.height
|
||||
categories = config.get("categories", {})
|
||||
label_font = font(13, True)
|
||||
small_font = font(11, True)
|
||||
for marker in markers:
|
||||
category = marker.get("category", "poi")
|
||||
settings = categories.get(category, {})
|
||||
x = float(marker["x"]) * base.width * sx
|
||||
y = float(marker["y"]) * base.height * sy
|
||||
extract = category in EXTRACT_CATEGORIES
|
||||
radius = 10 if extract else max(4, min(8, int(settings.get("size", 16) * 0.38)))
|
||||
color = settings.get("color", "#6c7682")
|
||||
outline = "#ffffff" if extract else "#e8edf2"
|
||||
draw.ellipse((x - radius, y - radius, x + radius, y + radius), fill=color,
|
||||
outline=outline, width=3 if extract else 2)
|
||||
symbol = str(settings.get("symbol", "•"))
|
||||
if symbol.isascii() and len(symbol) <= 2:
|
||||
box = draw.textbbox((0, 0), symbol, font=small_font)
|
||||
draw.text((x - (box[2] - box[0]) / 2, y - (box[3] - box[1]) / 2 - 1),
|
||||
symbol, fill="white", font=small_font)
|
||||
if extract:
|
||||
label = str(marker.get("label") or settings.get("label") or category)
|
||||
box = draw.textbbox((0, 0), label, font=label_font)
|
||||
tx, ty = x + radius + 4, y - (box[3] - box[1]) / 2
|
||||
draw.rounded_rectangle((tx - 3, ty - 2, tx + box[2] - box[0] + 3,
|
||||
ty + box[3] - box[1] + 3), radius=3, fill="#0c1115e6")
|
||||
draw.text((tx, ty), label, fill="white", font=label_font)
|
||||
return image
|
||||
|
||||
|
||||
def full_reference(image: Image.Image, crop: tuple[int, int, int, int]) -> Image.Image:
|
||||
full = fit(on_dark(image), (1600, 1200))
|
||||
draw = ImageDraw.Draw(full)
|
||||
sx, sy = full.width / image.width, full.height / image.height
|
||||
left, top, right, bottom = crop
|
||||
draw.rectangle((left * sx, top * sy, right * sx, bottom * sy), outline="#ffcf4a", width=3)
|
||||
draw.text((12, 10), "Yellow rectangle = configured map crop", fill="#ffcf4a",
|
||||
font=font(16, True), stroke_width=2, stroke_fill="#111111")
|
||||
return full
|
||||
|
||||
|
||||
def comparison(map_name: str, reference: Image.Image, semantic: Image.Image,
|
||||
count: int, extract_count: int) -> Image.Image:
|
||||
header = 54
|
||||
gap = 12
|
||||
width = reference.width + semantic.width + gap
|
||||
height = max(reference.height, semantic.height) + header
|
||||
canvas = Image.new("RGB", (width, height), "#101317")
|
||||
canvas.paste(reference, (0, header))
|
||||
canvas.paste(semantic, (reference.width + gap, header))
|
||||
draw = ImageDraw.Draw(canvas)
|
||||
draw.text((10, 8), f"{map_name}: flattened visible PSD", fill="white", font=font(18, True))
|
||||
draw.text((reference.width + gap + 10, 8),
|
||||
f"semantic layer: {count} markers / {extract_count} extracts",
|
||||
fill="white", font=font(18, True))
|
||||
return canvas
|
||||
|
||||
|
||||
def make_contact_sheet(paths: list[Path], output: Path) -> None:
|
||||
thumbs = []
|
||||
for path in paths:
|
||||
with Image.open(path) as image:
|
||||
thumbs.append(fit(image.convert("RGB"), (760, 430)))
|
||||
cols = 2
|
||||
rows = (len(thumbs) + cols - 1) // cols
|
||||
sheet = Image.new("RGB", (cols * 770, rows * 440), "#0d1014")
|
||||
for index, image in enumerate(thumbs):
|
||||
sheet.paste(image, ((index % cols) * 770, (index // cols) * 440))
|
||||
sheet.save(output, "JPEG", quality=90, optimize=True)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("ids", nargs="*")
|
||||
parser.add_argument("--source-root", type=Path)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "build" / "marker-audit")
|
||||
args = parser.parse_args()
|
||||
cfg = load_config()
|
||||
maps = [find_map(cfg, item) for item in args.ids] if args.ids else cfg.maps
|
||||
maps = [item for item in maps if not item.get("base")]
|
||||
markers = merged_markers()
|
||||
marker_config = json.loads((DATA / "marker-config.json").read_text(encoding="utf-8"))
|
||||
args.output.mkdir(parents=True, exist_ok=True)
|
||||
comparisons = []
|
||||
|
||||
for item in maps:
|
||||
local = ROOT / item["psd"]
|
||||
source = local if local.exists() else (args.source_root / item["psd"] if args.source_root else local)
|
||||
print(f"[{item['id']}] flattening {source}", flush=True)
|
||||
psd = PSDImage.open(source)
|
||||
image = flattened(psd)
|
||||
crop = tuple(map(int, item.get("crop") or (0, 0, psd.width, psd.height)))
|
||||
cropped_source = image.crop(crop)
|
||||
cropped = fit(on_dark(cropped_source))
|
||||
full = full_reference(image, crop)
|
||||
full.save(args.output / f"{item['id']}-visible-full.jpg", "JPEG", quality=91)
|
||||
|
||||
# Keep both audit panes on the exact same flattened PSD crop. Generated
|
||||
# build images can be stale after crop or alignment edits.
|
||||
selected = [marker for marker in markers if marker.get("mapId") == item["id"]]
|
||||
semantic = fit(marker_overlay(cropped_source, selected, marker_config))
|
||||
extracts = sum(marker.get("category") in EXTRACT_CATEGORIES for marker in selected)
|
||||
result = comparison(item.get("name", item["id"]), cropped, semantic,
|
||||
len(selected), extracts)
|
||||
path = args.output / f"{item['id']}-comparison.jpg"
|
||||
result.save(path, "JPEG", quality=92)
|
||||
comparisons.append(path)
|
||||
print(f"[{item['id']}] wrote {path.name}", flush=True)
|
||||
del psd, image, cropped, full, semantic, result
|
||||
|
||||
make_contact_sheet(comparisons, args.output / "all-comparisons.jpg")
|
||||
print(f"wrote {args.output / 'all-comparisons.jpg'}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user