saliacoel commited on
Commit
db5b97f
·
verified ·
1 Parent(s): eb1d1ab

Upload Salia_MiniMaxH3_Character_Swap_Download_Dependencies.py

Browse files
Salia_MiniMaxH3_Character_Swap_Download_Dependencies.py CHANGED
@@ -3,6 +3,17 @@
3
  Place this .py in ComfyUI/custom_nodes/, restart ComfyUI, add
4
  "Salia MiniMax H3 Character Swap Download Dependencies", and queue once.
5
  hf_key is a STRING; blank uses HF_TOKEN or your saved Hugging Face login.
 
 
 
 
 
 
 
 
 
 
 
6
  After installation, restart ComfyUI and import the generated workflow:
7
  output/Salia_H3_Character_Swap_Setup/Salia_H3_Character_Swap_2Pass.json.
8
 
@@ -85,6 +96,8 @@ import nodes
85
  LOG = logging.getLogger("Salia_H3_Character_Swap_Installer")
86
  MIN_HF_HUB_VERSION = (0, 32, 0)
87
  MAX_DOWNLOAD_ATTEMPTS = 3
 
 
88
  SHARED_LOCK_ATTRIBUTE = "_salia_5tar5ystem_mmh3_installer_lock_v1"
89
  CORE_PACKAGES = ("torch", "torchvision", "torchaudio", "numpy", "Pillow", "safetensors", "transformers", "triton")
90
  ATTENTION_MODES = ("Original (Comfy Kitchen)", "PyTorch")
@@ -417,6 +430,9 @@ def _ensure_huggingface_stack():
417
  )
418
 
419
  from huggingface_hub import (
 
 
 
420
  get_hf_file_metadata,
421
  hf_hub_download,
422
  hf_hub_url,
@@ -443,6 +459,9 @@ def _ensure_huggingface_stack():
443
  )
444
 
