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

Upload 2 files

Browse files
Files changed (2) hide show
  1. Salia_Load_Lora_Wan.py +723 -0
  2. salia_lora_x.py +683 -0
Salia_Load_Lora_Wan.py ADDED
@@ -0,0 +1,723 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Standalone: no imports from another custom-node file are required.
2
+ # Download behavior follows Salia_Dual_Checkpoint_Loader_Robust:
3
+ # Hugging Face Hub/Xet, a persistent resumable cache, retries, validation,
4
+ # fsync + atomic installation, and terminal / ComfyUI progress.
5
+ import errno
6
+ import hashlib
7
+ import importlib
8
+ import importlib.metadata
9
+ import importlib.util
10
+ import json
11
+ import logging
12
+ import os
13
+ import re
14
+ import shutil
15
+ import struct
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import threading
20
+ import time
21
+
22
+ import comfy.sd
23
+ import comfy.utils
24
+ import folder_paths
25
+
26
+
27
+ HF_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
28
+ HF_REPO_ID = "saliacoel/x"
29
+ HF_REVISION = "main"
30
+ MIN_HF_HUB_VERSION = (0, 32, 0)
31
+ MAX_DOWNLOAD_ATTEMPTS = 3
32
+ _SHARED_STATE_ATTRIBUTE = "_salia_robust_lora_download_state_v1"
33
+
34
+ os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "60")
35
+ os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "30")
36
+
37
+
38
+ LOG = logging.getLogger("Salia_Load_Lora_Wan")
39
+
40
+
41
+ def _version_tuple(version_string):
42
+ numbers = re.findall(r"\d+", str(version_string))
43
+ numbers = [int(value) for value in numbers[:3]]
44
+ while len(numbers) < 3:
45
+ numbers.append(0)
46
+ return tuple(numbers)
47
+
48
+
49
+ def _pip_install(*packages):
50
+ command = [sys.executable, "-m", "pip", "install", "-U", *packages]
51
+ LOG.info("[DEPENDENCY] Running: %s", " ".join(command))
52
+ subprocess.check_call(command)
53
+ importlib.invalidate_caches()
54
+
55
+
56
+ def _environment_flag_true(name):
57
+ value = os.environ.get(name)
58
+ if value is None:
59
+ return False
60
+ return str(value).strip().lower() in {"1", "true", "yes", "on"}
61
+
62
+
63
+ def _ensure_huggingface_stack():
64
+ """Install missing downloader dependencies only when a download is needed."""
65
+ loaded_hub = sys.modules.get("huggingface_hub")
66
+ if loaded_hub is not None:
67
+ loaded_version = getattr(loaded_hub, "__version__", "0.0.0")
68
+ if _version_tuple(loaded_version) < MIN_HF_HUB_VERSION:
69
+ raise RuntimeError(
70
+ "huggingface_hub is already loaded and is too old "
71
+ f"(version: {loaded_version}). Run "
72
+ "`python -m pip install -U huggingface_hub hf_xet` in "
73
+ "ComfyUI's Python environment and restart ComfyUI."
74
+ )
75
+
76
+ try:
77
+ installed_version = importlib.metadata.version("huggingface_hub")
78
+ except importlib.metadata.PackageNotFoundError:
79
+ installed_version = None
80
+
81
+ if loaded_hub is None and (
82
+ installed_version is None
83
+ or _version_tuple(installed_version) < MIN_HF_HUB_VERSION
84
+ ):
85
+ LOG.info("[DEPENDENCY] Installing/upgrading huggingface_hub>=0.32.0.")
86
+ try:
87
+ _pip_install("huggingface_hub>=0.32.0")
88
+ except Exception as exc:
89
+ raise RuntimeError(
90
+ "Could not install the Hugging Face downloader. Run "
91
+ "`python -m pip install -U huggingface_hub hf_xet` in "
92
+ "ComfyUI's Python environment, then restart ComfyUI."
93
+ ) from exc
94
+
95
+ xet_disabled = _environment_flag_true("HF_HUB_DISABLE_XET")
96
+ xet_available = importlib.util.find_spec("hf_xet") is not None
97
+ if not xet_available and not xet_disabled:
98
+ try:
99
+ LOG.info("[DEPENDENCY] hf_xet not found; installing it.")
100
+ _pip_install("hf_xet")
101
+ xet_available = importlib.util.find_spec("hf_xet") is not None
102
+ except Exception as exc:
103
+ LOG.warning(
104
+ "[DEPENDENCY] Could not install hf_xet; using the "
105
+ "Hugging Face Hub HTTP fallback. Reason: %s", exc,
106
+ )
107
+
108
+ from huggingface_hub import get_hf_file_metadata, hf_hub_download, hf_hub_url
109
+ import huggingface_hub
110
+
111
+ if not _environment_flag_true("HF_HUB_DISABLE_PROGRESS_BARS"):
112
+ try:
113
+ from huggingface_hub.utils import enable_progress_bars
114
+ enable_progress_bars()
115
+ except ImportError:
116
+ pass
117
+
118
+ return {
119
+ "hf_hub_download": hf_hub_download,
120
+ "hf_hub_url": hf_hub_url,
121
+ "get_hf_file_metadata": get_hf_file_metadata,
122
+ "hub_version": getattr(huggingface_hub, "__version__", "unknown"),
123
+ "backend_name": (
124
+ "hf_xet" if xet_available and not xet_disabled
125
+ else "huggingface_hub HTTP fallback"
126
+ ),
127
+ }
128
+
129
+
130
+ class _RealtimeProgress:
131
+ """Native ComfyUI progress plus detailed terminal state messages."""
132
+
133
+ TOTAL = 1000
134
+
135
+ def __init__(self, unique_id=None):
136
+ self.unique_id = str(unique_id) if unique_id is not None else None
137
+ self.current = 0
138
+
139
+ try:
140
+ if self.unique_id is None:
141
+ self.progress_bar = comfy.utils.ProgressBar(self.TOTAL)
142
+ else:
143
+ self.progress_bar = comfy.utils.ProgressBar(
144
+ self.TOTAL,
145
+ node_id=self.unique_id,
146
+ )
147
+ except TypeError:
148
+ self.progress_bar = comfy.utils.ProgressBar(self.TOTAL)
149
+
150
+ def set_absolute(self, value):
151
+ value = max(0, min(self.TOTAL, int(value)))
152
+ if value < self.current:
153
+ return
154
+ self.current = value
155
+
156
+ try:
157
+ self.progress_bar.update_absolute(value, self.TOTAL)
158
+ except TypeError:
159
+ try:
160
+ self.progress_bar.update_absolute(value)
161
+ except Exception:
162
+ pass
163
+ except Exception:
164
+ pass
165
+
166
+ def stage(self, value, message):
167
+ self.set_absolute(value)
168
+ LOG.info("[STATE] %s", message)
169
+
170
+ def finish(self):
171
+ self.set_absolute(self.TOTAL)
172
+
173
+
174
+ def _format_bytes(value):
175
+ try:
176
+ value = float(value)
177
+ except Exception:
178
+ return str(value)
179
+
180
+ units = ["B", "KiB", "MiB", "GiB", "TiB"]
181
+ for unit in units:
182
+ if abs(value) < 1024.0 or unit == units[-1]:
183
+ return f"{value:.2f} {unit}"
184
+ value /= 1024.0
185
+ return f"{value:.2f} TiB"
186
+
187
+
188
+ def _shared_state():
189
+ # Both standalone modules use the same lock, including dependency setup.
190
+ # dict.setdefault avoids separate locks if both modules start concurrently.
191
+ return vars(folder_paths).setdefault(
192
+ _SHARED_STATE_ATTRIBUTE, {"lock": threading.RLock()}
193
+ )
194
+
195
+
196
+ def _configured_lora_directories():
197
+ directories = folder_paths.get_folder_paths("loras")
198
+ if not directories:
199
+ raise RuntimeError("No ComfyUI 'loras' folder is configured.")
200
+ return list(dict.fromkeys(os.fspath(path) for path in directories))
201
+
202
+
203
+ def _lora_destination(filename):
204
+ directory = _configured_lora_directories()[0]
205
+ os.makedirs(directory, exist_ok=True)
206
+ return os.path.join(directory, filename)
207
+
208
+
209
+ def _find_lora_path(filename):
210
+ try:
211
+ configured_path = folder_paths.get_full_path("loras", filename)
212
+ except Exception:
213
+ configured_path = None
214
+ if configured_path and os.path.isfile(configured_path):
215
+ return configured_path
216
+
217
+ directories = _configured_lora_directories()
218
+ # Check directly too: ComfyUI's filename cache may predate a new download.
219
+ for root in directories:
220
+ direct_path = os.path.join(root, filename)
221
+ if os.path.isfile(direct_path):
222
+ return direct_path
223
+
224
+ # Recognize an existing LoRA in any configured folder or subfolder.
225
+ for root in directories:
226
+ if not os.path.isdir(root):
227
+ continue
228
+ for directory, subdirectories, filenames in os.walk(root):
229
+ subdirectories[:] = [
230
+ name for name in subdirectories if name not in {".git", ".cache"}
231
+ ]
232
+ if filename in filenames:
233
+ return os.path.join(directory, filename)
234
+ return None
235
+
236
+
237
+ def _hf_cache_directory():
238
+ root = getattr(folder_paths, "models_dir", None)
239
+ if not root:
240
+ root = _configured_lora_directories()[0]
241
+ directory = os.path.join(root, ".cache", "huggingface", "hub")
242
+ os.makedirs(directory, exist_ok=True)
243
+ return directory
244
+
245
+
246
+ def _validate_safetensors_file(path):
247
+ """Reject truncated or structurally incomplete safetensors files."""
248
+ path = os.path.realpath(path)
249
+ if not os.path.isfile(path):
250
+ return False, f"File does not exist: {path}"
251
+
252
+ file_size = os.path.getsize(path)
253
+ if file_size < 8:
254
+ return False, f"File is too small to be safetensors: {file_size} bytes"
255
+
256
+ try:
257
+ with open(path, "rb") as handle:
258
+ raw_header_length = handle.read(8)
259
+ if len(raw_header_length) != 8:
260
+ return False, "Could not read the safetensors header length."
261
+
262
+ header_length = struct.unpack("<Q", raw_header_length)[0]
263
+ if header_length <= 1 or header_length > 100_000_000:
264
+ return False, (
265
+ f"Invalid safetensors header length: {header_length}"
266
+ )
267
+
268
+ data_start = 8 + header_length
269
+ if data_start > file_size:
270
+ return False, (
271
+ "Incomplete safetensors header: "
272
+ f"header ends at {data_start}, file size is {file_size}."
273
+ )
274
+
275
+ header_bytes = handle.read(header_length)
276
+ if len(header_bytes) != header_length:
277
+ return False, (
278
+ "Incomplete safetensors header: expected "
279
+ f"{header_length} bytes, read {len(header_bytes)}."
280
+ )
281
+
282
+ try:
283
+ header = json.loads(header_bytes.decode("utf-8"))
284
+ except Exception as exc:
285
+ return False, f"Invalid safetensors JSON header: {exc}"
286
+
287
+ if not isinstance(header, dict):
288
+ return False, "Safetensors header is not a JSON object."
289
+
290
+ data_region_size = file_size - data_start
291
+ intervals = []
292
+
293
+ for tensor_name, tensor_info in header.items():
294
+ if tensor_name == "__metadata__":
295
+ continue
296
+ if not isinstance(tensor_info, dict):
297
+ return False, f"Invalid tensor entry for '{tensor_name}'."
298
+
299
+ offsets = tensor_info.get("data_offsets")
300
+ if (
301
+ not isinstance(offsets, list)
302
+ or len(offsets) != 2
303
+ or not all(type(value) is int for value in offsets)
304
+ ):
305
+ return False, (
306
+ f"Invalid data_offsets for tensor '{tensor_name}'."
307
+ )
308
+
309
+ start, end = offsets
310
+ if start < 0 or end < start:
311
+ return False, (
312
+ f"Invalid tensor offsets for '{tensor_name}': {offsets}"
313
+ )
314
+ if end > data_region_size:
315
+ return False, (
316
+ f"Tensor '{tensor_name}' ends at {end}, but the data "
317
+ f"region is only {data_region_size} bytes."
318
+ )
319
+ intervals.append((start, end, tensor_name))
320
+
321
+ if not intervals:
322
+ return False, "Safetensors file contains no tensor entries."
323
+
324
+ intervals.sort(key=lambda item: (item[0], item[1]))
325
+ expected_start = 0
326
+ for start, end, tensor_name in intervals:
327
+ if start != expected_start:
328
+ if start < expected_start:
329
+ return False, (
330
+ f"Tensor data overlaps before '{tensor_name}': "
331
+ f"expected {expected_start}, got {start}."
332
+ )
333
+ return False, (
334
+ f"Tensor data has a gap before '{tensor_name}': expected "
335
+ f"{expected_start}, got {start}."
336
+ )
337
+ expected_start = end
338
+
339
+ if expected_start != data_region_size:
340
+ return False, (
341
+ "Safetensors tensor data does not fully cover the file: "
342
+ f"covered={expected_start}, data region={data_region_size}."
343
+ )
344
+
345
+ return True, (
346
+ f"valid safetensors | size={_format_bytes(file_size)} | "
347
+ f"header={_format_bytes(header_length)} | tensors={len(intervals)}"
348
+ )
349
+ except Exception as exc:
350
+ return False, f"Safetensors validation failed: {exc}"
351
+
352
+
353
+ def _fsync_directory(directory):
354
+ try:
355
+ descriptor = os.open(directory, os.O_RDONLY)
356
+ except Exception:
357
+ return
358
+
359
+ try:
360
+ os.fsync(descriptor)
361
+ except Exception:
362
+ pass
363
+ finally:
364
+ os.close(descriptor)
365
+
366
+
367
+ class _DownloadIntegrityError(RuntimeError):
368
+ """A completed cached file must be fetched again rather than resumed."""
369
+
370
+
371
+ def _remote_file_details(stack, filename):
372
+ """Best-effort metadata: size, LFS SHA256, and a pinned revision."""
373
+ result = {"size": None, "sha256": None, "revision": HF_REVISION}
374
+ try:
375
+ url = stack["hf_hub_url"](
376
+ repo_id=HF_REPO_ID, filename=filename,
377
+ repo_type="model", revision=HF_REVISION,
378
+ )
379
+ metadata = stack["get_hf_file_metadata"](url, timeout=30)
380
+ size = getattr(metadata, "size", None)
381
+ if isinstance(size, int) and size > 0:
382
+ result["size"] = size
383
+ etag = str(getattr(metadata, "etag", "") or "").strip('"')
384
+ if re.fullmatch(r"[0-9a-fA-F]{64}", etag):
385
+ result["sha256"] = etag.lower()
386
+ commit = str(getattr(metadata, "commit_hash", "") or "")
387
+ if re.fullmatch(r"[0-9a-fA-F]{40}", commit):
388
+ result["revision"] = commit
389
+ LOG.info(
390
+ "[REMOTE] %s | size=%s | SHA256=%s", filename,
391
+ _format_bytes(size) if result["size"] is not None else "unknown",
392
+ "available" if result["sha256"] else "not provided",
393
+ )
394
+ except Exception as exc:
395
+ LOG.warning(
396
+ "[REMOTE] Could not pre-read metadata for %s: %s. "
397
+ "Will still try the Hub cache/downloader.", filename, exc,
398
+ )
399
+ return result
400
+
401
+
402
+ def _validate_download(path, remote_size=None, expected_sha256=None):
403
+ valid, reason = _validate_safetensors_file(path)
404
+ if not valid:
405
+ return valid, reason
406
+ local_size = os.path.getsize(path)
407
+ if remote_size is not None and local_size != remote_size:
408
+ return False, (
409
+ "Downloaded size does not match Hugging Face metadata: "
410
+ f"local={local_size}, remote={remote_size}."
411
+ )
412
+ if expected_sha256:
413
+ checksum = hashlib.sha256()
414
+ with open(path, "rb") as handle:
415
+ while True:
416
+ chunk = handle.read(8 * 1024 * 1024)
417
+ if not chunk:
418
+ break
419
+ checksum.update(chunk)
420
+ if checksum.hexdigest() != expected_sha256.lower():
421
+ return False, "Downloaded SHA256 does not match Hugging Face metadata."
422
+ reason += " | SHA256 verified"
423
+ return True, reason
424
+
425
+
426
+ def _atomic_install(cached_path, final_path, remote_size=None, expected_sha256=None):
427
+ """Validate and fsync a temporary copy before exposing the final filename."""
428
+ source_path = os.path.realpath(os.fspath(cached_path))
429
+ valid, reason = _validate_download(source_path, remote_size)
430
+ if not valid:
431
+ raise _DownloadIntegrityError(f"Cached LoRA failed validation: {reason}")
432
+
433
+ final_directory = os.path.dirname(final_path)
434
+ os.makedirs(final_directory, exist_ok=True)
435
+ descriptor, temporary_path = tempfile.mkstemp(
436
+ prefix=os.path.basename(final_path) + ".salia-install-",
437
+ suffix=".tmp", dir=final_directory,
438
+ )
439
+ try:
440
+ with os.fdopen(descriptor, "wb") as destination, open(source_path, "rb") as source:
441
+ shutil.copyfileobj(source, destination, length=16 * 1024 * 1024)
442
+ destination.flush()
443
+ os.fsync(destination.fileno())
444
+
445
+ valid, reason = _validate_download(
446
+ temporary_path, remote_size, expected_sha256,
447
+ )
448
+ if not valid:
449
+ raise _DownloadIntegrityError(f"Temporary LoRA failed validation: {reason}")
450
+
451
+ # Recheck after copying. Another node may have supplied the file.
452
+ # The shared lock handles concurrent executions of these two loaders.
453
+ if os.path.lexists(final_path):
454
+ existing_valid, existing_reason = _validate_download(final_path)
455
+ if not existing_valid:
456
+ raise RuntimeError(
457
+ "The LoRA destination already exists and is invalid; "
458
+ f"it was not overwritten: {final_path}. {existing_reason}"
459
+ )
460
+ return f"Existing LoRA preserved: {existing_reason}"
461
+
462
+ os.replace(temporary_path, final_path)
463
+ _fsync_directory(final_directory)
464
+ return reason
465
+ finally:
466
+ if os.path.exists(temporary_path):
467
+ os.remove(temporary_path)
468
+
469
+
470
+ def _download_missing_lora(filename, reporter, stack, stage_start, stage_end):
471
+ details = _remote_file_details(stack, filename)
472
+ destination_path = _lora_destination(filename)
473
+ force_download = False
474
+ last_error = None
475
+
476
+ for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
477
+ force_this_attempt = force_download
478
+ # Network retries retain/resume partial Hub downloads. Only a completed
479
+ # file which fails integrity validation triggers a forced fresh fetch.
480
+ force_download = False
481
+ reporter.stage(
482
+ stage_start,
483
+ f"Downloading {HF_REPO_ID}/{filename} "
484
+ f"(attempt {attempt}/{MAX_DOWNLOAD_ATTEMPTS}, "
485
+ f"force_download={force_this_attempt}). "
486
+ "Hugging Face transfer progress follows in the terminal.",
487
+ )
488
+ try:
489
+ cached_path = stack["hf_hub_download"](
490
+ repo_id=HF_REPO_ID, filename=filename, repo_type="model",
491
+ revision=details["revision"], cache_dir=_hf_cache_directory(),
492
+ force_download=force_this_attempt, etag_timeout=30,
493
+ )
494
+ reporter.stage(
495
+ max(stage_start, stage_end - 60),
496
+ f"Validating and atomically installing {filename}.",
497
+ )
498
+ summary = _atomic_install(
499
+ cached_path, destination_path,
500
+ remote_size=details["size"], expected_sha256=details["sha256"],
501
+ )
502
+ reporter.stage(stage_end, f"Installed {filename}: {summary}")
503
+ return destination_path
504
+ except Exception as exc:
505
+ last_error = exc
506
+ force_download = isinstance(exc, _DownloadIntegrityError)
507
+ LOG.warning(
508
+ "[DOWNLOAD] Attempt %d/%d failed for %s: %s",
509
+ attempt, MAX_DOWNLOAD_ATTEMPTS, filename, exc,
510
+ )
511
+ if isinstance(exc, OSError) and exc.errno in {
512
+ errno.ENOSPC, errno.EACCES, errno.EROFS,
513
+ }:
514
+ raise RuntimeError(
515
+ f"Cannot save LoRA to {destination_path}: {exc}"
516
+ ) from exc
517
+ if attempt == MAX_DOWNLOAD_ATTEMPTS:
518
+ break
519
+ retry_delay = min(2 ** attempt, 8)
520
+ LOG.info(
521
+ "[DOWNLOAD] Retrying %s in %ds (%s).", filename, retry_delay,
522
+ "fresh download after integrity failure" if force_download
523
+ else "preserving the resumable Hub cache",
524
+ )
525
+ time.sleep(retry_delay)
526
+
527
+ raise RuntimeError(
528
+ f"Failed to download {filename} from https://huggingface.co/{HF_REPO_ID} "
529
+ f"after {MAX_DOWNLOAD_ATTEMPTS} attempts. Last error: {last_error}"
530
+ ) from last_error
531
+
532
+
533
+ def _ensure_loras_available(filenames, reporter):
534
+ """Resolve all LoRAs before loading; valid local files need no network."""
535
+ with _shared_state()["lock"]:
536
+ paths = [_find_lora_path(filename) for filename in filenames]
537
+ missing = []
538
+ for index, (filename, path) in enumerate(zip(filenames, paths)):
539
+ if path is None:
540
+ missing.append((index, filename))
541
+ continue
542
+ valid, reason = _validate_download(path)
543
+ if not valid:
544
+ raise RuntimeError(
545
+ f"Existing LoRA is incomplete or invalid: {path}. {reason} "
546
+ "It was not overwritten. Move/delete the invalid file "
547
+ "and run the node again to download a clean copy."
548
+ )
549
+ LOG.info("[LOCAL] Download skipped for %s: %s", filename, reason)
550
+
551
+ if missing:
552
+ reporter.stage(10, "Missing LoRAs: " + ", ".join(name for _, name in missing))
553
+ stack = _ensure_huggingface_stack()
554
+ reporter.stage(
555
+ 50,
556
+ f"Downloader ready: huggingface_hub={stack['hub_version']}, "
557
+ f"backend={stack['backend_name']}",
558
+ )
559
+ span = 800 / len(missing)
560
+ for number, (index, filename) in enumerate(missing):
561
+ paths[index] = _download_missing_lora(
562
+ filename, reporter, stack,
563
+ int(80 + span * number), int(80 + span * (number + 1)),
564
+ )
565
+ else:
566
+ reporter.stage(880, "All requested LoRAs already exist; downloads skipped.")
567
+
568
+ for filename, path in zip(filenames, paths):
569
+ valid, reason = _validate_download(path)
570
+ if not valid:
571
+ raise RuntimeError(f"LoRA is not ready for loading: {filename}. {reason}")
572
+ return tuple(paths)
573
+
574
+
575
+ class Salia_Load_Lora_Wan:
576
+ """
577
+ Downloads paired *_HI / *_LO LoRAs from the public Hugging Face repo
578
+ `saliacoel/x` when missing, then applies them model-only to two separate
579
+ MODEL inputs.
580
+
581
+ Input examples that all resolve to the same pair:
582
+ - Fade_to_Black
583
+ - Fade_to_Black_HI
584
+ - Fade_to_Black_LO
585
+ - Fade_to_Black_HI.safetensors
586
+ """
587
+
588
+ CATEGORY = "loaders/saliacoel"
589
+ FUNCTION = "load_dual_loras"
590
+ RETURN_TYPES = ("MODEL", "MODEL")
591
+ RETURN_NAMES = ("loaded_out_HI", "loaded_out_LO")
592
+ DESCRIPTION = (
593
+ "Robustly downloads missing *_HI/*_LO LoRAs from saliacoel/x and applies them "
594
+ "with model-only LoRA loading to separate HI and LO model inputs."
595
+ )
596
+ OUTPUT_TOOLTIPS = (
597
+ "model_in_HI with the *_HI LoRA applied.",
598
+ "model_in_LO with the *_LO LoRA applied.",
599
+ )
600
+
601
+ def __init__(self):
602
+ self.loaded_lora_hi = None
603
+ self.loaded_lora_lo = None
604
+
605
+ @classmethod
606
+ def INPUT_TYPES(cls):
607
+ return {
608
+ "required": {
609
+ "filename": (
610
+ "STRING",
611
+ {
612
+ "default": "",
613
+ "multiline": False,
614
+ "placeholder": "Fade_to_Black or Fade_to_Black_HI",
615
+ "tooltip": (
616
+ "Base LoRA name. A trailing _HI, _LO, or .safetensors "
617
+ "is accepted and normalized automatically."
618
+ ),
619
+ },
620
+ ),
621
+ "model_in_HI": (
622
+ "MODEL",
623
+ {"tooltip": "The MODEL input that will receive the *_HI LoRA."},
624
+ ),
625
+ "model_in_LO": (
626
+ "MODEL",
627
+ {"tooltip": "The MODEL input that will receive the *_LO LoRA."},
628
+ ),
629
+ "strength_HI": (
630
+ "FLOAT",
631
+ {
632
+ "default": 1.0,
633
+ "min": -100.0,
634
+ "max": 100.0,
635
+ "step": 0.01,
636
+ "tooltip": "Strength used when applying the *_HI LoRA.",
637
+ },
638
+ ),
639
+ "strength_LO": (
640
+ "FLOAT",
641
+ {
642
+ "default": 1.0,
643
+ "min": -100.0,
644
+ "max": 100.0,
645
+ "step": 0.01,
646
+ "tooltip": "Strength used when applying the *_LO LoRA.",
647
+ },
648
+ ),
649
+ },
650
+ "hidden": {"unique_id": "UNIQUE_ID"},
651
+ }
652
+
653
+ @staticmethod
654
+ def _normalize_base_name(name: str) -> str:
655
+ base = str(name or "").strip().replace("\\", "/").rsplit("/", 1)[-1]
656
+ if base.lower().endswith(".safetensors"):
657
+ base = base[:-len(".safetensors")]
658
+ if base.endswith("_HI") or base.endswith("_LO"):
659
+ base = base[:-3]
660
+ base = base.strip()
661
+ if not base or base in {".", ".."} or "\x00" in base:
662
+ raise ValueError("filename resolves to an empty or invalid base name.")
663
+ return base
664
+
665
+ @classmethod
666
+ def _build_pair_names(cls, name: str) -> tuple[str, str]:
667
+ base = cls._normalize_base_name(name)
668
+ return f"{base}_HI.safetensors", f"{base}_LO.safetensors"
669
+
670
+
671
+ @classmethod
672
+ def _ensure_lora_available(cls, lora_name: str, reporter=None) -> str:
673
+ return _ensure_loras_available(
674
+ (lora_name,), reporter if reporter is not None else _RealtimeProgress(),
675
+ )[0]
676
+
677
+ def _get_or_load_lora(self, cache_attr: str, lora_path: str):
678
+ cached = getattr(self, cache_attr)
679
+ if cached is not None and cached[0] == lora_path:
680
+ return cached[1]
681
+
682
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
683
+ setattr(self, cache_attr, (lora_path, lora))
684
+ return lora
685
+
686
+ def _apply_lora_model_only(self, model, lora_path: str, strength: float, cache_attr: str):
687
+ if strength == 0:
688
+ return model
689
+
690
+ lora = self._get_or_load_lora(cache_attr, lora_path)
691
+ model_lora, _ = comfy.sd.load_lora_for_models(model, None, lora, strength, 0)
692
+ return model_lora
693
+
694
+ def load_dual_loras(
695
+ self, filename, model_in_HI, model_in_LO, strength_HI, strength_LO,
696
+ unique_id=None,
697
+ ):
698
+ reporter = _RealtimeProgress(unique_id)
699
+ hi_name, lo_name = self._build_pair_names(filename)
700
+ hi_path, lo_path = _ensure_loras_available((hi_name, lo_name), reporter)
701
+
702
+ reporter.stage(900, f"Applying HI LoRA: {hi_name} (strength={strength_HI}).")
703
+ loaded_out_HI = self._apply_lora_model_only(
704
+ model=model_in_HI, lora_path=hi_path,
705
+ strength=strength_HI, cache_attr="loaded_lora_hi",
706
+ )
707
+ reporter.stage(950, f"Applying LO LoRA: {lo_name} (strength={strength_LO}).")
708
+ loaded_out_LO = self._apply_lora_model_only(
709
+ model=model_in_LO, lora_path=lo_path,
710
+ strength=strength_LO, cache_attr="loaded_lora_lo",
711
+ )
712
+ reporter.stage(1000, "HI/LO LoRAs ready.")
713
+ return (loaded_out_HI, loaded_out_LO)
714
+
715
+
716
+ NODE_CLASS_MAPPINGS = {
717
+ "Salia_Load_Lora_Wan": Salia_Load_Lora_Wan,
718
+ }
719
+
720
+
721
+ NODE_DISPLAY_NAME_MAPPINGS = {
722
+ "Salia_Load_Lora_Wan": "Salia Dual LoRA Loader (Model Only)",
723
+ }
salia_lora_x.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Standalone: no imports from another custom-node file are required.
2
+ # Download behavior follows Salia_Dual_Checkpoint_Loader_Robust:
3
+ # Hugging Face Hub/Xet, a persistent resumable cache, retries, validation,
4
+ # fsync + atomic installation, and terminal / ComfyUI progress.
5
+ import errno
6
+ import hashlib
7
+ import importlib
8
+ import importlib.metadata
9
+ import importlib.util
10
+ import json
11
+ import logging
12
+ import os
13
+ import re
14
+ import shutil
15
+ import struct
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ import threading
20
+ import time
21
+
22
+ import comfy.sd
23
+ import comfy.utils
24
+ import folder_paths
25
+
26
+
27
+ HF_REPO_BASE = "https://huggingface.co/saliacoel/x/resolve/main"
28
+ HF_REPO_ID = "saliacoel/x"
29
+ HF_REVISION = "main"
30
+ MIN_HF_HUB_VERSION = (0, 32, 0)
31
+ MAX_DOWNLOAD_ATTEMPTS = 3
32
+ _SHARED_STATE_ATTRIBUTE = "_salia_robust_lora_download_state_v1"
33
+
34
+ os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "60")
35
+ os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "30")
36
+
37
+
38
+ LOG = logging.getLogger("Salia_Load_Lora_X")
39
+
40
+
41
+ def _version_tuple(version_string):
42
+ numbers = re.findall(r"\d+", str(version_string))
43
+ numbers = [int(value) for value in numbers[:3]]
44
+ while len(numbers) < 3:
45
+ numbers.append(0)
46
+ return tuple(numbers)
47
+
48
+
49
+ def _pip_install(*packages):
50
+ command = [sys.executable, "-m", "pip", "install", "-U", *packages]
51
+ LOG.info("[DEPENDENCY] Running: %s", " ".join(command))
52
+ subprocess.check_call(command)
53
+ importlib.invalidate_caches()
54
+
55
+
56
+ def _environment_flag_true(name):
57
+ value = os.environ.get(name)
58
+ if value is None:
59
+ return False
60
+ return str(value).strip().lower() in {"1", "true", "yes", "on"}
61
+
62
+
63
+ def _ensure_huggingface_stack():
64
+ """Install missing downloader dependencies only when a download is needed."""
65
+ loaded_hub = sys.modules.get("huggingface_hub")
66
+ if loaded_hub is not None:
67
+ loaded_version = getattr(loaded_hub, "__version__", "0.0.0")
68
+ if _version_tuple(loaded_version) < MIN_HF_HUB_VERSION:
69
+ raise RuntimeError(
70
+ "huggingface_hub is already loaded and is too old "
71
+ f"(version: {loaded_version}). Run "
72
+ "`python -m pip install -U huggingface_hub hf_xet` in "
73
+ "ComfyUI's Python environment and restart ComfyUI."
74
+ )
75
+
76
+ try:
77
+ installed_version = importlib.metadata.version("huggingface_hub")
78
+ except importlib.metadata.PackageNotFoundError:
79
+ installed_version = None
80
+
81
+ if loaded_hub is None and (
82
+ installed_version is None
83
+ or _version_tuple(installed_version) < MIN_HF_HUB_VERSION
84
+ ):
85
+ LOG.info("[DEPENDENCY] Installing/upgrading huggingface_hub>=0.32.0.")
86
+ try:
87
+ _pip_install("huggingface_hub>=0.32.0")
88
+ except Exception as exc:
89
+ raise RuntimeError(
90
+ "Could not install the Hugging Face downloader. Run "
91
+ "`python -m pip install -U huggingface_hub hf_xet` in "
92
+ "ComfyUI's Python environment, then restart ComfyUI."
93
+ ) from exc
94
+
95
+ xet_disabled = _environment_flag_true("HF_HUB_DISABLE_XET")
96
+ xet_available = importlib.util.find_spec("hf_xet") is not None
97
+ if not xet_available and not xet_disabled:
98
+ try:
99
+ LOG.info("[DEPENDENCY] hf_xet not found; installing it.")
100
+ _pip_install("hf_xet")
101
+ xet_available = importlib.util.find_spec("hf_xet") is not None
102
+ except Exception as exc:
103
+ LOG.warning(
104
+ "[DEPENDENCY] Could not install hf_xet; using the "
105
+ "Hugging Face Hub HTTP fallback. Reason: %s", exc,
106
+ )
107
+
108
+ from huggingface_hub import get_hf_file_metadata, hf_hub_download, hf_hub_url
109
+ import huggingface_hub
110
+
111
+ if not _environment_flag_true("HF_HUB_DISABLE_PROGRESS_BARS"):
112
+ try:
113
+ from huggingface_hub.utils import enable_progress_bars
114
+ enable_progress_bars()
115
+ except ImportError:
116
+ pass
117
+
118
+ return {
119
+ "hf_hub_download": hf_hub_download,
120
+ "hf_hub_url": hf_hub_url,
121
+ "get_hf_file_metadata": get_hf_file_metadata,
122
+ "hub_version": getattr(huggingface_hub, "__version__", "unknown"),
123
+ "backend_name": (
124
+ "hf_xet" if xet_available and not xet_disabled
125
+ else "huggingface_hub HTTP fallback"
126
+ ),
127
+ }
128
+
129
+
130
+ class _RealtimeProgress:
131
+ """Native ComfyUI progress plus detailed terminal state messages."""
132
+
133
+ TOTAL = 1000
134
+
135
+ def __init__(self, unique_id=None):
136
+ self.unique_id = str(unique_id) if unique_id is not None else None
137
+ self.current = 0
138
+
139
+ try:
140
+ if self.unique_id is None:
141
+ self.progress_bar = comfy.utils.ProgressBar(self.TOTAL)
142
+ else:
143
+ self.progress_bar = comfy.utils.ProgressBar(
144
+ self.TOTAL,
145
+ node_id=self.unique_id,
146
+ )
147
+ except TypeError:
148
+ self.progress_bar = comfy.utils.ProgressBar(self.TOTAL)
149
+
150
+ def set_absolute(self, value):
151
+ value = max(0, min(self.TOTAL, int(value)))
152
+ if value < self.current:
153
+ return
154
+ self.current = value
155
+
156
+ try:
157
+ self.progress_bar.update_absolute(value, self.TOTAL)
158
+ except TypeError:
159
+ try:
160
+ self.progress_bar.update_absolute(value)
161
+ except Exception:
162
+ pass
163
+ except Exception:
164
+ pass
165
+
166
+ def stage(self, value, message):
167
+ self.set_absolute(value)
168
+ LOG.info("[STATE] %s", message)
169
+
170
+ def finish(self):
171
+ self.set_absolute(self.TOTAL)
172
+
173
+
174
+ def _format_bytes(value):
175
+ try:
176
+ value = float(value)
177
+ except Exception:
178
+ return str(value)
179
+
180
+ units = ["B", "KiB", "MiB", "GiB", "TiB"]
181
+ for unit in units:
182
+ if abs(value) < 1024.0 or unit == units[-1]:
183
+ return f"{value:.2f} {unit}"
184
+ value /= 1024.0
185
+ return f"{value:.2f} TiB"
186
+
187
+
188
+ def _shared_state():
189
+ # Both standalone modules use the same lock, including dependency setup.
190
+ # dict.setdefault avoids separate locks if both modules start concurrently.
191
+ return vars(folder_paths).setdefault(
192
+ _SHARED_STATE_ATTRIBUTE, {"lock": threading.RLock()}
193
+ )
194
+
195
+
196
+ def _configured_lora_directories():
197
+ directories = folder_paths.get_folder_paths("loras")
198
+ if not directories:
199
+ raise RuntimeError("No ComfyUI 'loras' folder is configured.")
200
+ return list(dict.fromkeys(os.fspath(path) for path in directories))
201
+
202
+
203
+ def _lora_destination(filename):
204
+ directory = _configured_lora_directories()[0]
205
+ os.makedirs(directory, exist_ok=True)
206
+ return os.path.join(directory, filename)
207
+
208
+
209
+ def _find_lora_path(filename):
210
+ try:
211
+ configured_path = folder_paths.get_full_path("loras", filename)
212
+ except Exception:
213
+ configured_path = None
214
+ if configured_path and os.path.isfile(configured_path):
215
+ return configured_path
216
+
217
+ directories = _configured_lora_directories()
218
+ # Check directly too: ComfyUI's filename cache may predate a new download.
219
+ for root in directories:
220
+ direct_path = os.path.join(root, filename)
221
+ if os.path.isfile(direct_path):
222
+ return direct_path
223
+
224
+ # Recognize an existing LoRA in any configured folder or subfolder.
225
+ for root in directories:
226
+ if not os.path.isdir(root):
227
+ continue
228
+ for directory, subdirectories, filenames in os.walk(root):
229
+ subdirectories[:] = [
230
+ name for name in subdirectories if name not in {".git", ".cache"}
231
+ ]
232
+ if filename in filenames:
233
+ return os.path.join(directory, filename)
234
+ return None
235
+
236
+
237
+ def _hf_cache_directory():
238
+ root = getattr(folder_paths, "models_dir", None)
239
+ if not root:
240
+ root = _configured_lora_directories()[0]
241
+ directory = os.path.join(root, ".cache", "huggingface", "hub")
242
+ os.makedirs(directory, exist_ok=True)
243
+ return directory
244
+
245
+
246
+ def _validate_safetensors_file(path):
247
+ """Reject truncated or structurally incomplete safetensors files."""
248
+ path = os.path.realpath(path)
249
+ if not os.path.isfile(path):
250
+ return False, f"File does not exist: {path}"
251
+
252
+ file_size = os.path.getsize(path)
253
+ if file_size < 8:
254
+ return False, f"File is too small to be safetensors: {file_size} bytes"
255
+
256
+ try:
257
+ with open(path, "rb") as handle:
258
+ raw_header_length = handle.read(8)
259
+ if len(raw_header_length) != 8:
260
+ return False, "Could not read the safetensors header length."
261
+
262
+ header_length = struct.unpack("<Q", raw_header_length)[0]
263
+ if header_length <= 1 or header_length > 100_000_000:
264
+ return False, (
265
+ f"Invalid safetensors header length: {header_length}"
266
+ )
267
+
268
+ data_start = 8 + header_length
269
+ if data_start > file_size:
270
+ return False, (
271
+ "Incomplete safetensors header: "
272
+ f"header ends at {data_start}, file size is {file_size}."
273
+ )
274
+
275
+ header_bytes = handle.read(header_length)
276
+ if len(header_bytes) != header_length:
277
+ return False, (
278
+ "Incomplete safetensors header: expected "
279
+ f"{header_length} bytes, read {len(header_bytes)}."
280
+ )
281
+
282
+ try:
283
+ header = json.loads(header_bytes.decode("utf-8"))
284
+ except Exception as exc:
285
+ return False, f"Invalid safetensors JSON header: {exc}"
286
+
287
+ if not isinstance(header, dict):
288
+ return False, "Safetensors header is not a JSON object."
289
+
290
+ data_region_size = file_size - data_start
291
+ intervals = []
292
+
293
+ for tensor_name, tensor_info in header.items():
294
+ if tensor_name == "__metadata__":
295
+ continue
296
+ if not isinstance(tensor_info, dict):
297
+ return False, f"Invalid tensor entry for '{tensor_name}'."
298
+
299
+ offsets = tensor_info.get("data_offsets")
300
+ if (
301
+ not isinstance(offsets, list)
302
+ or len(offsets) != 2
303
+ or not all(type(value) is int for value in offsets)
304
+ ):
305
+ return False, (
306
+ f"Invalid data_offsets for tensor '{tensor_name}'."
307
+ )
308
+
309
+ start, end = offsets
310
+ if start < 0 or end < start:
311
+ return False, (
312
+ f"Invalid tensor offsets for '{tensor_name}': {offsets}"
313
+ )
314
+ if end > data_region_size:
315
+ return False, (
316
+ f"Tensor '{tensor_name}' ends at {end}, but the data "
317
+ f"region is only {data_region_size} bytes."
318
+ )
319
+ intervals.append((start, end, tensor_name))
320
+
321
+ if not intervals:
322
+ return False, "Safetensors file contains no tensor entries."
323
+
324
+ intervals.sort(key=lambda item: (item[0], item[1]))
325
+ expected_start = 0
326
+ for start, end, tensor_name in intervals:
327
+ if start != expected_start:
328
+ if start < expected_start:
329
+ return False, (
330
+ f"Tensor data overlaps before '{tensor_name}': "
331
+ f"expected {expected_start}, got {start}."
332
+ )
333
+ return False, (
334
+ f"Tensor data has a gap before '{tensor_name}': expected "
335
+ f"{expected_start}, got {start}."
336
+ )
337
+ expected_start = end
338
+
339
+ if expected_start != data_region_size:
340
+ return False, (
341
+ "Safetensors tensor data does not fully cover the file: "
342
+ f"covered={expected_start}, data region={data_region_size}."
343
+ )
344
+
345
+ return True, (
346
+ f"valid safetensors | size={_format_bytes(file_size)} | "
347
+ f"header={_format_bytes(header_length)} | tensors={len(intervals)}"
348
+ )
349
+ except Exception as exc:
350
+ return False, f"Safetensors validation failed: {exc}"
351
+
352
+
353
+ def _fsync_directory(directory):
354
+ try:
355
+ descriptor = os.open(directory, os.O_RDONLY)
356
+ except Exception:
357
+ return
358
+
359
+ try:
360
+ os.fsync(descriptor)
361
+ except Exception:
362
+ pass
363
+ finally:
364
+ os.close(descriptor)
365
+
366
+
367
+ class _DownloadIntegrityError(RuntimeError):
368
+ """A completed cached file must be fetched again rather than resumed."""
369
+
370
+
371
+ def _remote_file_details(stack, filename):
372
+ """Best-effort metadata: size, LFS SHA256, and a pinned revision."""
373
+ result = {"size": None, "sha256": None, "revision": HF_REVISION}
374
+ try:
375
+ url = stack["hf_hub_url"](
376
+ repo_id=HF_REPO_ID, filename=filename,
377
+ repo_type="model", revision=HF_REVISION,
378
+ )
379
+ metadata = stack["get_hf_file_metadata"](url, timeout=30)
380
+ size = getattr(metadata, "size", None)
381
+ if isinstance(size, int) and size > 0:
382
+ result["size"] = size
383
+ etag = str(getattr(metadata, "etag", "") or "").strip('"')
384
+ if re.fullmatch(r"[0-9a-fA-F]{64}", etag):
385
+ result["sha256"] = etag.lower()
386
+ commit = str(getattr(metadata, "commit_hash", "") or "")
387
+ if re.fullmatch(r"[0-9a-fA-F]{40}", commit):
388
+ result["revision"] = commit
389
+ LOG.info(
390
+ "[REMOTE] %s | size=%s | SHA256=%s", filename,
391
+ _format_bytes(size) if result["size"] is not None else "unknown",
392
+ "available" if result["sha256"] else "not provided",
393
+ )
394
+ except Exception as exc:
395
+ LOG.warning(
396
+ "[REMOTE] Could not pre-read metadata for %s: %s. "
397
+ "Will still try the Hub cache/downloader.", filename, exc,
398
+ )
399
+ return result
400
+
401
+
402
+ def _validate_download(path, remote_size=None, expected_sha256=None):
403
+ valid, reason = _validate_safetensors_file(path)
404
+ if not valid:
405
+ return valid, reason
406
+ local_size = os.path.getsize(path)
407
+ if remote_size is not None and local_size != remote_size:
408
+ return False, (
409
+ "Downloaded size does not match Hugging Face metadata: "
410
+ f"local={local_size}, remote={remote_size}."
411
+ )
412
+ if expected_sha256:
413
+ checksum = hashlib.sha256()
414
+ with open(path, "rb") as handle:
415
+ while True:
416
+ chunk = handle.read(8 * 1024 * 1024)
417
+ if not chunk:
418
+ break
419
+ checksum.update(chunk)
420
+ if checksum.hexdigest() != expected_sha256.lower():
421
+ return False, "Downloaded SHA256 does not match Hugging Face metadata."
422
+ reason += " | SHA256 verified"
423
+ return True, reason
424
+
425
+
426
+ def _atomic_install(cached_path, final_path, remote_size=None, expected_sha256=None):
427
+ """Validate and fsync a temporary copy before exposing the final filename."""
428
+ source_path = os.path.realpath(os.fspath(cached_path))
429
+ valid, reason = _validate_download(source_path, remote_size)
430
+ if not valid:
431
+ raise _DownloadIntegrityError(f"Cached LoRA failed validation: {reason}")
432
+
433
+ final_directory = os.path.dirname(final_path)
434
+ os.makedirs(final_directory, exist_ok=True)
435
+ descriptor, temporary_path = tempfile.mkstemp(
436
+ prefix=os.path.basename(final_path) + ".salia-install-",
437
+ suffix=".tmp", dir=final_directory,
438
+ )
439
+ try:
440
+ with os.fdopen(descriptor, "wb") as destination, open(source_path, "rb") as source:
441
+ shutil.copyfileobj(source, destination, length=16 * 1024 * 1024)
442
+ destination.flush()
443
+ os.fsync(destination.fileno())
444
+
445
+ valid, reason = _validate_download(
446
+ temporary_path, remote_size, expected_sha256,
447
+ )
448
+ if not valid:
449
+ raise _DownloadIntegrityError(f"Temporary LoRA failed validation: {reason}")
450
+
451
+ # Recheck after copying. Another node may have supplied the file.
452
+ # The shared lock handles concurrent executions of these two loaders.
453
+ if os.path.lexists(final_path):
454
+ existing_valid, existing_reason = _validate_download(final_path)
455
+ if not existing_valid:
456
+ raise RuntimeError(
457
+ "The LoRA destination already exists and is invalid; "
458
+ f"it was not overwritten: {final_path}. {existing_reason}"
459
+ )
460
+ return f"Existing LoRA preserved: {existing_reason}"
461
+
462
+ os.replace(temporary_path, final_path)
463
+ _fsync_directory(final_directory)
464
+ return reason
465
+ finally:
466
+ if os.path.exists(temporary_path):
467
+ os.remove(temporary_path)
468
+
469
+
470
+ def _download_missing_lora(filename, reporter, stack, stage_start, stage_end):
471
+ details = _remote_file_details(stack, filename)
472
+ destination_path = _lora_destination(filename)
473
+ force_download = False
474
+ last_error = None
475
+
476
+ for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
477
+ force_this_attempt = force_download
478
+ # Network retries retain/resume partial Hub downloads. Only a completed
479
+ # file which fails integrity validation triggers a forced fresh fetch.
480
+ force_download = False
481
+ reporter.stage(
482
+ stage_start,
483
+ f"Downloading {HF_REPO_ID}/{filename} "
484
+ f"(attempt {attempt}/{MAX_DOWNLOAD_ATTEMPTS}, "
485
+ f"force_download={force_this_attempt}). "
486
+ "Hugging Face transfer progress follows in the terminal.",
487
+ )
488
+ try:
489
+ cached_path = stack["hf_hub_download"](
490
+ repo_id=HF_REPO_ID, filename=filename, repo_type="model",
491
+ revision=details["revision"], cache_dir=_hf_cache_directory(),
492
+ force_download=force_this_attempt, etag_timeout=30,
493
+ )
494
+ reporter.stage(
495
+ max(stage_start, stage_end - 60),
496
+ f"Validating and atomically installing {filename}.",
497
+ )
498
+ summary = _atomic_install(
499
+ cached_path, destination_path,
500
+ remote_size=details["size"], expected_sha256=details["sha256"],
501
+ )
502
+ reporter.stage(stage_end, f"Installed {filename}: {summary}")
503
+ return destination_path
504
+ except Exception as exc:
505
+ last_error = exc
506
+ force_download = isinstance(exc, _DownloadIntegrityError)
507
+ LOG.warning(
508
+ "[DOWNLOAD] Attempt %d/%d failed for %s: %s",
509
+ attempt, MAX_DOWNLOAD_ATTEMPTS, filename, exc,
510
+ )
511
+ if isinstance(exc, OSError) and exc.errno in {
512
+ errno.ENOSPC, errno.EACCES, errno.EROFS,
513
+ }:
514
+ raise RuntimeError(
515
+ f"Cannot save LoRA to {destination_path}: {exc}"
516
+ ) from exc
517
+ if attempt == MAX_DOWNLOAD_ATTEMPTS:
518
+ break
519
+ retry_delay = min(2 ** attempt, 8)
520
+ LOG.info(
521
+ "[DOWNLOAD] Retrying %s in %ds (%s).", filename, retry_delay,
522
+ "fresh download after integrity failure" if force_download
523
+ else "preserving the resumable Hub cache",
524
+ )
525
+ time.sleep(retry_delay)
526
+
527
+ raise RuntimeError(
528
+ f"Failed to download {filename} from https://huggingface.co/{HF_REPO_ID} "
529
+ f"after {MAX_DOWNLOAD_ATTEMPTS} attempts. Last error: {last_error}"
530
+ ) from last_error
531
+
532
+
533
+ def _ensure_loras_available(filenames, reporter):
534
+ """Resolve all LoRAs before loading; valid local files need no network."""
535
+ with _shared_state()["lock"]:
536
+ paths = [_find_lora_path(filename) for filename in filenames]
537
+ missing = []
538
+ for index, (filename, path) in enumerate(zip(filenames, paths)):
539
+ if path is None:
540
+ missing.append((index, filename))
541
+ continue
542
+ valid, reason = _validate_download(path)
543
+ if not valid:
544
+ raise RuntimeError(
545
+ f"Existing LoRA is incomplete or invalid: {path}. {reason} "
546
+ "It was not overwritten. Move/delete the invalid file "
547
+ "and run the node again to download a clean copy."
548
+ )
549
+ LOG.info("[LOCAL] Download skipped for %s: %s", filename, reason)
550
+
551
+ if missing:
552
+ reporter.stage(10, "Missing LoRAs: " + ", ".join(name for _, name in missing))
553
+ stack = _ensure_huggingface_stack()
554
+ reporter.stage(
555
+ 50,
556
+ f"Downloader ready: huggingface_hub={stack['hub_version']}, "
557
+ f"backend={stack['backend_name']}",
558
+ )
559
+ span = 800 / len(missing)
560
+ for number, (index, filename) in enumerate(missing):
561
+ paths[index] = _download_missing_lora(
562
+ filename, reporter, stack,
563
+ int(80 + span * number), int(80 + span * (number + 1)),
564
+ )
565
+ else:
566
+ reporter.stage(880, "All requested LoRAs already exist; downloads skipped.")
567
+
568
+ for filename, path in zip(filenames, paths):
569
+ valid, reason = _validate_download(path)
570
+ if not valid:
571
+ raise RuntimeError(f"LoRA is not ready for loading: {filename}. {reason}")
572
+ return tuple(paths)
573
+
574
+
575
+ class Salia_Load_Lora_X:
576
+ """
577
+ Loads a single LoRA from the public Hugging Face repo `saliacoel/x`.
578
+
579
+ Behavior:
580
+ - Takes a single base name, e.g. `Fade_to_Black`
581
+ - Normalizes it to `Fade_to_Black.safetensors`
582
+ - Checks if it already exists in ComfyUI's loras folders
583
+ - If missing, downloads it
584
+ - Loads it and applies it model-only to one MODEL input
585
+ """
586
+
587
+ CATEGORY = "loaders/saliacoel"
588
+ FUNCTION = "load_lora"
589
+ RETURN_TYPES = ("MODEL",)
590
+ RETURN_NAMES = ("loaded_model",)
591
+ DESCRIPTION = (
592
+ "Loads a single LoRA from saliacoel/x. If missing locally, it is robustly "
593
+ "downloaded first, then applied model-only."
594
+ )
595
+ OUTPUT_TOOLTIPS = (
596
+ "model_in with the LoRA applied.",
597
+ )
598
+
599
+ def __init__(self):
600
+ self.loaded_lora = None
601
+
602
+ @classmethod
603
+ def INPUT_TYPES(cls):
604
+ return {
605
+ "required": {
606
+ "filename": (
607
+ "STRING",
608
+ {
609
+ "default": "",
610
+ "multiline": False,
611
+ "placeholder": "Fade_to_Black",
612
+ "tooltip": "LoRA name without .safetensors",
613
+ },
614
+ ),
615
+ "model_in": (
616
+ "MODEL",
617
+ {"tooltip": "The MODEL input that will receive the LoRA."},
618
+ ),
619
+ "strength": (
620
+ "FLOAT",
621
+ {
622
+ "default": 1.0,
623
+ "min": -100.0,
624
+ "max": 100.0,
625
+ "step": 0.01,
626
+ "tooltip": "Strength used when applying the LoRA.",
627
+ },
628
+ ),
629
+ },
630
+ "hidden": {"unique_id": "UNIQUE_ID"},
631
+ }
632
+
633
+ @staticmethod
634
+ def _normalize_lora_name(name: str) -> str:
635
+ base = str(name or "").strip().replace("\\", "/").rsplit("/", 1)[-1]
636
+ if base.lower().endswith(".safetensors"):
637
+ base = base[:-len(".safetensors")]
638
+ base = base.strip()
639
+ if not base or base in {".", ".."} or "\x00" in base:
640
+ raise ValueError("filename resolves to an empty or invalid name.")
641
+ return f"{base}.safetensors"
642
+
643
+
644
+ @classmethod
645
+ def _ensure_lora_available(cls, lora_name: str, reporter=None) -> str:
646
+ return _ensure_loras_available(
647
+ (lora_name,), reporter if reporter is not None else _RealtimeProgress(),
648
+ )[0]
649
+
650
+ def _get_or_load_lora(self, lora_path: str):
651
+ if self.loaded_lora is not None and self.loaded_lora[0] == lora_path:
652
+ return self.loaded_lora[1]
653
+
654
+ lora = comfy.utils.load_torch_file(lora_path, safe_load=True)
655
+ self.loaded_lora = (lora_path, lora)
656
+ return lora
657
+
658
+ def _apply_lora_model_only(self, model, lora_path: str, strength: float):
659
+ if strength == 0:
660
+ return model
661
+
662
+ lora = self._get_or_load_lora(lora_path)
663
+ model_lora, _ = comfy.sd.load_lora_for_models(model, None, lora, strength, 0)
664
+ return model_lora
665
+
666
+ def load_lora(self, filename, model_in, strength, unique_id=None):
667
+ reporter = _RealtimeProgress(unique_id)
668
+ lora_name = self._normalize_lora_name(filename)
669
+ lora_path = self._ensure_lora_available(lora_name, reporter)
670
+ reporter.stage(920, f"Applying LoRA: {lora_name} (strength={strength}).")
671
+ loaded_model = self._apply_lora_model_only(model_in, lora_path, strength)
672
+ reporter.stage(1000, "LoRA ready.")
673
+ return (loaded_model,)
674
+
675
+
676
+ NODE_CLASS_MAPPINGS = {
677
+ "Salia_Load_Lora_X": Salia_Load_Lora_X,
678
+ }
679
+
680
+
681
+ NODE_DISPLAY_NAME_MAPPINGS = {
682
+ "Salia_Load_Lora_X": "Salia LoRA Loader X (1)",
683
+ }