saliacoel commited on
Commit
aa2cfbb
·
verified ·
1 Parent(s): 0871f32

Upload 2 files

Browse files
salia_city_door_frontview_generator.py ADDED
@@ -0,0 +1,549 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """City — Door Frontview Generator (2 Laps), standalone ComfyUI node.
2
+
3
+ Install this file directly in ComfyUI/custom_nodes/ and restart ComfyUI.
4
+ No sibling custom node is required. Keep the separate Door Forward selector.
5
+
6
+ DISTRICT_NAME + IMAGE_INDEX -> frontview IMAGE, animation_filename,
7
+ side_image_filename. For N doors sorted by stable front-view location ID:
8
+ 1..N: unchanged frontview; filenames target the LEFT-side street view.
9
+ N+1..2N: horizontally mirrored SAME frontview; filenames target RIGHT and
10
+ both carry the temporary _UNMIRRORED suffix.
11
+ Other integers: black 1x1 IMAGE, INVALID, INVALID.
12
+
13
+ Feed the image to your front-to-left video generator. After generation, send
14
+ its IMAGE batch and animation_filename through UNMIRRORED_Fixer before the
15
+ animation uploader. On a separate branch send the raw final frame and
16
+ side_image_filename through a second fixer before the still uploader. Do NOT
17
+ apply a marked filename to already-fixed pixels: that would flip them twice.
18
+
19
+ Animation names are Unity's EXISTING canonical FRONT_to_SIDE names without
20
+ .zip. Store frames FRONT->SIDE; Unity already reverses them for SIDE->FRONT.
21
+ No _FWD_ANIM or _XXX_TURN_* suffix belongs to this particular animation.
22
+ The still output includes the exact authored image extension. The temporary
23
+ marker is appended after the whole name (e.g. door_right.png_UNMIRRORED);
24
+ the fixer removes it BEFORE either uploader receives it.
25
+
26
+ This selector downloads ONLY the front image. Side mappings are required,
27
+ but side pixels may be missing or obsolete; they are never downloaded.
28
+ It does not generate, upload, delete, or overwrite remote files. Configure
29
+ uploaders to overwrite these exact cleaned keys, not append counters.
30
+
31
+ The same validated navigation reader, door pairing and stable sorting as the
32
+ supplied Door Forward selector are included here. Downloads are commit-pinned
33
+ and checksum-cached; no Unity or extra Python package is needed beyond ComfyUI.
34
+ Local selection/catalog metadata: output/Salia_CityDoorFrontviewGenerator/.
35
+ """
36
+
37
+ VERSION = "1.0.0"
38
+
39
+ import hashlib
40
+ import io
41
+ import json
42
+ import os
43
+ import re
44
+ import tempfile
45
+ import time
46
+ from http.client import HTTPException
47
+ from pathlib import PurePosixPath
48
+ from urllib.error import HTTPError, URLError
49
+ from urllib.parse import quote
50
+ from urllib.request import Request, urlopen
51
+ import numpy as np
52
+ from PIL import Image, ImageOps
53
+
54
+ try:
55
+ from comfy.model_management import throw_exception_if_processing_interrupted as _interrupt
56
+ except ImportError:
57
+ def _interrupt():
58
+ pass
59
+
60
+ REPO = "saliacoel/map_imgs_gpt"
61
+ _JSON_LIMIT = 32 * 1024 * 1024
62
+ _IMAGE_LIMIT = 64 * 1024 * 1024
63
+ _TIMEOUT = 45
64
+ _ATTEMPTS = 3
65
+ _IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp"}
66
+
67
+ def _normalize_district(value):
68
+ if not isinstance(value, str):
69
+ raise ValueError("DISTRICT_NAME must be a string, e.g. District_19_A.")
70
+ value = value.strip()
71
+ if value.lower().endswith(".json"):
72
+ value = value[:-5]
73
+ if not re.fullmatch(r"[A-Za-z0-9](?:[A-Za-z0-9_.-]*[A-Za-z0-9])?", value):
74
+ raise ValueError("Enter a district ID only, e.g. District_19_A; do not enter a URL or folder path.")
75
+ return value
76
+
77
+ def _relative_image_path(value, district):
78
+ if not isinstance(value, str) or not value or value != value.strip():
79
+ raise ValueError("Image mapping contains an empty or invalid filename.")
80
+ if value.startswith(district + "/"):
81
+ value = value[len(district) + 1:]
82
+ if (value.startswith("/") or "\\" in value or ":" in value
83
+ or any(ord(c) < 32 or ord(c) == 127 for c in value)
84
+ or any(part in ("", ".", "..") for part in value.split("/"))):
85
+ raise ValueError("Unsafe relative image path in navigation: {!r}.".format(value))
86
+ if PurePosixPath(value).suffix.lower() not in _IMAGE_EXTENSIONS:
87
+ raise ValueError("Unsupported image filename in navigation: {!r}.".format(value))
88
+ return value
89
+
90
+ def _animation_name(district, first_path, last_path):
91
+ def stem(path):
92
+ path = _relative_image_path(path, district)
93
+ return quote(path[:path.rfind(".")], safe="-_.~")
94
+ result = district + "/" + stem(first_path) + "_to_" + stem(last_path)
95
+ if len((result + ".zip").encode("utf-8")) > 1024:
96
+ raise ValueError("The transition filename exceeds Backblaze's 1024-byte filename limit.")
97
+ return result
98
+
99
+ def _parse_json(data, label):
100
+ try:
101
+ value = json.loads(data.decode("utf-8-sig"))
102
+ except (ValueError, UnicodeError) as error:
103
+ raise ValueError("{} is not valid UTF-8 JSON: {}".format(label, error)) from None
104
+ if not isinstance(value, dict):
105
+ raise ValueError("{} must contain a JSON object.".format(label))
106
+ return value
107
+
108
+ class _HttpError(RuntimeError):
109
+ def __init__(self, url, status):
110
+ self.status = status
111
+ super().__init__("HTTP {} while downloading {}".format(status, url))
112
+
113
+ def _download(url, limit):
114
+ for attempt in range(_ATTEMPTS):
115
+ _interrupt()
116
+ try:
117
+ req = Request(url, headers={"User-Agent": "Salia-City-Door-Frontview-Generator/" + VERSION})
118
+ with urlopen(req, timeout=_TIMEOUT) as response:
119
+ data = bytearray()
120
+ while True:
121
+ _interrupt()
122
+ chunk = response.read(min(256 * 1024, limit + 1 - len(data)))
123
+ if not chunk:
124
+ return bytes(data)
125
+ data.extend(chunk)
126
+ if len(data) > limit:
127
+ raise ValueError("Download exceeds the allowed size: " + url)
128
+ except HTTPError as error:
129
+ status = error.code
130
+ error.close()
131
+ if status not in (408, 429, 500, 502, 503, 504) or attempt == _ATTEMPTS - 1:
132
+ raise _HttpError(url, status) from None
133
+ except (URLError, TimeoutError, OSError, HTTPException) as error:
134
+ if attempt == _ATTEMPTS - 1:
135
+ raise RuntimeError("Could not download {} after {} attempts: {}".format(url, _ATTEMPTS, error)) from None
136
+ end = time.monotonic() + 2 ** attempt
137
+ while time.monotonic() < end:
138
+ _interrupt()
139
+ time.sleep(min(0.1, max(0, end - time.monotonic())))
140
+ raise RuntimeError("Download failed: " + url)
141
+
142
+ def _directories():
143
+ try:
144
+ import folder_paths
145
+ cache = os.path.join(folder_paths.get_temp_directory(), "Salia_CityDoorFrontviewGenerator")
146
+ output = os.path.join(folder_paths.get_output_directory(), "Salia_CityDoorFrontviewGenerator")
147
+ except ImportError:
148
+ cache = os.path.join(tempfile.gettempdir(), "Salia_CityDoorFrontviewGenerator", "cache")
149
+ output = os.path.join(tempfile.gettempdir(), "Salia_CityDoorFrontviewGenerator", "output")
150
+ os.makedirs(cache, exist_ok=True)
151
+ os.makedirs(output, exist_ok=True)
152
+ return cache, output
153
+
154
+ def _atomic_write(path, data):
155
+ os.makedirs(os.path.dirname(path), exist_ok=True)
156
+ fd, temporary = tempfile.mkstemp(prefix=".writing-", dir=os.path.dirname(path))
157
+ try:
158
+ with os.fdopen(fd, "wb") as stream:
159
+ stream.write(data)
160
+ os.replace(temporary, path)
161
+ finally:
162
+ if os.path.exists(temporary):
163
+ os.remove(temporary)
164
+
165
+ def _content_digest(entry):
166
+ lfs = entry.get("lfs") or {}
167
+ value = lfs.get("sha256") or lfs.get("oid") or ""
168
+ if value.startswith("sha256:"):
169
+ value = value[7:]
170
+ if re.fullmatch(r"[a-fA-F0-9]{64}", value):
171
+ return "sha256", value.lower()
172
+ value = entry.get("blobId") or ""
173
+ if re.fullmatch(r"[a-fA-F0-9]{40}", value) and not lfs:
174
+ return "git", value.lower()
175
+ return "", ""
176
+
177
+ def _matches(data, kind, digest):
178
+ if not digest:
179
+ return True
180
+ if kind == "git":
181
+ return hashlib.sha1(b"blob " + str(len(data)).encode("ascii") + b"\0" + data).hexdigest() == digest
182
+ return hashlib.sha256(data).hexdigest() == digest
183
+
184
+ def _fetch_pinned(revision, path, files, limit, expected_sha="", force=False):
185
+ if path not in files:
186
+ raise ValueError("Image/metadata is not published in this district snapshot: {}. The pair index has not been changed; publish the missing file and run again.".format(path))
187
+ kind, digest = _content_digest(files[path])
188
+ token = digest or revision
189
+ cache, _ = _directories()
190
+ local = os.path.join(cache, hashlib.sha256((REPO + "|" + token + "|" + path).encode("utf-8")).hexdigest() + ".bin")
191
+ def valid(data):
192
+ return bool(data) and len(data) <= limit and _matches(data, kind, digest) and _matches(data, "sha256", expected_sha)
193
+ if not force:
194
+ try:
195
+ with open(local, "rb") as stream:
196
+ data = stream.read(limit + 1)
197
+ if valid(data):
198
+ return data
199
+ except FileNotFoundError:
200
+ pass
201
+ url = "https://huggingface.co/{}/resolve/{}/{}".format(REPO, revision, quote(path, safe="/"))
202
+ data = _download(url, limit)
203
+ if not valid(data):
204
+ raise ValueError("Downloaded file is empty or does not match its published checksum: " + path)
205
+ _atomic_write(local, data)
206
+ return data
207
+
208
+ def _load_district(requested):
209
+ district = _normalize_district(requested)
210
+ snapshot = _parse_json(_download("https://huggingface.co/api/models/{}/revision/main?blobs=true".format(REPO), _JSON_LIMIT), "Repository inventory")
211
+ revision = snapshot.get("sha", "")
212
+ if not isinstance(revision, str) or not re.fullmatch(r"[a-fA-F0-9]{40}", revision) or not isinstance(snapshot.get("siblings"), list):
213
+ raise ValueError("Repository inventory is missing its commit or file list.")
214
+ files = {entry["rfilename"]: entry for entry in snapshot["siblings"]
215
+ if isinstance(entry, dict) and isinstance(entry.get("rfilename"), str)}
216
+ if not any(path.startswith(district + "/") for path in files):
217
+ shorthand = re.fullmatch(r"(District_[0-9]+)([A-Za-z][A-Za-z0-9]*)", district)
218
+ alias = shorthand[1] + "_" + shorthand[2] if shorthand else ""
219
+ if alias and any(path.startswith(alias + "/") for path in files):
220
+ district = alias
221
+ nav_path = district + "/topdown_navigation_manifest.json"
222
+ if nav_path not in files:
223
+ nav_path = district + "/gpt_navigation_manifest.json"
224
+ if nav_path not in files:
225
+ raise ValueError("No published navigation for {} in {}. Use the published district ID, e.g. District_19_A; a recipe JSON alone has no image pairs.".format(district, REPO))
226
+ nav_bytes = _fetch_pinned(revision, nav_path, files, _JSON_LIMIT)
227
+ nav = _parse_json(nav_bytes, nav_path)
228
+ legacy = None
229
+ if not nav.get("batchSets"):
230
+ legacy_path = district + "/gpt_image_manifest.json"
231
+ legacy = _parse_json(_fetch_pinned(revision, legacy_path, files, _JSON_LIMIT), legacy_path)
232
+ expected = legacy.get("navigationManifestSha256") or ""
233
+ if expected and hashlib.sha256(nav_bytes).hexdigest() != expected.lower():
234
+ raise ValueError("Legacy navigation and image manifest hashes do not match; publish the matching pair of JSON files.")
235
+ return district, revision, nav, legacy, files
236
+
237
+ def _decode_pixels(data):
238
+ with Image.open(io.BytesIO(data)) as source:
239
+ source.load()
240
+ image = ImageOps.exif_transpose(source).convert("RGB")
241
+ return np.array(image, dtype=np.float32) / 255.0
242
+
243
+ def _load_image(district, revision, path, files, expected_sha=""):
244
+ full_path = district + "/" + path
245
+ for force in (False, True):
246
+ data = _fetch_pinned(revision, full_path, files, _IMAGE_LIMIT, expected_sha, force)
247
+ try:
248
+ return _decode_pixels(data), hashlib.sha256(data).hexdigest()
249
+ except (OSError, ValueError, Image.DecompressionBombError):
250
+ if force:
251
+ raise ValueError("Published file could not be decoded as an image: " + full_path) from None
252
+ raise RuntimeError("Could not load image: " + full_path)
253
+
254
+ def _read_tables(navigation, district, legacy=None):
255
+ """Validate the authored locations and exact published image mappings."""
256
+ if navigation.get("districtName") != district:
257
+ raise ValueError("Published navigation belongs to a different district.")
258
+ records = navigation.get("locations")
259
+ if not isinstance(records, list) or not records:
260
+ raise ValueError("Published JSON has no navigation locations; a small recipe is not a playable map.")
261
+ locations, custom_ids = {}, {}
262
+ for record in records:
263
+ loc = record.get("location") if isinstance(record, dict) else None
264
+ if not isinstance(loc, dict) or not isinstance(loc.get("id"), str) or not loc["id"]:
265
+ raise ValueError("Navigation contains an invalid location record.")
266
+ if loc["id"] in locations:
267
+ raise ValueError("Duplicate navigation location: " + loc["id"])
268
+ locations[loc["id"]] = loc
269
+ custom_ids[loc["id"]] = record.get("customId", "")
270
+
271
+ jobs = []
272
+ sets = navigation.get("batchSets")
273
+ if sets:
274
+ if not isinstance(sets, list):
275
+ raise ValueError("batchSets must be a list.")
276
+ for batch in sets:
277
+ if not isinstance(batch, dict) or not isinstance(batch.get("images"), list):
278
+ raise ValueError("Invalid image-mapping batch in navigation.")
279
+ jobs.extend(batch["images"])
280
+ path_field = "targetGeneratedFileName"
281
+ else:
282
+ if not isinstance(legacy, dict) or legacy.get("districtName") != district or not isinstance(legacy.get("items"), list):
283
+ raise ValueError("This older map requires its published gpt_image_manifest.json.")
284
+ if legacy.get("repoId") and legacy["repoId"] != REPO:
285
+ raise ValueError("Legacy image mapping belongs to another image repository.")
286
+ jobs, path_field = legacy["items"], "relativePath"
287
+
288
+ images, used_paths = {}, {}
289
+ for job in jobs:
290
+ if not isinstance(job, dict) or not isinstance(job.get("locationId"), str):
291
+ raise ValueError("Invalid image-mapping entry.")
292
+ location_id = job["locationId"]
293
+ if location_id in images:
294
+ raise ValueError("Duplicate image mapping for " + location_id)
295
+ path = _relative_image_path(job.get(path_field), district)
296
+ if path in used_paths and used_paths[path] != location_id:
297
+ raise ValueError("Different viewpoints share the same image file: " + path)
298
+ if location_id in custom_ids and custom_ids[location_id] and job.get("customId") != custom_ids[location_id]:
299
+ raise ValueError("Image customId does not match navigation for " + location_id)
300
+ digest = job.get("sha256") or ""
301
+ if digest and not re.fullmatch(r"[a-fA-F0-9]{64}", digest):
302
+ raise ValueError("Invalid image SHA256 for " + location_id)
303
+ images[location_id] = {"imagePath": path, "sha256": digest.lower()}
304
+ used_paths[path] = location_id
305
+
306
+ return locations, images
307
+
308
+
309
+ def _door_actions(location):
310
+ return [a for a in (location.get("actions") or [])
311
+ if isinstance(a, dict) and a.get("kind") == "door"]
312
+
313
+
314
+ def _side_label(location):
315
+ # This is the authored navigation side identifier, not an image-name guess.
316
+ explicit = location.get("doorSide") or location.get("entranceSide")
317
+ side = explicit.lower() if isinstance(explicit, str) else ""
318
+ suffix = location["id"].rsplit("__", 1)[-1].lower()
319
+ if side and side not in ("left", "right"):
320
+ raise ValueError("Unknown authored door side on " + location["id"])
321
+ if side and suffix in ("left", "right") and suffix != side:
322
+ raise ValueError("Conflicting authored door sides on " + location["id"])
323
+ return side or (suffix if suffix in ("left", "right") else "")
324
+
325
+
326
+ def _is_front(location):
327
+ return (location.get("kind") in ("door", "door_front")
328
+ or location.get("topology") in ("door_poi", "straight_door", "door_front"))
329
+
330
+
331
+ def _build_doors(navigation, district, legacy=None):
332
+ locations, images = _read_tables(navigation, district, legacy)
333
+ fronts = sorted((loc for loc in locations.values()
334
+ if not loc.get("batchOnly")
335
+ and _is_front(loc)),
336
+ key=lambda loc: loc["id"])
337
+ rows, keys, entrances = [], set(), set()
338
+ for index, front in enumerate(fronts, 1):
339
+ front_id = front["id"]
340
+ entrance_id = front.get("sourceEntranceId") or ""
341
+ if entrance_id:
342
+ if entrance_id in entrances:
343
+ raise ValueError("Multiple front views claim entrance " + entrance_id)
344
+ entrances.add(entrance_id)
345
+ front_mapping = images.get(front_id)
346
+ row = {"doorIndex": index, "entranceId": entrance_id,
347
+ "frontLocationId": front_id,
348
+ "frontImagePath": front_mapping["imagePath"] if front_mapping else "",
349
+ "frontImageSha256": front_mapping["sha256"] if front_mapping else "",
350
+ "frontError": "" if front_mapping else "Front view has no image mapping: " + front_id,
351
+ "sides": {}}
352
+ candidates = {"left": [], "right": []}
353
+ side_errors = []
354
+ for loc in locations.values():
355
+ if loc.get("batchOnly") or loc["id"] == front_id:
356
+ continue
357
+ actions = _door_actions(loc)
358
+ action_matches = any(a.get("targetLocationId") == front_id for a in actions)
359
+ entrance_matches = bool(entrance_id and loc.get("sourceEntranceId") == entrance_id)
360
+ if not (action_matches or entrance_matches):
361
+ continue
362
+ if loc.get("kind") == "station" or any(isinstance(a, dict) and a.get("kind") == "station"
363
+ for a in (loc.get("actions") or [])):
364
+ continue
365
+ if not (loc.get("topology") == "door_approach" or loc.get("kind") == "street"):
366
+ continue
367
+ if any(a.get("targetLocationId") and a["targetLocationId"] != front_id for a in actions):
368
+ side_errors.append("Door action points to a different front view: " + loc["id"])
369
+ continue
370
+ if action_matches and entrance_id and loc.get("sourceEntranceId") not in (None, "", entrance_id):
371
+ side_errors.append("Door action and entrance identity disagree: " + loc["id"])
372
+ continue
373
+ try:
374
+ side = _side_label(loc)
375
+ except ValueError as error:
376
+ side_errors.append(str(error))
377
+ continue
378
+ if not side:
379
+ side_errors.append("Door approach has no authored left/right side: " + loc["id"])
380
+ continue
381
+ candidates[side].append(loc)
382
+ for side in ("left", "right"):
383
+ options = candidates[side]
384
+ record = {"targetSide": side.upper(), "targetLocationId": "", "targetImagePath": "",
385
+ "targetImageSha256": "", "side_image_filename": "",
386
+ "filename": "", "zipFileName": "", "validationError": ""}
387
+ if side_errors:
388
+ record["validationError"] = "; ".join(side_errors)
389
+ elif len(options) != 1:
390
+ record["validationError"] = "Expected exactly one {} approach for {}; found {}.".format(side, front_id, len(options))
391
+ else:
392
+ loc = options[0]
393
+ record["targetLocationId"] = loc["id"]
394
+ mapped = images.get(loc["id"])
395
+ if not mapped:
396
+ record["validationError"] = "Side view has no authored image mapping: " + loc["id"]
397
+ else:
398
+ record["targetImagePath"] = mapped["imagePath"]
399
+ record["targetImageSha256"] = mapped["sha256"]
400
+ record["side_image_filename"] = district + "/" + mapped["imagePath"]
401
+ if mapped and front_mapping:
402
+ name = _animation_name(district, front_mapping["imagePath"], mapped["imagePath"])
403
+ if name in keys:
404
+ raise ValueError("Door animation filename collision: " + name)
405
+ keys.add(name)
406
+ record.update(filename=name, zipFileName=name + ".zip")
407
+ row["sides"][side] = record
408
+ rows.append(row)
409
+ return rows
410
+
411
+
412
+ _MIRROR_MARKER = "_UNMIRRORED"
413
+
414
+
415
+ def _build_frontview_jobs(navigation, district, legacy=None):
416
+ """Each door occupies one stable index in each lap, even if a mapping is bad."""
417
+ doors = _build_doors(navigation, district, legacy)
418
+ jobs = []
419
+ for lap, side in enumerate(("left", "right"), 1):
420
+ for door in doors:
421
+ record = door["sides"][side]
422
+ error = door["frontError"] or record["validationError"]
423
+ animation = record["filename"]
424
+ still = record["side_image_filename"]
425
+ # A workflow marker cannot be part of a canonical object name: the
426
+ # fixer would remove it. Fail instead of publishing under a new key.
427
+ if "UNMIRRORED" in animation or "UNMIRRORED" in still:
428
+ error = error or "An authored filename contains the reserved UNMIRRORED marker."
429
+ marker = _MIRROR_MARKER if lap == 2 else ""
430
+ marked_animation = animation + marker if animation else ""
431
+ if marked_animation and len((marked_animation + ".zip").encode("utf-8")) > 1024:
432
+ error = error or "The marked animation filename exceeds the 1024-byte filename limit."
433
+ jobs.append({
434
+ "index": len(jobs) + 1, "doorIndex": door["doorIndex"],
435
+ "lap": lap, "targetSide": side.upper(), "inputMirrored": lap == 2,
436
+ "entranceId": door["entranceId"],
437
+ "frontLocationId": door["frontLocationId"],
438
+ "frontImagePath": door["frontImagePath"],
439
+ "frontImageSha256": door["frontImageSha256"],
440
+ "targetLocationId": record["targetLocationId"],
441
+ "targetImagePath": record["targetImagePath"],
442
+ "animation_filename": marked_animation,
443
+ "side_image_filename": still + marker if still else "",
444
+ "canonicalAnimationFilename": animation,
445
+ "canonicalZipFilename": animation + ".zip" if animation else "",
446
+ "canonicalSideImageFilename": still,
447
+ "storedFrameDirection": "FRONT_TO_SIDE",
448
+ "unityApproachPlaysReverse": True,
449
+ "validationError": error,
450
+ })
451
+ return jobs
452
+
453
+
454
+ def _select_frontview(jobs, index):
455
+ if isinstance(index, bool) or not isinstance(index, int):
456
+ raise ValueError("IMAGE_INDEX must be an integer.")
457
+ if index <= 0 or index > len(jobs):
458
+ return None
459
+ selected = dict(jobs[index - 1])
460
+ if selected["validationError"]:
461
+ raise ValueError("IMAGE_INDEX {} cannot be used: {}".format(index, selected["validationError"]))
462
+ selected.update(requestedIndex=index, valid=True)
463
+ return selected
464
+
465
+
466
+ def _save_catalog(district, revision, jobs, selected):
467
+ _, output = _directories()
468
+ directory = os.path.join(output, district)
469
+ common = {
470
+ "schemaId": "salia_city_door_frontview_generator_v1", "schemaVersion": 1,
471
+ "nodeVersion": VERSION, "districtName": district,
472
+ "imageRepoId": REPO, "imageRevision": revision,
473
+ "doorCount": len(jobs) // 2, "indexCount": len(jobs), "lapCount": 2,
474
+ "indexing": "1..N LEFT; N+1..2N RIGHT; other integers INVALID",
475
+ "animationDirection": "FRONT_TO_SIDE; Unity plays this same clip backwards to approach the door",
476
+ "temporaryMarker": _MIRROR_MARKER,
477
+ }
478
+ for name, payload in (("door_frontview_generator_jobs.json", dict(common, jobs=jobs)),
479
+ ("selected_door_frontview_generator.json", dict(common, selected=selected))):
480
+ _atomic_write(os.path.join(directory, name),
481
+ (json.dumps(payload, ensure_ascii=False, indent=2) + "\n").encode("utf-8"))
482
+ return directory
483
+
484
+
485
+ class Salia_City_Door_Frontview_Generator:
486
+ CATEGORY = "Salia/City"
487
+ FUNCTION = "execute"
488
+ RETURN_TYPES = ("IMAGE", "STRING", "STRING")
489
+ RETURN_NAMES = ("frontview_image", "animation_filename", "side_image_filename")
490
+ DESCRIPTION = (
491
+ "Frontview input for door-side generation. Lap 1: original front, LEFT names. "
492
+ "Lap 2: mirrored front, RIGHT names ending _UNMIRRORED. Fix generated frames "
493
+ "and both names with UNMIRRORED_Fixer before upload. Unity expects FRONT_to_SIDE "
494
+ "recordings and reverses them for door approach. Other indices return INVALID."
495
+ )
496
+
497
+ @classmethod
498
+ def INPUT_TYPES(cls):
499
+ return {"required": {
500
+ "DISTRICT_NAME": ("STRING", {"default": "District_19_A"}),
501
+ "IMAGE_INDEX": ("INT", {"default": 1, "min": -2147483647, "max": 2147483647, "step": 1,
502
+ "tooltip": "1..N: frontview for LEFT. N+1..2N: mirrored frontview for RIGHT. No third lap. Side pixels need not exist yet."}),
503
+ }}
504
+
505
+ @classmethod
506
+ def IS_CHANGED(cls, **kwargs):
507
+ # Recheck repository revision, while reusing checksum-cached bytes.
508
+ return float("nan")
509
+
510
+ def execute(self, DISTRICT_NAME, IMAGE_INDEX):
511
+ _interrupt()
512
+ if isinstance(IMAGE_INDEX, bool) or not isinstance(IMAGE_INDEX, int):
513
+ raise ValueError("IMAGE_INDEX must be an integer.")
514
+ import torch
515
+ if IMAGE_INDEX <= 0:
516
+ return torch.zeros((1, 1, 1, 3), dtype=torch.float32), "INVALID", "INVALID"
517
+ district, revision, nav, legacy, files = _load_district(DISTRICT_NAME)
518
+ jobs = _build_frontview_jobs(nav, district, legacy)
519
+ selected = _select_frontview(jobs, IMAGE_INDEX)
520
+ if selected is None:
521
+ _save_catalog(district, revision, jobs, {
522
+ "requestedIndex": IMAGE_INDEX, "valid": False,
523
+ "animation_filename": "INVALID", "side_image_filename": "INVALID",
524
+ "reason": "Index outside the two laps",
525
+ })
526
+ print("[City door frontview] {} | index {} INVALID | {} doors, {} indices.".format(
527
+ district, IMAGE_INDEX, len(jobs) // 2, len(jobs)))
528
+ return torch.zeros((1, 1, 1, 3), dtype=torch.float32), "INVALID", "INVALID"
529
+ # Only the original front is loaded. Never fetch stale side pixels or
530
+ # change catalog indexing according to which images are already uploaded.
531
+ pixels, digest = _load_image(district, revision, selected["frontImagePath"],
532
+ files, selected["frontImageSha256"])
533
+ image = torch.from_numpy(pixels).unsqueeze(0)
534
+ if selected["inputMirrored"]:
535
+ image = image.flip((2,)) # BHWC: width only, not frame order.
536
+ selected.update(frontImageSha256=digest, imageWidth=int(pixels.shape[1]),
537
+ imageHeight=int(pixels.shape[0]))
538
+ _interrupt()
539
+ directory = _save_catalog(district, revision, jobs, selected)
540
+ print("[City door frontview] {} | index {}/{} | lap {}/2 {} | input mirrored={} | "
541
+ "canonical ZIP: {} | catalog: {}".format(
542
+ district, IMAGE_INDEX, len(jobs), selected["lap"], selected["targetSide"],
543
+ selected["inputMirrored"], selected["canonicalZipFilename"], directory))
544
+ return image, selected["animation_filename"], selected["side_image_filename"]
545
+
546
+
547
+ NODE_CLASS_MAPPINGS = {"Salia_City_Door_Frontview_Generator": Salia_City_Door_Frontview_Generator}
548
+ NODE_DISPLAY_NAME_MAPPINGS = {"Salia_City_Door_Frontview_Generator": "City — Door Frontview Generator (2 Laps)"}
549
+
salia_unmirrored_fixer.py ADDED
@@ -0,0 +1,86 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """UNMIRRORED_Fixer — independent ComfyUI image-batch and filename node.
2
+
3
+ Install in ComfyUI/custom_nodes/ and restart ComfyUI. Connect an IMAGE batch
4
+ (one still or a sequence of video frames) and its filename string. The node
5
+ removes every case-sensitive UNMIRRORED marker, consuming its preceding
6
+ underscore when present. This accepts both the usual ``_UNMIRRORED`` marker
7
+ and the bare ``UNMIRRORED`` occurrences in the supplied example names.
8
+
9
+ An odd total marker count flips every image horizontally. Zero or an even
10
+ count leaves the original batch untouched. No video-frame order is reversed.
11
+ No image is resized, transferred to the CPU, re-encoded, saved or uploaded.
12
+ The result retains its tensor dtype, device, dimensions and RGB/RGBA channels.
13
+
14
+ Examples:
15
+ exampleImageName -> exampleImageName (no flip)
16
+ otherExampleImgName_UNMIRRORED -> otherExampleImgName (flip)
17
+ YetAnother_UNMIRRORED_ExampleString -> YetAnother_ExampleString (flip)
18
+ UNMIRROREDA_xUNMIRROREDB_1UNMIRROREDC_UuuuUUNMIRROREDD
19
+ -> A_xB_1C_UuuuUD (no flip)
20
+
21
+ Use the cleaned filename AND returned image batch for upload. For separate
22
+ animation and still-image upload branches, use one fixer instance per branch
23
+ with that branch's original marked filename. Do not clean the filename first
24
+ and then expect another fixer to detect that the pixels still need mirroring.
25
+ """
26
+
27
+ import re
28
+
29
+
30
+ VERSION = "1.0.0"
31
+ _MARKER = re.compile(r"_?UNMIRRORED")
32
+
33
+
34
+ def _clean_filename(filename):
35
+ """Return (cleaned string, non-overlapping marker count)."""
36
+ if not isinstance(filename, str):
37
+ raise TypeError("UNMIRRORED_Fixer: filename must be a string.")
38
+ return _MARKER.subn("", filename)
39
+
40
+
41
+ class UNMIRRORED_Fixer:
42
+ CATEGORY = "Salia/City"
43
+ FUNCTION = "execute"
44
+ RETURN_TYPES = ("IMAGE", "STRING")
45
+ RETURN_NAMES = ("image_batch", "filename")
46
+ DESCRIPTION = (
47
+ "Remove all case-sensitive _UNMIRRORED markers (also bare UNMIRRORED). "
48
+ "Odd count: flip all frames horizontally. Even/zero: pass through. "
49
+ "Frame order is preserved. Use both outputs for upload."
50
+ )
51
+
52
+ @classmethod
53
+ def INPUT_TYPES(cls):
54
+ return {"required": {
55
+ "image_batch": ("IMAGE",),
56
+ "filename": ("STRING", {"forceInput": True, "default": ""}),
57
+ }}
58
+
59
+ def execute(self, image_batch, filename):
60
+ # Torch is part of ComfyUI; defer importing it so the pure filename
61
+ # helper can also be checked outside a ComfyUI installation.
62
+ import torch
63
+
64
+ cleaned, occurrences = _clean_filename(filename)
65
+ if not isinstance(image_batch, torch.Tensor):
66
+ raise TypeError(
67
+ "UNMIRRORED_Fixer: image_batch must be a ComfyUI IMAGE tensor "
68
+ "with shape [batch, height, width, channels]."
69
+ )
70
+ if image_batch.ndim != 4 or image_batch.shape[-1] not in (3, 4):
71
+ raise ValueError(
72
+ "UNMIRRORED_Fixer: expected [batch, height, width, 3 or 4] "
73
+ "RGB/RGBA images, received shape {}.".format(tuple(image_batch.shape))
74
+ )
75
+ if any(size <= 0 for size in image_batch.shape[:3]):
76
+ raise ValueError("UNMIRRORED_Fixer: the image batch must not be empty.")
77
+
78
+ # BHWC: width is dimension 2. In particular, never flip dimension 0
79
+ # (video time), dimension 1 (vertical) or dimension 3 (color channels).
80
+ if occurrences % 2:
81
+ return image_batch.flip(dims=(2,)), cleaned
82
+ return image_batch, cleaned
83
+
84
+
85
+ NODE_CLASS_MAPPINGS = {"UNMIRRORED_Fixer": UNMIRRORED_Fixer}
86
+ NODE_DISPLAY_NAME_MAPPINGS = {"UNMIRRORED_Fixer": "UNMIRRORED_Fixer"}