from __future__ import annotations import math from typing import Any import nodes as comfy_nodes import torch from comfy_api.latest import io from comfy_execution.graph_utils import GraphBuilder from ..utils.minimax import ( expand_image_inputs, flatten_media_inputs, remove_output_files_by_prefix, ) CATEGORY_MINIMAX = "EasyUse/MiniMax" CANVAS_MULTIPLE = 32 BASE_SHORT_EDGE = 768 MAX_PIXELS = 768 * 1344 REF_IMAGE_SHORT_EDGE = 2048 FPS = 24 AUDIO_LATENT_FPS = 40 MAX_REF_IMAGES = 9 MAX_REF_VIDEOS = 3 MAX_REF_AUDIOS = 3 REFERENCE_BRIDGE_NODE_ID = "easy MiniMaxH3ReferenceToVideoBridge" def _align_frame_count(frame_count: int) -> int: while frame_count % 17 != 5: frame_count += 1 return frame_count def _video_latent_length(frame_count: int) -> int: return 2 if frame_count <= 5 else ((frame_count - 5) // 17) * 5 + 2 def _temporal_shape(length: int) -> tuple[int, int, int]: frame_count = _align_frame_count(max(5, length)) duration = frame_count / FPS return ( frame_count, _video_latent_length(frame_count), round(duration * AUDIO_LATENT_FPS), ) def _empty_av_latent( width: int, height: int, length: int ) -> tuple[dict[str, Any], int]: try: import comfy.model_management import comfy.nested_tensor except ImportError as error: raise RuntimeError( "MiniMax H3 requires a ComfyUI version with nested AV latent support" ) from error frame_count, latent_length, audio_length = _temporal_shape(length) device = comfy.model_management.intermediate_device() video = torch.zeros( [1, 24, latent_length, height // 16, width // 16], device=device, ) audio = torch.zeros([1, 32, 2, audio_length], device=device) return {"samples": comfy.nested_tensor.NestedTensor((video, audio))}, frame_count def _resize(image: torch.Tensor, width: int, height: int, crop: str) -> torch.Tensor: try: import comfy.utils except ImportError as error: raise RuntimeError( "MiniMax H3 requires ComfyUI image resize utilities" ) from error samples = image[..., :3].movedim(-1, 1) samples = comfy.utils.common_upscale(samples, width, height, "lanczos", crop) return samples.movedim(1, -1) def _adapt_canvas(width: int, height: int) -> tuple[int, int]: ratio = width / height if ratio >= 1.0: nominal_width, nominal_height = BASE_SHORT_EDGE * ratio, BASE_SHORT_EDGE else: nominal_width, nominal_height = BASE_SHORT_EDGE, BASE_SHORT_EDGE / ratio if nominal_width * nominal_height > MAX_PIXELS: scale = math.sqrt(MAX_PIXELS / (nominal_width * nominal_height)) nominal_width *= scale nominal_height *= scale return ( max(CANVAS_MULTIPLE, round(nominal_width / CANVAS_MULTIPLE) * CANVAS_MULTIPLE), max(CANVAS_MULTIPLE, round(nominal_height / CANVAS_MULTIPLE) * CANVAS_MULTIPLE), ) def _set_conditioning_values( conditioning: Any, values: dict[str, Any], ) -> Any: try: import node_helpers except ImportError as error: raise RuntimeError( "MiniMax H3 requires ComfyUI conditioning helpers" ) from error return node_helpers.conditioning_set_values(conditioning, values) def _first_input(value: Any, default: Any = None) -> Any: while isinstance(value, list): if not value: return default value = value[0] return default if value is None else value def _audio_inputs(value: Any) -> list[dict[str, Any]]: audios: list[dict[str, Any]] = [] for audio in flatten_media_inputs(value): if ( not isinstance(audio, dict) or "waveform" not in audio or "sample_rate" not in audio ): raise TypeError("audios must contain AUDIO values") audios.append(audio) return audios def _encode_ref_audio( audio_vae: Any, audio: dict[str, Any] ) -> tuple[torch.Tensor, int]: waveform = audio["waveform"] sample_rate = audio["sample_rate"] vae_sample_rate = getattr(audio_vae, "audio_sample_rate", 32000) if sample_rate != vae_sample_rate: try: import torchaudio except ImportError as error: raise RuntimeError( "torchaudio is required to resample MiniMax H3 reference audio" ) from error waveform = torchaudio.functional.resample( waveform, sample_rate, vae_sample_rate, ) latent = audio_vae.encode(waveform[:1].movedim(1, -1)) return latent, latent.shape[-1] class MiniMaxH3ImageToVideoFallback(io.ComfyNode): """Compatibility copy used when ComfyUI does not ship the native H3 node.""" @classmethod def define_schema(cls) -> io.Schema: return io.Schema( node_id="MiniMaxH3ImageToVideo", display_name="MiniMax H3 Image to Video", category="model/conditioning/minimax", description=( "Create MiniMax H3 text-to-video or first/last-frame " "conditioning with a joint audio-video latent." ), inputs=[ io.Clip.Input("clip"), io.Vae.Input("vae"), io.String.Input("prompt", multiline=True, dynamic_prompts=True), io.Int.Input( "width", default=1344, min=32, max=comfy_nodes.MAX_RESOLUTION, step=32, ), io.Int.Input( "height", default=768, min=32, max=comfy_nodes.MAX_RESOLUTION, step=32, ), io.Int.Input("length", default=124, min=5, max=3600, step=17), io.Image.Input("first_frame", optional=True), io.Image.Input("last_frame", optional=True), ], outputs=[ io.Conditioning.Output(display_name="positive"), io.Latent.Output(), ], ) @classmethod def execute( cls, clip: Any, vae: Any, prompt: str, width: int, height: int, length: int, first_frame: torch.Tensor | None = None, last_frame: torch.Tensor | None = None, ) -> io.NodeOutput: latent, frame_count = _empty_av_latent(width, height, length) token_images: list[torch.Tensor] = [] keyframes: list[dict[str, Any]] = [] if first_frame is not None: image = _resize(first_frame[:1], width, height, "disabled") token_images.append(image) keyframes.append({"resolved_frame_index": 0, "image": image}) if last_frame is not None: image = _resize(last_frame[:1], width, height, "center") token_images.append(image) keyframes.append({"resolved_frame_index": frame_count - 1, "image": image}) tokens = clip.tokenize(prompt, images=token_images) conditioning = clip.encode_from_tokens_scheduled(tokens) for keyframe in keyframes: keyframe["latent"] = vae.encode(keyframe.pop("image")) if keyframes: conditioning = _set_conditioning_values( conditioning, { "minimax_keyframes": keyframes, "minimax_frame_count": frame_count, }, ) return io.NodeOutput(conditioning, latent) class MiniMaxH3ReferenceToVideoFallback(io.ComfyNode): """Compatibility copy used when ComfyUI does not ship the native H3 node.""" @classmethod def define_schema(cls) -> io.Schema: return io.Schema( node_id="MiniMaxH3ReferenceToVideo", display_name="MiniMax H3 Reference to Video", category="model/conditioning/minimax", description=( "Create MiniMax H3 reference conditioning from images, videos, " "and audio using ,