saliacoel commited on
Commit
1f5b54b
·
verified ·
1 Parent(s): 5599e32

Upload GPT_TO_HF_DoorIterations.py

Browse files
Files changed (1) hide show
  1. GPT_TO_HF_DoorIterations.py +181 -10
GPT_TO_HF_DoorIterations.py CHANGED
@@ -20,7 +20,7 @@ except ImportError: # Allows validation outside ComfyUI.
20
  folder_paths = None
21
 
22
 
23
- NODE_VERSION = "1.4.0"
24
  OPENAI_MODEL = "gpt-image-2"
25
  OPENAI_BATCH_ENDPOINT = "/v1/images/edits"
26
  SOURCE_REPO_ID = "saliacoel/maps_imgs"
@@ -740,6 +740,17 @@ def _navigation_entries(navigation: Mapping[str, Any]) -> List[Dict[str, Any]]:
740
  raise ValueError(f"Navigation location {index} is malformed.")
741
  custom_id = str(raw.get("customId") or "").strip()
742
  file_name = str(raw.get("sourceScreenshotFileName") or "").strip()
 
 
 
 
 
 
 
 
 
 
 
743
  if (
744
  not _SAFE_CUSTOM_ID.fullmatch(custom_id)
745
  or custom_id in seen
@@ -753,6 +764,8 @@ def _navigation_entries(navigation: Mapping[str, Any]) -> List[Dict[str, Any]]:
753
  {
754
  "customId": custom_id,
755
  "sourceScreenshotFileName": Path(file_name).name,
 
 
756
  }
757
  )
758
  return entries
@@ -762,10 +775,29 @@ def _door_item(
762
  navigation_entry: Mapping[str, Any],
763
  target_by_id: Mapping[str, Dict[str, Any]],
764
  capture_number: int,
 
765
  ) -> Dict[str, Any]:
766
  custom_id = str(navigation_entry["customId"])
767
  target = target_by_id.get(custom_id)
768
  if target is None:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
769
  raise ValueError(
770
  f"Door screenshot '{custom_id}' has no GPT image in map_imgs_gpt."
771
  )
@@ -792,6 +824,7 @@ def _door_item(
792
  "relativePath": relative_path,
793
  "sha256": sha256,
794
  "locationId": str(target.get("locationId") or ""),
 
795
  }
796
 
797
 
@@ -801,6 +834,12 @@ def discover_door_triplets(
801
  ) -> List[Dict[str, Any]]:
802
  """Map every building to side_1, side_2 and center by source filenames."""
803
  target_by_id = _target_items(target_manifest)
 
 
 
 
 
 
804
  grouped: Dict[str, Dict[str, List[Dict[str, Any]]]] = {}
805
 
806
  for entry in _navigation_entries(navigation):
