Add per-map editable markers and backups

This commit is contained in:
lucio committed 2026-08-08 22:03:49 -07:00
1 parent e71447da5d
commit bbb4cadddd
23 files changed
+11090 -129

No files matched your search

+165 -5
View File
@@ -1,4 +1,4 @@
"""Static server plus local placement/trim editing API, reachable on the LAN.
"""Static server plus local placement, trim and marker editing API.
python server/serve.py [port] # default 8080
@@ -17,11 +17,13 @@ import http.server
import json
import math
import os
import re
import socket
import socketserver
import subprocess
import sys
import threading
import uuid
from pathlib import Path
from urllib.parse import urlsplit
@@ -29,6 +31,8 @@ ROOT = Path(__file__).resolve().parent.parent
WEB = ROOT / "web"
CONFIG = ROOT / "maps.json"
BUILD_TOOL = ROOT / "tools" / "build.py"
MARKER_DIR = WEB / "data" / "markers"
MARKER_EDIT_DIR = WEB / "data" / "marker-edits"
CONFIG_LOCK = threading.Lock()
@@ -54,7 +58,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
def do_POST(self) -> None: # noqa: N802 - stdlib handler API
path = urlsplit(self.path).path
if path not in {"/api/placement", "/api/trim"}:
if path not in {"/api/placement", "/api/trim", "/api/marker"}:
self.send_json(404, {"error": "unknown API endpoint"})
return
@@ -63,7 +67,7 @@ class Handler(http.server.SimpleHTTPRequestHandler):
if not 0 < length <= 16_384:
raise ValueError("request body must be between 1 and 16384 bytes")
payload = json.loads(self.rfile.read(length))
map_id = payload["id"]
map_id = payload["mapId"] if path == "/api/marker" else payload["id"]
if not isinstance(map_id, str) or not map_id or map_id == "overall":
raise ValueError("id must name a detail map")
if path == "/api/placement":
@@ -73,11 +77,34 @@ class Handler(http.server.SimpleHTTPRequestHandler):
raise ValueError("cx, cy, w and h must be finite numbers")
if width <= 0 or height <= 0:
raise ValueError("w and h must be greater than zero")
else:
elif path == "/api/trim":
points = normalize_trim_points(payload["points"])
transparency = float(payload["outsideTransparency"])
if not math.isfinite(transparency) or not 0 <= transparency <= 1:
raise ValueError("outsideTransparency must be between 0 and 1")
else:
marker_id = payload.get("id")
action = payload.get("action", "save")
if action not in {"save", "delete"}:
raise ValueError("marker action must be save or delete")
if marker_id is not None and (
not isinstance(marker_id, str) or not 1 <= len(marker_id) <= 120
):
raise ValueError("marker id must be a string no longer than 120 characters")
if action == "delete":
if marker_id is None:
raise ValueError("deleting a marker requires its id")
else:
x, y = float(payload["x"]), float(payload["y"])
if not all(math.isfinite(v) and 0 <= v <= 1 for v in (x, y)):
raise ValueError("marker x and y must be finite numbers from 0 to 1")
label = payload["label"]
if not isinstance(label, str) or not label.strip() or len(label.strip()) > 160:
raise ValueError("marker label must contain 1 to 160 characters")
label = label.strip()
category = payload["category"]
if not isinstance(category, str) or not re.fullmatch(r"[a-z0-9-]{1,40}", category):
raise ValueError("marker category must use lowercase letters, numbers or hyphens")
except (KeyError, TypeError, ValueError, json.JSONDecodeError) as exc:
self.send_json(400, {"error": str(exc)})
return
@@ -85,8 +112,12 @@ class Handler(http.server.SimpleHTTPRequestHandler):
try:
if path == "/api/placement":
result = save_placement(map_id, cx, cy, width, height)
else:
elif path == "/api/trim":
result = save_trim(map_id, points, transparency)
elif action == "delete":
result = delete_marker(marker_id, map_id)
else:
result = save_marker(marker_id, map_id, x, y, label, category)
except PlacementError as exc:
self.send_json(exc.status, {"error": str(exc)})
return
@@ -142,6 +173,135 @@ def _write_world(raw: dict) -> None:
temporary.replace(path)
def _marker_file(directory: Path, map_id: str) -> Path:
if not re.fullmatch(r"[a-z0-9-]+", map_id):
raise PlacementError("map id contains unsupported filename characters", 400)
return directory / f"{map_id}.json"
def _write_marker_edits(map_id: str, raw: dict) -> None:
MARKER_EDIT_DIR.mkdir(parents=True, exist_ok=True)
destination = _marker_file(MARKER_EDIT_DIR, map_id)
temporary = destination.with_name(f"{destination.name}.{os.getpid()}.tmp")
temporary.write_text(
json.dumps(raw, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
)
temporary.replace(destination)
def save_marker(
marker_id: str | None,
map_id: str,
x: float,
y: float,
label: str,
category: str,
) -> dict:
"""Persist a user marker or an override without touching PSD extraction output."""
with CONFIG_LOCK:
maps = json.loads(CONFIG.read_text(encoding="utf-8")).get("maps", [])
if not any(m.get("id") == map_id and not m.get("base") for m in maps):
raise PlacementError(f"unknown map id: {map_id}", 404)
marker_path = _marker_file(MARKER_DIR, map_id)
edit_path = _marker_file(MARKER_EDIT_DIR, map_id)
if not marker_path.exists():
raise PlacementError(
f"web/data/markers/{map_id}.json is missing; extract markers first", 409
)
extracted = json.loads(marker_path.read_text(encoding="utf-8")).get("markers", [])
originals = {item.get("id"): item for item in extracted if item.get("id")}
if edit_path.exists():
edits = json.loads(edit_path.read_text(encoding="utf-8"))
else:
edits = {"version": 2, "overrides": {}, "added": [], "deleted": []}
edits["version"] = 2
overrides = edits.setdefault("overrides", {})
added = edits.setdefault("added", [])
deleted = edits.setdefault("deleted", [])
values = {
"mapId": map_id,
"x": round(x, 6),
"y": round(y, 6),
"label": label,
"category": category,
}
if marker_id is None:
marker_id = f"user-{uuid.uuid4().hex}"
record = {"id": marker_id, **values, "source": "User marker"}
added.append(record)
else:
if marker_id in deleted:
deleted.remove(marker_id)
added_record = next((item for item in added if item.get("id") == marker_id), None)
if added_record is not None:
added_record.update(values)
record = dict(added_record)
else:
original = originals.get(marker_id)
if original is None:
raise PlacementError(f"unknown marker id: {marker_id}", 404)
if original.get("mapId") != map_id:
raise PlacementError("an extracted marker cannot be moved to another map", 400)
comparable = {
**original,
"x": round(float(original.get("x", 0)), 6),
"y": round(float(original.get("y", 0)), 6),
}
override = {
key: value for key, value in values.items()
if value != comparable.get(key)
}
if override:
overrides[marker_id] = override
else:
overrides.pop(marker_id, None)
record = {**original, **override}
_write_marker_edits(map_id, edits)
return {"ok": True, "marker": record}
def delete_marker(marker_id: str, map_id: str) -> dict:
"""Hide an extracted marker or remove a user marker without touching defaults."""
with CONFIG_LOCK:
maps = json.loads(CONFIG.read_text(encoding="utf-8")).get("maps", [])
if not any(m.get("id") == map_id and not m.get("base") for m in maps):
raise PlacementError(f"unknown map id: {map_id}", 404)
marker_path = _marker_file(MARKER_DIR, map_id)
edit_path = _marker_file(MARKER_EDIT_DIR, map_id)
if not marker_path.exists():
raise PlacementError(
f"web/data/markers/{map_id}.json is missing; extract markers first", 409
)
extracted = json.loads(marker_path.read_text(encoding="utf-8")).get("markers", [])
originals = {item.get("id"): item for item in extracted if item.get("id")}
edits = json.loads(edit_path.read_text(encoding="utf-8")) if edit_path.exists() \
else {"version": 2, "overrides": {}, "added": [], "deleted": []}
edits["version"] = 2
overrides = edits.setdefault("overrides", {})
added = edits.setdefault("added", [])
deleted = edits.setdefault("deleted", [])
added_record = next((item for item in added if item.get("id") == marker_id), None)
if added_record is not None:
edits["added"] = [item for item in added if item.get("id") != marker_id]
else:
original = originals.get(marker_id)
if original is None:
raise PlacementError(f"unknown marker id: {marker_id}", 404)
if original.get("mapId") != map_id:
raise PlacementError("an extracted marker cannot be deleted from another map", 400)
if marker_id not in deleted:
deleted.append(marker_id)
deleted.sort()
overrides.pop(marker_id, None)
_write_marker_edits(map_id, edits)
return {"ok": True, "deletedId": marker_id, "mapId": map_id}
def save_trim(map_id: str, points: list[list[float]], transparency: float) -> dict:
"""Persist a polygon and build a separate, permanently masked raster copy."""
with CONFIG_LOCK: