Compare commits
1 commit
master
...
feat/video
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
db5c6c79d2 |
30 changed files with 755 additions and 536 deletions
8
.github/workflows/release-stable-all.yml
vendored
8
.github/workflows/release-stable-all.yml
vendored
|
|
@ -48,13 +48,13 @@ jobs:
|
|||
contents: "write"
|
||||
packages: "write"
|
||||
pull-requests: "read"
|
||||
name: "Release AMD ROCm 7.2"
|
||||
name: "Release AMD ROCm 7.14"
|
||||
uses: ./.github/workflows/stable-release.yml
|
||||
with:
|
||||
git_tag: ${{ inputs.git_tag }}
|
||||
cache_tag: "rocm72"
|
||||
python_minor: "12"
|
||||
python_patch: "10"
|
||||
cache_tag: "rocm714"
|
||||
python_minor: "13"
|
||||
python_patch: "14"
|
||||
rel_name: "amd"
|
||||
rel_extra_name: ""
|
||||
test_release: false
|
||||
|
|
|
|||
|
|
@ -2,12 +2,9 @@ from collections import deque
|
|||
from datetime import datetime
|
||||
import io
|
||||
import logging
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
|
||||
import comfy.logging
|
||||
|
||||
ANSI_NAMED_COLORS = {
|
||||
'black': '\033[30m',
|
||||
'red': '\033[31m',
|
||||
|
|
@ -21,7 +18,6 @@ ANSI_NAMED_COLORS = {
|
|||
|
||||
ANSI_LEVEL_COLORS = {
|
||||
'DEBUG': ANSI_NAMED_COLORS['cyan'],
|
||||
'DETAIL': ANSI_NAMED_COLORS['blue'],
|
||||
'INFO': ANSI_NAMED_COLORS['green'],
|
||||
'WARNING': ANSI_NAMED_COLORS['yellow'],
|
||||
'ERROR': ANSI_NAMED_COLORS['red'],
|
||||
|
|
@ -89,12 +85,7 @@ def on_flush(callback):
|
|||
if stderr_interceptor is not None:
|
||||
stderr_interceptor.on_flush(callback)
|
||||
|
||||
|
||||
def get_log_level(level):
|
||||
return comfy.logging.DETAIL if level == "DETAIL" else logging.getLevelName(level)
|
||||
|
||||
|
||||
def setup_logger(log_level: str = 'INFO', file_outputs=None, capacity: int = 300, use_stdout: bool = False):
|
||||
def setup_logger(log_level: str = 'INFO', capacity: int = 300, use_stdout: bool = False):
|
||||
global logs
|
||||
if logs:
|
||||
return
|
||||
|
|
@ -108,18 +99,13 @@ def setup_logger(log_level: str = 'INFO', file_outputs=None, capacity: int = 300
|
|||
stderr_interceptor = sys.stderr = LogInterceptor(sys.stderr)
|
||||
|
||||
# Setup default global logger
|
||||
if file_outputs is None:
|
||||
file_outputs = [('DETAIL', 'comfyui_detail.log')]
|
||||
logger = logging.getLogger()
|
||||
console_level = get_log_level(log_level)
|
||||
file_levels = [get_log_level(level) for level, _ in file_outputs]
|
||||
logger.setLevel(min(console_level, *file_levels))
|
||||
logger.setLevel(log_level)
|
||||
|
||||
formatter = ColoredFormatter("%(message)s")
|
||||
|
||||
stream_handler = logging.StreamHandler()
|
||||
stream_handler.setFormatter(formatter)
|
||||
stream_handler.setLevel(console_level)
|
||||
|
||||
if use_stdout:
|
||||
# Only errors and critical to stderr
|
||||
|
|
@ -128,24 +114,11 @@ def setup_logger(log_level: str = 'INFO', file_outputs=None, capacity: int = 300
|
|||
# Lesser to stdout
|
||||
stdout_handler = logging.StreamHandler(sys.stdout)
|
||||
stdout_handler.setFormatter(formatter)
|
||||
stdout_handler.setLevel(console_level)
|
||||
stdout_handler.addFilter(lambda record: record.levelno < logging.ERROR)
|
||||
logger.addHandler(stdout_handler)
|
||||
|
||||
logger.addHandler(stream_handler)
|
||||
|
||||
for output_level, output_path in file_outputs:
|
||||
output_path = os.path.abspath(output_path)
|
||||
try:
|
||||
output_handler = logging.FileHandler(output_path, encoding="utf-8")
|
||||
except OSError as e:
|
||||
logging.warning("Could not open %s log %s: %s", output_level, output_path, e)
|
||||
continue
|
||||
output_handler.setLevel(get_log_level(output_level))
|
||||
output_handler.setFormatter(logging.Formatter("[%(asctime)s] [%(levelname)s] %(message)s"))
|
||||
logger.addHandler(output_handler)
|
||||
logging.info("%s log: %s", output_level.title(), output_path)
|
||||
|
||||
|
||||
STARTUP_WARNINGS = []
|
||||
|
||||
|
|
|
|||
|
|
@ -33,31 +33,6 @@ class EnumAction(argparse.Action):
|
|||
setattr(namespace, self.dest, value)
|
||||
|
||||
|
||||
LOG_LEVELS = ('DEBUG', 'DETAIL', 'INFO', 'WARNING', 'ERROR', 'CRITICAL')
|
||||
|
||||
|
||||
class VerboseAction(argparse.Action):
|
||||
def __call__(self, parser, namespace, values, option_string=None):
|
||||
if len(values) == 0:
|
||||
output = ('DEBUG', None)
|
||||
elif len(values) == 1 and values[0] in LOG_LEVELS:
|
||||
output = (values[0], None)
|
||||
elif len(values) == 2 and values[0] in LOG_LEVELS:
|
||||
output = tuple(values)
|
||||
else:
|
||||
parser.error(f"{option_string} expects no values, a console LEVEL, or LEVEL FILE")
|
||||
setattr(namespace, self.dest, [*getattr(namespace, self.dest, []), output])
|
||||
|
||||
|
||||
def get_console_log_level(outputs):
|
||||
console_levels = [level for level, path in outputs if path is None]
|
||||
return min(console_levels, key=LOG_LEVELS.index, default='INFO')
|
||||
|
||||
|
||||
def get_file_log_outputs(outputs):
|
||||
return [(level, path) for level, path in outputs if path is not None]
|
||||
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
|
||||
parser.add_argument("--listen", type=str, default="127.0.0.1", metavar="IP", nargs="?", const="0.0.0.0,::", help="Specify the IP address to listen on (default: 127.0.0.1). You can give a list of ip addresses by separating them with a comma like: 127.2.2.2,127.3.3.3 If --listen is provided without an argument, it defaults to 0.0.0.0,:: (listens on all ipv4 and ipv6)")
|
||||
|
|
@ -212,7 +187,7 @@ parser.add_argument("--disable-api-nodes", action="store_true", help="Disable lo
|
|||
|
||||
parser.add_argument("--multi-user", action="store_true", help="Enables per-user storage.")
|
||||
|
||||
parser.add_argument("--verbose", action=VerboseAction, nargs='*', default=[], metavar='LEVEL FILE', help='Set console logging with no values or LEVEL, or add a LEVEL FILE log output. May be repeated.')
|
||||
parser.add_argument("--verbose", default='INFO', const='DEBUG', nargs="?", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'], help='Set the logging level')
|
||||
parser.add_argument("--log-stdout", action="store_true", help="Send normal process output to stdout instead of stderr (default).")
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -671,9 +671,9 @@ def freqs_cis_matrix(freqs, pad_size, split_mode, num_attention_heads, out_dtype
|
|||
cos_freq = torch.cat((cos_padding, cos_freq), dim=-1)
|
||||
sin_freq = torch.cat((sin_padding, sin_freq), dim=-1)
|
||||
|
||||
B, T, half_HD = cos_freq.shape
|
||||
cos_freq = cos_freq.reshape(B, T, num_attention_heads, half_HD // num_attention_heads)
|
||||
sin_freq = sin_freq.reshape(B, T, num_attention_heads, half_HD // num_attention_heads)
|
||||
B, T, _ = cos_freq.shape
|
||||
cos_freq = cos_freq.reshape(B, T, num_attention_heads, -1)
|
||||
sin_freq = sin_freq.reshape(B, T, num_attention_heads, -1)
|
||||
rotation_matrix = torch.stack(
|
||||
(cos_freq, -sin_freq, sin_freq, cos_freq), dim=-1
|
||||
)
|
||||
|
|
|
|||
|
|
@ -49,12 +49,6 @@ class CausalConv3d(nn.Module):
|
|||
)
|
||||
self.temporal_cache_state={}
|
||||
|
||||
def _empty_output(self, x):
|
||||
# empty (0 frame) outputs must still have the conv's output channels and spatial dims
|
||||
h = (x.shape[3] + 2 * self.conv.padding[1] - self.conv.kernel_size[1]) // self.conv.stride[1] + 1
|
||||
w = (x.shape[4] + 2 * self.conv.padding[2] - self.conv.kernel_size[2]) // self.conv.stride[2] + 1
|
||||
return x.new_empty((x.shape[0], self.out_channels, 0, h, w))
|
||||
|
||||
def forward(self, x, causal: bool = True):
|
||||
tid = threading.get_ident()
|
||||
|
||||
|
|
@ -64,7 +58,7 @@ class CausalConv3d(nn.Module):
|
|||
if not causal:
|
||||
padding_length = padding_length // 2
|
||||
if x.shape[2] == 0:
|
||||
return self._empty_output(x)
|
||||
return x
|
||||
cached = x[:, :, :1, :, :].repeat((1, 1, padding_length, 1, 1))
|
||||
pieces = [ cached, x ]
|
||||
if is_end and not causal:
|
||||
|
|
@ -89,7 +83,7 @@ class CausalConv3d(nn.Module):
|
|||
elif is_end:
|
||||
self.temporal_cache_state[tid] = (None, True)
|
||||
|
||||
return self.conv(x) if x.shape[2] >= self.time_kernel_size else self._empty_output(x)
|
||||
return self.conv(x) if x.shape[2] >= self.time_kernel_size else x[:, :, :0, :, :]
|
||||
|
||||
@property
|
||||
def weight(self):
|
||||
|
|
|
|||
|
|
@ -390,10 +390,10 @@ class Decoder(nn.Module):
|
|||
|
||||
# Compute output channel to be product of all channel-multiplier blocks
|
||||
output_channel = base_channels
|
||||
for block_name, block_params in blocks:
|
||||
for block_name, block_params in list(reversed(blocks)):
|
||||
block_params = block_params if isinstance(block_params, dict) else {}
|
||||
if block_name == "res_x_y":
|
||||
output_channel = block_params.get("in_channels", output_channel * block_params.get("multiplier", 2))
|
||||
output_channel = output_channel * block_params.get("multiplier", 2)
|
||||
if block_name == "compress_all":
|
||||
output_channel = output_channel * block_params.get("multiplier", 1)
|
||||
if block_name == "compress_space":
|
||||
|
|
@ -432,7 +432,7 @@ class Decoder(nn.Module):
|
|||
spatial_padding_mode=spatial_padding_mode,
|
||||
)
|
||||
elif block_name == "res_x_y":
|
||||
output_channel = block_params.get("out_channels", output_channel // block_params.get("multiplier", 2))
|
||||
output_channel = output_channel // block_params.get("multiplier", 2)
|
||||
block = ResnetBlock3D(
|
||||
dims=dims,
|
||||
in_channels=input_channel,
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
import logging
|
||||
|
||||
|
||||
DETAIL = 15
|
||||
logging.addLevelName(DETAIL, "DETAIL")
|
||||
|
||||
|
||||
def detail(message, *args, **kwargs):
|
||||
kwargs.setdefault("stacklevel", 2)
|
||||
logging.log(DETAIL, message, *args, **kwargs)
|
||||
|
|
@ -34,7 +34,6 @@ import comfy.utils
|
|||
import comfy.quant_ops
|
||||
import comfy_aimdo.host_buffer
|
||||
import comfy_aimdo.vram_buffer
|
||||
from comfy.logging import detail
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -633,50 +632,18 @@ def mark_mmap_dirty(storage):
|
|||
if mmap_refs is not None:
|
||||
DIRTY_MMAPS.add(mmap_refs[0])
|
||||
|
||||
PIN_SUBSETS = [ "weights", "patches" ]
|
||||
LOADED_PIN_SUBSETS = [ "weights-loaded", "patches-loaded" ]
|
||||
|
||||
def models_for_pin_eviction(active, current_prompt=None):
|
||||
for loaded_model in current_loaded_models:
|
||||
model = loaded_model.model
|
||||
if model is None or not model.is_dynamic():
|
||||
continue
|
||||
pin_state = model.model.dynamic_pins[model.load_device]
|
||||
if ((active is None or pin_state["active"] == active) and
|
||||
(current_prompt is None or pin_state["current_prompt"] == current_prompt)):
|
||||
yield model
|
||||
|
||||
def free_model_pins(size, subsets, current_prompt, active, registrations=False):
|
||||
def free_pins(size, evict_active=False):
|
||||
freed_total = 0
|
||||
for model in models_for_pin_eviction(active, current_prompt=current_prompt):
|
||||
for loaded_model in reversed(current_loaded_models):
|
||||
if size <= 0:
|
||||
return freed_total
|
||||
if registrations:
|
||||
freed = model.unregister_inactive_pins(size, subsets=subsets)
|
||||
else:
|
||||
freed = model.partially_unload_ram(size, subsets=subsets)
|
||||
freed_total += freed
|
||||
size -= freed
|
||||
model = loaded_model.model
|
||||
if model is not None and model.is_dynamic() and (evict_active or not model.model.dynamic_pins[model.load_device]["active"]):
|
||||
freed = model.partially_unload_ram(size)
|
||||
freed_total += freed
|
||||
size -= freed
|
||||
return freed_total
|
||||
|
||||
def pin_eviction_tiers(loaded, evict_active):
|
||||
tiers = [
|
||||
(PIN_SUBSETS, False, None),
|
||||
(LOADED_PIN_SUBSETS, False, None),
|
||||
(LOADED_PIN_SUBSETS, True, None),
|
||||
]
|
||||
if not loaded:
|
||||
tiers.append((PIN_SUBSETS, True, False))
|
||||
if evict_active:
|
||||
tiers.append((PIN_SUBSETS, True, True))
|
||||
return tiers
|
||||
|
||||
def free_pins(size, evict_active=False, loaded=False):
|
||||
freed = 0
|
||||
for subsets, current_prompt, active in pin_eviction_tiers(loaded, evict_active):
|
||||
freed += free_model_pins(size - freed, subsets, current_prompt, active)
|
||||
return freed
|
||||
|
||||
def should_free_pins_for_ram_pressure(shortfall):
|
||||
if shortfall <= 0:
|
||||
return False
|
||||
|
|
@ -686,7 +653,7 @@ def should_free_pins_for_ram_pressure(shortfall):
|
|||
return True
|
||||
return psutil.swap_memory().percent >= WINDOWS_PIN_EVICTION_SWAP_PERCENT
|
||||
|
||||
def ensure_pin_budget(size, evict_active=False, loaded=False):
|
||||
def ensure_pin_budget(size, evict_active=False):
|
||||
if args.high_ram:
|
||||
return True
|
||||
if args.fast_disk:
|
||||
|
|
@ -697,21 +664,32 @@ def ensure_pin_budget(size, evict_active=False, loaded=False):
|
|||
return True
|
||||
|
||||
to_free = shortfall + PIN_PRESSURE_HYSTERESIS
|
||||
return free_pins(to_free, evict_active=evict_active, loaded=loaded) >= shortfall
|
||||
return free_pins(to_free, evict_active=evict_active) >= shortfall
|
||||
|
||||
def free_registrations(shortfall, evict_active=True, loaded=False):
|
||||
def free_registrations(shortfall, evict_active=True):
|
||||
if MAX_PINNED_MEMORY <= 0:
|
||||
return False
|
||||
if shortfall <= 0:
|
||||
return True
|
||||
|
||||
shortfall += REGISTERABLE_PIN_HYSTERESIS
|
||||
for subsets, current_prompt, active in pin_eviction_tiers(loaded, evict_active):
|
||||
shortfall -= free_model_pins(shortfall, subsets, current_prompt, active, registrations=True)
|
||||
for loaded_model in reversed(current_loaded_models):
|
||||
model = loaded_model.model
|
||||
if model is not None and model.is_dynamic() and not model.model.dynamic_pins[model.load_device]["active"]:
|
||||
shortfall -= model.unregister_inactive_pins(shortfall)
|
||||
if shortfall <= 0:
|
||||
return True
|
||||
if evict_active:
|
||||
for loaded_model in current_loaded_models:
|
||||
model = loaded_model.model
|
||||
if model is not None and model.is_dynamic() and model.model.dynamic_pins[model.load_device]["active"]:
|
||||
shortfall -= model.unregister_inactive_pins(shortfall)
|
||||
if shortfall <= 0:
|
||||
return True
|
||||
return shortfall <= REGISTERABLE_PIN_HYSTERESIS
|
||||
|
||||
def ensure_pin_registerable(size, evict_active=True, loaded=False):
|
||||
return free_registrations(TOTAL_PINNED_MEMORY + size - MAX_PINNED_MEMORY, evict_active=evict_active, loaded=loaded)
|
||||
def ensure_pin_registerable(size, evict_active=True):
|
||||
return free_registrations(TOTAL_PINNED_MEMORY + size - MAX_PINNED_MEMORY, evict_active=evict_active)
|
||||
|
||||
class LoadedModel:
|
||||
def __init__(self, model: ModelPatcher):
|
||||
|
|
@ -837,8 +815,6 @@ def minimum_inference_memory():
|
|||
|
||||
def free_memory(memory_required, device, keep_loaded=[], for_dynamic=False, pins_required=0, ram_required=0):
|
||||
cleanup_models_gc()
|
||||
if not for_dynamic:
|
||||
detail("Non dynamic memory free called! memory_required=%s pins_required=%s ram_required=%s", memory_required, pins_required, ram_required)
|
||||
unloaded_model = []
|
||||
can_unload = []
|
||||
unloaded_models = []
|
||||
|
|
@ -977,9 +953,6 @@ def load_models_gpu(models, memory_required=0, force_patch_weights=False, minimu
|
|||
lowvram_model_memory = 0.1
|
||||
|
||||
loaded_model.model_load(lowvram_model_memory, force_patch_weights=force_patch_weights)
|
||||
vram_used = 0 if is_device_cpu(torch_dev) else loaded_model.model_loaded_memory()
|
||||
ram_used = model.loaded_ram_size() if model.is_dynamic() else loaded_model.model_memory() - vram_used
|
||||
detail("Model loaded: patcher=%s model=%s ram_mb=%.1f vram_mb=%.1f", model.__class__.__name__, model.model.__class__.__name__, ram_used / (1024 ** 2), vram_used / (1024 ** 2))
|
||||
current_loaded_models.insert(0, loaded_model)
|
||||
return
|
||||
|
||||
|
|
@ -1406,17 +1379,15 @@ def reset_cast_buffers():
|
|||
pin_state = model.model.dynamic_pins[model.load_device]
|
||||
|
||||
if pin_state["active"]:
|
||||
for subset in ("weights", "weights-loaded"):
|
||||
*_, buckets = pin_state[subset]
|
||||
for size, bucket in list(buckets.items()):
|
||||
bucket[:] = [ entry for entry in bucket if entry[-1] is not None ]
|
||||
if not bucket:
|
||||
del buckets[size]
|
||||
*_, buckets = pin_state["weights"]
|
||||
for size, bucket in list(buckets.items()):
|
||||
bucket[:] = [ entry for entry in bucket if entry[-1] is not None ]
|
||||
if not bucket:
|
||||
del buckets[size]
|
||||
|
||||
pin_state["active"] = False
|
||||
model.partially_unload_ram(1e30, subsets=[ "patches", "patches-loaded" ])
|
||||
for subset in ("patches", "patches-loaded"):
|
||||
pin_state[subset] = (comfy_aimdo.host_buffer.HostBuffer(0, 8 * 1024 * 1024, pinned_hostbuf_size(model.model_size())), [], [-1], [0], [0], {})
|
||||
model.partially_unload_ram(1e30, subsets=[ "patches" ])
|
||||
model.model.dynamic_pins[model.load_device]["patches"] = (comfy_aimdo.host_buffer.HostBuffer(0, 8 * 1024 * 1024, pinned_hostbuf_size(model.model_size())), [], [-1], [0], [0], {})
|
||||
|
||||
STREAM_CAST_BUFFERS.clear()
|
||||
STREAM_AIMDO_CAST_BUFFERS.clear()
|
||||
|
|
|
|||
|
|
@ -22,7 +22,6 @@ import collections
|
|||
import inspect
|
||||
import logging
|
||||
import math
|
||||
import time
|
||||
import uuid
|
||||
from typing import Callable, Optional
|
||||
|
||||
|
|
@ -38,58 +37,11 @@ import comfy.patcher_extension
|
|||
import comfy.utils
|
||||
import comfy_aimdo.host_buffer
|
||||
from comfy.comfy_types import UnetWrapperFunction
|
||||
from comfy.logging import detail
|
||||
from comfy.quant_ops import QuantizedTensor
|
||||
from comfy.patcher_extension import CallbacksMP, PatcherInjection, WrappersMP
|
||||
|
||||
import comfy_aimdo.model_vbar
|
||||
|
||||
def is_model_patcher_output(output):
|
||||
return isinstance(output, ModelPatcher) or isinstance(getattr(output, "patcher", None), ModelPatcher)
|
||||
|
||||
class PromptModelTracker:
|
||||
def __init__(self):
|
||||
self.models = {}
|
||||
|
||||
def start(self):
|
||||
self.end()
|
||||
|
||||
def add(self, outputs):
|
||||
if isinstance(outputs, collections.abc.Mapping):
|
||||
outputs = outputs.values()
|
||||
elif not isinstance(outputs, (list, tuple)):
|
||||
outputs = (outputs,)
|
||||
|
||||
for output in outputs:
|
||||
if isinstance(output, (collections.abc.Mapping, list, tuple)):
|
||||
self.add(output)
|
||||
continue
|
||||
|
||||
models = []
|
||||
if isinstance(output, ModelPatcher):
|
||||
models.append(output)
|
||||
models.extend(output.model_patches_models())
|
||||
models.extend(output.get_nested_additional_models())
|
||||
else:
|
||||
patcher = getattr(output, "patcher", None)
|
||||
if isinstance(patcher, ModelPatcher):
|
||||
models.append(patcher)
|
||||
get_models = getattr(output, "get_models", None)
|
||||
if callable(get_models):
|
||||
models.extend(get_models())
|
||||
|
||||
for model in models:
|
||||
if not isinstance(model, ModelPatcher) or not model.is_dynamic():
|
||||
continue
|
||||
key = (id(model.model), model.load_device)
|
||||
self.models[key] = model
|
||||
model.set_in_use_by_current_prompt(True)
|
||||
|
||||
def end(self):
|
||||
for model in self.models.values():
|
||||
model.set_in_use_by_current_prompt(False)
|
||||
self.models.clear()
|
||||
|
||||
def set_model_options_patch_replace(model_options, patch, name, block_name, number, transformer_index=None):
|
||||
to = model_options["transformer_options"].copy()
|
||||
|
||||
|
|
@ -1772,20 +1724,14 @@ class ModelPatcherDynamic(ModelPatcher):
|
|||
self.model.dynamic_pins[device] = {
|
||||
"weights": (comfy_aimdo.host_buffer.HostBuffer(0, 0, 0), [], [-1], [0], [0], {}),
|
||||
"patches": (comfy_aimdo.host_buffer.HostBuffer(0, 0, 0), [], [-1], [0], [0], {}),
|
||||
"weights-loaded": (comfy_aimdo.host_buffer.HostBuffer(0, 0, 0), [], [-1], [0], [0], {}),
|
||||
"patches-loaded": (comfy_aimdo.host_buffer.HostBuffer(0, 0, 0), [], [-1], [0], [0], {}),
|
||||
"hostbufs_initialized": False,
|
||||
"failed": False,
|
||||
"active": False,
|
||||
"current_prompt": False,
|
||||
}
|
||||
|
||||
def is_dynamic(self):
|
||||
return True
|
||||
|
||||
def set_in_use_by_current_prompt(self, in_use):
|
||||
self.model.dynamic_pins[self.load_device]["current_prompt"] = in_use
|
||||
|
||||
def _vbar_get(self, create=False):
|
||||
if self.load_device == torch.device("cpu"):
|
||||
return None
|
||||
|
|
@ -1856,8 +1802,6 @@ class ModelPatcherDynamic(ModelPatcher):
|
|||
hostbuf_size = comfy.model_management.pinned_hostbuf_size(self.model_size())
|
||||
pin_state["weights"] = (comfy_aimdo.host_buffer.HostBuffer(0, 64 * 1024 * 1024, hostbuf_size), [], [-1], [0], [0], {})
|
||||
pin_state["patches"] = (comfy_aimdo.host_buffer.HostBuffer(0, 8 * 1024 * 1024, hostbuf_size), [], [-1], [0], [0], {})
|
||||
pin_state["weights-loaded"] = (comfy_aimdo.host_buffer.HostBuffer(0, 64 * 1024 * 1024, hostbuf_size), [], [-1], [0], [0], {})
|
||||
pin_state["patches-loaded"] = (comfy_aimdo.host_buffer.HostBuffer(0, 8 * 1024 * 1024, hostbuf_size), [], [-1], [0], [0], {})
|
||||
pin_state["hostbufs_initialized"] = True
|
||||
pin_state["failed"] = False
|
||||
pin_state["active"] = True
|
||||
|
|
@ -1991,37 +1935,20 @@ class ModelPatcherDynamic(ModelPatcher):
|
|||
assert self.load_device != torch.device("cpu")
|
||||
|
||||
vbar = self._vbar_get()
|
||||
vbar_freed = 0 if vbar is None else vbar.free_memory(memory_to_free)
|
||||
freed = vbar_freed
|
||||
freed = 0 if vbar is None else vbar.free_memory(memory_to_free)
|
||||
|
||||
backup_freed = 0
|
||||
if freed < memory_to_free:
|
||||
backup_freed = self.restore_loaded_backups()
|
||||
freed += backup_freed
|
||||
|
||||
method = "vbar+backups" if vbar_freed and backup_freed else "vbar" if vbar_freed else "backups" if backup_freed else "none"
|
||||
free_methods = getattr(self, "_free_methods", {})
|
||||
free_methods[method] = free_methods.get(method, 0) + 1
|
||||
self._free_methods = free_methods
|
||||
now = time.monotonic()
|
||||
if now - getattr(self, "_last_free_log_time", 0) >= 5:
|
||||
requested = "all" if memory_to_free >= 1e30 else f"{memory_to_free / (1024 ** 2):.1f}MB"
|
||||
prevailing_method = max(free_methods, key=free_methods.get)
|
||||
detail("AIMDO free: model=%s device=%s prevailing_method=%s methods=%s requested=%s vbar_mb=%.1f backups_mb=%.1f", self.model.__class__.__name__, self.load_device, prevailing_method, free_methods, requested, vbar_freed / (1024 ** 2), backup_freed / (1024 ** 2))
|
||||
self._free_methods = {}
|
||||
self._last_free_log_time = now
|
||||
freed += self.restore_loaded_backups()
|
||||
|
||||
return freed
|
||||
|
||||
def loaded_ram_size(self):
|
||||
pin_state = self.model.dynamic_pins[self.load_device]
|
||||
return pin_state["weights"][0].size + pin_state["weights-loaded"][0].size
|
||||
return (self.model.dynamic_pins[self.load_device]["weights"][0].size)
|
||||
|
||||
def pinned_memory_size(self):
|
||||
pin_state = self.model.dynamic_pins[self.load_device]
|
||||
return pin_state["weights"][3][0] + pin_state["weights-loaded"][3][0]
|
||||
return (self.model.dynamic_pins[self.load_device]["weights"][3][0])
|
||||
|
||||
def unregister_inactive_pins(self, ram_to_unload, subsets=[ "weights-loaded", "patches-loaded", "weights", "patches" ]):
|
||||
def unregister_inactive_pins(self, ram_to_unload, subsets=[ "weights", "patches" ]):
|
||||
freed = 0
|
||||
pin_state = self.model.dynamic_pins[self.load_device]
|
||||
for subset in subsets:
|
||||
|
|
@ -2029,17 +1956,15 @@ class ModelPatcherDynamic(ModelPatcher):
|
|||
split = stack_split[0]
|
||||
while split >= 0:
|
||||
module, offset = stack[split]
|
||||
module_pin = module._pins[subset]
|
||||
split -= 1
|
||||
stack_split[0] = split
|
||||
if not module_pin["registered"]:
|
||||
if not module._pin_registered:
|
||||
continue
|
||||
pin = module_pin["pin"]
|
||||
size = pin.numel() * pin.element_size()
|
||||
if torch.cuda.cudart().cudaHostUnregister(pin.data_ptr()) != 0:
|
||||
size = module._pin.numel() * module._pin.element_size()
|
||||
if torch.cuda.cudart().cudaHostUnregister(module._pin.data_ptr()) != 0:
|
||||
comfy.model_management.discard_cuda_async_error()
|
||||
continue
|
||||
module_pin["registered"] = False
|
||||
module._pin_registered = False
|
||||
comfy.model_management.TOTAL_PINNED_MEMORY = max(0, comfy.model_management.TOTAL_PINNED_MEMORY - size)
|
||||
pinned_size[0] = max(0, pinned_size[0] - size)
|
||||
freed += size
|
||||
|
|
@ -2048,23 +1973,20 @@ class ModelPatcherDynamic(ModelPatcher):
|
|||
return freed
|
||||
return freed
|
||||
|
||||
def partially_unload_ram(self, ram_to_unload, subsets=[ "weights-loaded", "patches-loaded", "weights", "patches" ]):
|
||||
def partially_unload_ram(self, ram_to_unload, subsets=[ "weights", "patches" ]):
|
||||
freed = 0
|
||||
pin_state = self.model.dynamic_pins[self.load_device]
|
||||
for subset in subsets:
|
||||
hostbuf, stack, stack_split, pinned_size, *_ = pin_state[subset]
|
||||
while len(stack) > 0:
|
||||
module, offset = stack.pop()
|
||||
module_pin = module._pins[subset]
|
||||
pin = module_pin["pin"]
|
||||
size = pin.numel() * pin.element_size()
|
||||
module_pin["balancer_entry"][-1] = None
|
||||
del module_pin["balancer_entry"]
|
||||
del module_pin["pin"]
|
||||
registered = module_pin["registered"]
|
||||
hostbuf.truncate(offset, do_unregister=registered)
|
||||
size = module._pin.numel() * module._pin.element_size()
|
||||
module._pin_balancer_entry[-1] = None
|
||||
del module._pin_balancer_entry
|
||||
del module._pin
|
||||
hostbuf.truncate(offset, do_unregister=module._pin_registered)
|
||||
stack_split[0] = min(stack_split[0], len(stack) - 1)
|
||||
if registered:
|
||||
if module._pin_registered:
|
||||
comfy.model_management.TOTAL_PINNED_MEMORY = max(0, comfy.model_management.TOTAL_PINNED_MEMORY - size)
|
||||
pinned_size[0] = max(0, pinned_size[0] - size)
|
||||
freed += size
|
||||
|
|
|
|||
47
comfy/ops.py
47
comfy/ops.py
|
|
@ -144,13 +144,8 @@ def cast_modules_with_vbar(comfy_modules, dtype, device, bias_dtype, non_blockin
|
|||
needs_cast = False
|
||||
|
||||
xfer_source = [ s.weight, s.bias ]
|
||||
subset = "weights"
|
||||
pin = comfy.pinned_memory.get_pin(s, subset=subset)
|
||||
if pin is None and not args.fast_disk:
|
||||
loaded_pin = comfy.pinned_memory.get_pin(s, subset="weights-loaded")
|
||||
if loaded_pin is not None or signature is not None:
|
||||
subset = "weights-loaded"
|
||||
pin = loaded_pin
|
||||
|
||||
pin = comfy.pinned_memory.get_pin(s)
|
||||
if pin is not None:
|
||||
xfer_source = [ pin ]
|
||||
|
||||
|
|
@ -187,12 +182,12 @@ def cast_modules_with_vbar(comfy_modules, dtype, device, bias_dtype, non_blockin
|
|||
if pin is not None:
|
||||
cast_maybe_lowvram_patch([pin], dest, offload_stream)
|
||||
return
|
||||
if signature is None or not args.fast_disk or args.high_ram:
|
||||
if signature is None or args.high_ram:
|
||||
comfy.pinned_memory.pin_memory(m, subset=subset, size=size)
|
||||
pin = comfy.pinned_memory.get_pin(m, subset=subset)
|
||||
cast_maybe_lowvram_patch(source, pin, offload_stream, xfer_dest2=dest)
|
||||
|
||||
handle_pin(s, pin, xfer_source, xfer_dest, subset=subset, size=dest_size)
|
||||
handle_pin(s, pin, xfer_source, xfer_dest, size=dest_size)
|
||||
|
||||
for param_key in ("weight", "bias"):
|
||||
lowvram_source = getattr(s, param_key + "_lowvram_function", None)
|
||||
|
|
@ -202,16 +197,8 @@ def cast_modules_with_vbar(comfy_modules, dtype, device, bias_dtype, non_blockin
|
|||
lowvram_dest = get_cast_buffer(lowvram_size)
|
||||
lowvram_source.prepare(lowvram_dest, None, copy=False, commit=True)
|
||||
|
||||
subset = "patches"
|
||||
pin = comfy.pinned_memory.get_pin(lowvram_source, subset=subset)
|
||||
if pin is None:
|
||||
loaded_pin = comfy.pinned_memory.get_pin(lowvram_source, subset="patches-loaded")
|
||||
if loaded_pin is not None:
|
||||
subset = "patches-loaded"
|
||||
pin = loaded_pin
|
||||
elif signature is not None and not args.fast_disk:
|
||||
subset = "patches-loaded"
|
||||
handle_pin(lowvram_source, pin, lowvram_source, lowvram_dest, subset=subset, size=lowvram_size)
|
||||
pin = comfy.pinned_memory.get_pin(lowvram_source, subset="patches")
|
||||
handle_pin(lowvram_source, pin, lowvram_source, lowvram_dest, subset="patches", size=lowvram_size)
|
||||
|
||||
|
||||
prefetch["xfer_dest"] = xfer_dest
|
||||
|
|
@ -1482,12 +1469,12 @@ def mixed_precision_ops(quant_config={}, compute_dtype=torch.bfloat16, full_prec
|
|||
if layer_conf is not None:
|
||||
layer_conf = json.loads(layer_conf.numpy().tobytes())
|
||||
|
||||
# Only fp8 and int8_tensorwise support per-row dequant via index select.
|
||||
# Only fp8 makes sense for embeddings (per-row dequant via index select).
|
||||
# Block-scaled formats (NVFP4, MXFP8) can't do per-row lookup efficiently.
|
||||
quant_format = layer_conf.get("format") if layer_conf is not None else None
|
||||
manually_loaded_keys = []
|
||||
|
||||
if quant_format in ("float8_e4m3fn", "float8_e5m2", "int8_tensorwise") and weight_key in state_dict:
|
||||
if quant_format in ("float8_e4m3fn", "float8_e5m2") and weight_key in state_dict:
|
||||
self.quant_format = quant_format
|
||||
qconfig = QUANT_ALGOS[quant_format]
|
||||
self.layout_type = qconfig["comfy_tensor_layout"]
|
||||
|
|
@ -1501,16 +1488,10 @@ def mixed_precision_ops(quant_config={}, compute_dtype=torch.bfloat16, full_prec
|
|||
scale = scale.float()
|
||||
manually_loaded_keys.append(scale_key)
|
||||
|
||||
extra = {}
|
||||
if quant_format == "int8_tensorwise" and layer_conf.get("convrot", False):
|
||||
# rotated embedding table: record it so the forward un-rotates after lookup
|
||||
extra["convrot"] = True
|
||||
extra["convrot_groupsize"] = int(layer_conf.get("convrot_groupsize", 256))
|
||||
params = layout_cls.Params(
|
||||
scale=scale if scale is not None else torch.ones((), dtype=torch.float32),
|
||||
orig_dtype=MixedPrecisionOps._compute_dtype,
|
||||
orig_shape=(self.num_embeddings, self.embedding_dim),
|
||||
**extra,
|
||||
)
|
||||
self.weight = torch.nn.Parameter(
|
||||
QuantizedTensor(weight.to(dtype=qconfig["storage_t"]), qconfig["comfy_tensor_layout"], params),
|
||||
|
|
@ -1532,23 +1513,15 @@ def mixed_precision_ops(quant_config={}, compute_dtype=torch.bfloat16, full_prec
|
|||
def forward_comfy_cast_weights(self, input, out_dtype=None):
|
||||
weight = self.weight
|
||||
|
||||
# Optimized path: lookup in fp8/int8, dequantize only the selected rows.
|
||||
# Optimized path: lookup in fp8, dequantize only the selected rows.
|
||||
if isinstance(weight, QuantizedTensor) and len(self.weight_function) == 0:
|
||||
qdata, _, offload_stream = cast_bias_weight(self, device=input.device, dtype=weight.dtype, offloadable=True)
|
||||
if isinstance(qdata, QuantizedTensor):
|
||||
params = qdata._params
|
||||
scale = params.scale
|
||||
scale = qdata._params.scale
|
||||
qdata = qdata._qdata
|
||||
else:
|
||||
params = weight._params
|
||||
scale = None
|
||||
|
||||
# int8: per-row scale possible ConvRot, so let the layout do the gather
|
||||
if self.quant_format == "int8_tensorwise":
|
||||
x = get_layout_class(self.layout_type).dequantize_embedding(qdata, params, input)
|
||||
uncast_bias_weight(self, qdata, None, offload_stream)
|
||||
return x if out_dtype is None else x.to(dtype=out_dtype)
|
||||
|
||||
x = torch.nn.functional.embedding(
|
||||
input, qdata, self.padding_idx, self.max_norm,
|
||||
self.norm_type, self.scale_grad_by_freq, self.sparse)
|
||||
|
|
|
|||
|
|
@ -9,14 +9,14 @@ import torch
|
|||
|
||||
from comfy.cli_args import args
|
||||
|
||||
def _add_to_bucket(module, module_pin, buckets, size, priority):
|
||||
def _add_to_bucket(module, buckets, size, priority):
|
||||
bucket = buckets.setdefault(size, [])
|
||||
entry = [-priority, 0, module]
|
||||
entry[1] = id(entry)
|
||||
bisect.insort(bucket, entry)
|
||||
module_pin["balancer_entry"] = entry
|
||||
module._pin_balancer_entry = entry
|
||||
|
||||
def _steal_pin(module, stack, buckets, size, priority, subset):
|
||||
def _steal_pin(module, stack, buckets, size, priority):
|
||||
bucket = buckets.get(size)
|
||||
if bucket is None:
|
||||
return False
|
||||
|
|
@ -31,39 +31,34 @@ def _steal_pin(module, stack, buckets, size, priority, subset):
|
|||
return False
|
||||
|
||||
*_, victim = bucket.pop()
|
||||
module_pin = module._pins[subset]
|
||||
victim_pin = victim._pins[subset]
|
||||
module_pin["pin"] = victim_pin["pin"]
|
||||
module_pin["registered"] = victim_pin["registered"]
|
||||
module_pin["stack_index"] = victim_pin["stack_index"]
|
||||
stack_index = module_pin["stack_index"]
|
||||
stack[stack_index] = (module, stack[stack_index][1])
|
||||
module._pin = victim._pin
|
||||
module._pin_registered = victim._pin_registered
|
||||
module._pin_stack_index = victim._pin_stack_index
|
||||
stack[module._pin_stack_index] = (module, stack[module._pin_stack_index][1])
|
||||
|
||||
victim_pin["registered"] = False
|
||||
del victim_pin["pin"]
|
||||
del victim_pin["stack_index"]
|
||||
del victim_pin["balancer_entry"]
|
||||
victim._pin_registered = False
|
||||
del victim._pin
|
||||
del victim._pin_stack_index
|
||||
del victim._pin_balancer_entry
|
||||
|
||||
_add_to_bucket(module, module_pin, buckets, size, priority)
|
||||
_add_to_bucket(module, buckets, size, priority)
|
||||
return True
|
||||
|
||||
def get_pin(module, subset="weights"):
|
||||
pins = module.__dict__.get("_pins")
|
||||
module_pin = None if pins is None else pins.get(subset)
|
||||
pin = None if module_pin is None else module_pin.get("pin")
|
||||
if pin is None or module_pin["registered"] or args.disable_pinned_memory:
|
||||
pin = getattr(module, "_pin", None)
|
||||
if pin is None or module._pin_registered or args.disable_pinned_memory:
|
||||
return pin
|
||||
|
||||
_, _, stack_split, pinned_size, *_ = module._pin_state[subset]
|
||||
size = pin.nbytes
|
||||
comfy.model_management.ensure_pin_registerable(size, loaded=subset.endswith("-loaded"))
|
||||
comfy.model_management.ensure_pin_registerable(size)
|
||||
|
||||
if torch.cuda.cudart().cudaHostRegister(pin.data_ptr(), size, 1) != 0:
|
||||
comfy.model_management.discard_cuda_async_error()
|
||||
return pin
|
||||
|
||||
module_pin["registered"] = True
|
||||
stack_split[0] = max(stack_split[0], module_pin["stack_index"])
|
||||
module._pin_registered = True
|
||||
stack_split[0] = max(stack_split[0], module._pin_stack_index)
|
||||
comfy.model_management.TOTAL_PINNED_MEMORY += size
|
||||
pinned_size[0] += size
|
||||
return pin
|
||||
|
|
@ -77,26 +72,23 @@ def pin_memory(module, subset="weights", size=None):
|
|||
if pin is not None:
|
||||
return
|
||||
|
||||
pins = module.__dict__.setdefault("_pins", {})
|
||||
module_pin = pins.setdefault(subset, {})
|
||||
hostbuf, stack, stack_split, pinned_size, counter, buckets = pin_state[subset]
|
||||
if size is None:
|
||||
size = comfy.memory_management.vram_aligned_size([ module.weight, module.bias ])
|
||||
offset = hostbuf.size
|
||||
registerable_size = size
|
||||
loaded = subset.endswith("-loaded")
|
||||
priority = module_pin.get("balancer_priority")
|
||||
priority = getattr(module, "_pin_balancer_priority", None)
|
||||
|
||||
if priority is None:
|
||||
priority = comfy.utils.bit_reverse_range(counter[0], 16)
|
||||
counter[0] += 1
|
||||
module_pin["balancer_priority"] = priority
|
||||
module._pin_balancer_priority = priority
|
||||
|
||||
comfy.memory_management.extra_ram_release(comfy.memory_management.RAM_CACHE_HEADROOM)
|
||||
if (not comfy.model_management.ensure_pin_budget(size, loaded=loaded) or
|
||||
not comfy.model_management.ensure_pin_registerable(registerable_size, loaded=loaded)):
|
||||
return _steal_pin(module, stack, buckets, size, priority, subset)
|
||||
if (not comfy.model_management.ensure_pin_budget(size) or
|
||||
not comfy.model_management.ensure_pin_registerable(registerable_size)):
|
||||
return _steal_pin(module, stack, buckets, size, priority)
|
||||
|
||||
offset = hostbuf.size
|
||||
extended = False
|
||||
try:
|
||||
hostbuf.extend(size=size, register=False)
|
||||
|
|
@ -105,23 +97,23 @@ def pin_memory(module, subset="weights", size=None):
|
|||
pin.untyped_storage()._comfy_hostbuf = hostbuf
|
||||
if torch.cuda.cudart().cudaHostRegister(pin.data_ptr(), size, 1) != 0:
|
||||
comfy.model_management.discard_cuda_async_error()
|
||||
comfy.model_management.free_registrations(size, loaded=loaded)
|
||||
comfy.model_management.free_registrations(size)
|
||||
if torch.cuda.cudart().cudaHostRegister(pin.data_ptr(), size, 1) != 0:
|
||||
comfy.model_management.discard_cuda_async_error()
|
||||
del pin
|
||||
hostbuf.truncate(offset, do_unregister=False)
|
||||
return _steal_pin(module, stack, buckets, size, priority, subset)
|
||||
return _steal_pin(module, stack, buckets, size, priority)
|
||||
except RuntimeError:
|
||||
if extended:
|
||||
hostbuf.truncate(offset, do_unregister=False)
|
||||
return _steal_pin(module, stack, buckets, size, priority, subset)
|
||||
return _steal_pin(module, stack, buckets, size, priority)
|
||||
|
||||
module_pin["pin"] = pin
|
||||
module._pin = pin
|
||||
stack.append((module, offset))
|
||||
module_pin["registered"] = True
|
||||
module_pin["stack_index"] = len(stack) - 1
|
||||
stack_split[0] = max(stack_split[0], module_pin["stack_index"])
|
||||
module._pin_registered = True
|
||||
module._pin_stack_index = len(stack) - 1
|
||||
stack_split[0] = max(stack_split[0], module._pin_stack_index)
|
||||
comfy.model_management.TOTAL_PINNED_MEMORY += size
|
||||
pinned_size[0] += size
|
||||
_add_to_bucket(module, module_pin, buckets, size, priority)
|
||||
_add_to_bucket(module, buckets, size, priority)
|
||||
return True
|
||||
|
|
|
|||
|
|
@ -20,7 +20,6 @@ import comfy.hooks
|
|||
import comfy.context_windows
|
||||
import comfy.multigpu
|
||||
import comfy.utils
|
||||
from comfy.logging import detail
|
||||
import scipy.stats
|
||||
import numpy
|
||||
|
||||
|
|
@ -992,15 +991,10 @@ class KSAMPLER(Sampler):
|
|||
|
||||
noise = model_wrap.inner_model.model_sampling.noise_scaling(sigmas[0], noise, latent_image, self.max_denoise(model_wrap, sigmas))
|
||||
|
||||
k_callback = None
|
||||
total_steps = len(sigmas) - 1
|
||||
first_step = True
|
||||
def k_callback(x):
|
||||
nonlocal first_step
|
||||
if first_step:
|
||||
detail("First sampler step: model=%s sampler=%s step=%s total_steps=%s cfg=%s seed=%s sigma=%s sigma_hat=%s latent_shape=%s denoised_shape=%s", model_wrap.model_patcher.model.__class__.__name__, self.sampler_function.__name__, x["i"], total_steps, model_wrap.cfg, extra_args.get("seed"), x.get("sigma"), x.get("sigma_hat"), tuple(x["x"].shape), tuple(x["denoised"].shape))
|
||||
first_step = False
|
||||
if callback is not None:
|
||||
callback(x["i"], x["denoised"], x["x"], total_steps)
|
||||
if callback is not None:
|
||||
k_callback = lambda x: callback(x["i"], x["denoised"], x["x"], total_steps)
|
||||
|
||||
samples = self.sampler_function(model_k, noise, sigmas, extra_args=extra_args, callback=k_callback, disable=disable_pbar, **self.extra_options)
|
||||
samples = model_wrap.inner_model.model_sampling.inverse_noise_scaling(sigmas[-1], samples)
|
||||
|
|
@ -1276,13 +1270,10 @@ class CFGGuider:
|
|||
return latent_image
|
||||
|
||||
if latent_image.is_nested:
|
||||
sampler_shapes = [tuple(x.shape) for x in latent_image.unbind()]
|
||||
latent_image, latent_shapes = comfy.utils.pack_latents(latent_image.unbind())
|
||||
noise, _ = comfy.utils.pack_latents(noise.unbind())
|
||||
else:
|
||||
latent_shapes = [latent_image.shape]
|
||||
sampler_shapes = [tuple(latent_image.shape)]
|
||||
detail("Sampler: model=%s latent_shapes=%s", self.model_patcher.model.__class__.__name__, sampler_shapes)
|
||||
|
||||
if denoise_mask is not None:
|
||||
if denoise_mask.is_nested:
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ from fractions import Fraction
|
|||
from typing import Optional, Union, IO
|
||||
import io
|
||||
import av
|
||||
from .._util import VideoContainer, VideoCodec, VideoComponents
|
||||
from .._util import VideoContainer, VideoCodec, VideoComponents, normalize_crop_rect
|
||||
|
||||
class VideoInput(ABC):
|
||||
"""
|
||||
|
|
@ -52,6 +52,45 @@ class VideoInput(ABC):
|
|||
"""
|
||||
pass
|
||||
|
||||
def as_cropped(
|
||||
self,
|
||||
x: int = 0,
|
||||
y: int = 0,
|
||||
width: int = 0,
|
||||
height: int = 0,
|
||||
) -> VideoInput:
|
||||
"""
|
||||
Create a new VideoInput spatially cropped to the given pixel rectangle.
|
||||
|
||||
The rectangle is clamped to the frame and even-aligned for encoder
|
||||
compatibility. An empty or full-frame rectangle returns the input
|
||||
unchanged.
|
||||
|
||||
Default implementation materializes the video via get_components();
|
||||
subclasses should override with lazier strategies when possible.
|
||||
"""
|
||||
components = self.get_components()
|
||||
rect = normalize_crop_rect(
|
||||
x, y, width, height, components.images.shape[2], components.images.shape[1]
|
||||
)
|
||||
if rect is None:
|
||||
return self
|
||||
from .._input_impl.video_types import VideoFromComponents
|
||||
|
||||
cx, cy, cw, ch = rect
|
||||
return VideoFromComponents(
|
||||
VideoComponents(
|
||||
images=components.images[:, cy:cy + ch, cx:cx + cw, :],
|
||||
audio=components.audio,
|
||||
frame_rate=components.frame_rate,
|
||||
metadata=components.metadata,
|
||||
alpha=components.alpha[:, cy:cy + ch, cx:cx + cw]
|
||||
if components.alpha is not None
|
||||
else None,
|
||||
),
|
||||
bit_depth=self.get_bit_depth(),
|
||||
)
|
||||
|
||||
def get_stream_source(self) -> Union[str, io.BytesIO]:
|
||||
"""
|
||||
Get a streamable source for the video. This allows processing without
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import numpy as np
|
|||
import math
|
||||
import os
|
||||
import torch
|
||||
from .._util import VideoContainer, VideoCodec, VideoComponents
|
||||
from .._util import VideoContainer, VideoCodec, VideoComponents, normalize_crop_rect
|
||||
import logging
|
||||
|
||||
|
||||
|
|
@ -111,12 +111,17 @@ def mp4_output_open_kwargs(path: str | io.BytesIO, format: VideoContainer, codec
|
|||
return open_kwargs
|
||||
|
||||
|
||||
def _rotation_quadrant(frame: av.VideoFrame) -> int:
|
||||
return int(round(frame.rotation // 90)) % 4 if frame.rotation else 0
|
||||
|
||||
|
||||
class VideoFromFile(VideoInput):
|
||||
"""
|
||||
Class representing video input from a file.
|
||||
"""
|
||||
|
||||
def __init__(self, file: str | io.BytesIO, *, start_time: float=0, duration: float=0):
|
||||
def __init__(self, file: str | io.BytesIO, *, start_time: float=0, duration: float=0,
|
||||
crop: tuple[int, int, int, int] | None = None):
|
||||
"""
|
||||
Initialize the VideoFromFile object based off of either a path on disk or a BytesIO object
|
||||
containing the file contents.
|
||||
|
|
@ -124,6 +129,7 @@ class VideoFromFile(VideoInput):
|
|||
self.__file = file
|
||||
self.__start_time = start_time
|
||||
self.__duration = duration
|
||||
self.__crop = crop
|
||||
|
||||
def get_stream_source(self) -> str | io.BytesIO:
|
||||
"""
|
||||
|
|
@ -153,7 +159,31 @@ class VideoFromFile(VideoInput):
|
|||
for stream in container.streams:
|
||||
if stream.type == 'video':
|
||||
assert isinstance(stream, av.VideoStream)
|
||||
return stream.width, stream.height
|
||||
if self.__crop is None:
|
||||
return stream.width, stream.height
|
||||
|
||||
display_width, display_height = self._get_display_dimensions()
|
||||
rect = normalize_crop_rect(*self.__crop, display_width, display_height)
|
||||
if rect is not None:
|
||||
return rect[2], rect[3]
|
||||
return display_width, display_height
|
||||
raise ValueError(f"No video stream found in file '{self.__file}'")
|
||||
|
||||
def _get_display_dimensions(self) -> tuple[int, int]:
|
||||
if isinstance(self.__file, io.BytesIO):
|
||||
self.__file.seek(0)
|
||||
with av.open(self.__file, mode='r') as container:
|
||||
for stream in container.streams:
|
||||
if stream.type == 'video':
|
||||
assert isinstance(stream, av.VideoStream)
|
||||
width, height = stream.width, stream.height
|
||||
try:
|
||||
frame = next(container.decode(stream), None)
|
||||
except av.error.FFmpegError:
|
||||
frame = None
|
||||
if frame is not None and _rotation_quadrant(frame) % 2:
|
||||
width, height = height, width
|
||||
return width, height
|
||||
raise ValueError(f"No video stream found in file '{self.__file}'")
|
||||
|
||||
def get_bit_depth(self) -> int:
|
||||
|
|
@ -323,6 +353,8 @@ class VideoFromFile(VideoInput):
|
|||
streams = [video_stream]
|
||||
has_first_audio_frame = False
|
||||
checked_alpha = False
|
||||
crop_rect = None
|
||||
crop_resolved = False
|
||||
|
||||
# Default to False so we decode until EOF if duration is 0
|
||||
video_done = False
|
||||
|
|
@ -393,9 +425,16 @@ class VideoFromFile(VideoInput):
|
|||
img = np.ascontiguousarray(align_graph[2].pull().to_ndarray(format=image_format)[:frame.height, :frame.width])
|
||||
else:
|
||||
img = frame.to_ndarray(format=image_format)
|
||||
if frame.rotation != 0:
|
||||
k = int(round(frame.rotation // 90))
|
||||
img = np.rot90(img, k=k, axes=(0, 1)).copy()
|
||||
rotation_quadrant = _rotation_quadrant(frame)
|
||||
if rotation_quadrant:
|
||||
img = np.rot90(img, k=rotation_quadrant, axes=(0, 1)).copy()
|
||||
if self.__crop is not None:
|
||||
if not crop_resolved:
|
||||
crop_rect = normalize_crop_rect(*self.__crop, img.shape[1], img.shape[0])
|
||||
crop_resolved = True
|
||||
if crop_rect is not None:
|
||||
cx, cy, cw, ch = crop_rect
|
||||
img = np.ascontiguousarray(img[cy:cy + ch, cx:cx + cw])
|
||||
if alphas is None:
|
||||
frames.append(torch.from_numpy(img))
|
||||
else:
|
||||
|
|
@ -477,6 +516,8 @@ class VideoFromFile(VideoInput):
|
|||
reuse_streams = False
|
||||
if self.__start_time or self.__duration:
|
||||
reuse_streams = False
|
||||
if self.__crop is not None:
|
||||
reuse_streams = False
|
||||
|
||||
if not reuse_streams:
|
||||
if bit_depth is None:
|
||||
|
|
@ -568,6 +609,8 @@ class VideoFromFile(VideoInput):
|
|||
source_size = None
|
||||
rotation_k = 0
|
||||
rotation_filter = None
|
||||
crop_rect = None
|
||||
crop_filter = None
|
||||
audio_started = False
|
||||
samples_written = 0
|
||||
pending_audio = []
|
||||
|
|
@ -641,11 +684,15 @@ class VideoFromFile(VideoInput):
|
|||
if end_pts is not None and frame.pts is not None:
|
||||
frame_duration = min(frame_duration, end_pts - frame.pts)
|
||||
if output is None:
|
||||
rotation_k = int(round(frame.rotation // 90)) % 4 if frame.rotation else 0
|
||||
rotation_k = _rotation_quadrant(frame)
|
||||
if rotation_k % 2:
|
||||
out_width, out_height = frame.height, frame.width
|
||||
else:
|
||||
out_width, out_height = frame.width, frame.height
|
||||
if self.__crop is not None:
|
||||
crop_rect = normalize_crop_rect(*self.__crop, out_width, out_height)
|
||||
if crop_rect is not None:
|
||||
out_width, out_height = crop_rect[2], crop_rect[3]
|
||||
if out_width % 2 or out_height % 2:
|
||||
raise ValueError(f"H.264 output requires even dimensions, got {out_width}x{out_height}")
|
||||
source_size = (frame.width, frame.height)
|
||||
|
|
@ -684,9 +731,22 @@ class VideoFromFile(VideoInput):
|
|||
g_sink = g.add("buffersink")
|
||||
tail.link_to(g_sink)
|
||||
g.configure()
|
||||
rotation_filter = (g_src, g_sink)
|
||||
rotation_filter[0].push(frame)
|
||||
frame = rotation_filter[1].pull()
|
||||
rotation_filter = (g, g_src, g_sink)
|
||||
rotation_filter[1].push(frame)
|
||||
frame = rotation_filter[2].pull()
|
||||
if crop_rect is not None:
|
||||
if crop_filter is None:
|
||||
g = av.filter.Graph()
|
||||
g_src = g.add_buffer(width=frame.width, height=frame.height,
|
||||
format=frame.format.name, time_base=video_stream.time_base)
|
||||
g_crop = g.add("crop", f"{crop_rect[2]}:{crop_rect[3]}:{crop_rect[0]}:{crop_rect[1]}")
|
||||
g_sink = g.add("buffersink")
|
||||
g_src.link_to(g_crop)
|
||||
g_crop.link_to(g_sink)
|
||||
g.configure()
|
||||
crop_filter = (g, g_src, g_sink)
|
||||
crop_filter[1].push(frame)
|
||||
frame = crop_filter[2].pull()
|
||||
if frame.color_range == ColorRange.JPEG:
|
||||
# compress full-range sources (yuvj/MJPEG) to limited range
|
||||
frame = frame.reformat(format=pix_fmt, src_color_range="JPEG", dst_color_range="MPEG")
|
||||
|
|
@ -794,11 +854,42 @@ class VideoFromFile(VideoInput):
|
|||
self.get_stream_source(),
|
||||
start_time=start_time + self.__start_time,
|
||||
duration=duration,
|
||||
crop=self.__crop,
|
||||
)
|
||||
if trimmed.get_duration() < duration and strict_duration:
|
||||
return None
|
||||
return trimmed
|
||||
|
||||
def as_cropped(
|
||||
self, x: int = 0, y: int = 0, width: int = 0, height: int = 0
|
||||
) -> VideoInput:
|
||||
if int(width) <= 0 or int(height) <= 0:
|
||||
return self
|
||||
|
||||
display_width, display_height = self._get_display_dimensions()
|
||||
outer = (
|
||||
normalize_crop_rect(*self.__crop, display_width, display_height)
|
||||
if self.__crop is not None
|
||||
else None
|
||||
)
|
||||
if outer is None:
|
||||
rect = normalize_crop_rect(x, y, width, height, display_width, display_height)
|
||||
else:
|
||||
inner = normalize_crop_rect(x, y, width, height, outer[2], outer[3])
|
||||
rect = (
|
||||
(outer[0] + inner[0], outer[1] + inner[1], inner[2], inner[3])
|
||||
if inner is not None
|
||||
else None
|
||||
)
|
||||
if rect is None:
|
||||
return self
|
||||
return VideoFromFile(
|
||||
self.get_stream_source(),
|
||||
start_time=self.__start_time,
|
||||
duration=self.__duration,
|
||||
crop=rect,
|
||||
)
|
||||
|
||||
|
||||
class VideoFromComponents(VideoInput):
|
||||
"""
|
||||
|
|
@ -815,6 +906,8 @@ class VideoFromComponents(VideoInput):
|
|||
images=self.__components.images,
|
||||
audio=self.__components.audio,
|
||||
frame_rate=self.__components.frame_rate,
|
||||
metadata=self.__components.metadata,
|
||||
alpha=self.__components.alpha,
|
||||
)
|
||||
|
||||
def get_bit_depth(self) -> int:
|
||||
|
|
|
|||
|
|
@ -1361,6 +1361,41 @@ class BoundingBoxes(ComfyTypeIO):
|
|||
self.default = []
|
||||
|
||||
|
||||
@comfytype(io_type="VIDEO_EDIT")
|
||||
class VideoEdit(ComfyTypeIO):
|
||||
class VideoTrimSection(TypedDict):
|
||||
start_time: float
|
||||
duration: float
|
||||
|
||||
class VideoCropSection(TypedDict):
|
||||
x: int
|
||||
y: int
|
||||
width: int
|
||||
height: int
|
||||
|
||||
class VideoEditDict(TypedDict, total=False):
|
||||
trim: 'VideoEdit.VideoTrimSection'
|
||||
crop: 'VideoEdit.VideoCropSection'
|
||||
Type = VideoEditDict
|
||||
|
||||
class Input(WidgetInput):
|
||||
def __init__(self, id: str, display_name: str=None, optional=False, tooltip: str=None,
|
||||
socketless: bool=True, default: dict=None, features: list[str]=None, advanced: bool=None):
|
||||
super().__init__(id, display_name, optional, tooltip, None, default, socketless, None, None, None, None, advanced)
|
||||
self.features = features if features is not None else ["trim", "crop"]
|
||||
if default is None:
|
||||
self.default = {}
|
||||
if "trim" in self.features:
|
||||
self.default["trim"] = {"start_time": 0.0, "duration": 0.0}
|
||||
if "crop" in self.features:
|
||||
self.default["crop"] = {"x": 0, "y": 0, "width": 0, "height": 0}
|
||||
|
||||
def as_dict(self):
|
||||
return super().as_dict() | prune_dict({
|
||||
"features": self.features,
|
||||
})
|
||||
|
||||
|
||||
@comfytype(io_type="HISTOGRAM")
|
||||
class Histogram(ComfyTypeIO):
|
||||
"""A histogram represented as a list of bin counts."""
|
||||
|
|
@ -2436,5 +2471,6 @@ __all__ = [
|
|||
"Curve",
|
||||
"Histogram",
|
||||
"Range",
|
||||
"VideoEdit",
|
||||
"NodeReplace",
|
||||
]
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
from .video_types import VideoContainer, VideoCodec, VideoComponents
|
||||
from .video_types import VideoContainer, VideoCodec, VideoComponents, normalize_crop_rect
|
||||
from .geometry_types import VOXEL, MESH, SPLAT, File3D
|
||||
from .image_types import SVG
|
||||
|
||||
|
|
@ -7,6 +7,7 @@ __all__ = [
|
|||
"VideoContainer",
|
||||
"VideoCodec",
|
||||
"VideoComponents",
|
||||
"normalize_crop_rect",
|
||||
"VOXEL",
|
||||
"MESH",
|
||||
"SPLAT",
|
||||
|
|
|
|||
|
|
@ -48,3 +48,23 @@ class VideoComponents:
|
|||
audio: Optional[AudioInput] = None
|
||||
metadata: Optional[dict] = None
|
||||
alpha: Optional[MaskInput] = None
|
||||
|
||||
|
||||
def normalize_crop_rect(
|
||||
x: int, y: int, width: int, height: int, source_width: int, source_height: int
|
||||
) -> Optional[tuple[int, int, int, int]]:
|
||||
width = int(width)
|
||||
height = int(height)
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
x = max(0, min(int(x), source_width - 1))
|
||||
y = max(0, min(int(y), source_height - 1))
|
||||
width = min(width, source_width - x)
|
||||
height = min(height, source_height - y)
|
||||
if x == 0 and y == 0 and width == source_width and height == source_height:
|
||||
return None
|
||||
width -= width % 2
|
||||
height -= height % 2
|
||||
if width <= 0 or height <= 0:
|
||||
return None
|
||||
return x, y, width, height
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import psutil
|
|||
import time
|
||||
import torch
|
||||
from typing import Sequence, Mapping, Dict
|
||||
from comfy.model_patcher import is_model_patcher_output
|
||||
from comfy.model_patcher import ModelPatcher
|
||||
from comfy_execution.graph import DynamicPrompt
|
||||
from abc import ABC, abstractmethod
|
||||
|
||||
|
|
@ -524,13 +524,6 @@ class RAMPressureCache(LRUCache):
|
|||
def __init__(self, key_class, enable_providers=False):
|
||||
super().__init__(key_class, 0, enable_providers=enable_providers)
|
||||
self.timestamps = {}
|
||||
self.active_evictions = False
|
||||
self.full_evictions = False
|
||||
|
||||
async def set_prompt(self, dynprompt, node_ids, is_changed_cache):
|
||||
self.active_evictions = False
|
||||
self.full_evictions = False
|
||||
await super().set_prompt(dynprompt, node_ids, is_changed_cache)
|
||||
|
||||
def clean_unused(self):
|
||||
self._clean_subcaches()
|
||||
|
|
@ -574,7 +567,7 @@ class RAMPressureCache(LRUCache):
|
|||
elif isinstance(output, torch.Tensor) and output.device.type == 'cpu':
|
||||
ram_usage += output.numel() * output.element_size()
|
||||
oom_ram_usage += output.numel() * output.element_size()
|
||||
elif is_model_patcher_output(output) and self.used_generation[key] != self.generation:
|
||||
elif isinstance(output, ModelPatcher) and self.used_generation[key] != self.generation:
|
||||
#old ModelPatchers are the first to go
|
||||
oom_ram_usage = 1e30
|
||||
scan_list_for_ram_usage(cache_entry.outputs)
|
||||
|
|
@ -595,8 +588,4 @@ class RAMPressureCache(LRUCache):
|
|||
self.timestamps.pop(key, None)
|
||||
self.children.pop(key, None)
|
||||
freed += ram_usage
|
||||
if freed and free_active:
|
||||
self.active_evictions = True
|
||||
if min_entry_size == 0:
|
||||
self.full_evictions = True
|
||||
return freed
|
||||
|
|
|
|||
|
|
@ -195,10 +195,9 @@ class ExecutionList(TopologicalSort):
|
|||
ExecutionList implements a topological dissolve of the graph. After a node is staged for execution,
|
||||
it can still be returned to the graph after having further dependencies added.
|
||||
"""
|
||||
def __init__(self, dynprompt, output_cache, output_link_callback=None):
|
||||
def __init__(self, dynprompt, output_cache):
|
||||
super().__init__(dynprompt)
|
||||
self.output_cache = output_cache
|
||||
self.output_link_callback = output_link_callback
|
||||
self.staged_node_id = None
|
||||
self.execution_cache = {}
|
||||
self.execution_cache_listeners = {}
|
||||
|
|
@ -206,16 +205,13 @@ class ExecutionList(TopologicalSort):
|
|||
def is_cached(self, node_id):
|
||||
return self.output_cache.get_local(node_id) is not None
|
||||
|
||||
def cache_link(self, from_node_id, to_node_id, from_socket=None):
|
||||
def cache_link(self, from_node_id, to_node_id):
|
||||
if to_node_id not in self.execution_cache:
|
||||
self.execution_cache[to_node_id] = {}
|
||||
value = self.output_cache.get_local(from_node_id)
|
||||
self.execution_cache[to_node_id][from_node_id] = value
|
||||
self.execution_cache[to_node_id][from_node_id] = self.output_cache.get_local(from_node_id)
|
||||
if from_node_id not in self.execution_cache_listeners:
|
||||
self.execution_cache_listeners[from_node_id] = set()
|
||||
self.execution_cache_listeners[from_node_id].add((to_node_id, from_socket))
|
||||
if value is not None and from_socket is not None and self.output_link_callback is not None:
|
||||
self.output_link_callback(value.outputs[from_socket])
|
||||
self.execution_cache_listeners[from_node_id].add(to_node_id)
|
||||
|
||||
def get_cache(self, from_node_id, to_node_id):
|
||||
if to_node_id not in self.execution_cache:
|
||||
|
|
@ -229,15 +225,13 @@ class ExecutionList(TopologicalSort):
|
|||
|
||||
def cache_update(self, node_id, value):
|
||||
if node_id in self.execution_cache_listeners:
|
||||
for to_node_id, from_socket in self.execution_cache_listeners[node_id]:
|
||||
for to_node_id in self.execution_cache_listeners[node_id]:
|
||||
if to_node_id in self.execution_cache:
|
||||
self.execution_cache[to_node_id][node_id] = value
|
||||
if from_socket is not None and self.output_link_callback is not None:
|
||||
self.output_link_callback(value.outputs[from_socket])
|
||||
|
||||
def add_strong_link(self, from_node_id, from_socket, to_node_id):
|
||||
super().add_strong_link(from_node_id, from_socket, to_node_id)
|
||||
self.cache_link(from_node_id, to_node_id, from_socket)
|
||||
self.cache_link(from_node_id, to_node_id)
|
||||
|
||||
async def stage_node_execution(self):
|
||||
assert self.staged_node_id is None
|
||||
|
|
|
|||
|
|
@ -43,98 +43,6 @@ def load_and_process_images(image_files, input_dir):
|
|||
return output_images
|
||||
|
||||
|
||||
def secure_subfolder_path(base_dir, folder_name):
|
||||
"""Resolve folder_name inside base_dir, rejecting anything that escapes it.
|
||||
|
||||
Blocks '..', absolute paths, drive letters and symlink escapes using the
|
||||
same realpath containment check as the core file endpoints.
|
||||
"""
|
||||
target = os.path.abspath(os.path.join(base_dir, folder_name))
|
||||
if not folder_paths.is_within_directory(base_dir, target):
|
||||
raise ValueError(f"Invalid folder name {folder_name!r}: resolves outside of {base_dir}")
|
||||
return target
|
||||
|
||||
|
||||
def list_dataset_folders():
|
||||
"""Relative paths of dataset folders found under all dataset roots.
|
||||
|
||||
Any subfolder containing a metadata.json or *.safetensors shard counts as
|
||||
a dataset; the walk doesn't descend into matched folders.
|
||||
|
||||
Symlinked directories are followed, but symlink loops are avoided.
|
||||
"""
|
||||
found = set()
|
||||
|
||||
for root in folder_paths.get_folder_paths("datasets"):
|
||||
if not os.path.isdir(root):
|
||||
continue
|
||||
|
||||
root = os.path.abspath(root)
|
||||
seen_dirs = set()
|
||||
|
||||
for dirpath, subdirs, filenames in os.walk(root, followlinks=True):
|
||||
try:
|
||||
st = os.stat(dirpath) # follows symlinks
|
||||
except OSError:
|
||||
subdirs[:] = []
|
||||
continue
|
||||
|
||||
dir_key = (st.st_dev, st.st_ino)
|
||||
if dir_key in seen_dirs:
|
||||
subdirs[:] = []
|
||||
continue
|
||||
|
||||
seen_dirs.add(dir_key)
|
||||
|
||||
if dirpath != root and (
|
||||
"metadata.json" in filenames
|
||||
or any(f.endswith(".safetensors") for f in filenames)
|
||||
):
|
||||
found.add(os.path.relpath(dirpath, root).replace(os.sep, "/"))
|
||||
subdirs[:] = []
|
||||
continue
|
||||
|
||||
kept_subdirs = []
|
||||
for name in subdirs:
|
||||
child = os.path.join(dirpath, name)
|
||||
try:
|
||||
child_st = os.stat(child) # follows symlinks
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
child_key = (child_st.st_dev, child_st.st_ino)
|
||||
if child_key not in seen_dirs:
|
||||
kept_subdirs.append(name)
|
||||
|
||||
subdirs[:] = kept_subdirs
|
||||
|
||||
return sorted(found)
|
||||
|
||||
|
||||
def get_dataset_save_dir(folder_name):
|
||||
"""Resolve the folder to save a new dataset into, inside the default root.
|
||||
|
||||
The folder is not created here; callers makedirs after validation.
|
||||
"""
|
||||
root = folder_paths.get_folder_paths("datasets")[0]
|
||||
target = secure_subfolder_path(root, folder_name)
|
||||
if os.path.realpath(target) == os.path.realpath(root):
|
||||
raise ValueError("folder_name must name a subfolder of the datasets directory, e.g. 'my_dataset'.")
|
||||
return target
|
||||
|
||||
|
||||
def get_dataset_dir(folder_name):
|
||||
"""Find an existing dataset folder by relative name across all dataset roots."""
|
||||
roots = folder_paths.get_folder_paths("datasets")
|
||||
for root in roots:
|
||||
target = secure_subfolder_path(root, folder_name)
|
||||
if os.path.realpath(target) == os.path.realpath(root):
|
||||
raise ValueError("folder_name must name a subfolder of the datasets directory, e.g. 'my_dataset'.")
|
||||
if os.path.isdir(target):
|
||||
return target
|
||||
raise ValueError(f"Dataset folder {folder_name!r} not found in: {', '.join(roots)}")
|
||||
|
||||
|
||||
VALID_VIDEO_EXTENSIONS = [".mp4", ".avi", ".mov", ".webm", ".mkv", ".flv"]
|
||||
|
||||
|
||||
|
|
@ -487,7 +395,7 @@ class SaveImageDataSetToFolderNode(io.ComfyNode):
|
|||
filename_prefix = filename_prefix[0]
|
||||
mode = mode[0]
|
||||
|
||||
output_dir = secure_subfolder_path(folder_paths.get_output_directory(), folder_name)
|
||||
output_dir = os.path.join(folder_paths.get_output_directory(), folder_name)
|
||||
saved_files = save_images_to_folder(images, output_dir, filename_prefix, mode=='overwrite')
|
||||
|
||||
logging.info(f"Saved {len(saved_files)} images to {output_dir}.")
|
||||
|
|
@ -541,7 +449,7 @@ class SaveImageTextDataSetToFolderNode(io.ComfyNode):
|
|||
filename_prefix = filename_prefix[0]
|
||||
mode = mode[0]
|
||||
|
||||
output_dir = secure_subfolder_path(folder_paths.get_output_directory(), folder_name)
|
||||
output_dir = os.path.join(folder_paths.get_output_directory(), folder_name)
|
||||
saved_files = save_images_to_folder(images, output_dir, filename_prefix, mode=='overwrite')
|
||||
|
||||
# Save captions
|
||||
|
|
@ -1953,7 +1861,7 @@ class SaveTrainingDataset(io.ComfyNode):
|
|||
io.String.Input(
|
||||
"folder_name",
|
||||
default="training_dataset",
|
||||
tooltip="Name of folder to save the dataset into, inside the datasets directory. Subfolders like 'project/run1' are allowed.",
|
||||
tooltip="Name of folder to save dataset (inside output directory).",
|
||||
),
|
||||
io.Int.Input(
|
||||
"shard_size",
|
||||
|
|
@ -1983,8 +1891,8 @@ class SaveTrainingDataset(io.ComfyNode):
|
|||
f"Something went wrong in dataset preparation."
|
||||
)
|
||||
|
||||
# Create output directory (inside the datasets root, traversal-safe)
|
||||
output_dir = get_dataset_save_dir(folder_name)
|
||||
# Create output directory
|
||||
output_dir = os.path.join(folder_paths.get_output_directory(), folder_name)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# Prepare data pairs
|
||||
|
|
@ -2043,10 +1951,10 @@ class LoadTrainingDataset(io.ComfyNode):
|
|||
description="Load encoded training dataset (latents + conditioning) from disk for use in training.",
|
||||
is_experimental=True,
|
||||
inputs=[
|
||||
io.Combo.Input(
|
||||
io.String.Input(
|
||||
"folder_name",
|
||||
options=list_dataset_folders(),
|
||||
tooltip="Saved dataset to load, from the datasets directory.",
|
||||
default="training_dataset",
|
||||
tooltip="Name of folder containing the saved dataset (inside output directory).",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
|
|
@ -2065,8 +1973,11 @@ class LoadTrainingDataset(io.ComfyNode):
|
|||
|
||||
@classmethod
|
||||
def execute(cls, folder_name):
|
||||
# Get dataset directory (searched across all dataset roots, traversal-safe)
|
||||
dataset_dir = get_dataset_dir(folder_name)
|
||||
# Get dataset directory
|
||||
dataset_dir = os.path.join(folder_paths.get_output_directory(), folder_name)
|
||||
|
||||
if not os.path.exists(dataset_dir):
|
||||
raise ValueError(f"Dataset directory not found: {dataset_dir}")
|
||||
|
||||
# Find all shard files
|
||||
shard_files = sorted(
|
||||
|
|
|
|||
|
|
@ -202,8 +202,14 @@ class LoadVideo(io.ComfyNode):
|
|||
display_name="Load Video",
|
||||
category="video",
|
||||
essentials_category="Basics",
|
||||
has_intermediate_output=True,
|
||||
inputs=[
|
||||
io.Combo.Input("file", options=sorted(files), upload=io.UploadType.video),
|
||||
io.VideoEdit.Input(
|
||||
"edit",
|
||||
optional=True,
|
||||
tooltip="Trim (seconds) and crop (pixels) applied on load. Zero values leave the video unchanged.",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.Output(),
|
||||
|
|
@ -211,12 +217,17 @@ class LoadVideo(io.ComfyNode):
|
|||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, file) -> io.NodeOutput:
|
||||
def execute(cls, file, edit=None) -> io.NodeOutput:
|
||||
video_path = folder_paths.get_annotated_filepath(file)
|
||||
return io.NodeOutput(InputImpl.VideoFromFile(video_path))
|
||||
source = InputImpl.VideoFromFile(video_path)
|
||||
video = apply_video_trim(source, (edit or {}).get("trim"))
|
||||
video = apply_video_crop(video, (edit or {}).get("crop"))
|
||||
if video is source:
|
||||
return io.NodeOutput(video)
|
||||
return io.NodeOutput(video, ui=save_video_preview(video))
|
||||
|
||||
@classmethod
|
||||
def fingerprint_inputs(s, file):
|
||||
def fingerprint_inputs(s, file, edit=None):
|
||||
video_path = folder_paths.get_annotated_filepath(file)
|
||||
mod_time = os.path.getmtime(video_path)
|
||||
# Instead of hashing the file, we can just use the modification time to avoid
|
||||
|
|
@ -224,12 +235,54 @@ class LoadVideo(io.ComfyNode):
|
|||
return mod_time
|
||||
|
||||
@classmethod
|
||||
def validate_inputs(s, file):
|
||||
def validate_inputs(s, file, edit=None):
|
||||
if not folder_paths.exists_annotated_filepath(file):
|
||||
return "Invalid video file: {}".format(file)
|
||||
|
||||
return True
|
||||
|
||||
def save_video_preview(video: Input.Video) -> ui.PreviewVideo:
|
||||
width, height = video.get_dimensions()
|
||||
full_output_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(
|
||||
"ComfyUI_temp_video", folder_paths.get_temp_directory(), width, height
|
||||
)
|
||||
preview_format = Types.VideoContainer.MP4
|
||||
file = f"{filename}_{counter:05}_.{Types.VideoContainer.get_extension(preview_format)}"
|
||||
video.save_to(
|
||||
os.path.join(full_output_folder, file),
|
||||
format=preview_format,
|
||||
codec="auto",
|
||||
)
|
||||
return ui.PreviewVideo([ui.SavedResult(file, subfolder, io.FolderType.temp)])
|
||||
|
||||
|
||||
def apply_video_trim(video: Input.Video, trim, strict_duration: bool = False) -> Input.Video:
|
||||
trim = trim or {}
|
||||
start_time = float(trim.get("start_time", 0.0))
|
||||
duration = float(trim.get("duration", 0.0))
|
||||
if duration < 0:
|
||||
raise ValueError(f"Trim duration must be >= 0, got {duration}")
|
||||
if start_time == 0.0 and duration == 0.0:
|
||||
return video
|
||||
|
||||
trimmed = video.as_trimmed(start_time, duration, strict_duration=strict_duration)
|
||||
if trimmed is None:
|
||||
raise ValueError(
|
||||
f"Failed to trim video:\nSource duration: {video.get_duration()}\nStart time: {start_time}\nTarget duration: {duration}"
|
||||
)
|
||||
return trimmed
|
||||
|
||||
|
||||
def apply_video_crop(video: Input.Video, crop) -> Input.Video:
|
||||
crop = crop or {}
|
||||
return video.as_cropped(
|
||||
int(crop.get("x", 0)),
|
||||
int(crop.get("y", 0)),
|
||||
int(crop.get("width", 0)),
|
||||
int(crop.get("height", 0)),
|
||||
)
|
||||
|
||||
|
||||
class VideoSlice(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
|
|
@ -277,6 +330,72 @@ class VideoSlice(io.ComfyNode):
|
|||
)
|
||||
|
||||
|
||||
class VideoTrim(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="VideoTrim",
|
||||
display_name="Trim Video",
|
||||
search_aliases=["trim video duration", "skip first frames", "cut video", "start time"],
|
||||
category="video",
|
||||
is_experimental=True,
|
||||
essentials_category="Video Tools",
|
||||
has_intermediate_output=True,
|
||||
inputs=[
|
||||
io.Video.Input("video"),
|
||||
io.VideoEdit.Input(
|
||||
"trim",
|
||||
features=["trim"],
|
||||
tooltip="Trim window in seconds. Duration 0 keeps the video until the end.",
|
||||
),
|
||||
io.Boolean.Input(
|
||||
"strict_duration",
|
||||
default=False,
|
||||
advanced=True,
|
||||
tooltip="If True, when the specified duration is not possible, an error will be raised.",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, video: io.Video.Type, trim: io.VideoEdit.Type, strict_duration: bool) -> io.NodeOutput:
|
||||
trimmed = apply_video_trim(video, (trim or {}).get("trim"), strict_duration=strict_duration)
|
||||
return io.NodeOutput(trimmed, ui=save_video_preview(trimmed))
|
||||
|
||||
|
||||
class VideoCrop(io.ComfyNode):
|
||||
@classmethod
|
||||
def define_schema(cls):
|
||||
return io.Schema(
|
||||
node_id="VideoCrop",
|
||||
display_name="Crop Video",
|
||||
search_aliases=["crop video", "cut region", "spatial crop"],
|
||||
category="video",
|
||||
is_experimental=True,
|
||||
essentials_category="Video Tools",
|
||||
has_intermediate_output=True,
|
||||
inputs=[
|
||||
io.Video.Input("video"),
|
||||
io.VideoEdit.Input(
|
||||
"crop",
|
||||
features=["crop"],
|
||||
tooltip="Crop region in pixels. Zero width/height keeps the full frame.",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.Output(),
|
||||
],
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def execute(cls, video: io.Video.Type, crop: io.VideoEdit.Type) -> io.NodeOutput:
|
||||
cropped = apply_video_crop(video, (crop or {}).get("crop"))
|
||||
return io.NodeOutput(cropped, ui=save_video_preview(cropped))
|
||||
|
||||
|
||||
class VideoExtension(ComfyExtension):
|
||||
@override
|
||||
async def get_node_list(self) -> list[type[io.ComfyNode]]:
|
||||
|
|
@ -287,6 +406,8 @@ class VideoExtension(ComfyExtension):
|
|||
GetVideoComponents,
|
||||
LoadVideo,
|
||||
VideoSlice,
|
||||
VideoTrim,
|
||||
VideoCrop,
|
||||
]
|
||||
|
||||
async def comfy_entrypoint() -> VideoExtension:
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
# This file is automatically generated by the build process when version is
|
||||
# updated in pyproject.toml.
|
||||
__version__ = "0.29.0"
|
||||
__version__ = "0.28.0"
|
||||
|
|
|
|||
13
execution.py
13
execution.py
|
|
@ -13,13 +13,11 @@ import asyncio
|
|||
|
||||
import torch
|
||||
|
||||
from comfy.cli_args import args, get_console_log_level
|
||||
from comfy.cli_args import args
|
||||
import comfy.memory_management
|
||||
import comfy.model_management
|
||||
import comfy.model_patcher
|
||||
import comfy.model_prefetch
|
||||
import comfy_aimdo.model_vbar
|
||||
from comfy.logging import detail
|
||||
|
||||
from latent_preview import set_preview_method
|
||||
import nodes
|
||||
|
|
@ -545,7 +543,7 @@ async def execute(server, dynprompt, caches, current_item, extra_data, executed,
|
|||
output_data, output_ui, has_subgraph, has_pending_tasks = await get_output_data(prompt_id, unique_id, obj, input_data_all, execution_block_cb=execution_block_cb, pre_execute_cb=pre_execute_cb, v3_data=v3_data)
|
||||
finally:
|
||||
if comfy.memory_management.aimdo_enabled:
|
||||
if get_console_log_level(args.verbose) == "DEBUG":
|
||||
if args.verbose == "DEBUG":
|
||||
comfy_aimdo.control.analyze()
|
||||
comfy.model_management.reset_cast_buffers()
|
||||
comfy.model_prefetch.cleanup_prefetch_queues()
|
||||
|
|
@ -666,7 +664,6 @@ class PromptExecutor:
|
|||
self.cache_args = cache_args
|
||||
self.cache_type = cache_type
|
||||
self.server = server
|
||||
self.prompt_model_tracker = comfy.model_patcher.PromptModelTracker()
|
||||
self.reset()
|
||||
|
||||
def reset(self):
|
||||
|
|
@ -731,7 +728,6 @@ class PromptExecutor:
|
|||
set_preview_method(extra_data.get("preview_method"))
|
||||
|
||||
nodes.interrupt_processing(False)
|
||||
self.prompt_model_tracker.start()
|
||||
|
||||
if "client_id" in extra_data:
|
||||
self.server.client_id = extra_data["client_id"]
|
||||
|
|
@ -774,7 +770,7 @@ class PromptExecutor:
|
|||
pending_async_nodes = {} # TODO - Unify this with pending_subgraph_results
|
||||
ui_node_outputs = {}
|
||||
executed = set()
|
||||
execution_list = ExecutionList(dynamic_prompt, self.caches.outputs, self.prompt_model_tracker.add)
|
||||
execution_list = ExecutionList(dynamic_prompt, self.caches.outputs)
|
||||
current_outputs = self.caches.outputs.all_node_ids()
|
||||
for node_id in list(execute_outputs):
|
||||
execution_list.add_node(node_id)
|
||||
|
|
@ -836,10 +832,7 @@ class PromptExecutor:
|
|||
if comfy.model_management.DISABLE_SMART_MEMORY:
|
||||
comfy.model_management.unload_all_models()
|
||||
finally:
|
||||
if self.cache_type == CacheType.RAM_PRESSURE:
|
||||
detail("RAM cache evictions: prompt=%s active=%s full=%s", prompt_id, self.caches.outputs.active_evictions, self.caches.outputs.full_evictions)
|
||||
comfy.memory_management.set_ram_cache_release_state(None, 0)
|
||||
self.prompt_model_tracker.end()
|
||||
self._notify_prompt_lifecycle("end", prompt_id)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -29,7 +29,6 @@
|
|||
# upscale_models: models/upscale_models/
|
||||
# latent_upscale_models: models/latent_upscale_models/
|
||||
# custom_nodes: custom_nodes/
|
||||
# datasets: datasets/
|
||||
# hypernetworks: models/hypernetworks/
|
||||
# photomaker: models/photomaker/
|
||||
# classifiers: models/classifiers/
|
||||
|
|
|
|||
|
|
@ -44,8 +44,6 @@ folder_names_and_paths["latent_upscale_models"] = ([os.path.join(models_dir, "la
|
|||
|
||||
folder_names_and_paths["custom_nodes"] = ([os.path.join(base_path, "custom_nodes")], set())
|
||||
|
||||
folder_names_and_paths["datasets"] = ([os.path.join(base_path, "datasets")], set())
|
||||
|
||||
folder_names_and_paths["hypernetworks"] = ([os.path.join(models_dir, "hypernetworks")], supported_pt_extensions)
|
||||
|
||||
folder_names_and_paths["photomaker"] = ([os.path.join(models_dir, "photomaker")], supported_pt_extensions)
|
||||
|
|
|
|||
18
main.py
18
main.py
|
|
@ -2,7 +2,6 @@ import comfy.options
|
|||
comfy.options.enable_args_parsing()
|
||||
|
||||
from comfy.cli_args import args
|
||||
from comfy.cli_args import get_console_log_level, get_file_log_outputs
|
||||
|
||||
if args.list_feature_flags:
|
||||
import json
|
||||
|
|
@ -18,9 +17,7 @@ import folder_paths
|
|||
import time
|
||||
from comfy.cli_args import enables_dynamic_vram
|
||||
from app.logger import setup_logger
|
||||
console_log_level = get_console_log_level(args.verbose)
|
||||
file_log_outputs = [('DETAIL', 'comfyui_detail.log'), *get_file_log_outputs(args.verbose)]
|
||||
setup_logger(log_level=console_log_level, file_outputs=file_log_outputs, use_stdout=args.log_stdout)
|
||||
setup_logger(log_level=args.verbose, use_stdout=args.log_stdout)
|
||||
|
||||
from app.assets.seeder import asset_seeder
|
||||
from app.assets.services import register_output_files
|
||||
|
|
@ -254,18 +251,13 @@ if args.enable_dynamic_vram or (enables_dynamic_vram() and comfy.model_managemen
|
|||
aimdo_initialized = comfy_aimdo.control.init_devices(d.index for d in comfy.model_management.get_all_torch_devices())
|
||||
|
||||
if aimdo_initialized:
|
||||
if console_log_level == 'DEBUG':
|
||||
if args.verbose == 'DEBUG':
|
||||
comfy_aimdo.control.set_log_debug()
|
||||
elif console_log_level == 'DETAIL':
|
||||
try:
|
||||
comfy_aimdo.control.set_log_detail()
|
||||
except AttributeError:
|
||||
comfy_aimdo.control.set_log_info()
|
||||
elif console_log_level == 'CRITICAL':
|
||||
elif args.verbose == 'CRITICAL':
|
||||
comfy_aimdo.control.set_log_critical()
|
||||
elif console_log_level == 'ERROR':
|
||||
elif args.verbose == 'ERROR':
|
||||
comfy_aimdo.control.set_log_error()
|
||||
elif console_log_level == 'WARNING':
|
||||
elif args.verbose == 'WARNING':
|
||||
comfy_aimdo.control.set_log_warning()
|
||||
else: #INFO
|
||||
comfy_aimdo.control.set_log_info()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[project]
|
||||
name = "ComfyUI"
|
||||
version = "0.29.0"
|
||||
version = "0.28.0"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
requires-python = ">=3.10"
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ alembic
|
|||
SQLAlchemy>=2.0.0
|
||||
filelock
|
||||
av>=16.0.0
|
||||
comfy-kitchen==0.2.24
|
||||
comfy-kitchen==0.2.22
|
||||
comfy-aimdo==0.4.10
|
||||
requests
|
||||
simpleeval>=1.0.0
|
||||
|
|
|
|||
137
server.py
137
server.py
|
|
@ -31,6 +31,7 @@ from io import BytesIO
|
|||
|
||||
import aiohttp
|
||||
from aiohttp import web
|
||||
import av
|
||||
import logging
|
||||
|
||||
import mimetypes
|
||||
|
|
@ -212,6 +213,52 @@ def create_block_external_middleware():
|
|||
return block_external_middleware
|
||||
|
||||
|
||||
def resolve_view_media_path(request, user_manager):
|
||||
if "filename" not in request.rel_url.query:
|
||||
return web.Response(status=400)
|
||||
filename = request.rel_url.query["filename"]
|
||||
|
||||
# The frontend's LoadImage combo widget uses asset_hash values
|
||||
# (e.g. "blake3:...") as widget values. When litegraph renders the
|
||||
# node preview, it constructs /view?filename=<asset_hash>, so this
|
||||
# endpoint must resolve blake3 hashes to their on-disk file paths.
|
||||
if filename.startswith("blake3:"):
|
||||
owner_id = user_manager.get_request_user_id(request)
|
||||
result = resolve_hash_to_path(filename, owner_id=owner_id)
|
||||
if result is None:
|
||||
return web.Response(status=404)
|
||||
return result.abs_path, result.download_name, result.content_type
|
||||
|
||||
filename, output_dir = folder_paths.annotated_filepath(filename)
|
||||
|
||||
if not filename:
|
||||
return web.Response(status=400)
|
||||
|
||||
# validation for security: prevent accessing arbitrary path
|
||||
if filename[0] == '/' or '..' in filename:
|
||||
return web.Response(status=400)
|
||||
|
||||
if output_dir is None:
|
||||
type = request.rel_url.query.get("type", "output")
|
||||
output_dir = folder_paths.get_directory_by_type(type)
|
||||
|
||||
if output_dir is None:
|
||||
return web.Response(status=400)
|
||||
|
||||
if "subfolder" in request.rel_url.query:
|
||||
subfolder = request.rel_url.query["subfolder"]
|
||||
if os.path.isabs(subfolder) or os.path.splitdrive(subfolder)[0]:
|
||||
return web.Response(status=403)
|
||||
base_dir = os.path.abspath(output_dir)
|
||||
full_output_dir = os.path.join(base_dir, subfolder)
|
||||
if os.path.commonpath((os.path.abspath(full_output_dir), base_dir)) != base_dir:
|
||||
return web.Response(status=403)
|
||||
output_dir = full_output_dir
|
||||
|
||||
filename = os.path.basename(filename)
|
||||
return os.path.join(output_dir, filename), filename, None
|
||||
|
||||
|
||||
class PromptServer():
|
||||
def __init__(self, loop):
|
||||
PromptServer.instance = self
|
||||
|
|
@ -516,44 +563,10 @@ class PromptServer():
|
|||
@routes.get("/view")
|
||||
async def view_image(request):
|
||||
if "filename" in request.rel_url.query:
|
||||
filename = request.rel_url.query["filename"]
|
||||
|
||||
# The frontend's LoadImage combo widget uses asset_hash values
|
||||
# (e.g. "blake3:...") as widget values. When litegraph renders the
|
||||
# node preview, it constructs /view?filename=<asset_hash>, so this
|
||||
# endpoint must resolve blake3 hashes to their on-disk file paths.
|
||||
if filename.startswith("blake3:"):
|
||||
owner_id = self.user_manager.get_request_user_id(request)
|
||||
result = resolve_hash_to_path(filename, owner_id=owner_id)
|
||||
if result is None:
|
||||
return web.Response(status=404)
|
||||
file, filename, resolved_content_type = result.abs_path, result.download_name, result.content_type
|
||||
else:
|
||||
resolved_content_type = None
|
||||
filename, output_dir = folder_paths.annotated_filepath(filename)
|
||||
|
||||
if not filename:
|
||||
return web.Response(status=400)
|
||||
|
||||
# validation for security: prevent accessing arbitrary path
|
||||
if filename[0] == '/' or '..' in filename:
|
||||
return web.Response(status=400)
|
||||
|
||||
if output_dir is None:
|
||||
type = request.rel_url.query.get("type", "output")
|
||||
output_dir = folder_paths.get_directory_by_type(type)
|
||||
|
||||
if output_dir is None:
|
||||
return web.Response(status=400)
|
||||
|
||||
if "subfolder" in request.rel_url.query:
|
||||
full_output_dir = os.path.join(output_dir, request.rel_url.query["subfolder"])
|
||||
if os.path.commonpath((os.path.abspath(full_output_dir), output_dir)) != output_dir:
|
||||
return web.Response(status=403)
|
||||
output_dir = full_output_dir
|
||||
|
||||
filename = os.path.basename(filename)
|
||||
file = os.path.join(output_dir, filename)
|
||||
resolved = resolve_view_media_path(request, self.user_manager)
|
||||
if isinstance(resolved, web.Response):
|
||||
return resolved
|
||||
file, filename, resolved_content_type = resolved
|
||||
|
||||
if os.path.isfile(file):
|
||||
if 'preview' in request.rel_url.query:
|
||||
|
|
@ -650,6 +663,54 @@ class PromptServer():
|
|||
|
||||
return web.Response(status=404)
|
||||
|
||||
@routes.get("/video_metadata")
|
||||
async def get_video_metadata(request):
|
||||
resolved = resolve_view_media_path(request, self.user_manager)
|
||||
if isinstance(resolved, web.Response):
|
||||
return resolved
|
||||
file = resolved[0]
|
||||
|
||||
if not os.path.isfile(file):
|
||||
return web.Response(status=404)
|
||||
|
||||
def probe_video_metadata():
|
||||
with av.open(file) as container:
|
||||
stream = next((s for s in container.streams if s.type == "video"), None)
|
||||
if stream is None:
|
||||
return None
|
||||
|
||||
fps = float(stream.average_rate) if stream.average_rate else None
|
||||
duration = None
|
||||
if stream.duration is not None and stream.time_base is not None:
|
||||
duration = float(stream.duration * stream.time_base)
|
||||
elif container.duration is not None:
|
||||
duration = float(container.duration * av.time_base)
|
||||
frame_count = stream.frames or None
|
||||
if frame_count is None and duration is not None and fps is not None:
|
||||
frame_count = round(duration * fps)
|
||||
|
||||
return {
|
||||
"fps": fps,
|
||||
"duration": duration,
|
||||
"frame_count": frame_count,
|
||||
"width": stream.codec_context.width,
|
||||
"height": stream.codec_context.height,
|
||||
"size": os.path.getsize(file),
|
||||
}
|
||||
|
||||
try:
|
||||
metadata = await asyncio.to_thread(probe_video_metadata)
|
||||
except FileNotFoundError:
|
||||
return web.Response(status=404)
|
||||
except PermissionError:
|
||||
return web.Response(status=403)
|
||||
except av.error.FFmpegError:
|
||||
return web.Response(status=415)
|
||||
if metadata is None:
|
||||
return web.Response(status=415)
|
||||
|
||||
return web.json_response(metadata)
|
||||
|
||||
@routes.get("/view_metadata/{folder_name}")
|
||||
async def view_metadata(request):
|
||||
folder_name = request.match_info.get("folder_name", None)
|
||||
|
|
|
|||
191
tests-unit/comfy_api_test/video_crop_test.py
Normal file
191
tests-unit/comfy_api_test/video_crop_test.py
Normal file
|
|
@ -0,0 +1,191 @@
|
|||
import pytest
|
||||
import torch
|
||||
import av
|
||||
import struct
|
||||
from fractions import Fraction
|
||||
from comfy_api.latest._input_impl.video_types import VideoFromFile, VideoFromComponents
|
||||
from comfy_api.latest._util.video_types import VideoComponents, normalize_crop_rect
|
||||
|
||||
|
||||
RED = torch.tensor([1.0, 0.0, 0.0])
|
||||
GREEN = torch.tensor([0.0, 1.0, 0.0])
|
||||
BLUE = torch.tensor([0.0, 0.0, 1.0])
|
||||
WHITE = torch.tensor([1.0, 1.0, 1.0])
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def quadrant_components():
|
||||
"""64x64, 2 frames; each 32x32 quadrant a distinct solid color to locate crops"""
|
||||
images = torch.zeros(2, 64, 64, 3)
|
||||
images[:, :32, :32] = RED
|
||||
images[:, :32, 32:] = GREEN
|
||||
images[:, 32:, :32] = BLUE
|
||||
images[:, 32:, 32:] = WHITE
|
||||
return VideoComponents(images=images, frame_rate=Fraction(30))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def src(quadrant_components, tmp_path_factory):
|
||||
path = str(tmp_path_factory.mktemp("video") / "src.mp4")
|
||||
VideoFromComponents(quadrant_components).save_to(path)
|
||||
return path
|
||||
|
||||
|
||||
def probe_dimensions(path):
|
||||
with av.open(path) as container:
|
||||
stream = container.streams.video[0]
|
||||
return stream.width, stream.height
|
||||
|
||||
|
||||
def decoded_center_color(path):
|
||||
"""Mean RGB of the center 8x8 of the first decoded frame"""
|
||||
with av.open(path) as container:
|
||||
frame = next(container.decode(container.streams.video[0]))
|
||||
rgb = torch.from_numpy(frame.to_ndarray(format="rgb24")).float() / 255.0
|
||||
h, w = rgb.shape[0], rgb.shape[1]
|
||||
return rgb[h // 2 - 4:h // 2 + 4, w // 2 - 4:w // 2 + 4].mean(dim=(0, 1))
|
||||
|
||||
|
||||
def assert_color(actual, expected, tolerance=0.15):
|
||||
assert torch.allclose(actual, expected, atol=tolerance), f"{actual} != {expected}"
|
||||
|
||||
|
||||
class TestNormalizeCropRect:
|
||||
def test_clamps_to_frame_and_even_aligns(self):
|
||||
assert normalize_crop_rect(10, 10, 100, 100, 64, 64) == (10, 10, 54, 54)
|
||||
assert normalize_crop_rect(0, 0, 33, 31, 64, 64) == (0, 0, 32, 30)
|
||||
|
||||
def test_empty_and_full_frame_are_none(self):
|
||||
assert normalize_crop_rect(0, 0, 0, 0, 64, 64) is None
|
||||
assert normalize_crop_rect(0, 0, -2, 10, 64, 64) is None
|
||||
assert normalize_crop_rect(0, 0, 64, 64, 64, 64) is None
|
||||
|
||||
def test_negative_origin_clamps_to_zero(self):
|
||||
assert normalize_crop_rect(-10, -10, 32, 32, 64, 64) == (0, 0, 32, 32)
|
||||
|
||||
def test_full_frame_on_odd_source_is_none(self):
|
||||
assert normalize_crop_rect(0, 0, 65, 63, 65, 63) is None
|
||||
|
||||
|
||||
class TestVideoFromComponentsCrop:
|
||||
def test_slices_images(self, quadrant_components):
|
||||
cropped = VideoFromComponents(quadrant_components).as_cropped(32, 0, 32, 32)
|
||||
components = cropped.get_components()
|
||||
assert components.images.shape == (2, 32, 32, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), GREEN, tolerance=0.01)
|
||||
|
||||
def test_noop_returns_self(self, quadrant_components):
|
||||
video = VideoFromComponents(quadrant_components)
|
||||
assert video.as_cropped(0, 0, 0, 0) is video
|
||||
assert video.as_cropped(0, 0, 64, 64) is video
|
||||
|
||||
def test_slices_alpha(self, quadrant_components):
|
||||
alpha = torch.zeros(2, 64, 64)
|
||||
alpha[:, :32, :32] = 1.0
|
||||
with_alpha = VideoComponents(
|
||||
images=quadrant_components.images,
|
||||
frame_rate=quadrant_components.frame_rate,
|
||||
alpha=alpha,
|
||||
)
|
||||
components = VideoFromComponents(with_alpha).as_cropped(0, 0, 32, 32).get_components()
|
||||
assert components.alpha.shape == (2, 32, 32)
|
||||
assert components.alpha.min() == 1.0
|
||||
|
||||
|
||||
class TestVideoFromFileCrop:
|
||||
def test_dimensions_and_components(self, src):
|
||||
cropped = VideoFromFile(src).as_cropped(0, 32, 32, 32)
|
||||
assert cropped.get_dimensions() == (32, 32)
|
||||
components = cropped.get_components()
|
||||
assert components.images.shape == (2, 32, 32, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), BLUE)
|
||||
|
||||
def test_save_streams_cropped_output(self, src, tmp_path):
|
||||
path = str(tmp_path / "cropped.mp4")
|
||||
VideoFromFile(src).as_cropped(32, 32, 32, 32).save_to(path)
|
||||
assert probe_dimensions(path) == (32, 32)
|
||||
assert_color(decoded_center_color(path), WHITE)
|
||||
|
||||
def test_noop_returns_self(self, src):
|
||||
video = VideoFromFile(src)
|
||||
assert video.as_cropped(0, 0, 0, 0) is video
|
||||
assert video.as_cropped(0, 0, 64, 64) is video
|
||||
|
||||
def test_nested_crop_composes_against_normalized_outer(self, src):
|
||||
outer = VideoFromFile(src).as_cropped(0, 0, 33, 31)
|
||||
assert outer.get_dimensions() == (32, 30)
|
||||
assert outer.as_cropped(0, 0, 32, 30) is outer
|
||||
|
||||
inner = outer.as_cropped(0, 0, 16, 16)
|
||||
components = inner.get_components()
|
||||
assert components.images.shape == (2, 16, 16, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), RED)
|
||||
|
||||
def test_composes_with_trim(self, src, tmp_path):
|
||||
video = VideoFromFile(src).as_trimmed(0, 1 / 30, strict_duration=False).as_cropped(32, 0, 32, 32)
|
||||
components = video.get_components()
|
||||
assert components.images.shape == (1, 32, 32, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), GREEN)
|
||||
|
||||
path = str(tmp_path / "trim_crop.mp4")
|
||||
video.save_to(path)
|
||||
assert probe_dimensions(path) == (32, 32)
|
||||
assert_color(decoded_center_color(path), GREEN)
|
||||
|
||||
def test_crop_survives_trim(self, src):
|
||||
video = VideoFromFile(src).as_cropped(32, 0, 32, 32).as_trimmed(0, 1 / 30, strict_duration=False)
|
||||
components = video.get_components()
|
||||
assert components.images.shape == (1, 32, 32, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), GREEN)
|
||||
|
||||
def test_crop_of_crop_composes(self, src):
|
||||
cropped = VideoFromFile(src).as_cropped(32, 0, 32, 64).as_cropped(0, 32, 32, 32)
|
||||
components = cropped.get_components()
|
||||
assert components.images.shape == (2, 32, 32, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), WHITE)
|
||||
|
||||
|
||||
def tag_rotation_90(path):
|
||||
"""Patch the mp4 tkhd display matrix to a 90-degree rotation (phone-style metadata)"""
|
||||
with open(path, "rb") as f:
|
||||
data = bytearray(f.read())
|
||||
index = data.find(b"tkhd")
|
||||
assert index != -1
|
||||
matrix_offset = index + 4 + 40
|
||||
data[matrix_offset:matrix_offset + 36] = struct.pack(
|
||||
">9i", 0, 65536, 0, -65536, 0, 0, 0, 0, 1073741824
|
||||
)
|
||||
with open(path, "wb") as f:
|
||||
f.write(bytes(data))
|
||||
|
||||
|
||||
@pytest.fixture(scope="module")
|
||||
def rotated_src(tmp_path_factory):
|
||||
"""64x32 coded video (left RED, right GREEN) tagged with a 90-degree display
|
||||
matrix, so its display space is 32x64 with RED on top and GREEN below"""
|
||||
images = torch.zeros(2, 32, 64, 3)
|
||||
images[:, :, :32] = RED
|
||||
images[:, :, 32:] = GREEN
|
||||
path = str(tmp_path_factory.mktemp("video") / "rotated.mp4")
|
||||
VideoFromComponents(VideoComponents(images=images, frame_rate=Fraction(30))).save_to(path)
|
||||
tag_rotation_90(path)
|
||||
return path
|
||||
|
||||
|
||||
class TestRotatedSourceCrop:
|
||||
def test_components_are_rotation_corrected(self, rotated_src):
|
||||
components = VideoFromFile(rotated_src).get_components()
|
||||
assert components.images.shape == (2, 64, 32, 3)
|
||||
|
||||
def test_crop_applies_in_display_space(self, rotated_src):
|
||||
cropped = VideoFromFile(rotated_src).as_cropped(0, 32, 32, 32)
|
||||
assert cropped.get_dimensions() == (32, 32)
|
||||
components = cropped.get_components()
|
||||
assert components.images.shape == (2, 32, 32, 3)
|
||||
assert_color(components.images[0].mean(dim=(0, 1)), GREEN)
|
||||
|
||||
def test_save_crops_in_display_space(self, rotated_src, tmp_path):
|
||||
path = str(tmp_path / "rotated_crop.mp4")
|
||||
VideoFromFile(rotated_src).as_cropped(0, 32, 32, 32).save_to(path)
|
||||
assert probe_dimensions(path) == (32, 32)
|
||||
assert_color(decoded_center_color(path), GREEN)
|
||||
Loading…
Add table
Reference in a new issue