@@ -814,7 +853,16 @@ def discover_door_triplets(
814
  continue
815
  key = match.group("key")
816
  number = int(match.group("number"))
817
- item = _door_item(entry, target_by_id, number)
 
 
 
 
 
 
 
 
 
818
  grouped.setdefault(key, {"side": [], "center": []})[role].append(item)
819
 
820
  if not grouped:
@@ -903,6 +951,11 @@ def build_iteration_requests(
903
  "targetCustomId": str(target["customId"]),
904
  "targetRelativePath": str(target["relativePath"]),
905
  "targetBeforeSha256": str(target["sha256"]),
 
 
 
 
 
906
  "inputRoles": input_roles,
907
  "inputCustomIds": input_custom_ids,
908
  "inputUrls": input_urls,
@@ -1217,6 +1270,8 @@ def _initial_navigation_metadata(
1217
  if not isinstance(locations, list) or not locations:
1218
  raise ValueError("gpt_navigation_manifest.json contains no locations.")
1219
  mapping: Dict[str, Dict[str, str]] = {}
 
 
1220
  location_ids = set()
1221
  for index, raw in enumerate(locations):
1222
  if not isinstance(raw, dict):
@@ -1229,6 +1284,11 @@ def _initial_navigation_metadata(
1229
  else ""
1230
  )
1231
  source_name = str(raw.get("sourceScreenshotFileName") or "").strip()
 
 
 
 
 
1232
  if (
1233
  not _SAFE_CUSTOM_ID.fullmatch(custom_id)
1234
  or custom_id in mapping
@@ -1240,15 +1300,36 @@ def _initial_navigation_metadata(
1240
  f"Navigation location {index} has an unsafe or duplicate mapping."
1241
  )
1242
  location_ids.add(location_id)
1243
- mapping[custom_id] = {
1244
  "locationId": location_id,
1245
  "sourceScreenshotFileName": source_name,
 
1246
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1247
 
1248
  return {
1249
  "recipe": recipe,
1250
  "navigation": navigation,
1251
  "mapping": mapping,
 
 
1252
  "recipeSha256": recipe_sha256,
1253
  "navigationSha256": navigation_sha256,
1254
  "generatorVersion": str(recipe.get("generatorVersion") or ""),
@@ -1415,8 +1496,24 @@ def _publish_initial_batch(
1415
  recipe_bytes,
1416
  navigation_bytes,
1417
  )
1418
- expected_count = len(source_metadata["mapping"])
1419
  total, completed, failed = _request_counts(batch)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1420
  output_file_id = str(batch.get("output_file_id") or "")
1421
  if (
1422
  failed != 0
@@ -1443,7 +1540,7 @@ def _publish_initial_batch(
1443
  items, total_lines = _extract_initial_batch_results(
1444
  output_jsonl,
1445
  images_directory,
1446
- source_metadata["mapping"],
1447
  )
1448
  content_key = _initial_content_key(
1449
  str(source_metadata["recipeSha256"]),
@@ -1476,6 +1573,9 @@ def _publish_initial_batch(
1476
  "compactRecipeSha256": source_metadata["recipeSha256"],
1477
  "navigationManifestSha256": source_metadata["navigationSha256"],
1478
  "resultLineCount": total_lines,
 
 
 
1479
  "imageCount": len(items),
1480
  "failedCount": 0,
1481
  "imageWidth": TARGET_WIDTH,
@@ -1533,7 +1633,9 @@ def _publish_initial_batch(
1533
  )
1534
  return (
1535
  f"Published initial GPT image set for {district} from Batch {batch_id}: "
1536
- f"{len(items)} images and gpt_image_manifest.json."
 
 
1537
  )
1538
 
1539
 
@@ -2479,12 +2581,49 @@ def _apply_results_to_manifest(
2479
  results: Sequence[Mapping[str, Any]],
2480
  ) -> str:
2481
  by_id = _target_items(manifest)
 
 
 
 
 
 
 
2482
  for result in results:
2483
- item = by_id.get(str(result["targetCustomId"]))
 
2484
  if item is None:
2485
- raise ValueError(
2486
- f"Target custom id vanished: {result['targetCustomId']}"
 
 
 
 
 
2487
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2488
  if str(item.get("relativePath") or "") != str(result["targetRelativePath"]):
2489
  raise ValueError(
2490
  f"Target path changed for {result['targetCustomId']}."
@@ -2495,7 +2634,21 @@ def _apply_results_to_manifest(
2495
  item["width"] = int(result["width"])
2496
  item["height"] = int(result["height"])
2497
 
2498
- iteration = int(state["iteration"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2499
  consistency = manifest.get("doorConsistency")
2500
  if not isinstance(consistency, dict):
2501
  consistency = {}
@@ -2604,6 +2757,24 @@ def publish_door_iteration(
2604
  + (" for overwrite mode." if overwrite_mode else ".")
2605
  )
2606
  _verify_publish_guards(current_manifest, state)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2607
  content_key = _apply_results_to_manifest(current_manifest, state, results)
2608
  updated_manifest_path = run_root / "gpt_image_manifest.updated.json"
2609
  _write_json(updated_manifest_path, current_manifest)
 
20
  folder_paths = None
21
 
22
 
23
+ NODE_VERSION = "1.5.0"
24
  OPENAI_MODEL = "gpt-image-2"
25
  OPENAI_BATCH_ENDPOINT = "/v1/images/edits"
26
  SOURCE_REPO_ID = "saliacoel/maps_imgs"
 
740
  raise ValueError(f"Navigation location {index} is malformed.")
741
  custom_id = str(raw.get("customId") or "").strip()
742
  file_name = str(raw.get("sourceScreenshotFileName") or "").strip()
743
+ location = raw.get("location")
744
+ location_kind = (
745
+ str(location.get("kind") or "").strip()
746
+ if isinstance(location, Mapping)
747
+ else ""
748
+ )
749
+ location_id = (
750
+ str(location.get("id") or "").strip()
751
+ if isinstance(location, Mapping)
752
+ else ""
753
+ )
754
  if (
755
  not _SAFE_CUSTOM_ID.fullmatch(custom_id)
756
  or custom_id in seen
 
764
  {
765
  "customId": custom_id,
766
  "sourceScreenshotFileName": Path(file_name).name,
767
+ "locationKind": location_kind,
768
+ "locationId": location_id,
769
  }
770
  )
771
  return entries
 
775
  navigation_entry: Mapping[str, Any],
776
  target_by_id: Mapping[str, Dict[str, Any]],
777
  capture_number: int,
778
+ allow_deferred_initial_image: bool = False,
779
  ) -> Dict[str, Any]:
780
  custom_id = str(navigation_entry["customId"])
781
  target = target_by_id.get(custom_id)
782
  if target is None:
783
+ if allow_deferred_initial_image:
784
+ location_kind = str(navigation_entry.get("locationKind") or "")
785
+ location_id = str(navigation_entry.get("locationId") or "")
786
+ if location_kind.lower() != "door" or not location_id:
787
+ raise ValueError(
788
+ f"Missing GPT image '{custom_id}' is not an explicitly "
789
+ "deferred door location."
790
+ )
791
+ source_name = str(navigation_entry["sourceScreenshotFileName"])
792
+ return {
793
+ "customId": custom_id,
794
+ "captureNumber": capture_number,
795
+ "sourceScreenshotFileName": source_name,
796
+ "relativePath": f"images/{custom_id}.png",
797
+ "sha256": "missing",
798
+ "locationId": location_id,
799
+ "deferredInitialImage": True,
800
+ }
801
  raise ValueError(
802
  f"Door screenshot '{custom_id}' has no GPT image in map_imgs_gpt."
803
  )
 
824
  "relativePath": relative_path,
825
  "sha256": sha256,
826
  "locationId": str(target.get("locationId") or ""),
827
+ "deferredInitialImage": False,
828
  }
829
 
830
 
 
834
  ) -> List[Dict[str, Any]]:
835
  """Map every building to side_1, side_2 and center by source filenames."""
836
  target_by_id = _target_items(target_manifest)
837
+ deferred_initial_ids = {
838
+ str(entry.get("customId") or "")
839
+ for entry in target_manifest.get("deferredInitialItems", [])
840
+ if isinstance(entry, Mapping)
841
+ }
842
+ can_have_deferred_centers = _manifest_stage(target_manifest) == 0
843
  grouped: Dict[str, Dict[str, List[Dict[str, Any]]]] = {}
844
 
845
  for entry in _navigation_entries(navigation):
 
853
  continue
854
  key = match.group("key")
855
  number = int(match.group("number"))
856
+ item = _door_item(
857
+ entry,
858
+ target_by_id,
859
+ number,
860
+ allow_deferred_initial_image=(
861
+ role == "center"
862
+ and can_have_deferred_centers
863
+ and str(entry["customId"]) in deferred_initial_ids
864
+ ),
865
+ )
866
  grouped.setdefault(key, {"side": [], "center": []})[role].append(item)
867
 
868
  if not grouped:
 
951
  "targetCustomId": str(target["customId"]),
952
  "targetRelativePath": str(target["relativePath"]),
953
  "targetBeforeSha256": str(target["sha256"]),
954
+ "targetLocationId": str(target.get("locationId") or ""),
955
+ "targetSourceScreenshotFileName": str(
956
+ target.get("sourceScreenshotFileName") or ""
957
+ ),
958
+ "targetWasMissing": bool(target.get("deferredInitialImage")),
959
  "inputRoles": input_roles,
960
  "inputCustomIds": input_custom_ids,
961
  "inputUrls": input_urls,
 
1270
  if not isinstance(locations, list) or not locations:
1271
  raise ValueError("gpt_navigation_manifest.json contains no locations.")
1272
  mapping: Dict[str, Dict[str, str]] = {}
1273
+ initial_batch_mapping: Dict[str, Dict[str, str]] = {}
1274
+ deferred_door_items: List[Dict[str, str]] = []
1275
  location_ids = set()
1276
  for index, raw in enumerate(locations):
1277
  if not isinstance(raw, dict):
 
1284
  else ""
1285
  )
1286
  source_name = str(raw.get("sourceScreenshotFileName") or "").strip()
1287
+ location_kind = (
1288
+ str(location.get("kind") or "").strip()
1289
+ if isinstance(location, Mapping)
1290
+ else ""
1291
+ )
1292
  if (
1293
  not _SAFE_CUSTOM_ID.fullmatch(custom_id)
1294
  or custom_id in mapping
 
1300
  f"Navigation location {index} has an unsafe or duplicate mapping."
1301
  )
1302
  location_ids.add(location_id)
1303
+ entry = {
1304
  "locationId": location_id,
1305
  "sourceScreenshotFileName": source_name,
1306
+ "locationKind": location_kind,
1307
  }
1308
+ mapping[custom_id] = entry
1309
+ if location_kind.lower() == "door":
1310
+ deferred_door_items.append(
1311
+ {
1312
+ "customId": custom_id,
1313
+ "locationId": location_id,
1314
+ "sourceScreenshotFileName": source_name,
1315
+ "reason": "created_by_door_iteration_1",
1316
+ }
1317
+ )
1318
+ else:
1319
+ initial_batch_mapping[custom_id] = entry
1320
+
1321
+ if not initial_batch_mapping:
1322
+ raise ValueError(
1323
+ "gpt_navigation_manifest.json has no non-door locations for the "
1324
+ "initial screenshot Batch."
1325
+ )
1326
 
1327
  return {
1328
  "recipe": recipe,
1329
  "navigation": navigation,
1330
  "mapping": mapping,
1331
+ "initialBatchMapping": initial_batch_mapping,
1332
+ "deferredDoorItems": deferred_door_items,
1333
  "recipeSha256": recipe_sha256,
1334
  "navigationSha256": navigation_sha256,
1335
  "generatorVersion": str(recipe.get("generatorVersion") or ""),
 
1496
  recipe_bytes,
1497
  navigation_bytes,
1498
  )
 
1499
  total, completed, failed = _request_counts(batch)
1500
+ all_mapping = source_metadata["mapping"]
1501
+ initial_mapping = source_metadata["initialBatchMapping"]
1502
+ if total == len(initial_mapping):
1503
+ selected_mapping = initial_mapping
1504
+ deferred_items = list(source_metadata["deferredDoorItems"])
1505
+ elif total == len(all_mapping):
1506
+ # Backwards compatibility for already-created V6.0.18 Batches, which
1507
+ # still generated the redundant frontal door images initially.
1508
+ selected_mapping = all_mapping
1509
+ deferred_items = []
1510
+ else:
1511
+ raise ValueError(
1512
+ f"Initial Batch {batch_id} has {total} request(s); expected either "
1513
+ f"{len(initial_mapping)} with door frontviews deferred or "
1514
+ f"{len(all_mapping)} for the legacy all-location format."
1515
+ )
1516
+ expected_count = len(selected_mapping)
1517
  output_file_id = str(batch.get("output_file_id") or "")
1518
  if (
1519
  failed != 0
 
1540
  items, total_lines = _extract_initial_batch_results(
1541
  output_jsonl,
1542
  images_directory,
1543
+ selected_mapping,
1544
  )
1545
  content_key = _initial_content_key(
1546
  str(source_metadata["recipeSha256"]),
 
1573
  "compactRecipeSha256": source_metadata["recipeSha256"],
1574
  "navigationManifestSha256": source_metadata["navigationSha256"],
1575
  "resultLineCount": total_lines,
1576
+ "initialBatchImageCount": len(items),
1577
+ "deferredInitialImageCount": len(deferred_items),
1578
+ "deferredInitialItems": deferred_items,
1579
  "imageCount": len(items),
1580
  "failedCount": 0,
1581
  "imageWidth": TARGET_WIDTH,
 
1633
  )
1634
  return (
1635
  f"Published initial GPT image set for {district} from Batch {batch_id}: "
1636
+ f"{len(items)} images and gpt_image_manifest.json; "
1637
+ f"{len(deferred_items)} frontal door image(s) deferred to Door "
1638
+ "Iteration 1."
1639
  )
1640
 
1641
 
 
2581
  results: Sequence[Mapping[str, Any]],
2582
  ) -> str:
2583
  by_id = _target_items(manifest)
2584
+ requests = state.get("requests")
2585
+ request_by_target = {
2586
+ str(request.get("targetCustomId") or ""): request
2587
+ for request in requests
2588
+ if isinstance(request, Mapping) and request.get("targetCustomId")
2589
+ } if isinstance(requests, list) else {}
2590
+ iteration = int(state["iteration"])
2591
  for result in results:
2592
+ target_custom_id = str(result["targetCustomId"])
2593
+ item = by_id.get(target_custom_id)
2594
  if item is None:
2595
+ request = request_by_target.get(target_custom_id)
2596
+ can_create_deferred_door = (
2597
+ iteration == 1
2598
+ and isinstance(request, Mapping)
2599
+ and request.get("targetWasMissing") is True
2600
+ and str(request.get("targetBeforeSha256") or "") == "missing"
2601
+ and str(request.get("targetRole") or "") == "center"
2602
  )
2603
+ if not can_create_deferred_door:
2604
+ raise ValueError(
2605
+ f"Target custom id vanished: {target_custom_id}"
2606
+ )
2607
+ location_id = str(request.get("targetLocationId") or "").strip()
2608
+ source_name = str(
2609
+ request.get("targetSourceScreenshotFileName") or ""
2610
+ ).strip()
2611
+ if not location_id or not source_name:
2612
+ raise ValueError(
2613
+ f"Deferred door target '{target_custom_id}' has incomplete "
2614
+ "navigation metadata."
2615
+ )
2616
+ item = {
2617
+ "customId": target_custom_id,
2618
+ "relativePath": str(result["targetRelativePath"]),
2619
+ "locationId": location_id,
2620
+ "sourceScreenshotFileName": source_name,
2621
+ }
2622
+ manifest_items = manifest.get("items")
2623
+ if not isinstance(manifest_items, list):
2624
+ raise ValueError("gpt_image_manifest.json contains no image items.")
2625
+ manifest_items.append(item)
2626
+ by_id[target_custom_id] = item
2627
  if str(item.get("relativePath") or "") != str(result["targetRelativePath"]):
2628
  raise ValueError(
2629
  f"Target path changed for {result['targetCustomId']}."
 
2634
  item["width"] = int(result["width"])
2635
  item["height"] = int(result["height"])
2636
 
2637
+ manifest["imageCount"] = len(by_id)
2638
+ deferred = manifest.get("deferredInitialItems")
2639
+ if isinstance(deferred, list):
2640
+ resolved_ids = {
2641
+ str(result["targetCustomId"]) for result in results
2642
+ }
2643
+ deferred = [
2644
+ entry
2645
+ for entry in deferred
2646
+ if not isinstance(entry, Mapping)
2647
+ or str(entry.get("customId") or "") not in resolved_ids
2648
+ ]
2649
+ manifest["deferredInitialItems"] = deferred
2650
+ manifest["deferredInitialImageCount"] = len(deferred)
2651
+
2652
  consistency = manifest.get("doorConsistency")
2653
  if not isinstance(consistency, dict):
2654
  consistency = {}
 
2757
  + (" for overwrite mode." if overwrite_mode else ".")
2758
  )
2759
  _verify_publish_guards(current_manifest, state)
2760
+ current_items = _target_items(current_manifest)
2761
+ for result in results:
2762
+ target_custom_id = str(result["targetCustomId"])
2763
+ if target_custom_id in current_items:
2764
+ continue
2765
+ path_in_repo = f"{district}/{result['targetRelativePath']}"
2766
+ if api.file_exists(
2767
+ repo_id=TARGET_REPO_ID,
2768
+ filename=path_in_repo,
2769
+ repo_type=HF_REPO_TYPE,
2770
+ revision=current_commit,
2771
+ token=hf_token,
2772
+ ):
2773
+ raise ValueError(
2774
+ f"Deferred door path '{path_in_repo}' already exists outside "
2775
+ "gpt_image_manifest.json. Automatic publication refused to "
2776
+ "overwrite it."
2777
+ )
2778
  content_key = _apply_results_to_manifest(current_manifest, state, results)
2779
  updated_manifest_path = run_root / "gpt_image_manifest.updated.json"
2780
  _write_json(updated_manifest_path, current_manifest)