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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import itertools
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import psutil
|
| 7 |
+
|
| 8 |
+
# Constants (consistent with ComfyUI conventions)
|
| 9 |
+
BIGMAX = 2**32
|
| 10 |
+
DIMMAX = 16384
|
| 11 |
+
|
| 12 |
+
def strip_path(path):
|
| 13 |
+
return path.strip().strip('"').strip("'")
|
| 14 |
+
|
| 15 |
+
def validate_path(path, allow_none=False):
|
| 16 |
+
if allow_none and path is None:
|
| 17 |
+
return True
|
| 18 |
+
return os.path.isfile(path)
|
| 19 |
+
|
| 20 |
+
def target_size(width, height, force_size, downscale_ratio=8):
|
| 21 |
+
if force_size == "Disabled":
|
| 22 |
+
pass
|
| 23 |
+
elif force_size == "256x?":
|
| 24 |
+
height = int(height * 256 / width)
|
| 25 |
+
width = 256
|
| 26 |
+
elif force_size == "?x256":
|
| 27 |
+
width = int(width * 256 / height)
|
| 28 |
+
height = 256
|
| 29 |
+
elif force_size == "256x256":
|
| 30 |
+
width, height = 256, 256
|
| 31 |
+
elif force_size == "512x?":
|
| 32 |
+
height = int(height * 512 / width)
|
| 33 |
+
width = 512
|
| 34 |
+
elif force_size == "?x512":
|
| 35 |
+
width = int(width * 512 / height)
|
| 36 |
+
height = 512
|
| 37 |
+
elif force_size == "512x512":
|
| 38 |
+
width, height = 512, 512
|
| 39 |
+
width = int(width / downscale_ratio + 0.5) * downscale_ratio
|
| 40 |
+
height = int(height / downscale_ratio + 0.5) * downscale_ratio
|
| 41 |
+
return (width, height)
|
| 42 |
+
|
| 43 |
+
def webp_frame_generator(webp_path, force_rate, frame_load_cap, skip_first_frames, select_every_nth):
|
| 44 |
+
webp_path = strip_path(webp_path)
|
| 45 |
+
print(f"Attempting to load WebP animation: {webp_path}")
|
| 46 |
+
|
| 47 |
+
with Image.open(webp_path) as img:
|
| 48 |
+
if not img.format == "WEBP":
|
| 49 |
+
raise ValueError(f"File {webp_path} is not a WebP file.")
|
| 50 |
+
|
| 51 |
+
# Get metadata
|
| 52 |
+
width, height = img.size
|
| 53 |
+
total_frames = getattr(img, 'n_frames', 1)
|
| 54 |
+
duration = getattr(img, 'info', {}).get('duration', 100) / 1000 # Default to 100ms if no duration
|
| 55 |
+
fps = 1 / duration if duration > 0 else 10 # Default to 10 FPS if no duration
|
| 56 |
+
|
| 57 |
+
print(f"WebP metadata: FPS={fps}, Width={width}, Height={height}, Total Frames={total_frames}")
|
| 58 |
+
|
| 59 |
+
base_frame_time = 1 / fps if fps > 0 else 1
|
| 60 |
+
target_frame_time = base_frame_time if force_rate == 0 else 1 / force_rate
|
| 61 |
+
|
| 62 |
+
yield (width, height, fps, duration * total_frames, total_frames, target_frame_time)
|
| 63 |
+
|
| 64 |
+
frames_added = 0
|
| 65 |
+
frame_idx = 0
|
| 66 |
+
time_offset = 0
|
| 67 |
+
|
| 68 |
+
yieldable_frames = total_frames if force_rate == 0 else int(total_frames / fps * force_rate)
|
| 69 |
+
if frame_load_cap != 0:
|
| 70 |
+
yieldable_frames = min(frame_load_cap, yieldable_frames)
|
| 71 |
+
print(f"Expected yieldable frames: {yieldable_frames}")
|
| 72 |
+
|
| 73 |
+
while frame_idx < total_frames:
|
| 74 |
+
if time_offset < target_frame_time:
|
| 75 |
+
time_offset += base_frame_time
|
| 76 |
+
frame_idx += 1
|
| 77 |
+
continue
|
| 78 |
+
time_offset -= target_frame_time
|
| 79 |
+
|
| 80 |
+
if frame_idx < skip_first_frames:
|
| 81 |
+
frame_idx += 1
|
| 82 |
+
continue
|
| 83 |
+
|
| 84 |
+
if (frame_idx - skip_first_frames) % select_every_nth != 0:
|
| 85 |
+
frame_idx += 1
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
img.seek(frame_idx)
|
| 89 |
+
frame = img.copy().convert('RGB')
|
| 90 |
+
frame = np.array(frame, dtype=np.float32) / 255.0
|
| 91 |
+
yield frame
|
| 92 |
+
frames_added += 1
|
| 93 |
+
print(f"Frame {frames_added} added.")
|
| 94 |
+
|
| 95 |
+
frame_idx += 1
|
| 96 |
+
if frame_load_cap > 0 and frames_added >= frame_load_cap:
|
| 97 |
+
break
|
| 98 |
+
|
| 99 |
+
print(f"Total frames yielded: {frames_added}")
|
| 100 |
+
if frames_added == 0:
|
| 101 |
+
print("Warning: No frames were yielded from the WebP animation.")
|
| 102 |
+
|
| 103 |
+
def common_upscale(samples, width, height, upscale_method="lanczos", crop="center"):
|
| 104 |
+
s = samples.movedim(-1, 1) # Move channels to second dimension
|
| 105 |
+
s = torch.nn.functional.interpolate(s, size=(height, width), mode=upscale_method)
|
| 106 |
+
return s.movedim(1, -1) # Move channels back to last dimension
|
| 107 |
+
|
| 108 |
+
def load_webp_advanced(webp_path, force_rate, force_size, frame_load_cap, skip_first_frames, select_every_nth, memory_limit_mb=None):
|
| 109 |
+
gen = webp_frame_generator(webp_path, force_rate, frame_load_cap, skip_first_frames, select_every_nth)
|
| 110 |
+
metadata = next(gen)
|
| 111 |
+
width, height, fps, duration, total_frames, target_frame_time = metadata
|
| 112 |
+
print(f"Loaded metadata: {metadata}")
|
| 113 |
+
|
| 114 |
+
# Memory limit calculation
|
| 115 |
+
memory_limit = None
|
| 116 |
+
if memory_limit_mb is not None and memory_limit_mb > 0:
|
| 117 |
+
memory_limit = memory_limit_mb * (2 ** 20) # Convert MB to bytes
|
| 118 |
+
else:
|
| 119 |
+
try:
|
| 120 |
+
memory_limit = (psutil.virtual_memory().available + psutil.swap_memory().free) - (2 ** 27)
|
| 121 |
+
except:
|
| 122 |
+
print("Warning: Failed to calculate memory limit.")
|
| 123 |
+
|
| 124 |
+
if memory_limit is not None:
|
| 125 |
+
max_loadable_frames = int(memory_limit // (width * height * 3 * 4)) # 3 channels, 4 bytes per float32
|
| 126 |
+
gen = itertools.islice(gen, max_loadable_frames)
|
| 127 |
+
print(f"Applied memory limit: Max frames = {max_loadable_frames}")
|
| 128 |
+
|
| 129 |
+
# Handle resizing
|
| 130 |
+
downscale_ratio = 8
|
| 131 |
+
if force_size != "Disabled":
|
| 132 |
+
new_size = target_size(width, height, force_size, downscale_ratio)
|
| 133 |
+
if new_size[0] != width or new_size[1] != height:
|
| 134 |
+
def rescale(frame):
|
| 135 |
+
s = torch.from_numpy(np.array(frame, dtype=np.float32))
|
| 136 |
+
s = s.movedim(-1, 1) # (H, W, C) -> (C, H, W)
|
| 137 |
+
s = common_upscale(s.unsqueeze(0), new_size[0], new_size[1], "lanczos", "center").squeeze(0)
|
| 138 |
+
return s.movedim(1, -1).numpy() # (C, H, W) -> (H, W, C)
|
| 139 |
+
gen = map(rescale, gen)
|
| 140 |
+
print(f"Resizing frames to {new_size}")
|
| 141 |
+
else:
|
| 142 |
+
new_size = (width, height)
|
| 143 |
+
|
| 144 |
+
# Load frames into a tensor
|
| 145 |
+
images = torch.from_numpy(np.fromiter(gen, dtype=np.dtype((np.float32, (new_size[1], new_size[0], 3)))))
|
| 146 |
+
if len(images) == 0:
|
| 147 |
+
raise RuntimeError("No frames generated from the WebP animation.")
|
| 148 |
+
|
| 149 |
+
# Video info dictionary
|
| 150 |
+
video_info = {
|
| 151 |
+
"source_fps": fps,
|
| 152 |
+
"source_frame_count": total_frames,
|
| 153 |
+
"source_duration": duration,
|
| 154 |
+
"source_width": width,
|
| 155 |
+
"source_height": height,
|
| 156 |
+
"loaded_fps": 1 / (target_frame_time * select_every_nth),
|
| 157 |
+
"loaded_frame_count": len(images),
|
| 158 |
+
"loaded_duration": len(images) * target_frame_time * select_every_nth,
|
| 159 |
+
"loaded_width": new_size[0],
|
| 160 |
+
"loaded_height": new_size[1],
|
| 161 |
+
}
|
| 162 |
+
print(f"Loaded {len(images)} frames. Video info: {video_info}")
|
| 163 |
+
|
| 164 |
+
return (images, len(images), video_info)
|
| 165 |
+
|
| 166 |
+
class LoadWebPAnimationAdvanced:
|
| 167 |
+
@classmethod
|
| 168 |
+
def INPUT_TYPES(cls):
|
| 169 |
+
input_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "input")
|
| 170 |
+
files = [f for f in os.listdir(input_dir) if os.path.isfile(os.path.join(input_dir, f)) and f.lower().endswith('.webp')]
|
| 171 |
+
return {
|
| 172 |
+
"required": {
|
| 173 |
+
"webp_file": (sorted(files),),
|
| 174 |
+
"force_rate": ("INT", {"default": 0, "min": 0, "max": 60, "step": 1}),
|
| 175 |
+
"force_size": (["Disabled", "256x?", "?x256", "256x256", "512x?", "?x512", "512x512"],),
|
| 176 |
+
"frame_load_cap": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
|
| 177 |
+
"skip_first_frames": ("INT", {"default": 0, "min": 0, "max": BIGMAX, "step": 1}),
|
| 178 |
+
"select_every_nth": ("INT", {"default": 1, "min": 1, "max": BIGMAX, "step": 1}),
|
| 179 |
+
},
|
| 180 |
+
"optional": {
|
| 181 |
+
"memory_limit_mb": ("INT", {"default": 0, "min": 0, "max": 1024*1024, "step": 1}),
|
| 182 |
+
},
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
CATEGORY = "Image Helper"
|
| 186 |
+
RETURN_TYPES = ("IMAGE", "INT", "DICT")
|
| 187 |
+
RETURN_NAMES = ("IMAGE", "frame_count", "video_info")
|
| 188 |
+
FUNCTION = "load_webp"
|
| 189 |
+
|
| 190 |
+
def load_webp(self, webp_file, force_rate, force_size, frame_load_cap, skip_first_frames, select_every_nth, memory_limit_mb=None):
|
| 191 |
+
input_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "input")
|
| 192 |
+
webp_path = os.path.join(input_dir, strip_path(webp_file))
|
| 193 |
+
if not validate_path(webp_path):
|
| 194 |
+
raise ValueError(f"Invalid WebP file path: {webp_path}")
|
| 195 |
+
if not webp_path.lower().endswith('.webp'):
|
| 196 |
+
raise ValueError("This node only supports .webp files.")
|
| 197 |
+
|
| 198 |
+
return load_webp_advanced(
|
| 199 |
+
webp_path=webp_path,
|
| 200 |
+
force_rate=force_rate,
|
| 201 |
+
force_size=force_size,
|
| 202 |
+
frame_load_cap=frame_load_cap,
|
| 203 |
+
skip_first_frames=skip_first_frames,
|
| 204 |
+
select_every_nth=select_every_nth,
|
| 205 |
+
memory_limit_mb=memory_limit_mb
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
@classmethod
|
| 209 |
+
def IS_CHANGED(cls, webp_file, **kwargs):
|
| 210 |
+
input_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "input")
|
| 211 |
+
webp_path = os.path.join(input_dir, strip_path(webp_file))
|
| 212 |
+
return hash(str(webp_path) + str(os.path.getmtime(webp_path) if os.path.exists(webp_path) else 0))
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def VALIDATE_INPUTS(cls, webp_file, **kwargs):
|
| 216 |
+
input_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "input")
|
| 217 |
+
webp_path = os.path.join(input_dir, strip_path(webp_file))
|
| 218 |
+
if not validate_path(webp_path):
|
| 219 |
+
return f"Invalid WebP file path: {webp_path}"
|
| 220 |
+
if not webp_path.lower().endswith('.webp'):
|
| 221 |
+
return "Only .webp files are supported."
|
| 222 |
+
return True
|
| 223 |
+
|
| 224 |
+
NODE_CLASS_MAPPINGS = {
|
| 225 |
+
"LoadWebPAnimationAdvanced": LoadWebPAnimationAdvanced
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
NODE_DISPLAY_NAME_MAPPINGS = {
|
| 229 |
+
"LoadWebPAnimationAdvanced": "Load WebP Animation (Advanced)"
|
| 230 |
+
}
|