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

Upload GPT_TO_HF_DoorIterations.py

Browse files
Files changed (1) hide show
  1. GPT_TO_HF_DoorIterations.py +318 -26
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.3.0"
24
  OPENAI_MODEL = "gpt-image-2"
25
  OPENAI_BATCH_ENDPOINT = "/v1/images/edits"
26
  SOURCE_REPO_ID = "saliacoel/maps_imgs"
@@ -29,6 +29,8 @@ HF_REPO_TYPE = "model"
29
  HF_REVISION = "main"
30
  UV_PATH = "UV.png"
31
  ALL_IN_ONE_STATE_NAME = "door_consistency_all_in_one_state.json"
 
 
32
  FINAL_ITERATION = 3
33
  TARGET_WIDTH = 1536
34
  TARGET_HEIGHT = 1024
@@ -296,31 +298,165 @@ def _top_level_repository_folder(entry: Any) -> str | None:
296
  return None
297
 
298
 
299
- def _discover_repository_districts(
 
 
 
 
 
 
 
 
 
 
 
 
300
  hf_key: str,
301
- ) -> Tuple[List[str], List[str]]:
302
- """Find every source map and identify those awaiting initial GPT import."""
303
- _, HfApi, _ = _load_hf_tools()
304
- api = HfApi(token=hf_key)
305
- source_commit = _repo_commit(api, SOURCE_REPO_ID, hf_key)
306
- target_commit = _repo_commit(api, TARGET_REPO_ID, hf_key)
307
- candidates = set()
308
  for entry in api.list_repo_tree(
309
- repo_id=SOURCE_REPO_ID,
310
  path_in_repo=None,
311
  recursive=False,
312
  expand=False,
313
- revision=source_commit,
314
  repo_type=HF_REPO_TYPE,
315
  token=hf_key,
316
  ):
317
  folder = _top_level_repository_folder(entry)
318
  if folder is not None:
319
- candidates.add(folder)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
 
321
  districts: List[str] = []
 
322
  missing_target_manifests: List[str] = []
323
- for district in sorted(candidates, key=_natural_name_key):
 
 
 
 
 
 
 
 
 
 
324
  source_manifest = f"{district}/gpt_navigation_manifest.json"
325
  target_manifest = f"{district}/gpt_image_manifest.json"
