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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone Salia_WanFirstLast_Easy custom node for ComfyUI.
2
+
3
+ Install this single file in ComfyUI/custom_nodes/ and restart ComfyUI.
4
+ Neither of the original Salia custom-node files is required.
5
+
6
+ Image rules (ComfyUI IMAGE layout is [batch, height, width, channels]):
7
+ - One image: round each dimension UP to a multiple of 16, using transparent
8
+ canvas padding, never scaling. Already aligned RGB passes through unchanged.
9
+ - Two RGBA images: pad both to ceil16(max(widths)) x ceil16(max(heights)).
10
+ - Two images with either RGB: Lanczos-resize both to that same common size.
11
+ - Composite all RGBA images, including padded RGB images, onto gradientbg.png.
12
+ - Width padding is left/right, height padding is top/bottom. Odd extra pixels
13
+ always go to the left or top. Foreground alpha is preserved until compositing.
14
+
15
+ Inputs/outputs match Salia_WanFirstLastFrameToVideo except width and height
16
+ are inferred. start_image/end_image remain optional sockets for compatibility,
17
+ but at least one must be connected. An end-only input supplies the size too.
18
+ RGBA means an actual four-channel IMAGE tensor; a separate MASK is not read.
19
+
20
+ The fixed WAN VAE downloader and ComfyUI core wrapper are embedded from the
21
+ supplied Salia_Wan_VAE_DECODE source. Existing Salia WAN nodes share the same
22
+ process-wide VAE cache, but this file does not import either custom node.
23
+ The gradient is downloaded on first use and cached next to this file.
24
+ """
25
+
26
+ import importlib
27
+ import importlib.metadata
28
+ import importlib.util
29
+ import json
30
+ import logging
31
+ import os
32
+ from pathlib import Path
33
+ import re
34
+ import shutil
35
+ import struct
36
+ import subprocess
37
+ import sys
38
+ import tempfile
39
+ import threading
40
+ import time
41
+ import urllib.request
42
+
43
+ import numpy as np
44
+ from PIL import Image
45
+ import torch
46
+
47
+ import comfy.utils
48
+ import folder_paths
49
+ import nodes
50
+
51
+
52
+ LOG = logging.getLogger("Salia_Wan_VAE")
53
+
54
+ HF_REPO_ID = "saliacoel/x"
55
+ HF_REVISION = "main"
56
+ VAE_FILENAME = "wan_2.1_vae.safetensors"
57
+ MIN_HF_HUB_VERSION = (0, 32, 0)
58
+ MAX_DOWNLOAD_ATTEMPTS = 3
59
+ _SHARED_STATE_ATTRIBUTE = "_salia_wan_vae_shared_state_v1"
60
+
61
+ # Avoid indefinitely stalled Hugging Face network reads while respecting any
62
+ # values the user already configured before ComfyUI started.
63
+ os.environ.setdefault("HF_HUB_DOWNLOAD_TIMEOUT", "60")
64
+ os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "30")
65
+
66
+
67
+ def _version_tuple(version_string):
68
+ numbers = re.findall(r"\d+", str(version_string))
69
+ numbers = [int(value) for value in numbers[:3]]
70
+ while len(numbers) < 3:
71
+ numbers.append(0)
72
+ return tuple(numbers)
73
+
74
+
75
+ def _pip_install(*packages):
76
+ command = [sys.executable, "-m", "pip", "install", "-U", *packages]
77
+ LOG.info("[DEPENDENCY] Running: %s", " ".join(command))
78
+ subprocess.check_call(command)
79
+ importlib.invalidate_caches()
80
+
81
+
82
+ def _environment_flag_true(name):
83
+ value = os.environ.get(name)
84
+ if value is None:
85
+ return False
86
+ return str(value).strip().lower() in {"1", "true", "yes", "on"}
87
+
88
+
89
+ def _ensure_huggingface_stack():
90
+ """Ensure a Hugging Face Hub version with the modern hf_xet path."""
91
+ try:
92
+ installed_version = importlib.metadata.version("huggingface_hub")
93
+ except importlib.metadata.PackageNotFoundError:
94
+ installed_version = None
95
+
96
+ needs_install = (
97
+ installed_version is None
98
+ or _version_tuple(installed_version) < MIN_HF_HUB_VERSION
99
+ )
100
+
101
+ if needs_install:
102
+ # Replacing an already-imported package in a live Python process is not
103
+ # reliable. Upgrade it and require a restart in that special case.
104
+ if "huggingface_hub" in sys.modules:
105
+ loaded_version = getattr(
106
+ sys.modules["huggingface_hub"],
107
+ "__version__",
108
+ "unknown",
109
+ )
110
+ raise RuntimeError(
111
+ "huggingface_hub is already loaded in this ComfyUI process "
112
+ f"and is too old (loaded version: {loaded_version}). Run "
113
+ "`python -m pip install -U huggingface_hub hf_xet` and restart "
114
+ "ComfyUI."
115
+ )
116
+
117
+ LOG.info(
118
+ "[DEPENDENCY] Installing/upgrading huggingface_hub>=0.32.0."
119
+ )
120
+ _pip_install("huggingface_hub>=0.32.0")
121
+
122
+ xet_available = importlib.util.find_spec("hf_xet") is not None
123
+ if not xet_available:
124
+ try:
125
+ LOG.info("[DEPENDENCY] hf_xet not found; installing it.")
126
+ _pip_install("hf_xet")
127
+ xet_available = importlib.util.find_spec("hf_xet") is not None
128
+ except Exception as exc:
129
+ LOG.warning(
130
+ "[DEPENDENCY] Could not install hf_xet; Hugging Face Hub will "
131
+ "use its available fallback. Reason: %s",
132
+ exc,
133
+ )
134
+
135
+ from huggingface_hub import (
136
+ get_hf_file_metadata,
137
+ hf_hub_download,
138
+ hf_hub_url,
139
+ )
140
+ import huggingface_hub
141
+
142
+ if not _environment_flag_true("HF_HUB_DISABLE_PROGRESS_BARS"):
143
+ try:
144
+ from huggingface_hub.utils import enable_progress_bars
145
+
146
+ enable_progress_bars()
147
+ except Exception:
148
+ pass
149
+
150
+ return {
151
+ "hf_hub_download": hf_hub_download,
152
+ "hf_hub_url": hf_hub_url,
153
+ "get_hf_file_metadata": get_hf_file_metadata,
154
+ "hub_version": getattr(huggingface_hub, "__version__", "unknown"),
155
+ "backend_name": (
156
+ "hf_xet" if xet_available else "huggingface_hub fallback"
157
+ ),
158
+ }
159
+
160
+
161
+ class _RealtimeProgress:
162
+ """Native ComfyUI progress plus detailed terminal state messages."""
163
+
164
+ TOTAL = 1000
165
+
166
+ def __init__(self, unique_id=None):
167
+ self.unique_id = str(unique_id) if unique_id is not None else None
168
+ self.current = 0
169
+
170
+ try:
171
+ if self.unique_id is None:
172
+ self.progress_bar = comfy.utils.ProgressBar(self.TOTAL)
173
+ else:
174
+ self.progress_bar = comfy.utils.ProgressBar(
175
+ self.TOTAL,
176
+ node_id=self.unique_id,
177
+ )
178
+ except TypeError:
179
+ self.progress_bar = comfy.utils.ProgressBar(self.TOTAL)
180
+
181
+ def set_absolute(self, value):
182
+ value = max(0, min(self.TOTAL, int(value)))
183
+ if value < self.current:
184
+ return
185
+ self.current = value
186
+
187
+ try:
188
+ self.progress_bar.update_absolute(value, self.TOTAL)
189
+ except TypeError:
190
+ try:
191
+ self.progress_bar.update_absolute(value)
192
+ except Exception:
193
+ pass
194
+ except Exception:
195
+ pass
196
+
197
+ def stage(self, value, message):
198
+ self.set_absolute(value)
199
+ LOG.info("[STATE] %s", message)
200
+
201
+ def finish(self):
202
+ self.set_absolute(self.TOTAL)
203
+
204
+
205
+ def _format_bytes(value):
206
+ try:
207
+ value = float(value)
208
+ except Exception:
209
+ return str(value)
210
+
211
+ units = ["B", "KiB", "MiB", "GiB", "TiB"]
212
+ for unit in units:
213
+ if abs(value) < 1024.0 or unit == units[-1]:
214
+ return f"{value:.2f} {unit}"
215
+ value /= 1024.0
216
+ return f"{value:.2f} TiB"
217
+
218
+
219
+ def _vae_directory():
220
+ models_directory = getattr(folder_paths, "models_dir", None)
221
+ if models_directory:
222
+ directory = os.path.join(models_directory, "vae")
223
+ else:
224
+ directories = folder_paths.get_folder_paths("vae")
225
+ if not directories:
226
+ raise RuntimeError("No ComfyUI VAE folder is configured.")
227
+ directory = directories[0]
228
+
229
+ os.makedirs(directory, exist_ok=True)
230
+ return directory
231
+
232
+
233
+ def _vae_destination_path():
234
+ return os.path.join(_vae_directory(), VAE_FILENAME)
235
+
236
+
237
+ def _existing_vae_path():
238
+ direct_path = _vae_destination_path()
239
+ if os.path.isfile(direct_path):
240
+ return direct_path
241
+
242
+ try:
243
+ configured_path = folder_paths.get_full_path("vae", VAE_FILENAME)
244
+ except Exception:
245
+ configured_path = None
246
+
247
+ if configured_path and os.path.isfile(configured_path):
248
+ return configured_path
249
+ return None
250
+
251
+
252
+ def _hf_cache_directory():
253
+ models_directory = getattr(folder_paths, "models_dir", None)
254
+ if not models_directory:
255
+ return None
256
+
257
+ directory = os.path.join(
258
+ models_directory,
259
+ ".cache",
260
+ "huggingface",
261
+ "hub",
262
+ )
263
+ os.makedirs(directory, exist_ok=True)
264
+ return directory
265
+
266
+
267
+ def _validate_safetensors_file(path):
268
+ """Reject truncated or structurally incomplete safetensors files."""
269
+ path = os.path.realpath(path)
270
+ if not os.path.isfile(path):
271
+ return False, f"File does not exist: {path}"
272
+
273
+ file_size = os.path.getsize(path)
274
+ if file_size < 8:
275
+ return False, f"File is too small to be safetensors: {file_size} bytes"
276
+
277
+ try:
278
+ with open(path, "rb") as handle:
279
+ raw_header_length = handle.read(8)
280
+ if len(raw_header_length) != 8:
281
+ return False, "Could not read the safetensors header length."
282
+
283
+ header_length = struct.unpack("<Q", raw_header_length)[0]
284
+ if header_length <= 1:
285
+ return False, (
286
+ f"Invalid safetensors header length: {header_length}"
287
+ )
288
+
289
+ data_start = 8 + header_length
290
+ if data_start > file_size:
291
+ return False, (
292
+ "Incomplete safetensors header: "
293
+ f"header ends at {data_start}, file size is {file_size}."
294
+ )
295
+
296
+ header_bytes = handle.read(header_length)
297
+ if len(header_bytes) != header_length:
298
+ return False, (
299
+ "Incomplete safetensors header: expected "
300
+ f"{header_length} bytes, read {len(header_bytes)}."
301
+ )
302
+
303
+ try:
304
+ header = json.loads(header_bytes.decode("utf-8"))
305
+ except Exception as exc:
306
+ return False, f"Invalid safetensors JSON header: {exc}"
307
+
308
+ if not isinstance(header, dict):
309
+ return False, "Safetensors header is not a JSON object."
310
+
311
+ data_region_size = file_size - data_start
312
+ intervals = []
313
+
314
+ for tensor_name, tensor_info in header.items():
315
+ if tensor_name == "__metadata__":
316
+ continue
317
+ if not isinstance(tensor_info, dict):
318
+ return False, f"Invalid tensor entry for '{tensor_name}'."
319
+
320
+ offsets = tensor_info.get("data_offsets")
321
+ if (
322
+ not isinstance(offsets, list)
323
+ or len(offsets) != 2
324
+ or not all(isinstance(value, int) for value in offsets)
325
+ ):
326
+ return False, (
327
+ f"Invalid data_offsets for tensor '{tensor_name}'."
328
+ )
329
+
330
+ start, end = offsets
331
+ if start < 0 or end < start:
332
+ return False, (
333
+ f"Invalid tensor offsets for '{tensor_name}': {offsets}"
334
+ )
335
+ if end > data_region_size:
336
+ return False, (
337
+ f"Tensor '{tensor_name}' ends at {end}, but the data "
338
+ f"region is only {data_region_size} bytes."
339
+ )
340
+ intervals.append((start, end, tensor_name))
341
+
342
+ if not intervals:
343
+ return False, "Safetensors file contains no tensor entries."
344
+
345
+ intervals.sort(key=lambda item: (item[0], item[1]))
346
+ expected_start = 0
347
+ for start, end, tensor_name in intervals:
348
+ if start != expected_start:
349
+ if start < expected_start:
350
+ return False, (
351
+ f"Tensor data overlaps before '{tensor_name}': "
352
+ f"expected {expected_start}, got {start}."
353
+ )
354
+ return False, (
355
+ f"Tensor data has a gap before '{tensor_name}': expected "
356
+ f"{expected_start}, got {start}."
357
+ )
358
+ expected_start = end
359
+
360
+ if expected_start != data_region_size:
361
+ return False, (
362
+ "Safetensors tensor data does not fully cover the file: "
363
+ f"covered={expected_start}, data region={data_region_size}."
364
+ )
365
+
366
+ return True, (
367
+ f"valid safetensors | size={_format_bytes(file_size)} | "
368
+ f"header={_format_bytes(header_length)} | tensors={len(intervals)}"
369
+ )
370
+ except Exception as exc:
371
+ return False, f"Safetensors validation failed: {exc}"
372
+
373
+
374
+ def _remote_file_size(stack):
375
+ """Best-effort size lookup used as an extra completeness check."""
376
+ try:
377
+ url = stack["hf_hub_url"](
378
+ repo_id=HF_REPO_ID,
379
+ filename=VAE_FILENAME,
380
+ repo_type="model",
381
+ revision=HF_REVISION,
382
+ )
383
+ metadata = stack["get_hf_file_metadata"](url, timeout=30)
384
+ size = getattr(metadata, "size", None)
385
+ if isinstance(size, int) and size > 0:
386
+ LOG.info("[REMOTE] VAE size: %s", _format_bytes(size))
387
+ return size
388
+ except Exception as exc:
389
+ LOG.warning("[REMOTE] Could not pre-read VAE size: %s", exc)
390
+ return None
391
+
392
+
393
+ def _validate_download(path, remote_size=None):
394
+ path = os.path.realpath(path)
395
+ if not os.path.isfile(path):
396
+ return False, f"Downloaded path does not exist: {path}"
397
+
398
+ local_size = os.path.getsize(path)
399
+ if remote_size is not None and local_size != remote_size:
400
+ return False, (
401
+ "Downloaded size does not match Hugging Face metadata: "
402
+ f"local={local_size}, remote={remote_size}."
403
+ )
404
+ return _validate_safetensors_file(path)
405
+
406
+
407
+ def _fsync_directory(directory):
408
+ try:
409
+ descriptor = os.open(directory, os.O_RDONLY)
410
+ except Exception:
411
+ return
412
+
413
+ try:
414
+ os.fsync(descriptor)
415
+ except Exception:
416
+ pass
417
+ finally:
418
+ os.close(descriptor)
419
+
420
+
421
+ def _atomic_install(cached_path, final_path, remote_size=None):
422
+ """Validate, copy, fsync, revalidate, and atomically install the VAE."""
423
+ source_path = os.path.realpath(os.fspath(cached_path))
424
+ final_path = os.fspath(final_path)
425
+
426
+ valid, reason = _validate_download(source_path, remote_size)
427
+ if not valid:
428
+ raise RuntimeError(
429
+ f"Downloaded WAN VAE failed validation before install: {reason}"
430
+ )
431
+
432
+ final_directory = os.path.dirname(final_path)
433
+ os.makedirs(final_directory, exist_ok=True)
434
+ temporary_path = (
435
+ final_path
436
+ + f".salia-install-{os.getpid()}-{int(time.time() * 1000)}.tmp"
437
+ )
438
+
439
+ try:
440
+ with open(source_path, "rb") as source, open(
441
+ temporary_path,
442
+ "wb",
443
+ ) as destination:
444
+ shutil.copyfileobj(
445
+ source,
446
+ destination,
447
+ length=16 * 1024 * 1024,
448
+ )
449
+ destination.flush()
450
+ os.fsync(destination.fileno())
451
+
452
+ if os.path.getsize(temporary_path) != os.path.getsize(source_path):
453
+ raise RuntimeError("Temporary WAN VAE copy has the wrong size.")
454
+
455
+ valid, reason = _validate_download(temporary_path, remote_size)
456
+ if not valid:
457
+ raise RuntimeError(
458
+ f"Temporary WAN VAE failed validation: {reason}"
459
+ )
460
+
461
+ os.replace(temporary_path, final_path)
462
+ _fsync_directory(final_directory)
463
+
464
+ valid, reason = _validate_download(final_path, remote_size)
465
+ if not valid:
466
+ raise RuntimeError(
467
+ f"Installed WAN VAE failed final validation: {reason}"
468
+ )
469
+ return reason
470
+ finally:
471
+ try:
472
+ if os.path.exists(temporary_path):
473
+ os.remove(temporary_path)
474
+ except Exception:
475
+ pass
476
+
477
+
478
+ def _download_missing_vae(reporter):
479
+ """Download the fixed VAE through HF cache and install it atomically."""
480
+ stack = _ensure_huggingface_stack()
481
+ remote_size = _remote_file_size(stack)
482
+ last_error = None
483
+ cached_path = None
484
+
485
+ reporter.stage(
486
+ 60,
487
+ (
488
+ "WAN VAE downloader ready: "
489
+ f"huggingface_hub={stack['hub_version']}, "
490
+ f"backend={stack['backend_name']}"
491
+ ),
492
+ )
493
+
494
+ for attempt in range(1, MAX_DOWNLOAD_ATTEMPTS + 1):
495
+ force_download = attempt > 1
496
+ reporter.stage(
497
+ 100,
498
+ (
499
+ f"Downloading {HF_REPO_ID}/{VAE_FILENAME} "
500
+ f"(attempt {attempt}/{MAX_DOWNLOAD_ATTEMPTS}, "
501
+ f"force_download={force_download}). Hugging Face native "
502
+ "progress follows in the terminal."
503
+ ),
504
+ )
505
+
506
+ try:
507
+ cached_path = stack["hf_hub_download"](
508
+ repo_id=HF_REPO_ID,
509
+ filename=VAE_FILENAME,
510
+ repo_type="model",
511
+ revision=HF_REVISION,
512
+ cache_dir=_hf_cache_directory(),
513
+ force_download=force_download,
514
+ etag_timeout=30,
515
+ )
516
+
517
+ valid, reason = _validate_download(cached_path, remote_size)
518
+ if not valid:
519
+ raise RuntimeError(
520
+ f"Hugging Face returned an invalid WAN VAE: {reason}"
521
+ )
522
+
523
+ reporter.stage(850, f"WAN VAE download validated: {reason}")
524
+ last_error = None
525
+ break
526
+ except Exception as exc:
527
+ last_error = exc
528
+ LOG.exception(
529
+ "[DOWNLOAD] Attempt %d/%d failed for %s",
530
+ attempt,
531
+ MAX_DOWNLOAD_ATTEMPTS,
532
+ VAE_FILENAME,
533
+ )
534
+ if attempt >= MAX_DOWNLOAD_ATTEMPTS:
535
+ break
536
+
537
+ retry_delay = min(2 ** attempt, 8)
538
+ reporter.stage(
539
+ 100,
540
+ (
541
+ f"Attempt {attempt} failed: {exc}. Retrying in "
542
+ f"{retry_delay}s with a forced fresh transfer."
543
+ ),
544
+ )
545
+ time.sleep(retry_delay)
546
+
547
+ if last_error is not None or cached_path is None:
548
+ raise RuntimeError(
549
+ f"Failed to download {VAE_FILENAME} from "
550
+ f"https://huggingface.co/{HF_REPO_ID} after "
551
+ f"{MAX_DOWNLOAD_ATTEMPTS} attempts. Last error: {last_error}"
552
+ ) from last_error
553
+
554
+ destination_path = _vae_destination_path()
555
+ reporter.stage(880, "Installing the validated WAN VAE atomically.")
556
+ validation_summary = _atomic_install(
557
+ cached_path,
558
+ destination_path,
559
+ remote_size=remote_size,
560
+ )
561
+ reporter.stage(
562
+ 910,
563
+ f"WAN VAE installed: {destination_path} | {validation_summary}",
564
+ )
565
+ return destination_path
566
+
567
+
568
+ def _shared_state():
569
+ state = getattr(nodes, _SHARED_STATE_ATTRIBUTE, None)
570
+ if not isinstance(state, dict) or "lock" not in state:
571
+ state = {
572
+ "lock": threading.RLock(),
573
+ "vae": None,
574
+ "path": None,
575
+ }
576
+ setattr(nodes, _SHARED_STATE_ATTRIBUTE, state)
577
+ return state
578
+
579
+
580
+ def _unwrap_single_output(result, operation_name):
581
+ if hasattr(result, "result"):
582
+ result = result.result
583
+ elif isinstance(result, dict) and "result" in result:
584
+ result = result["result"]
585
+
586
+ if not isinstance(result, (tuple, list)) or len(result) < 1:
587
+ raise RuntimeError(
588
+ f"Core {operation_name} returned an unexpected result: "
589
+ f"{type(result).__name__}"
590
+ )
591
+ return result[0]
592
+
593
+
594
+ def _get_shared_wan_vae(reporter):
595
+ """Ensure the file exists, then return one shared core VAELoader result."""
596
+ state = _shared_state()
597
+
598
+ # One lock covers existence check, download, and load. Concurrent executions
599
+ # therefore cannot download or deserialize a second copy.
600
+ with state["lock"]:
601
+ vae_path = _existing_vae_path()
602
+ if vae_path is None:
603
+ reporter.stage(
604
+ 10,
605
+ f"{VAE_FILENAME} is missing from the VAE directory.",
606
+ )
607
+ vae_path = _download_missing_vae(reporter)
608
+ else:
609
+ reporter.stage(
610
+ 100,
611
+ f"WAN VAE already exists; download skipped: {vae_path}",
612
+ )
613
+
614
+ if state["vae"] is None:
615
+ reporter.stage(
616
+ 930,
617
+ "Loading WAN VAE once through ComfyUI core VAELoader.",
618
+ )
619
+ core_result = nodes.VAELoader().load_vae(VAE_FILENAME)
620
+ state["vae"] = _unwrap_single_output(
621
+ core_result,
622
+ "VAELoader",
623
+ )
624
+ state["path"] = os.path.realpath(vae_path)
625
+ LOG.info(
626
+ "[VAE] Shared WAN VAE object created once: %s",
627
+ state["path"],
628
+ )
629
+ else:
630
+ reporter.stage(
631
+ 930,
632
+ "Reusing the already-loaded shared WAN VAE object.",
633
+ )
634
+
635
+ return state["vae"]
636
+
637
+
638
+ def _vae_presence_fingerprint():
639
+ """Make file deletion invalidate a cached node result."""
640
+ return (
641
+ f"present:{VAE_FILENAME}"
642
+ if _existing_vae_path() is not None
643
+ else f"missing:{VAE_FILENAME}"
644
+ )
645
+
646
+
647
+ def _unwrap_three_outputs(result, operation_name):
648
+ if hasattr(result, "result"):
649
+ result = result.result
650
+ elif isinstance(result, dict) and "result" in result:
651
+ result = result["result"]
652
+
653
+ if not isinstance(result, (tuple, list)) or len(result) != 3:
654
+ raise RuntimeError(
655
+ f"Core {operation_name} returned an unexpected result."
656
+ )
657
+ return tuple(result)
658
+
659
+
660
+ def _run_core_wan_first_last_frame(
661
+ *,
662
+ positive,
663
+ negative,
664
+ vae,
665
+ width,
666
+ height,
667
+ length,
668
+ batch_size,
669
+ clip_vision_start_image=None,
670
+ clip_vision_end_image=None,
671
+ start_image=None,
672
+ end_image=None,
673
+ ):
674
+ core_class = nodes.NODE_CLASS_MAPPINGS.get("WanFirstLastFrameToVideo")
675
+ if core_class is None:
676
+ raise RuntimeError(
677
+ "ComfyUI core node 'WanFirstLastFrameToVideo' is unavailable. "
678
+ "Update ComfyUI and restart it."
679
+ )
680
+
681
+ arguments = {
682
+ "positive": positive,
683
+ "negative": negative,
684
+ "vae": vae,
685
+ "width": width,
686
+ "height": height,
687
+ "length": length,
688
+ "batch_size": batch_size,
689
+ "clip_vision_start_image": clip_vision_start_image,
690
+ "clip_vision_end_image": clip_vision_end_image,
691
+ "start_image": start_image,
692
+ "end_image": end_image,
693
+ }
694
+
695
+ # Current ComfyUI exposes this core node through the V3 `execute`
696
+ # classmethod. The fallback also supports older V1-style registrations.
697
+ execute = getattr(core_class, "execute", None)
698
+ if callable(execute):
699
+ result = execute(**arguments)
700
+ else:
701
+ core_instance = core_class()
702
+ function_name = getattr(core_class, "FUNCTION", None)
703
+ if not function_name:
704
+ raise RuntimeError(
705
+ "Core WanFirstLastFrameToVideo has no executable function."
706
+ )
707
+ result = getattr(core_instance, function_name)(**arguments)
708
+
709
+ return _unwrap_three_outputs(result, "WanFirstLastFrameToVideo")
710
+
711
+
712
+ class Salia_WanFirstLast_Easy:
713
+ """Automatic image sizing/compositing plus the original WAN operation."""
714
+
715
+ CATEGORY = "loaders/saliacoel"
716
+ FUNCTION = "encode"
717
+ RETURN_TYPES = ("CONDITIONING", "CONDITIONING", "LATENT")
718
+ RETURN_NAMES = ("positive", "negative", "latent")
719
+ DESCRIPTION = (
720
+ "WAN first/last frame conditioning with an internal shared WAN VAE. "
721
+ "Automatically rounds dimensions up to multiples of 16. A single "
722
+ "image or two RGBA images use transparent canvas padding; two images "
723
+ "with either RGB use Lanczos resizing. RGBA is composited onto the "
724
+ "cached gradient background. At least one image must be connected."
725
+ )
726
+ GRADIENT_URL = (
727
+ "https://huggingface.co/saliacoel/x/resolve/main/gradientbg.png"
728
+ )
729
+ _gradient_download_lock = threading.RLock()
730
+
731
+ def __init__(self):
732
+ self.cache_dir = Path(__file__).resolve().parent / "cache"
733
+ self.cache_path = self.cache_dir / "gradientbg.png"
734
+
735
+ @classmethod
736
+ def INPUT_TYPES(cls):
737
+ maximum_resolution = getattr(nodes, "MAX_RESOLUTION", 16384)
738
+ return {
739
+ "required": {
740
+ "positive": ("CONDITIONING",),
741
+ "negative": ("CONDITIONING",),
742
+ "length": (
743
+ "INT",
744
+ {
745
+ "default": 81,
746
+ "min": 1,
747
+ "max": maximum_resolution,
748
+ "step": 4,
749
+ },
750
+ ),
751
+ },
752
+ "optional": {
753
+ "start_image": ("IMAGE",),
754
+ "end_image": ("IMAGE",),
755
+ },
756
+ "hidden": {"unique_id": "UNIQUE_ID"},
757
+ }
758
+
759
+ @classmethod
760
+ def IS_CHANGED(cls, **kwargs):
761
+ return _vae_presence_fingerprint()
762
+
763
+ @staticmethod
764
+ def _validate_image(image, name):
765
+ if not isinstance(image, torch.Tensor):
766
+ raise TypeError(f"{name} must be a ComfyUI IMAGE tensor.")
767
+ if image.ndim != 4:
768
+ raise ValueError(
769
+ f"{name} must have shape [batch, height, width, channels]; "
770
+ f"received {tuple(image.shape)}."
771
+ )
772
+ batch, height, width, channels = image.shape
773
+ if batch < 1 or height < 1 or width < 1:
774
+ raise ValueError(f"{name} has an empty dimension: {tuple(image.shape)}.")
775
+ if channels not in (3, 4):
776
+ raise ValueError(
777
+ f"{name} must be RGB (3 channels) or RGBA (4 channels); "
778
+ f"received {channels} channels."
779
+ )
780
+
781
+ @staticmethod
782
+ def _next_multiple_of_16(value):
783
+ return max(16, ((int(value) + 15) // 16) * 16)
784
+
785
+ def _ensure_gradient_cached(self):
786
+ """Use the source node's cache; download atomically if missing/broken."""
787
+ with self._gradient_download_lock:
788
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
789
+ if self.cache_path.is_file() and self.cache_path.stat().st_size > 0:
790
+ try:
791
+ with Image.open(self.cache_path) as cached:
792
+ cached.verify()
793
+ return self.cache_path
794
+ except (OSError, ValueError, SyntaxError):
795
+ LOG.warning("[GRADIENT] Invalid cache; downloading a new copy.")
796
+
797
+ temporary_path = None
798
+ try:
799
+ LOG.info("[GRADIENT] Downloading %s", self.GRADIENT_URL)
800
+ request = urllib.request.Request(
801
+ self.GRADIENT_URL,
802
+ headers={"User-Agent": "ComfyUI-Salia-GradientBG/1.0"},
803
+ )
804
+ with urllib.request.urlopen(request, timeout=60) as response:
805
+ with tempfile.NamedTemporaryFile(
806
+ mode="wb",
807
+ prefix="gradientbg-",
808
+ suffix=".png.tmp",
809
+ dir=str(self.cache_dir),
810
+ delete=False,
811
+ ) as destination:
812
+ temporary_path = Path(destination.name)
813
+ shutil.copyfileobj(response, destination, length=1024 * 1024)
814
+
815
+ with Image.open(temporary_path) as downloaded:
816
+ downloaded.verify()
817
+ os.replace(temporary_path, self.cache_path)
818
+ LOG.info("[GRADIENT] Cached at %s", self.cache_path)
819
+ except Exception as exc:
820
+ raise RuntimeError(
821
+ "Could not load the gradient background. Check the connection "
822
+ f"to {self.GRADIENT_URL}, or place gradientbg.png in "
823
+ f"{self.cache_dir}. Details: {exc}"
824
+ ) from exc
825
+ finally:
826
+ if temporary_path is not None:
827
+ try:
828
+ temporary_path.unlink(missing_ok=True)
829
+ except OSError:
830
+ pass
831
+ return self.cache_path
832
+
833
+ def _load_gradient(self, width, height):
834
+ gradient_path = self._ensure_gradient_cached()
835
+ with Image.open(gradient_path) as source:
836
+ return source.convert("RGBA").resize(
837
+ (width, height), resample=Image.Resampling.LANCZOS
838
+ )
839
+
840
+ @staticmethod
841
+ def _tensor_to_pil(image):
842
+ """Match the attached gradient node's 8-bit Pillow conversion."""
843
+ array = (
844
+ image.detach().cpu().float().clamp(0.0, 1.0).numpy() * 255.0
845
+ ).round().astype(np.uint8)
846
+ return Image.fromarray(array)
847
+
848
+ @staticmethod
849
+ def _pil_rgb_to_tensor(image):
850
+ array = np.array(image.convert("RGB"), dtype=np.float32) / 255.0
851
+ return torch.from_numpy(array)
852
+
853
+ @staticmethod
854
+ def _pad_rgba(foreground, target_width, target_height):
855
+ """Expand only the canvas; never resize/crop the foreground pixels."""
856
+ foreground = foreground.convert("RGBA")
857
+ extra_width = target_width - foreground.width
858
+ extra_height = target_height - foreground.height
859
+ if extra_width < 0 or extra_height < 0:
860
+ raise ValueError("The target canvas must not be smaller than the image.")
861
+ if extra_width == 0 and extra_height == 0:
862
+ return foreground
863
+
864
+ left = (extra_width + 1) // 2
865
+ top = (extra_height + 1) // 2
866
+ canvas = Image.new("RGBA", (target_width, target_height), (0, 0, 0, 0))
867
+ # No paste mask: copy all four channels unchanged, including alpha.
868
+ canvas.paste(foreground, (left, top))
869
+ return canvas
870
+
871
+ def _resize_or_pad_batch(self, image, width, height, use_padding, gradient):
872
+ if image is None:
873
+ return None
874
+
875
+ already_fits = image.shape[2] == width and image.shape[1] == height
876
+ is_rgba = image.shape[-1] == 4
877
+ if already_fits and not is_rgba:
878
+ # Do not quantize or download a gradient for unchanged RGB images.
879
+ return image
880
+
881
+ needs_gradient = is_rgba or use_padding
882
+ if needs_gradient and gradient is None:
883
+ raise RuntimeError("A gradient background is required for RGBA images.")
884
+
885
+ output_images = []
886
+ for batch_index in range(image.shape[0]):
887
+ foreground = self._tensor_to_pil(image[batch_index])
888
+ if use_padding:
889
+ foreground = self._pad_rgba(foreground, width, height)
890
+ elif not already_fits:
891
+ # Both target dimensions are independent: intentionally stretch
892
+ # to the exact shared size, without cropping or letterboxing.
893
+ # Pillow handles RGBA Lanczos in premultiplied-alpha space.
894
+ foreground = foreground.resize(
895
+ (width, height), resample=Image.Resampling.LANCZOS
896
+ )
897
+
898
+ if needs_gradient:
899
+ foreground = Image.alpha_composite(
900
+ gradient, foreground.convert("RGBA")
901
+ )
902
+ output_images.append(self._pil_rgb_to_tensor(foreground))
903
+
904
+ return torch.stack(output_images, dim=0).to(
905
+ device=image.device, dtype=torch.float32
906
+ )
907
+
908
+ def _prepare_images(self, start_image=None, end_image=None):
909
+ supplied = [
910
+ (name, image)
911
+ for name, image in (("start_image", start_image), ("end_image", end_image))
912
+ if image is not None
913
+ ]
914
+ if not supplied:
915
+ raise ValueError(
916
+ "Salia_WanFirstLast_Easy needs start_image or end_image "
917
+ "to determine width and height."
918
+ )
919
+ for name, image in supplied:
920
+ self._validate_image(image, name)
921
+
922
+ width = self._next_multiple_of_16(max(image.shape[2] for _, image in supplied))
923
+ height = self._next_multiple_of_16(max(image.shape[1] for _, image in supplied))
924
+
925
+ # Decide using ORIGINAL channel counts, before converting any RGB input.
926
+ both_rgba = len(supplied) == 2 and all(
927
+ image.shape[-1] == 4 for _, image in supplied
928
+ )
929
+ use_padding = len(supplied) == 1 or both_rgba
930
+ needs_gradient = any(
931
+ image.shape[-1] == 4
932
+ or (use_padding and (image.shape[2] != width or image.shape[1] != height))
933
+ for _, image in supplied
934
+ )
935
+ gradient = self._load_gradient(width, height) if needs_gradient else None
936
+
937
+ for name, image in supplied:
938
+ source_height, source_width = image.shape[1:3]
939
+ if source_width == width and source_height == height:
940
+ operation = "size unchanged"
941
+ elif use_padding:
942
+ extra_width = width - source_width
943
+ extra_height = height - source_height
944
+ operation = (
945
+ f"canvas padding: left={(extra_width + 1) // 2}, "
946
+ f"right={extra_width // 2}, top={(extra_height + 1) // 2}, "
947
+ f"bottom={extra_height // 2}"
948
+ )
949
+ else:
950
+ operation = "Lanczos resize"
951
+ LOG.info(
952
+ "[Salia_WanFirstLast_Easy] %s: %sx%s -> %sx%s; %s",
953
+ name, source_width, source_height, width, height, operation,
954
+ )
955
+
956
+ start_rgb = self._resize_or_pad_batch(
957
+ start_image, width, height, use_padding, gradient
958
+ )
959
+ end_rgb = self._resize_or_pad_batch(
960
+ end_image, width, height, use_padding, gradient
961
+ )
962
+ return start_rgb, end_rgb, width, height
963
+
964
+ def encode(
965
+ self,
966
+ positive,
967
+ negative,
968
+ length,
969
+ start_image=None,
970
+ end_image=None,
971
+ unique_id=None,
972
+ ):
973
+ # Validate and prepare before downloading/loading a potentially large VAE.
974
+ start_rgb, end_rgb, width, height = self._prepare_images(start_image, end_image)
975
+ reporter = _RealtimeProgress(unique_id)
976
+ vae = _get_shared_wan_vae(reporter)
977
+ reporter.stage(
978
+ 970,
979
+ f"Running ComfyUI core WanFirstLastFrameToVideo at {width}x{height}.",
980
+ )
981
+ result = _run_core_wan_first_last_frame(
982
+ positive=positive,
983
+ negative=negative,
984
+ vae=vae,
985
+ width=width,
986
+ height=height,
987
+ length=length,
988
+ batch_size=1,
989
+ start_image=start_rgb,
990
+ end_image=end_rgb,
991
+ )
992
+ reporter.finish()
993
+ return result
994
+
995
+
996
+ NODE_CLASS_MAPPINGS = {
997
+ "Salia_WanFirstLast_Easy": Salia_WanFirstLast_Easy,
998
+ }
999
+
1000
+ NODE_DISPLAY_NAME_MAPPINGS = {
1001
+ "Salia_WanFirstLast_Easy": "Salia_WanFirstLast_Easy",
1002
+ }