445
  return {
 
 
 
446
  "hf_hub_download": hf_hub_download,
447
  "hf_hub_url": hf_hub_url,
448
  "get_hf_file_metadata": get_hf_file_metadata,
@@ -701,7 +720,9 @@ def _has_module(name):
701
 
702
  def _error_text(error, token=None):
703
  message = str(error)
704
- return message.replace(token, "[REDACTED]") if token else message
 
 
705
 
706
 
707
  def _token(hf_key):
@@ -896,17 +917,242 @@ def _download_http(url, name, cache, reporter, start, end, force=False, expected
896
  return target
897
 
898
 
899
- def _download_asset(asset, token, get_stack, reporter, start, end, verify_sha256):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
900
  existing, relative = _existing_asset(asset)
901
  if existing is not None:
902
  kind = "torch" if existing.suffix == ".pth" else asset["kind"]
903
  _validate_file(existing, kind)
 
904
  reporter.stage(end, f"Already exists; skipped: {existing}")
905
  return existing, relative, False
906
  directory = _model_directory(asset["folder"])
907
  target = directory / asset["relative"]
908
  if os.path.lexists(target):
909
  raise RuntimeError(f"Existing unreadable target was left untouched: {target}")
 
 
 
 
 
 
 
 
910
  force = False
911
  last_error = None
912
  for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
@@ -925,6 +1171,7 @@ def _download_asset(asset, token, get_stack, reporter, start, end, verify_sha256
925
  expected_size=asset.get("size"),
926
  expected_sha256=asset.get("sha256") if verify_sha256 else None)
927
  changed = _install_cached_file(cached, target, asset, verify_sha256)
 
928
  reporter.stage(end, f"Ready: {target}")
929
  return target, asset["relative"], changed
930
  except Exception as exc:
@@ -1094,17 +1341,22 @@ def _find_pack(kind):
1094
  return None
1095
 
1096
 
1097
- def _install_pack(kind, reporter, start, end):
 
 
 
1098
  existing = _find_pack(kind)
1099
  if existing:
 
 
 
1100
  reporter.stage(end, f"Custom node pack already present: {existing}")
1101
  return existing, False
1102
- item = PACKS[kind]
1103
  root = _custom_node_roots()[0]
1104
  root.mkdir(parents=True, exist_ok=True)
1105
  destination = root / item["dirname"]
1106
- name = f"{item['dirname']}-{item['revision']}.zip"
1107
- sources = [f"https://github.com/{item['repo']}/archive/{item['revision']}.zip",
1108
  f"https://codeload.github.com/{item['repo']}/zip/{item['revision']}"]
1109
  errors = []
1110
  for url in sources:
@@ -1112,7 +1364,7 @@ def _install_pack(kind, reporter, start, end):
1112
  for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
1113
  try:
1114
  reporter.stage(start, f"Downloading {item['dirname']} ({attempt}/{MAX_DOWNLOAD_ATTEMPTS})")
1115
- cached = _download_http(url, name, _download_cache(), reporter, start, max(start, end - 10),
1116
  force=force, expected_size=item["size"], expected_sha256=item["sha256"])
1117
  _validate_file(cached, "zip", item["size"])
1118
  if _sha256(cached) != item["sha256"]:
@@ -1122,13 +1374,16 @@ def _install_pack(kind, reporter, start, end):
1122
  staging.mkdir()
1123
  _extract_safe(cached, staging, kind)
1124
  changed = _install_pack_tree(staging, destination, kind)
 
1125
  reporter.stage(end, f"Custom node pack installed: {destination}")
1126
  return destination, changed
1127
  except Exception as exc:
1128
- errors.append(str(exc))
1129
  if os.path.lexists(destination):
1130
- raise RuntimeError(str(exc)) from None
1131
  force = force or isinstance(exc, (_InvalidAsset, zipfile.BadZipFile))
 
 
1132
  if isinstance(exc, urllib.error.HTTPError) and exc.code in {401, 403, 404}:
1133
  break
1134
  if attempt < MAX_DOWNLOAD_ATTEMPTS:
@@ -1238,13 +1493,19 @@ def _save_preserving_edits(path, data):
1238
  raise RuntimeError("No free workflow output filename was found; existing files were preserved.")
1239
 
1240
 
1241
- def _get_workflow(output, reporter):
1242
  bundled = _bundled_workflow_bytes()
1243
  destination = output / WORKFLOW_ASSET["name"]
1244
  # No HTTP request on repeat runs, including when the canonical file was edited.
1245
  for existing in [destination, *sorted(output.glob(destination.stem + "_*" + destination.suffix))]:
1246
  if existing.is_file() and existing.read_bytes() == bundled:
 
1247
  return existing, "Existing verified original workflow reused."
 
 
 
 
 
1248
  error = None
1249
  force = False
1250
  for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
@@ -1256,7 +1517,9 @@ def _get_workflow(output, reporter):
1256
  _validate_file(cached, "json", WORKFLOW_ASSET["size"])
1257
  if _sha256(cached) != WORKFLOW_ASSET["sha256"]:
1258
  raise _InvalidAsset("Civitai workflow SHA256 mismatch")
1259
- return _save_preserving_edits(destination, cached.read_bytes()), "Verified workflow downloaded from Civitai."
 
 
1260
  except Exception as exc:
1261
  error = str(exc)
1262
  force = force or isinstance(exc, _InvalidAsset)
@@ -1267,7 +1530,9 @@ def _get_workflow(output, reporter):
1267
  if attempt < MAX_DOWNLOAD_ATTEMPTS:
1268
  time.sleep(min(2 ** attempt, 8))
1269
  reporter.stage(170, "Civitai unavailable; using the bundled, checksum-verified original workflow.")
1270
- return _save_preserving_edits(destination, bundled), "Used the bundled exact workflow because Civitai was unavailable."
 
 
1271
 
1272
 
1273
  def _write_workflow(source, locations, output, attention_mode):
@@ -1341,13 +1606,13 @@ class Salia_MiniMaxH3_Character_Swap_Download_Dependencies:
1341
  RETURN_TYPES = ("STRING",)
1342
  RETURN_NAMES = ("report",)
1343
  OUTPUT_NODE = True
1344
- DESCRIPTION = "Install all ten models/LoRAs, using the matching pruned DARETIES LoRA, three custom packs and Python dependencies for Civitai 3390723. HF/Xet high-performance, resume, retries, SHA256 and no model overwrites. Produces the ready-to-import 2-pass workflow. Queue once, then restart ComfyUI."
1345
 
1346
  @classmethod
1347
  def INPUT_TYPES(cls):
1348
  return {
1349
  "required": {"hf_key": ("STRING", {"default": "", "multiline": False,
1350
- "tooltip": "HF read token. Blank uses HF_TOKEN or saved HF login. Clear the widget before sharing your installer workflow."})},
1351
  "optional": {
1352
  "verify_sha256": ("BOOLEAN", {"default": True,
1353
  "tooltip": "Verify new model downloads against the published SHA256. Existing structurally valid model files are skipped."}),
@@ -1388,21 +1653,22 @@ class Salia_MiniMaxH3_Character_Swap_Download_Dependencies:
1388
  raise RuntimeError("Update ComfyUI core and restart before installing this workflow; missing built-in nodes: " + ", ".join(missing_core))
1389
  output = Path(folder_paths.get_output_directory()) / OUTPUT_SUBDIR
1390
  output.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
1391
  packs, pack_records = {}, []
1392
  for index, kind in enumerate(PACKS):
1393
- directory, changed = _install_pack(kind, reporter, 10 + 35 * index, 45 + 35 * index)
1394
  packs[kind] = directory
1395
  pack_records.append({"pack": kind, "repository": PACKS[kind]["repo"],
1396
  "path": str(directory), "status": "installed" if changed else "already present"})
1397
  reporter.stage(130, "Checking Python dependencies, Comfy Kitchen, frontend and FFmpeg.")
1398
  python_installs = _ensure_python_packages(packs)
1399
- original, workflow_source = _get_workflow(output, reporter)
1400
- stack_holder = {}
1401
- def get_stack():
1402
- if "stack" not in stack_holder:
1403
- stack_holder["stack"] = _ensure_huggingface_stack()
1404
- LOG.info("[DOWNLOAD] huggingface_hub=%s | %s", stack_holder["stack"]["hub_version"], stack_holder["stack"]["backend_name"])
1405
- return stack_holder["stack"]
1406
  assets = list(MODELS.items())
1407
  if install_tiny_preview:
1408
  assets.append(("tiny_preview", TINY_VAE))
@@ -1413,16 +1679,22 @@ class Salia_MiniMaxH3_Character_Swap_Download_Dependencies:
1413
  start = 180 + int(720 * cumulative / total)
1414
  cumulative += asset["size"]
1415
  end = 180 + int(720 * cumulative / total)
1416
- path, relative, changed = _download_asset(asset, token, get_stack, reporter, start, end, verify_sha256)
1417
  locations[label] = relative
1418
  records.append({"asset": label, "path": str(path), "selector": relative,
1419
  "status": "installed" if changed else "already present"})
1420
  reporter.stage(930, "Preparing the 2-pass workflow with the pruned DARETIES LoRA and local model filenames.")
1421
  prepared = _write_workflow(original, locations, output, attention_mode)
1422
  pending_types = sorted(name for name in CUSTOM_NODE_PACKS if name not in loaded)
1423
- lines = ["MiniMax H3 Character Swap dependency installation finished.", workflow_source]
 
1424
  lines.extend(f"{item['pack']}: {item['status']} | {item['path']}" for item in pack_records)
1425
  lines.extend(f"{item['asset']}: {item['status']} | {item['path']}" for item in records)
 
 
 
 
 
1426
  lines.append("Attention selection: " + attention_mode)
1427
  lines.append("Ready-to-import workflow: " + str(prepared))
1428
  lines.append("DARETIES replacement: " + locations["turbo_lora"])
@@ -1435,6 +1707,8 @@ class Salia_MiniMaxH3_Character_Swap_Download_Dependencies:
1435
  "packs": pack_records, "models": records, "python_packages_installed": python_installs,
1436
  "source_workflow": str(original), "prepared_workflow": str(prepared),
1437
  "workflow_sha256": WORKFLOW_ASSET["sha256"], "attention_mode": attention_mode,
 
 
1438
  "node_types_available_after_restart": pending_types, "restart_required": True}
1439
  (output / "install_report.txt").write_text(text_report + "\n", encoding="utf-8")
1440
  (output / "install_report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")
 
3
  Place this .py in ComfyUI/custom_nodes/, restart ComfyUI, add
4
  "Salia MiniMax H3 Character Swap Download Dependencies", and queue once.
5
  hf_key is a STRING; blank uses HF_TOKEN or your saved Hugging Face login.
6
+ Use a token with write access to saliacoel/x to mirror missing dependencies.
7
+ All managed file downloads try that repo first, then the pinned original
8
+ sources. Existing mirrors are found at the root or in subdirectories; new
9
+ files are stored at the repo root using their original filenames (node-pack
10
+ ZIP filenames include their pinned commit). HF sources first use a native
11
+ cross-repository copy; unsupported/failed copies fall back to local upload.
12
+ Fresh repo snapshots and parent-commit guards prevent overwriting files,
13
+ including when another client adds them while this node runs. Reused local
14
+ weights also fill missing mirrors after exact size/SHA256 validation. Mirror
15
+ errors are reported separately and do not discard successful installation.
16
+ Python packages installed by pip are handled by pip, not mirrored as files.
17
  After installation, restart ComfyUI and import the generated workflow:
18
  output/Salia_H3_Character_Swap_Setup/Salia_H3_Character_Swap_2Pass.json.
19
 
 
96
  LOG = logging.getLogger("Salia_H3_Character_Swap_Installer")
97
  MIN_HF_HUB_VERSION = (0, 32, 0)
98
  MAX_DOWNLOAD_ATTEMPTS = 3
99
+ MIRROR_REPO_ID = "saliacoel/x"
100
+ MIRROR_REVISION = "main"
101
  SHARED_LOCK_ATTRIBUTE = "_salia_5tar5ystem_mmh3_installer_lock_v1"
102
  CORE_PACKAGES = ("torch", "torchvision", "torchaudio", "numpy", "Pillow", "safetensors", "transformers", "triton")
103
  ATTENTION_MODES = ("Original (Comfy Kitchen)", "PyTorch")
 
430
  )
431
 
432
  from huggingface_hub import (
433
+ CommitOperationCopy,
434
+ HfApi,
435
+ get_token,
436
  get_hf_file_metadata,
437
  hf_hub_download,
438
  hf_hub_url,
 
459
  )
460
 
461
  return {
462
+ "HfApi": HfApi,
463
+ "CommitOperationCopy": CommitOperationCopy,
464
+ "get_token": get_token,
465
  "hf_hub_download": hf_hub_download,
466
  "hf_hub_url": hf_hub_url,
467
  "get_hf_file_metadata": get_hf_file_metadata,
 
720
 
721
  def _error_text(error, token=None):
722
  message = str(error)
723
+ if token:
724
+ message = message.replace(token, "[REDACTED]")
725
+ return re.sub(r"\bhf_[A-Za-z0-9]{10,}\b", "[REDACTED]", message)
726
 
727
 
728
  def _token(hf_key):
 
917
  return target
918
 
919
 
920
+ def _http_status(error):
921
+ response = getattr(error, "response", None)
922
+ return getattr(response, "status_code", None) or getattr(error, "code", None)
923
+
924
+
925
+ def _hf_origin(asset):
926
+ """Keep the publisher's pinned revision for HF-to-HF copies."""
927
+ if "repo_id" in asset:
928
+ return {"repo_id": asset["repo_id"], "filename": asset["filename"],
929
+ "repo_type": asset.get("repo_type", "model"),
930
+ "revision": asset.get("revision", "main")}
931
+ parsed = urllib.parse.urlparse(asset.get("url", ""))
932
+ if parsed.hostname != "huggingface.co":
933
+ return None
934
+ parts = parsed.path.strip("/").split("/")
935
+ repo_type = "model"
936
+ if parts and parts[0] in {"datasets", "spaces"}:
937
+ repo_type = "dataset" if parts.pop(0) == "datasets" else "space"
938
+ if len(parts) < 5 or parts[2] not in {"resolve", "blob"}:
939
+ return None
940
+ return {"repo_id": "/".join(parts[:2]), "repo_type": repo_type,
941
+ "revision": urllib.parse.unquote(parts[3]),
942
+ "filename": urllib.parse.unquote("/".join(parts[4:]))}
943
+
944
+
945
+ class _HFDependencyMirror:
946
+ """Download from saliacoel/x first; only add files confirmed missing.
947
+
948
+ Repo discovery errors never mean a file is absent. Every write uses a
949
+ fresh tree and its parent SHA so concurrent clients cannot be overwritten.
950
+ The SDK handles LFS/Xet; no git clone or re-upload for supported HF copies.
951
+ """
952
+
953
+ def __init__(self, token, get_stack, reporter):
954
+ self.token = token
955
+ self.get_stack = get_stack
956
+ self.reporter = reporter
957
+ self.api = None
958
+ self.entries = {}
959
+ self.head = None
960
+ self.snapshot_attempted = False
961
+ self.snapshot_error = None
962
+ self.write_error = None
963
+ self.records = []
964
+
965
+ def _connect(self):
966
+ if self.api is None:
967
+ stack = self.get_stack()
968
+ self.token = self.token or stack["get_token"]()
969
+ self.api = stack["HfApi"](token=self.token)
970
+ return self.api
971
+
972
+ def _refresh(self):
973
+ info = self._connect().repo_info(repo_id=MIRROR_REPO_ID, repo_type="model",
974
+ revision=MIRROR_REVISION, token=self.token,
975
+ files_metadata=True)
976
+ if not info.sha:
977
+ raise RuntimeError("HF mirror returned no commit SHA; no write is safe.")
978
+ entries = {}
979
+ for sibling in info.siblings or []:
980
+ lfs = getattr(sibling, "lfs", None)
981
+ digest = lfs.get("sha256") if isinstance(lfs, dict) else getattr(lfs, "sha256", None)
982
+ entries[sibling.rfilename] = {"size": getattr(sibling, "size", None), "sha256": digest}
983
+ self.entries, self.head = entries, info.sha
984
+ self.snapshot_attempted = True
985
+ self.snapshot_error = None
986
+
987
+ def _snapshot(self):
988
+ if not self.snapshot_attempted:
989
+ self.snapshot_attempted = True
990
+ try:
991
+ self._refresh()
992
+ except Exception as exc:
993
+ self.snapshot_error = _error_text(exc, self.token)
994
+ LOG.warning("[MIRROR] Repo lookup failed; using original sources: %s", self.snapshot_error)
995
+ return self.snapshot_error is None and self.head is not None
996
+
997
+ @staticmethod
998
+ def _name(asset):
999
+ return asset.get("mirror_name") or PurePosixPath(asset.get("relative") or asset["name"]).name
1000
+
1001
+ def _matching_paths(self, asset):
1002
+ name = self._name(asset)
1003
+ preferred = [name]
1004
+ if asset.get("folder"):
1005
+ relative = asset.get("relative", name)
1006
+ preferred.extend((f"MiniMax-H3/{asset['folder']}/{relative}",
1007
+ f"MiniMax-H3/{asset['folder']}/{name}",
1008
+ f"{asset['folder']}/{relative}"))
1009
+ if asset.get("filename"):
1010
+ preferred.append(asset["filename"])
1011
+ matches = [path for path in self.entries if PurePosixPath(path).name == name]
1012
+ return sorted(matches, key=lambda path: (preferred.index(path) if path in preferred else len(preferred), path))
1013
+
1014
+ def download(self, asset, start, end, verify_sha256=True):
1015
+ """Return a validated mirrored cache file, or let the caller fall back."""
1016
+ if not self._snapshot():
1017
+ return None
1018
+ name = self._name(asset)
1019
+ for filename in self._matching_paths(asset):
1020
+ metadata = self.entries[filename]
1021
+ if (asset.get("size") is not None and metadata["size"] is not None
1022
+ and asset["size"] != metadata["size"]):
1023
+ LOG.warning("[MIRROR] %s has a different size; trying another source.", filename)
1024
+ continue
1025
+ if (verify_sha256 and asset.get("sha256") and metadata["sha256"]
1026
+ and asset["sha256"].lower() != metadata["sha256"].lower()):
1027
+ LOG.warning("[MIRROR] %s has a different SHA256; trying another source.", filename)
1028
+ continue
1029
+ force = False
1030
+ for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
1031
+ try:
1032
+ self.reporter.stage(start, f"Mirror first: {MIRROR_REPO_ID}/{filename} ({attempt}/{MAX_DOWNLOAD_ATTEMPTS})")
1033
+ cached = Path(self.get_stack()["hf_hub_download"](
1034
+ repo_id=MIRROR_REPO_ID, filename=filename, repo_type="model",
1035
+ revision=self.head, token=self.token, cache_dir=_hf_cache_directory(),
1036
+ etag_timeout=30, force_download=force))
1037
+ _validate_file(cached, asset["kind"], asset.get("size"))
1038
+ if verify_sha256 and asset.get("sha256") and _sha256(cached) != asset["sha256"]:
1039
+ raise _InvalidAsset(f"Mirror SHA256 mismatch for {name}")
1040
+ LOG.info("[MIRROR] Download ready: %s/%s", MIRROR_REPO_ID, filename)
1041
+ return cached
1042
+ except Exception as exc:
1043
+ LOG.warning("[MIRROR] %s attempt %d failed: %s", filename, attempt, _error_text(exc, self.token))
1044
+ force = force or isinstance(exc, _InvalidAsset)
1045
+ if _http_status(exc) in {401, 403, 404}:
1046
+ break
1047
+ if attempt < MAX_DOWNLOAD_ATTEMPTS:
1048
+ time.sleep(min(2 ** attempt, 8))
1049
+ LOG.info("[MIRROR] No usable mirror for %s; falling back to the original source.", name)
1050
+ return None
1051
+
1052
+ def _record(self, asset, status, path=None, error=None):
1053
+ record = {"file": self._name(asset), "repository": MIRROR_REPO_ID,
1054
+ "path_in_repo": path or self._name(asset), "status": status}
1055
+ if error:
1056
+ record["error"] = _error_text(error, self.token)
1057
+ LOG.warning("[MIRROR] %s: %s", record["file"], record["error"])
1058
+ else:
1059
+ LOG.info("[MIRROR] %s: %s/%s", status, MIRROR_REPO_ID, record["path_in_repo"])
1060
+ self.records.append(record)
1061
+ return record
1062
+
1063
+ def sync_file(self, asset, local_path, verified=False):
1064
+ """Also supports valid cached/local files on reruns after upload failure."""
1065
+ name = self._name(asset)
1066
+ try:
1067
+ self._refresh()
1068
+ matches = self._matching_paths(asset)
1069
+ if matches:
1070
+ return self._record(asset, "already present; upload skipped", matches[0])
1071
+ if not self.token:
1072
+ raise RuntimeError("Missing HF write token. Set hf_key, HF_TOKEN, or a saved HF login with write access to saliacoel/x.")
1073
+ if self.write_error:
1074
+ raise RuntimeError(self.write_error)
1075
+ # Never mirror a different local model under the pinned filename.
1076
+ _validate_file(local_path, asset["kind"], asset.get("size"))
1077
+ if not verified and asset.get("sha256") and _sha256(local_path) != asset["sha256"]:
1078
+ raise _InvalidAsset(f"Local SHA256 differs from the pinned dependency: {name}; upload skipped.")
1079
+ except Exception as exc:
1080
+ return self._record(asset, "failed", error=exc)
1081
+
1082
+ origin = _hf_origin(asset)
1083
+ try_copy = bool(origin and origin["repo_id"] != MIRROR_REPO_ID)
1084
+ last_error = None
1085
+ for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
1086
+ try:
1087
+ # Refresh again just before each commit and after every retry.
1088
+ self._refresh()
1089
+ matches = self._matching_paths(asset)
1090
+ if matches:
1091
+ return self._record(asset, "already present; upload skipped", matches[0])
1092
+ if try_copy:
1093
+ try:
1094
+ LOG.info("[MIRROR] Trying HF-to-HF copy: %s/%s -> %s/%s",
1095
+ origin["repo_id"], origin["filename"], MIRROR_REPO_ID, name)
1096
+ operation = self.get_stack()["CommitOperationCopy"](
1097
+ src_path_in_repo=origin["filename"], path_in_repo=name,
1098
+ src_revision=origin["revision"], src_repo_id=origin["repo_id"],
1099
+ src_repo_type=origin["repo_type"])
1100
+ commit = self.api.create_commit(repo_id=MIRROR_REPO_ID, repo_type="model",
1101
+ revision=MIRROR_REVISION, token=self.token,
1102
+ operations=[operation], parent_commit=self.head,
1103
+ commit_message=f"Mirror H3 dependency: {name}")
1104
+ self.head = getattr(commit, "oid", self.head)
1105
+ self.entries[name] = {"size": asset.get("size"), "sha256": asset.get("sha256")}
1106
+ return self._record(asset, "copied HF-to-HF")
1107
+ except Exception as exc:
1108
+ if _http_status(exc) in {409, 412}:
1109
+ raise
1110
+ LOG.warning("[MIRROR] HF-to-HF copy unavailable/failed; using local upload: %s", _error_text(exc, self.token))
1111
+ try_copy = False
1112
+ # A timed-out copy may actually have committed already.
1113
+ self._refresh()
1114
+ matches = self._matching_paths(asset)
1115
+ if matches:
1116
+ return self._record(asset, "already present; upload skipped", matches[0])
1117
+ LOG.info("[MIRROR] Uploading %s -> %s/%s (%d/%d)", local_path, MIRROR_REPO_ID, name, attempt, MAX_DOWNLOAD_ATTEMPTS)
1118
+ commit = self.api.upload_file(repo_id=MIRROR_REPO_ID, repo_type="model",
1119
+ revision=MIRROR_REVISION, token=self.token,
1120
+ path_in_repo=name, path_or_fileobj=str(local_path),
1121
+ parent_commit=self.head, commit_message=f"Mirror H3 dependency: {name}")
1122
+ self.head = getattr(commit, "oid", self.head)
1123
+ self.entries[name] = {"size": asset.get("size"), "sha256": asset.get("sha256")}
1124
+ return self._record(asset, "uploaded")
1125
+ except Exception as exc:
1126
+ last_error = _error_text(exc, self.token)
1127
+ LOG.warning("[MIRROR] %s sync attempt %d failed: %s", name, attempt, last_error)
1128
+ if _http_status(exc) in {401, 403, 404}:
1129
+ self.write_error = last_error
1130
+ break
1131
+ if attempt < MAX_DOWNLOAD_ATTEMPTS:
1132
+ time.sleep(min(2 ** attempt, 8))
1133
+ return self._record(asset, "failed", error=last_error)
1134
+
1135
+
1136
+ def _download_asset(asset, token, get_stack, reporter, start, end, verify_sha256, mirror):
1137
  existing, relative = _existing_asset(asset)
1138
  if existing is not None:
1139
  kind = "torch" if existing.suffix == ".pth" else asset["kind"]
1140
  _validate_file(existing, kind)
1141
+ mirror.sync_file(asset, existing)
1142
  reporter.stage(end, f"Already exists; skipped: {existing}")
1143
  return existing, relative, False
1144
  directory = _model_directory(asset["folder"])
1145
  target = directory / asset["relative"]
1146
  if os.path.lexists(target):
1147
  raise RuntimeError(f"Existing unreadable target was left untouched: {target}")
1148
+ cached = mirror.download(asset, start, max(start, end - 30), verify_sha256)
1149
+ if cached is not None:
1150
+ # Mirror.download already checked the requested SHA256. Avoid hashing
1151
+ # tens of gigabytes a second time while copying into the model folder.
1152
+ changed = _install_cached_file(cached, target, asset, False)
1153
+ mirror.sync_file(asset, target, verified=changed and verify_sha256)
1154
+ reporter.stage(end, f"Ready from {MIRROR_REPO_ID}: {target}")
1155
+ return target, asset["relative"], changed
1156
  force = False
1157
  last_error = None
1158
  for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
 
1171
  expected_size=asset.get("size"),
1172
  expected_sha256=asset.get("sha256") if verify_sha256 else None)
1173
  changed = _install_cached_file(cached, target, asset, verify_sha256)
1174
+ mirror.sync_file(asset, target, verified=changed and verify_sha256)
1175
  reporter.stage(end, f"Ready: {target}")
1176
  return target, asset["relative"], changed
1177
  except Exception as exc:
 
1341
  return None
1342
 
1343
 
1344
+ def _install_pack(kind, reporter, start, end, mirror):
1345
+ item = PACKS[kind]
1346
+ name = f"{item['dirname']}-{item['revision']}.zip"
1347
+ archive_asset = {"relative": name, "kind": "zip", "size": item["size"], "sha256": item["sha256"]}
1348
  existing = _find_pack(kind)
1349
  if existing:
1350
+ cached = _download_cache() / name
1351
+ if cached.is_file():
1352
+ mirror.sync_file(archive_asset, cached)
1353
  reporter.stage(end, f"Custom node pack already present: {existing}")
1354
  return existing, False
 
1355
  root = _custom_node_roots()[0]
1356
  root.mkdir(parents=True, exist_ok=True)
1357
  destination = root / item["dirname"]
1358
+ mirrored = mirror.download(archive_asset, start, max(start, end - 10))
1359
+ sources = ([None] if mirrored is not None else []) + [f"https://github.com/{item['repo']}/archive/{item['revision']}.zip",
1360
  f"https://codeload.github.com/{item['repo']}/zip/{item['revision']}"]
1361
  errors = []
1362
  for url in sources:
 
1364
  for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
1365
  try:
1366
  reporter.stage(start, f"Downloading {item['dirname']} ({attempt}/{MAX_DOWNLOAD_ATTEMPTS})")
1367
+ cached = mirrored if url is None else _download_http(url, name, _download_cache(), reporter, start, max(start, end - 10),
1368
  force=force, expected_size=item["size"], expected_sha256=item["sha256"])
1369
  _validate_file(cached, "zip", item["size"])
1370
  if _sha256(cached) != item["sha256"]:
 
1374
  staging.mkdir()
1375
  _extract_safe(cached, staging, kind)
1376
  changed = _install_pack_tree(staging, destination, kind)
1377
+ mirror.sync_file(archive_asset, cached, verified=True)
1378
  reporter.stage(end, f"Custom node pack installed: {destination}")
1379
  return destination, changed
1380
  except Exception as exc:
1381
+ errors.append(_error_text(exc, mirror.token))
1382
  if os.path.lexists(destination):
1383
+ raise RuntimeError(_error_text(exc, mirror.token)) from None
1384
  force = force or isinstance(exc, (_InvalidAsset, zipfile.BadZipFile))
1385
+ if url is None:
1386
+ break
1387
  if isinstance(exc, urllib.error.HTTPError) and exc.code in {401, 403, 404}:
1388
  break
1389
  if attempt < MAX_DOWNLOAD_ATTEMPTS:
 
1493
  raise RuntimeError("No free workflow output filename was found; existing files were preserved.")
1494
 
1495
 
1496
+ def _get_workflow(output, reporter, mirror):
1497
  bundled = _bundled_workflow_bytes()
1498
  destination = output / WORKFLOW_ASSET["name"]
1499
  # No HTTP request on repeat runs, including when the canonical file was edited.
1500
  for existing in [destination, *sorted(output.glob(destination.stem + "_*" + destination.suffix))]:
1501
  if existing.is_file() and existing.read_bytes() == bundled:
1502
+ mirror.sync_file(WORKFLOW_ASSET, existing, verified=True)
1503
  return existing, "Existing verified original workflow reused."
1504
+ cached = mirror.download(WORKFLOW_ASSET, 150, 170)
1505
+ if cached is not None:
1506
+ saved = _save_preserving_edits(destination, cached.read_bytes())
1507
+ mirror.sync_file(WORKFLOW_ASSET, saved, verified=True)
1508
+ return saved, "Verified workflow downloaded from saliacoel/x."
1509
  error = None
1510
  force = False
1511
  for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
 
1517
  _validate_file(cached, "json", WORKFLOW_ASSET["size"])
1518
  if _sha256(cached) != WORKFLOW_ASSET["sha256"]:
1519
  raise _InvalidAsset("Civitai workflow SHA256 mismatch")
1520
+ saved = _save_preserving_edits(destination, cached.read_bytes())
1521
+ mirror.sync_file(WORKFLOW_ASSET, saved, verified=True)
1522
+ return saved, "Verified workflow downloaded from Civitai."
1523
  except Exception as exc:
1524
  error = str(exc)
1525
  force = force or isinstance(exc, _InvalidAsset)
 
1530
  if attempt < MAX_DOWNLOAD_ATTEMPTS:
1531
  time.sleep(min(2 ** attempt, 8))
1532
  reporter.stage(170, "Civitai unavailable; using the bundled, checksum-verified original workflow.")
1533
+ saved = _save_preserving_edits(destination, bundled)
1534
+ mirror.sync_file(WORKFLOW_ASSET, saved, verified=True)
1535
+ return saved, "Used the bundled exact workflow because Civitai was unavailable."
1536
 
1537
 
1538
  def _write_workflow(source, locations, output, attention_mode):
 
1606
  RETURN_TYPES = ("STRING",)
1607
  RETURN_NAMES = ("report",)
1608
  OUTPUT_NODE = True
1609
+ DESCRIPTION = "Install all ten models/LoRAs, the matching pruned DARETIES LoRA, three custom packs and Python dependencies for Civitai 3390723. Downloads try saliacoel/x first, then pinned original sources. Missing files are mirrored using HF-to-HF copy first, with local-upload fallback. Existing repo files are never replaced. Produces the ready-to-import 2-pass workflow. Queue once, then restart ComfyUI."
1610
 
1611
  @classmethod
1612
  def INPUT_TYPES(cls):
1613
  return {
1614
  "required": {"hf_key": ("STRING", {"default": "", "multiline": False,
1615
+ "tooltip": "HF token with WRITE access to saliacoel/x for missing-file mirroring. Blank uses HF_TOKEN or saved HF login. Clear the widget before sharing your installer workflow."})},
1616
  "optional": {
1617
  "verify_sha256": ("BOOLEAN", {"default": True,
1618
  "tooltip": "Verify new model downloads against the published SHA256. Existing structurally valid model files are skipped."}),
 
1653
  raise RuntimeError("Update ComfyUI core and restart before installing this workflow; missing built-in nodes: " + ", ".join(missing_core))
1654
  output = Path(folder_paths.get_output_directory()) / OUTPUT_SUBDIR
1655
  output.mkdir(parents=True, exist_ok=True)
1656
+ stack_holder = {}
1657
+ def get_stack():
1658
+ if "stack" not in stack_holder:
1659
+ stack_holder["stack"] = _ensure_huggingface_stack()
1660
+ LOG.info("[DOWNLOAD] huggingface_hub=%s | %s", stack_holder["stack"]["hub_version"], stack_holder["stack"]["backend_name"])
1661
+ return stack_holder["stack"]
1662
+ mirror = _HFDependencyMirror(token, get_stack, reporter)
1663
  packs, pack_records = {}, []
1664
  for index, kind in enumerate(PACKS):
1665
+ directory, changed = _install_pack(kind, reporter, 10 + 35 * index, 45 + 35 * index, mirror)
1666
  packs[kind] = directory
1667
  pack_records.append({"pack": kind, "repository": PACKS[kind]["repo"],
1668
  "path": str(directory), "status": "installed" if changed else "already present"})
1669
  reporter.stage(130, "Checking Python dependencies, Comfy Kitchen, frontend and FFmpeg.")
1670
  python_installs = _ensure_python_packages(packs)
1671
+ original, workflow_source = _get_workflow(output, reporter, mirror)
 
 
 
 
 
 
1672
  assets = list(MODELS.items())
1673
  if install_tiny_preview:
1674
  assets.append(("tiny_preview", TINY_VAE))
 
1679
  start = 180 + int(720 * cumulative / total)
1680
  cumulative += asset["size"]
1681
  end = 180 + int(720 * cumulative / total)
1682
+ path, relative, changed = _download_asset(asset, token, get_stack, reporter, start, end, verify_sha256, mirror)
1683
  locations[label] = relative
1684
  records.append({"asset": label, "path": str(path), "selector": relative,
1685
  "status": "installed" if changed else "already present"})
1686
  reporter.stage(930, "Preparing the 2-pass workflow with the pruned DARETIES LoRA and local model filenames.")
1687
  prepared = _write_workflow(original, locations, output, attention_mode)
1688
  pending_types = sorted(name for name in CUSTOM_NODE_PACKS if name not in loaded)
1689
+ mirror_failures = [item for item in mirror.records if item["status"] == "failed"]
1690
+ lines = ["MiniMax H3 Character Swap local dependency installation finished.", workflow_source]
1691
  lines.extend(f"{item['pack']}: {item['status']} | {item['path']}" for item in pack_records)
1692
  lines.extend(f"{item['asset']}: {item['status']} | {item['path']}" for item in records)
1693
+ lines.append("HF mirror: " + MIRROR_REPO_ID + " (new files at repo root; existing root/subfolder files skipped).")
1694
+ lines.extend(f"Mirror {item['file']}: {item['status']} | {item['path_in_repo']}"
1695
+ + (" | " + item["error"] if item.get("error") else "") for item in mirror.records)
1696
+ if mirror_failures:
1697
+ lines.append(f"HF mirroring incomplete: {len(mirror_failures)} file(s) could not be mirrored. Fix the reported cause and queue again; valid local models are reused.")
1698
  lines.append("Attention selection: " + attention_mode)
1699
  lines.append("Ready-to-import workflow: " + str(prepared))
1700
  lines.append("DARETIES replacement: " + locations["turbo_lora"])
 
1707
  "packs": pack_records, "models": records, "python_packages_installed": python_installs,
1708
  "source_workflow": str(original), "prepared_workflow": str(prepared),
1709
  "workflow_sha256": WORKFLOW_ASSET["sha256"], "attention_mode": attention_mode,
1710
+ "mirror_repository": MIRROR_REPO_ID, "mirror_files": mirror.records,
1711
+ "mirror_complete_for_processed_files": not mirror_failures,
1712
  "node_types_available_after_restart": pending_types, "restart_required": True}
1713
  (output / "install_report.txt").write_text(text_report + "\n", encoding="utf-8")
1714
  (output / "install_report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8")