326
  if not api.file_exists(
@@ -343,7 +479,18 @@ def _discover_repository_districts(
343
  ):
344
  missing_target_manifests.append(district)
345
  districts.append(district)
346
- return districts, missing_target_manifests
 
 
 
 
 
 
 
 
 
 
 
347
 
348
 
349
  def _download_hf_bytes(
@@ -380,6 +527,102 @@ def _download_hf_json(
380
  return parsed, data
381
 
382
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
383
  def _hf_resolve_url(repo_id: str, revision: str, path_in_repo: str) -> str:
384
  encoded_path = "/".join(
385
  urllib.parse.quote(part, safe="")
@@ -2665,25 +2908,37 @@ def run_all_door_iterations(
2665
  iteration: _prompt_value(prompts.get(iteration), iteration)
2666
  for iteration in range(1, FINAL_ITERATION + 1)
2667
  }
2668
- districts, missing_target_manifests = _discover_repository_districts(hf_token)
 
 
 
 
2669
  if not districts:
2670
  return (
2671
  f"No map folders with gpt_navigation_manifest.json were found in "
2672
  f"{SOURCE_REPO_ID}.",
2673
  )
2674
 
 
 
 
 
 
2675
  missing_set = set(missing_target_manifests)
2676
  initial_lookup_error = ""
2677
- try:
2678
- initial_batches = _list_initial_batches(openai_token, missing_set)
2679
- except Exception as exception:
2680
- initial_lookup_error = str(exception)
2681
- initial_batches = {district: [] for district in missing_set}
 
 
2682
 
2683
  statuses: List[Tuple[str, str]] = []
2684
- all_done_count = 0
 
2685
  error_count = 0
2686
- for district in districts:
2687
  try:
2688
  initial_status = ""
2689
  if district in missing_set:
@@ -2705,22 +2960,52 @@ def run_all_door_iterations(
2705
  statuses.append((district, status))
2706
  continue
2707
 
2708
- status = _advance_door_iterations_for_district(
2709
  district,
2710
  openai_token,
2711
  hf_token,
2712
  validated_prompts,
2713
  )[0]
 
 
 
 
2714
  if initial_status:
2715
  status = initial_status + "\n" + status
2716
  except Exception as exception:
2717
  error_count += 1
2718
  status = f"ERROR: {exception}"
2719
- if status == "All Done":
2720
- all_done_count += 1
2721
  statuses.append((district, status))
2722
 
2723
- if districts and all_done_count == len(districts):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2724
  return ("All Done",)
2725
 
2726
  active_count = len(districts) - all_done_count - error_count
@@ -2729,6 +3014,13 @@ def run_all_door_iterations(
2729
  f"{len(districts)} maps; {all_done_count} All Done; "
2730
  f"{active_count} active; {error_count} errors."
2731
  ]
 
 
 
 
 
 
 
2732
  lines.extend(f"{district}: {status}" for district, status in statuses)
2733
  return ("\n".join(lines),)
2734
 
 
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"
 
29
  HF_REVISION = "main"
30
  UV_PATH = "UV.png"
31
  ALL_IN_ONE_STATE_NAME = "door_consistency_all_in_one_state.json"
32
+ COMPLETION_INDEX_NAME = "door_consistency_finished_maps.json"
33
+ COMPLETION_INDEX_FORMAT_VERSION = 1
34
  FINAL_ITERATION = 3
35
  TARGET_WIDTH = 1536
36
  TARGET_HEIGHT = 1024
 
298
  return None
299
 
300
 
301
+ def _repository_folder_tree_id(entry: Any) -> str:
302
+ """Return the immutable Git tree id exposed for a repository folder."""
303
+ for attribute in ("tree_id", "oid", "sha"):
304
+ value = str(getattr(entry, attribute, "") or "").strip()
305
+ if value:
306
+ return value
307
+ return ""
308
+
309
+
310
+ def _repository_root_folders(
311
+ api: Any,
312
+ repo_id: str,
313
+ revision: str,
314
  hf_key: str,
315
+ ) -> Dict[str, str]:
316
+ """List root folders once and retain their change-detection fingerprints."""
317
+ folders: Dict[str, str] = {}
 
 
 
 
318
  for entry in api.list_repo_tree(
319
+ repo_id=repo_id,
320
  path_in_repo=None,
321
  recursive=False,
322
  expand=False,
323
+ revision=revision,
324
  repo_type=HF_REPO_TYPE,
325
  token=hf_key,
326
  ):
327
  folder = _top_level_repository_folder(entry)
328
  if folder is not None:
329
+ folders[folder] = _repository_folder_tree_id(entry)
330
+ return folders
331
+
332
+
333
+ def _empty_completion_index() -> Dict[str, Any]:
334
+ return {
335
+ "formatVersion": COMPLETION_INDEX_FORMAT_VERSION,
336
+ "pipelineVersion": NODE_VERSION,
337
+ "sourceRepoId": SOURCE_REPO_ID,
338
+ "targetRepoId": TARGET_REPO_ID,
339
+ "finalIteration": FINAL_ITERATION,
340
+ "finishedCount": 0,
341
+ "finishedDistricts": [],
342
+ "finishedMaps": {},
343
+ "updatedUtc": "",
344
+ }
345
+
346
+
347
+ def _validate_completion_index(document: Mapping[str, Any]) -> None:
348
+ if int(document.get("formatVersion") or 0) != COMPLETION_INDEX_FORMAT_VERSION:
349
+ raise ValueError("unsupported formatVersion")
350
+ if str(document.get("sourceRepoId") or "") != SOURCE_REPO_ID:
351
+ raise ValueError("sourceRepoId does not match this pipeline")
352
+ if str(document.get("targetRepoId") or "") != TARGET_REPO_ID:
353
+ raise ValueError("targetRepoId does not match this pipeline")
354
+ if int(document.get("finalIteration") or 0) != FINAL_ITERATION:
355
+ raise ValueError("finalIteration does not match this pipeline")
356
+ finished_maps = document.get("finishedMaps")
357
+ if not isinstance(finished_maps, Mapping):
358
+ raise ValueError("finishedMaps must be a JSON object")
359
+ for district, entry in finished_maps.items():
360
+ _district_name(str(district))
361
+ if not isinstance(entry, Mapping):
362
+ raise ValueError(f"finishedMaps entry '{district}' is malformed")
363
+ if int(entry.get("completedStage") or 0) < FINAL_ITERATION:
364
+ raise ValueError(
365
+ f"finishedMaps entry '{district}' is not at the final iteration"
366
+ )
367
+
368
+
369
+ def _load_completion_index(
370
+ api: Any,
371
+ target_commit: str,
372
+ hf_key: str,
373
+ ) -> Tuple[Dict[str, Any], bool, str]:
374
+ """Load the optional root cache; an invalid cache safely becomes a miss."""
375
+ exists = api.file_exists(
376
+ repo_id=TARGET_REPO_ID,
377
+ filename=COMPLETION_INDEX_NAME,
378
+ repo_type=HF_REPO_TYPE,
379
+ revision=target_commit,
380
+ token=hf_key,
381
+ )
382
+ if not exists:
383
+ return _empty_completion_index(), False, ""
384
+ try:
385
+ document, _ = _download_hf_json(
386
+ TARGET_REPO_ID,
387
+ COMPLETION_INDEX_NAME,
388
+ target_commit,
389
+ hf_key,
390
+ )
391
+ _validate_completion_index(document)
392
+ return document, True, ""
393
+ except Exception as exception:
394
+ return (
395
+ _empty_completion_index(),
396
+ False,
397
+ f"Ignored invalid {COMPLETION_INDEX_NAME}: {exception}",
398
+ )
399
+
400
+
401
+ def _completion_entry_matches(
402
+ entry: Any,
403
+ source_tree_id: str,
404
+ target_tree_id: str,
405
+ ) -> bool:
406
+ """A cache hit is safe only while both map folders are byte-for-byte unchanged."""
407
+ return bool(
408
+ isinstance(entry, Mapping)
409
+ and int(entry.get("completedStage") or 0) >= FINAL_ITERATION
410
+ and source_tree_id
411
+ and target_tree_id
412
+ and str(entry.get("sourceTreeId") or "") == source_tree_id
413
+ and str(entry.get("targetTreeId") or "") == target_tree_id
414
+ )
415
+
416
+
417
+ def _discover_repository_districts(
418
+ hf_key: str,
419
+ ) -> Dict[str, Any]:
420
+ """Find maps, skipping unchanged final maps through one shared root index."""
421
+ _, HfApi, _ = _load_hf_tools()
422
+ api = HfApi(token=hf_key)
423
+ source_commit = _repo_commit(api, SOURCE_REPO_ID, hf_key)
424
+ target_commit = _repo_commit(api, TARGET_REPO_ID, hf_key)
425
+ source_folders = _repository_root_folders(
426
+ api,
427
+ SOURCE_REPO_ID,
428
+ source_commit,
429
+ hf_key,
430
+ )
431
+ target_folders = _repository_root_folders(
432
+ api,
433
+ TARGET_REPO_ID,
434
+ target_commit,
435
+ hf_key,
436
+ )
437
+ completion_index, index_usable, index_warning = _load_completion_index(
438
+ api,
439
+ target_commit,
440
+ hf_key,
441
+ )
442
+ finished_entries = completion_index.get("finishedMaps")
443
+ if not isinstance(finished_entries, Mapping):
444
+ finished_entries = {}
445
 
446
  districts: List[str] = []
447
+ pending_districts: List[str] = []
448
  missing_target_manifests: List[str] = []
449
+ cached_finished: List[str] = []
450
+ for district in sorted(source_folders, key=_natural_name_key):
451
+ if index_usable and _completion_entry_matches(
452
+ finished_entries.get(district),
453
+ source_folders.get(district, ""),
454
+ target_folders.get(district, ""),
455
+ ):
456
+ districts.append(district)
457
+ cached_finished.append(district)
458
+ continue
459
+
460
  source_manifest = f"{district}/gpt_navigation_manifest.json"
461
  target_manifest = f"{district}/gpt_image_manifest.json"
462
  if not api.file_exists(
 
479
  ):
480
  missing_target_manifests.append(district)
481
  districts.append(district)
482
+ pending_districts.append(district)
483
+ return {
484
+ "districts": districts,
485
+ "pendingDistricts": pending_districts,
486
+ "missingTargetManifests": missing_target_manifests,
487
+ "cachedFinished": cached_finished,
488
+ "sourceTreeIds": source_folders,
489
+ "targetTreeIds": target_folders,
490
+ "completionIndex": completion_index,
491
+ "completionIndexUsable": index_usable,
492
+ "completionIndexWarning": index_warning,
493
+ }
494
 
495
 
496
  def _download_hf_bytes(
 
527
  return parsed, data
528
 
529
 
530
+ def _completion_index_comparable(document: Mapping[str, Any]) -> Dict[str, Any]:
531
+ """Remove the write timestamp so unchanged indexes do not create commits."""
532
+ return {
533
+ key: value
534
+ for key, value in document.items()
535
+ if key != "updatedUtc"
536
+ }
537
+
538
+
539
+ def _update_completion_index(
540
+ hf_key: str,
541
+ finished_districts: Iterable[str],
542
+ source_tree_ids: Mapping[str, str],
543
+ ) -> Tuple[bool, str]:
544
+ """Atomically write one root index containing all verified finished maps."""
545
+ CommitOperationAdd, HfApi, _ = _load_hf_tools()
546
+ api = HfApi(token=hf_key)
547
+ target_commit = _repo_commit(api, TARGET_REPO_ID, hf_key)
548
+ target_tree_ids = _repository_root_folders(
549
+ api,
550
+ TARGET_REPO_ID,
551
+ target_commit,
552
+ hf_key,
553
+ )
554
+ existing, existing_usable, _warning = _load_completion_index(
555
+ api,
556
+ target_commit,
557
+ hf_key,
558
+ )
559
+ existing_entries = existing.get("finishedMaps")
560
+ if not isinstance(existing_entries, Mapping):
561
+ existing_entries = {}
562
+
563
+ now = _utc_now()
564
+ ordered_districts = sorted(
565
+ {_district_name(district) for district in finished_districts},
566
+ key=_natural_name_key,
567
+ )
568
+ entries: Dict[str, Dict[str, Any]] = {}
569
+ for district in ordered_districts:
570
+ source_tree_id = str(source_tree_ids.get(district) or "")
571
+ target_tree_id = str(target_tree_ids.get(district) or "")
572
+ old_entry = existing_entries.get(district)
573
+ unchanged_old_entry = _completion_entry_matches(
574
+ old_entry,
575
+ source_tree_id,
576
+ target_tree_id,
577
+ )
578
+ completed_utc = (
579
+ str(old_entry.get("completedUtc") or "")
580
+ if unchanged_old_entry and isinstance(old_entry, Mapping)
581
+ else now
582
+ )
583
+ entries[district] = {
584
+ "completedStage": FINAL_ITERATION,
585
+ "sourceTreeId": source_tree_id,
586
+ "targetTreeId": target_tree_id,
587
+ "completedUtc": completed_utc or now,
588
+ }
589
+
590
+ document = {
591
+ "formatVersion": COMPLETION_INDEX_FORMAT_VERSION,
592
+ "pipelineVersion": NODE_VERSION,
593
+ "sourceRepoId": SOURCE_REPO_ID,
594
+ "targetRepoId": TARGET_REPO_ID,
595
+ "finalIteration": FINAL_ITERATION,
596
+ "finishedCount": len(ordered_districts),
597
+ "finishedDistricts": ordered_districts,
598
+ "finishedMaps": entries,
599
+ "updatedUtc": now,
600
+ }
601
+ if existing_usable and _completion_index_comparable(
602
+ existing
603
+ ) == _completion_index_comparable(document):
604
+ return False, target_commit
605
+
606
+ local_root = _output_root() / "FemUnisim_Door_Iterations" / "all_in_one"
607
+ local_path = local_root / COMPLETION_INDEX_NAME
608
+ _write_json(local_path, document)
609
+ commit = api.create_commit(
610
+ repo_id=TARGET_REPO_ID,
611
+ repo_type=HF_REPO_TYPE,
612
+ revision=HF_REVISION,
613
+ operations=[
614
+ CommitOperationAdd(
615
+ path_in_repo=COMPLETION_INDEX_NAME,
616
+ path_or_fileobj=str(local_path),
617
+ )
618
+ ],
619
+ commit_message="Update finished door-consistency maps index",
620
+ parent_commit=target_commit,
621
+ token=hf_key,
622
+ )
623
+ return True, str(getattr(commit, "oid", "") or "")
624
+
625
+
626
  def _hf_resolve_url(repo_id: str, revision: str, path_in_repo: str) -> str:
627
  encoded_path = "/".join(
628
  urllib.parse.quote(part, safe="")
 
2908
  iteration: _prompt_value(prompts.get(iteration), iteration)
2909
  for iteration in range(1, FINAL_ITERATION + 1)
2910
  }
2911
+ discovery = _discover_repository_districts(hf_token)
2912
+ districts = list(discovery["districts"])
2913
+ pending_districts = list(discovery["pendingDistricts"])
2914
+ missing_target_manifests = list(discovery["missingTargetManifests"])
2915
+ cached_finished = set(discovery["cachedFinished"])
2916
  if not districts:
2917
  return (
2918
  f"No map folders with gpt_navigation_manifest.json were found in "
2919
  f"{SOURCE_REPO_ID}.",
2920
  )
2921
 
2922
+ # Fast path: two root-folder listings plus one shared index read proved that
2923
+ # every source and target map folder is unchanged and already final.
2924
+ if not pending_districts and len(cached_finished) == len(districts):
2925
+ return ("All Done",)
2926
+
2927
  missing_set = set(missing_target_manifests)
2928
  initial_lookup_error = ""
2929
+ initial_batches: Dict[str, List[Dict[str, Any]]] = {}
2930
+ if missing_set:
2931
+ try:
2932
+ initial_batches = _list_initial_batches(openai_token, missing_set)
2933
+ except Exception as exception:
2934
+ initial_lookup_error = str(exception)
2935
+ initial_batches = {district: [] for district in missing_set}
2936
 
2937
  statuses: List[Tuple[str, str]] = []
2938
+ verified_finished = set(cached_finished)
2939
+ newly_finished = set()
2940
  error_count = 0
2941
+ for district in pending_districts:
2942
  try:
2943
  initial_status = ""
2944
  if district in missing_set:
 
2960
  statuses.append((district, status))
2961
  continue
2962
 
2963
+ door_status = _advance_door_iterations_for_district(
2964
  district,
2965
  openai_token,
2966
  hf_token,
2967
  validated_prompts,
2968
  )[0]
2969
+ if door_status == "All Done":
2970
+ verified_finished.add(district)
2971
+ newly_finished.add(district)
2972
+ status = door_status
2973
  if initial_status:
2974
  status = initial_status + "\n" + status
2975
  except Exception as exception:
2976
  error_count += 1
2977
  status = f"ERROR: {exception}"
 
 
2978
  statuses.append((district, status))
2979
 
2980
+ existing_index = discovery.get("completionIndex")
2981
+ existing_entries = (
2982
+ existing_index.get("finishedMaps")
2983
+ if isinstance(existing_index, Mapping)
2984
+ else {}
2985
+ )
2986
+ if not isinstance(existing_entries, Mapping):
2987
+ existing_entries = {}
2988
+ existing_finished = set(existing_entries)
2989
+ index_needs_update = bool(
2990
+ not discovery.get("completionIndexUsable")
2991
+ or newly_finished
2992
+ or existing_finished != verified_finished
2993
+ )
2994
+ index_error = ""
2995
+ if index_needs_update:
2996
+ try:
2997
+ _update_completion_index(
2998
+ hf_token,
2999
+ verified_finished,
3000
+ discovery.get("sourceTreeIds") or {},
3001
+ )
3002
+ except Exception as exception:
3003
+ index_error = (
3004
+ f"Could not update {COMPLETION_INDEX_NAME}: {exception}"
3005
+ )
3006
+
3007
+ all_done_count = len(verified_finished)
3008
+ if districts and all_done_count == len(districts) and not index_error:
3009
  return ("All Done",)
3010
 
3011
  active_count = len(districts) - all_done_count - error_count
 
3014
  f"{len(districts)} maps; {all_done_count} All Done; "
3015
  f"{active_count} active; {error_count} errors."
3016
  ]
3017
+ if cached_finished:
3018
+ lines.append(
3019
+ f"Fast completion index: skipped {len(cached_finished)} unchanged "
3020
+ "finished maps."
3021
+ )
3022
+ if index_error:
3023
+ lines.append("Completion index warning: " + index_error)
3024
  lines.extend(f"{district}: {status}" for district, status in statuses)
3025
  return ("\n".join(lines),)
3026