Upload app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859609 unmodified lines707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327from __future__ import annotationsimport osimport tempfileimport timefrom functools import lru_cacheimport spacesos.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")import gradio as grimport torchfrom h3_split_blocks import MiniMaxH3GeneratorBlocksMODEL_REPO = "MiniMaxAI/MiniMax-H3"LORA_REPO = "rzgar/minimax-h3_fl2v_8Step_motion_enhancer"LORA_FILE = "minimax-h3_fl2v_8Step_motion_enhancer.safetensors"CONDITIONER_SPACE = "multimodalart/qwen3vl-conditioner"FPS = 24STEPS = 8OUTPUT_DIR = os.path.join(tempfile.gettempdir(), "minimax-h3-motion-enhancer")os.makedirs(OUTPUT_DIR, exist_ok=True)CANVASES = {"960x544 · 16:9 fast": (544, 960),"1024x576 · 16:9 fast": (576, 1024),"544x960 · 9:16 fast": (960, 544),"544x544 · 1:1 fast": (544, 544),"768x576 · 4:3 fast": (576, 768),"576x768 · 3:4 fast": (768, 576),"1152x512 · 21:9 fast": (512, 1152),}DEFAULT_CANVAS = "960x544 · 16:9 fast"def _reorder_interleaved_qkv(weight: torch.Tensor, num_heads: int, head_dim: int) -> torch.Tensor:grouped = weight.reshape(num_heads, 3 * head_dim, *weight.shape[1:])query, key, value = grouped.split(head_dim, dim=1)return torch.cat([part.reshape(num_heads * head_dim, *weight.shape[1:]) for part in (query, key, value)], dim=0)def _lora_target_name(source_name: str) -> str:target = source_name.removeprefix("diffusion_model.")if target.startswith("token_refiner.blocks."):target = target.replace("token_refiner.blocks.", "token_refiner.refiner_blocks.", 1)elif target.startswith("blocks."):target = target.replace("blocks.", "transformer_blocks.", 1)return target.replace("final_layer.adaln_proj.linear", "norm_out.linear")def _lora_targets(name: str, b_weight: torch.Tensor, num_heads: int, head_dim: int):target = _lora_target_name(name)if target.endswith(".attn.qkv_proj"):prefix = target.removesuffix("qkv_proj")rows = _reorder_interleaved_qkv(b_weight, num_heads, head_dim)9 unmodified lineselse:yield target + ".weight", b_weightdef _apply_motion_lora(transformer) -> str:from huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filepath = hf_hub_download(LORA_REPO, LORA_FILE)lora = load_file(path, device="cpu")suffix_a = ".lora_A.weight"suffix_b = ".lora_B.weight"bases = sorted({key[: -len(suffix_a)] for key in lora if key.endswith(suffix_a)})if not bases:raise ValueError("The motion enhancer LoRA did not contain any lora_A/lora_B pairs")params = dict(transformer.named_parameters())num_heads = transformer.config.num_attention_headshead_dim = transformer.config.attention_head_dimfolded = 0missed = []with torch.no_grad():for name in bases:a = lora[f"{name}{suffix_a}"]b = lora.get(f"{name}{suffix_b}")if b is None:raise ValueError(f"Missing LoRA B matrix for {name}")for key, b_part in _lora_targets(name, b, num_heads, head_dim):param = params.get(key)if param is None:missed.append(key)continuedelta = b_part.float() @ a.float()if delta.shape != param.shape:raise ValueError(f"LoRA shape mismatch for {key}: {delta.shape} vs {param.shape}")param.data = (param.data.float() + delta.to(param.device)).to(param.dtype)folded += 1if missed:raise ValueError(f"{len(missed)} LoRA targets did not match the H3 transformer, e.g. {missed[:3]}")return f"Motion enhancer loaded: {len(bases)} adapters, {folded} matrices"def _load_pipeline():from diffusers import ComponentsManagermanager = ComponentsManager()blocks = MiniMaxH3GeneratorBlocks()pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3")pipe.load_components(dtype=torch.bfloat16)pipe.vae.set_attention_backend("native")pipe.audio_vae.set_attention_backend("native")pipe.transformer.set_attention_backend(os.environ.get("H3_ATTENTION", "_native_cudnn"))print(_apply_motion_lora(pipe.transformer), flush=True)# Module-scope placement lets ZeroGPU pack the weights once instead of per request.pipe.transformer.to("cuda")return pipePIPE = _load_pipeline()@lru_cache(maxsize=1)def _conditioner_client():from gradio_client import Clientreturn Client(CONDITIONER_SPACE)def _snap_frames(seconds: float) -> int:frames = max(120, round(float(seconds) * FPS))while frames % 17 != 5:frames += 1return framesdef _cover_crop(image_path: str, canvas: str) -> str:from PIL import Image, ImageOpsheight, width = CANVASES[canvas]with Image.open(image_path) as image:image = ImageOps.exif_transpose(image).convert("RGB")image = ImageOps.fit(image, (width, height), method=Image.Resampling.LANCZOS)output = os.path.join(OUTPUT_DIR, f"frame-{time.time_ns()}.png")image.save(output)return outputdef _condition(prompt: str, image_path: str, canvas: str, num_frames: int, rewrite_prompt: bool = False):"""Encode the prompt through the same Qwen3-VL conditioner path used by FlashGen.When rewrite_prompt=True, the conditioner first rewrites the user's prompt intoMiniMax-H3's structured shot description, then encodes that rewritten prompt.This is the "Upsample/Enhance prompt" behavior from the FlashGen Space."""from gradio_client import handle_filefrom safetensors import safe_opendef call():return _conditioner_client().predict(prompt=prompt,image_path=handle_file(image_path),last_image_path=None,canvas=canvas,num_frames=num_frames,rewrite_prompt=bool(rewrite_prompt),api_name="/encode",)try:path, plan = call()except Exception as first:# The conditioner can occasionally leave a stale Gradio client behind.# Retry once with a fresh client, matching the FlashGen implementation.print(f"[conditioner] retrying with a fresh client after: {first}", flush=True)_conditioner_client.cache_clear()path, plan = call()with safe_open(path, framework="pt") as handle:embeds = handle.get_tensor("prompt_embeds")tags = handle.get_tensor("text_token_tags")metadata = handle.metadata()return embeds, tags, metadata, plan@spaces.GPU(duration=120, size="xlarge")def _generate_gpu(embeds, tags, image, height: int, width: int, num_frames: int, seed: int):"""Run MiniMax-H3 denoising and return CPU video frames plus soundtrack."""PIPE.vae.to("cuda")PIPE.audio_vae.to("cuda")pipe_state = PIPE(prompt_embeds=embeds.to("cuda"),text_token_tags=tags,image=image,height=int(height),width=int(width),num_frames=int(num_frames),num_inference_steps=STEPS + 1,generator=torch.Generator("cpu").manual_seed(int(seed)),)frames = pipe_state.get("videos")[0]audio = pipe_state.get("audio")[0]if torch.is_tensor(frames):frames = frames.cpu()if torch.is_tensor(audio):audio = audio.cpu()return frames, audio, int(pipe_state.get("sampling_rate"))def generate(prompt: str,image_path: str | None,canvas: str,duration: float,seed: int,enhance_prompt: bool = False,progress=gr.Progress(track_tqdm=True),):"""Animate an uploaded image, optionally using H3's Qwen3-VL prompt enhancement."""if not image_path:raise gr.Error("Upload a first frame before generating.")if not prompt or not prompt.strip():raise gr.Error("Describe the motion you want to see.")height, width = CANVASES[canvas]num_frames = _snap_frames(duration)cropped_path = _cover_crop(image_path, canvas)from PIL import Imagefrom diffusers.utils import encode_videoprogress(0.05,desc="Enhancing prompt, then encoding..." if enhance_prompt else "Encoding the first frame...",)embeds, tags, metadata, plan = _condition(prompt.strip(), cropped_path, canvas, num_frames, rewrite_prompt=bool(enhance_prompt))height = int(metadata.get("height", height))width = int(metadata.get("width", width))num_frames = int(metadata.get("num_frames", num_frames))enhanced = (plan or {}).get("refined_prompt") or ""progress(0.15, desc=f"Generating {num_frames / FPS:.1f}s at {width}x{height} in {STEPS} steps")with Image.open(cropped_path) as image:frames, audio, sampling_rate = _generate_gpu(embeds, tags, image.convert("RGB"), height, width, num_frames, int(seed))output = os.path.join(OUTPUT_DIR, f"motion-enhanced-{time.time_ns()}.mp4")encode_video(frames, fps=FPS, output_path=output, audio=audio, audio_sample_rate=sampling_rate)status = (f"{width}x{height} · {num_frames / FPS:.2f}s · {STEPS} denoising steps · "f"seed {int(seed)}")return output, status, enhanced, gr.update(visible=bool(enhanced))DESCRIPTION = """# MiniMax-H3 Motion EnhancerUpload a still image and describe the movement. The Space uses the **8-step Motion Enhancer LoRA**with MiniMax-H3 and synchronized audio.**Enhance / Upsample prompt** uses the same Qwen3-VL prompt-rewriting path as the MiniMax-H3 FlashGenSpace: your short instruction is first expanded into a structured shot/action/sound description andthen those rewritten embeddings are sent to H3.Use only images you own or have permission to animate."""with gr.Blocks(title="MiniMax-H3 Motion Enhancer") as demo:gr.Markdown(DESCRIPTION)with gr.Row(equal_height=True):with gr.Column(scale=1):image = gr.Image(label="First frame", type="filepath", sources=["upload", "webcam"])prompt = gr.Textbox(label="Motion prompt",value="The person naturally performs the described action. Keep the same identity and appearance. Natural body motion, realistic facial expression, synchronized sound effects and speech if specified.",lines=5,placeholder="Describe the action, camera movement and sound...",)enhance = gr.Checkbox(label="Enhance / Upsample prompt",value=False,info="Rewrite the prompt with H3's Qwen3-VL into a detailed structured shot description before generation.",)with gr.Row():canvas = gr.Dropdown(list(CANVASES), value=DEFAULT_CANVAS, label="Output canvas")duration = gr.Slider(5, 15, value=5, step=1, label="Duration (seconds)")seed = gr.Number(value=42, precision=0, label="Seed")generate_button = gr.Button("Generate motion", variant="primary", size="lg")with gr.Column(scale=1):video = gr.Video(label="Generated video + soundtrack", autoplay=True)status = gr.Markdown()with gr.Accordion("Upsampled prompt", open=False, visible=False) as enhanced_panel:enhanced_box = gr.Textbox(show_label=False, lines=10, interactive=False)outputs = [video, status, enhanced_box, enhanced_panel]generate_button.click(fn=generate,inputs=[prompt, image, canvas, duration, seed, enhance],outputs=outputs,api_name="generate",)prompt.submit(fn=generate,inputs=[prompt, image, canvas, duration, seed, enhance],outputs=outputs,api_name="generate_submit",)demo.queue(max_size=8).launch(mcp_server=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909 unmodified lines100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639from __future__ import annotationsimport osimport re# Set allocator behavior before spaces/torch initialize CUDA. Large H3 components# can otherwise fragment the ZeroGPU allocator during their first device transfer.os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")# Import spaces before torch: this is required by ZeroGPU.import spacesimport timeimport tempfileimport tracebackimport subprocessimport shutilfrom pathlib import Pathfrom functools import cacheimport gradio as grMODEL_REPO = os.environ.get("H3_MODEL_REPO", "MiniMaxAI/MiniMax-H3")CONDITIONER_SPACE = os.environ.get("H3_CONDITIONER", "multimodalart/qwen3vl-conditioner")HYPERFLOW_REPO = os.environ.get("H3_HYPERFLOW_REPO", "videorebirth/hyperflow")GPU_SIZE = os.environ.get("H3_GPU_SIZE", "xlarge")GPU_MEMORY_RESERVE_MARGIN = os.environ.get("H3_MEMORY_RESERVE_MARGIN", "8GB")FPS = 24 # MiniMax-H3 native frame rate; keep video and generated audio timing consistent.FRAMES_PER_CHUNK = 17LATENTS_PER_CHUNK = 5MIN_DURATION = 5MAX_DURATION = 14# Canvas labels must exactly match the choices exposed by the remote conditioner.# Use its fast presets to avoid accidentally requesting unsupported dimensions.CANVASES = {"960x544 · 16:9 fast": (544, 960),"768x576 · 4:3 fast": (576, 768),"544x544 · 1:1 fast": (544, 544),"576x768 · 3:4 fast": (768, 576),"544x960 · 9:16 fast": (960, 544),}DEFAULT_CANVAS = "960x544 · 16:9 fast"PIPE = NoneMANAGER = NoneLOAD_ERROR = Nonedef snap_frames(seconds: float) -> int:"""Choose the nearest decodable frame count instead of always rounding up."""target = max(1, round(float(seconds) * FPS))# MiniMax-H3 is natively 24 fps. Valid counts are 17*n + 5;# n=7..19 covers approximately 5.2..13.7 seconds without slowing playback.valid = [n * FRAMES_PER_CHUNK + LATENTS_PER_CHUNKfor n in range(7, 20)]return min(valid, key=lambda frames: abs(frames - target))def lower_duration_floor(seconds: float = 2.0) -> None:from diffusers.modular_pipelines.minimax_h3.modular_pipeline import MiniMaxH3ModularPipelineMiniMaxH3ModularPipeline.min_duration = property(lambda self: float(seconds))# Motion Adapter v1.0 from the reference Space supplied by the user.MOTION_LORA_REPO = os.environ.get("H3_MOTION_LORA_REPO", "rzgar/minimax-h3_fl2v_8Step_motion_enhancer")MOTION_LORA_FILE = os.environ.get("H3_MOTION_LORA_FILE", "minimax-h3_fl2v_8Step_motion_enhancer.safetensors")def _reorder_interleaved_qkv(weight, num_heads: int, head_dim: int):grouped = weight.reshape(num_heads, 3 * head_dim, *weight.shape[1:])query, key, value = grouped.split(head_dim, dim=1)return torch.cat([part.reshape(num_heads * head_dim, *weight.shape[1:]) for part in (query, key, value)], dim=0)def _motion_lora_targets(source_name: str, b_weight, num_heads: int, head_dim: int):import torchtarget = source_name.removeprefix("diffusion_model.")if target.startswith("token_refiner.blocks."):target = target.replace("token_refiner.blocks.", "token_refiner.refiner_blocks.", 1)elif target.startswith("blocks."):target = target.replace("blocks.", "transformer_blocks.", 1)target = target.replace("final_layer.adaln_proj.linear", "norm_out.linear")if target.endswith(".attn.qkv_proj"):prefix = target.removesuffix("qkv_proj")rows = _reorder_interleaved_qkv(b_weight, num_heads, head_dim)9 unmodified lineselse:yield target + ".weight", b_weightdef apply_motion_adapter(transformer) -> str:"""Load the reference Space's 8-step motion-enhancer LoRA, validating all keys before mutation."""import torchfrom huggingface_hub import hf_hub_downloadfrom safetensors.torch import load_filepath = hf_hub_download(repo_id=MOTION_LORA_REPO, filename=MOTION_LORA_FILE)lora = load_file(path, device="cpu")suffix_a, suffix_b = ".lora_A.weight", ".lora_B.weight"bases = sorted({key[:-len(suffix_a)] for key in lora if key.endswith(suffix_a)})if not bases:raise RuntimeError(f"Motion Adapter has no lora_A/lora_B pairs: {MOTION_LORA_REPO}/{MOTION_LORA_FILE}")params = dict(transformer.named_parameters())num_heads = transformer.config.num_attention_headshead_dim = transformer.config.attention_head_dimplanned, missing = [], []for name in bases:a = lora[f"{name}{suffix_a}"]b = lora.get(f"{name}{suffix_b}")if b is None:raise RuntimeError(f"Motion Adapter is missing LoRA B matrix for {name}")for key, b_part in _motion_lora_targets(name, b, num_heads, head_dim):param = params.get(key)if param is None:missing.append(key)continuedelta = b_part.float() @ a.float()if tuple(delta.shape) != tuple(param.shape):raise RuntimeError(f"Motion Adapter shape mismatch for {key}: delta={tuple(delta.shape)}, target={tuple(param.shape)}")planned.append((param, delta))# Validate the complete mapping before changing a single model tensor.if missing:raise RuntimeError(f"Motion Adapter key mapping incompatible with this HyperFlow transformer: {len(missing)} target(s) missing; "f"examples: {', '.join(missing[:8])}")if not planned:raise RuntimeError("Motion Adapter matched zero transformer parameters")with torch.no_grad():for param, delta in planned:param.data.copy_((param.data.float() + delta.to(param.device)).to(param.dtype))return f"Motion Adapter v1.0 loaded: {len(bases)} LoRA pairs / {len(planned)} weight tensors from {MOTION_LORA_REPO}"def load_models() -> None:global PIPE, MANAGER, LOAD_ERRORif PIPE is not None or LOAD_ERROR:returnstarted = time.time()try:import torch# Work around a device mismatch in some released Diffusers builds:# build_ref2va_packed_sequence creates token_tags on the active default# device, but may receive text_token_tags on CPU from the split conditioner.# Move text_token_tags to token_tags.device at the assignment itself.import diffusers# Work around a second CPU/CUDA mismatch in some Diffusers builds:# context_embedder's weights may be on CUDA while encoder_hidden_states# remain on CPU. Match both the module device and dtype before matmul.diffusers_root = Path(diffusers.__file__).parenttransformer_files = list(diffusers_root.rglob("transformer_minimax_h3.py"))context_patch_applied = Falsefor transformer_file in transformer_files:transformer_source = transformer_file.read_text(encoding="utf-8")old_context = "encoder_hidden_states.to(self.context_embedder.weight.dtype)"new_context = "encoder_hidden_states.to(device=self.context_embedder.weight.device, dtype=self.context_embedder.weight.dtype)"if old_context in transformer_source:transformer_file.write_text(transformer_source.replace(old_context, new_context), encoding="utf-8")context_patch_applied = Trueprint(f"[HyperFlow] Applied context_embedder CPU/CUDA device fix: {transformer_file}", flush=True)elif new_context in transformer_source:context_patch_applied = Trueprint(f"[HyperFlow] context_embedder device fix already present: {transformer_file}", flush=True)if not context_patch_applied:print("[HyperFlow] WARNING: transformer_minimax_h3.py context_embedder line not found; second device patch may not apply", flush=True)# The traceback in affected Diffusers builds points to before_denoise.py,# not packing_ref2va.py. Patch both possible implementations because versions differ.packing_files = [diffusers_root / "modular_pipelines" / "minimax_h3" / "before_denoise.py",diffusers_root / "modular_pipelines" / "minimax_h3" / "packing_ref2va.py",]token_patch_applied = Falseold_line = "token_tags[text_indices] = text_token_tags.to(torch.long)"new_line = "token_tags[text_indices.to(device=token_tags.device)] = text_token_tags.to(device=token_tags.device, dtype=torch.long)"for packing_file in packing_files:if not packing_file.exists():continuesource = packing_file.read_text(encoding="utf-8")if old_line in source:packing_file.write_text(source.replace(old_line, new_line), encoding="utf-8")token_patch_applied = Trueprint(f"[HyperFlow] Applied Ref2VA CPU/CUDA token-tag fix: {packing_file}", flush=True)elif new_line in source:token_patch_applied = Trueprint(f"[HyperFlow] Ref2VA token-tag device fix already present: {packing_file}", flush=True)if not token_patch_applied:print("[HyperFlow] WARNING: token-tag assignment not found in before_denoise.py or packing_ref2va.py; device patch not applied", flush=True)from diffusers import ComponentsManagerfrom hyperflow_h3 import swap_hyperflow_blocks, load_hyperflow_lorafrom h3_split_blocks import MiniMaxH3GeneratorBlockslower_duration_floor()manager = ComponentsManager()blocks = MiniMaxH3GeneratorBlocks()# FL2VA uses the official transformer partition and anchors the generated# video's first frame to the source video's final frame.swap_hyperflow_blocks(blocks)print(f"[HyperFlow] Loading FL2VA keyframe components from {MODEL_REPO}", flush=True)pipe = blocks.init_pipeline(MODEL_REPO, components_manager=manager, collection="h3-hyperflow")pipe.load_components(dtype=torch.bfloat16, trust_remote_code=True)pipe.vae.set_attention_backend("native")pipe.audio_vae.set_attention_backend("native")# Use the native cuDNN attention backend when the installed Diffusers/CUDA# build supports it; fall back safely on builds without that backend.try:pipe.transformer.set_attention_backend("_native_cudnn")print("[HyperFlow] transformer attention backend=_native_cudnn", flush=True)except Exception as attention_exc:pipe.transformer.set_attention_backend("native")print(f"[HyperFlow] transformer cuDNN attention unavailable; using native: "f"{type(attention_exc).__name__}: {attention_exc}", flush=True)# Apply the reference Space's Motion Adapter using its published key conversion.# It is validated in full before any tensor is changed, so an incompatible# adapter fails clearly instead of partially corrupting the transformer.print("[HyperFlow] Loading Motion Adapter v1.0 from the reference Space", flush=True)print("[HyperFlow] " + apply_motion_adapter(pipe.transformer), flush=True)# HyperFlow's own adapter adds the two-time embedder and fixed 8-step sigma grid.load_hyperflow_lora(pipe, HYPERFLOW_REPO)# This Space runs the Qwen conditioner remotely, so reserve less local GPU# memory than the 24GB H200 recipe. Keep it configurable for hardware-specific tuning.print(f"[HyperFlow] auto CPU offload memory_reserve_margin={GPU_MEMORY_RESERVE_MARGIN}", flush=True)manager.enable_auto_cpu_offload(device="cuda", memory_reserve_margin=GPU_MEMORY_RESERVE_MARGIN)PIPE, MANAGER = pipe, managerprint(f"[HyperFlow] FL2VA ready in {time.time() - started:.0f}s", flush=True)except Exception as exc:traceback.print_exc()LOAD_ERROR = f"Loading HyperFlow failed: {type(exc).__name__}: {exc}"@cachedef conditioner():from gradio_client import Clientreturn Client(CONDITIONER_SPACE, token=os.environ.get("HF_TOKEN") or os.environ.get("HUGGINGFACEHUB_API_TOKEN"))def encode_remote(prompt: str, last_frame_path: str, canvas: str, num_frames: int):"""Encode the source video's final frame as a true FL2VA first keyframe."""from gradio_client import handle_filefrom safetensors import safe_openpath, plan = conditioner().predict(prompt=prompt,image_path=handle_file(last_frame_path),last_image_path=None,canvas=canvas,num_frames=num_frames,api_name="/encode",)with safe_open(path, framework="pt") as handle:return (handle.get_tensor("prompt_embeds"),handle.get_tensor("text_token_tags"),handle.metadata(),plan,)def _preserve_uploaded_video(video_value) -> str:"""Copy Gradio's temporary upload into an app-owned temp directory before processing."""if isinstance(video_value, dict):path = (video_value.get("path") or video_value.get("name") orvideo_value.get("video") or video_value.get("orig_name"))else:path = video_valueif not path:raise gr.Error("Upload a source MP4 first.")path = os.fspath(path)if not os.path.isfile(path):# Gradio versions can return a stale path after temporary-cache cleanup.# Try to recover the same basename from the active Gradio upload cache.basename = os.path.basename(path)matches = []for root in (os.path.join(tempfile.gettempdir(), "gradio"),):if os.path.isdir(root):for current_root, _, files in os.walk(root):if basename in files:candidate = os.path.join(current_root, basename)if os.path.isfile(candidate):matches.append(candidate)if matches:path = max(matches, key=os.path.getmtime)if not os.path.isfile(path):raise gr.Error("Gradio's temporary video file has disappeared before processing. ""Please upload the MP4 again and run immediately. "f"Missing path: {path}")safe_dir = os.path.join(tempfile.gettempdir(), "h3-hyperflow-inputs")os.makedirs(safe_dir, exist_ok=True)preserved = os.path.join(safe_dir, f"source-{int(time.time() * 1000)}-{os.path.basename(path)}")shutil.copy2(path, preserved)print(f"[Input] Preserved uploaded video: {preserved} ({os.path.getsize(preserved)} bytes)", flush=True)return preserveddef _probe_video(path: str) -> tuple[float, bool]:import avwith av.open(path) as container:if not container.streams.video:raise gr.Error("The uploaded file has no video stream.")stream = container.streams.video[0]seconds = float(stream.duration * stream.time_base) if stream.duration and stream.time_base else (container.duration / av.time_base if container.duration else 0.0)has_audio = bool(container.streams.audio)return seconds, has_audiodef _extract_last_frame(path: str) -> str:"""Save the exact final decoded source frame for FL2VA first-frame anchoring."""import avout_dir = os.path.join(tempfile.gettempdir(), "h3-hyperflow-inputs")os.makedirs(out_dir, exist_ok=True)frame_path = os.path.join(out_dir, f"last-frame-{int(time.time() * 1000)}.png")last_frame = Nonewith av.open(path) as container:stream = container.streams.video[0]for frame in container.decode(stream):last_frame = frameif last_frame is None:raise gr.Error("Could not decode the final frame of the source video.")last_frame.to_image().convert("RGB").save(frame_path, format="PNG")print(f"[Input] Extracted final source frame: {frame_path} ({last_frame.width}x{last_frame.height})", flush=True)return frame_pathdef _concat_source_and_segment(source: str, segment: str, output: str, source_has_audio: bool) -> str:"""Join source + continuation without stretching either image; preserve audio where present."""import avwith av.open(source) as c:sv = c.streams.video[0]source_width, source_height = sv.width, sv.heightsource_duration = float(c.duration / av.time_base) if c.duration else float(sv.duration * sv.time_base)source_has_audio = bool(c.streams.audio)with av.open(segment) as c:gv = c.streams.video[0]width, height = gv.width, gv.heightsegment_duration = float(c.duration / av.time_base) if c.duration else float(gv.duration * gv.time_base)segment_has_audio = bool(c.streams.audio)# Always produce source + continuation, including silent source clips. Fit each clip# into the output canvas with padding rather than stretching/cropping its aspect ratio.cmd = ["ffmpeg", "-y", "-i", source, "-i", segment]source_audio_input = "0:a"segment_audio_input = "1:a"if not source_has_audio:cmd += ["-f", "lavfi", "-t", f"{max(source_duration, 0.1):.4f}", "-i","anullsrc=channel_layout=stereo:sample_rate=32000"]source_audio_input = "2:a"if not segment_has_audio:silent_index = 3 if not source_has_audio else 2cmd += ["-f", "lavfi", "-t", f"{max(segment_duration, 0.1):.4f}", "-i","anullsrc=channel_layout=stereo:sample_rate=32000"]segment_audio_input = f"{silent_index}:a"filter_complex = (f"[0:v]fps={FPS},scale={width}:{height}:force_original_aspect_ratio=decrease,"f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1[v0];"f"[1:v]fps={FPS},scale={width}:{height}:force_original_aspect_ratio=decrease,"f"pad={width}:{height}:(ow-iw)/2:(oh-ih)/2:color=black,setsar=1[v1];"f"[{source_audio_input}]aresample=32000,aformat=sample_fmts=fltp:channel_layouts=stereo,"f"atrim=duration={max(source_duration, 0.1):.4f},asetpts=PTS-STARTPTS[a0];"f"[{segment_audio_input}]aresample=32000,aformat=sample_fmts=fltp:channel_layouts=stereo,"f"atrim=duration={max(segment_duration, 0.1):.4f},asetpts=PTS-STARTPTS[a1];""[v0][a0][v1][a1]concat=n=2:v=1:a=1[outv][outa]")cmd += ["-filter_complex", filter_complex, "-map", "[outv]", "-map", "[outa]","-c:v", "libx264", "-preset", "veryfast", "-crf", "18", "-c:a", "aac","-b:a", "192k", "-movflags", "+faststart", output]try:subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=240)return outputexcept Exception as exc:print(f"[concat] Could not join clips; returning generated continuation only: {type(exc).__name__}: {exc}", flush=True)return segmentdef _quoted_dialogue(prompt: str) -> list[str]:"""Extract explicit dialogue in common straight/curly/Russian quote styles."""patterns = [r'«([^»]+)»', r'“([^”]+)”', r'"([^"]+)"', r'„([^“]+)“']found = []for pattern in patterns:for match in re.findall(pattern, prompt):text = match.strip()if text and text not in found:found.append(text)return founddef _add_continuity_and_dialogue_rules(prompt: str, original_prompt: str) -> str:"""Keep the scene constraints explicit, without replacing the user's prompt."""rules = ["Continuation constraints: continue the existing shot from the exact final moment of the reference. Keep the same scene, character identity, clothing, pose, camera position, framing, lighting, and background. Continue only the requested action with small physically plausible movements. Do not cut to a new scene, change location, introduce new characters, or invent a new action.",]dialogue = _quoted_dialogue(original_prompt)if dialogue:lines = "; ".join(f'«{line}»' for line in dialogue)rules.append(f"Spoken dialogue must use the original wording exactly: {lines}. Speak each quoted line in the same language it is written in; do not translate, paraphrase, or add unscripted speech.")return prompt.rstrip() + "\n\n" + "\n".join(rules)def format_official_h3_prompt(prompt: str) -> str:"""Format a last-frame continuation as official MiniMax-H3 I2VA prompt fields.The user wording is preserved verbatim inside the main description; this is adeterministic formatter, not a generative rewriter, so it cannot invent actions."""body = prompt.strip()return ("For the target video, at 0.00 seconds into the target video, ""Picture 1 (from [Shot 1]) is fully referenced.\n\n"f"integrated_multimodal_description: [Shot 1] {body}\n\n""overall_soundscape: Preserve the reference scene's existing ambient and ""diegetic sound character; add only sounds directly caused by the requested action.\n\n""non_diegetic_music: Do not introduce new background music unless the user explicitly requests it.")# Keep the reservation conservative: this is a per-call ZeroGPU request, not a queue timeout.# A larger duration does not create quota; requests can be rejected before inference.# ZeroGPU validates duration after applying the selected GPU-size multiplier.# With xlarge, 240s becomes a 480s request and is rejected on the free account.# Cap the decorator duration at 120s by default: xlarge then requests 240s.# Keep this configurable (30-120s) so the reservation stays within ZeroGPU limits.GPU_TASK_SECONDS = max(30, min(120, int(os.environ.get("H3_GPU_TASK_SECONDS", "120"))))@spaces.GPU(duration=GPU_TASK_SECONDS, size=GPU_SIZE)def _generate(prompt_embeds, text_token_tags, last_frame_path, height, width, num_frames, seed):# Temporary diagnostic instrumentation. Keep the last [DIAG] marker in logs# if ZeroGPU terminates the task before Python can emit a traceback.started = time.monotonic()stage = "function_entry"print(f"[DIAG] GPU_TASK_START reservation={GPU_TASK_SECONDS}s size={GPU_SIZE} "f"frames={num_frames} canvas={width}x{height} seed={seed}",flush=True,)import torchtry:if torch.cuda.is_available():props = torch.cuda.get_device_properties(0)free_bytes, total_bytes = torch.cuda.mem_get_info(0)print(f"[DIAG] CUDA_DEVICE name={props.name} total={total_bytes/1024**3:.1f}GiB "f"free={free_bytes/1024**3:.1f}GiB allocator={os.environ.get('PYTORCH_CUDA_ALLOC_CONF')}",flush=True,)stage = "imports_and_pipeline_check"from PIL import Imageif PIPE is None:raise RuntimeError(LOAD_ERROR or "PIPE is None / model is not loaded")stage = "load_first_keyframe"t0 = time.monotonic()with Image.open(last_frame_path) as source_image:first_frame = source_image.convert("RGB").copy()print(f"[DIAG] FIRST_KEYFRAME_READY elapsed={time.monotonic()-t0:.1f}s size={first_frame.size}", flush=True)# HyperFlow's schedule is fixed by the adapter. Do not pass num_inference_steps.stage = "pipeline_inference"print(f"[DIAG] INFERENCE_BEGIN prompt_embeds_shape={getattr(prompt_embeds, 'shape', None)} "f"prompt_embeds_device={getattr(prompt_embeds, 'device', None)} "f"tags_shape={getattr(text_token_tags, 'shape', None)} "f"tags_device={getattr(text_token_tags, 'device', None)}",flush=True,)t0 = time.monotonic()# Temporarily instrument tqdm's standard update method. The H3 Modular# Diffusers pipeline uses its own loop, so callback_on_step_end is not# assumed to exist. This logs completed inference steps without changing# the HyperFlow schedule or model math.from tqdm.std import tqdm as _TqdmClass_original_tqdm_update = _TqdmClass.update_last_logged_step = {"n": -1}def _diag_tqdm_update(bar, n=1):result = _original_tqdm_update(bar, n)try:total_steps = getattr(bar, "total", None)current_step = int(getattr(bar, "n", 0))if total_steps == 8 and current_step != _last_logged_step["n"]:_last_logged_step["n"] = current_stepprint(f"[DIAG] INFERENCE_STEP {current_step}/8 "f"elapsed={time.monotonic()-t0:.1f}s "f"task_elapsed={time.monotonic()-started:.1f}s",flush=True,)except BaseException as diag_exc:print(f"[DIAG] STEP_LOG_FAILED {type(diag_exc).__name__}: {diag_exc}", flush=True)return result_TqdmClass.update = _diag_tqdm_updatetry:state = PIPE(prompt_embeds=prompt_embeds.to("cuda"),text_token_tags=text_token_tags.to("cuda"),image=first_frame,height=int(height),width=int(width),num_frames=int(num_frames),generator=torch.Generator(device="cpu").manual_seed(int(seed)),)finally:_TqdmClass.update = _original_tqdm_updateprint(f"[DIAG] INFERENCE_RETURNED elapsed={time.monotonic()-t0:.1f}s total={time.monotonic()-started:.1f}s", flush=True)stage = "extract_pipeline_outputs"videos = state.get("videos")audios = state.get("audio")sampling_rate = state.get("sampling_rate")print(f"[DIAG] OUTPUTS videos_type={type(videos).__name__} "f"videos_len={len(videos) if videos is not None else None} "f"audio_type={type(audios).__name__} "f"audio_len={len(audios) if audios is not None else None} "f"sampling_rate={sampling_rate}",flush=True,)return videos[0], audios[0].cpu(), sampling_rateexcept BaseException as exc:print(f"[DIAG] GPU_STAGE_FAILED stage={stage} elapsed={time.monotonic()-started:.1f}s "f"exception={type(exc).__name__}: {exc}",flush=True,)traceback.print_exc()try:if torch.cuda.is_available():print(f"[DIAG] CUDA_MEMORY allocated={torch.cuda.memory_allocated()/1024**3:.2f}GiB "f"reserved={torch.cuda.memory_reserved()/1024**3:.2f}GiB "f"max_allocated={torch.cuda.max_memory_allocated()/1024**3:.2f}GiB",flush=True,)except BaseException as diag_exc:print(f"[DIAG] CUDA_MEMORY_QUERY_FAILED {type(diag_exc).__name__}: {diag_exc}", flush=True)raisedef generate(video_path, prompt, canvas, duration, seed, progress=gr.Progress()):if LOAD_ERROR:raise gr.Error(LOAD_ERROR)if PIPE is None:raise gr.Error("Model is loading. Refresh the page after the Space logs say HyperFlow is ready.")if not video_path:raise gr.Error("Upload a source MP4 first.")if not prompt or not prompt.strip():raise gr.Error("Enter a prompt describing what should happen next.")video_path = _preserve_uploaded_video(video_path)source_seconds, source_has_audio = _probe_video(video_path)if not 2 <= source_seconds <= 15:raise gr.Error(f"Source video must be 2–15 seconds long; this file is {source_seconds:.1f}s.")num_frames = snap_frames(float(duration))last_frame_path = _extract_last_frame(video_path)# No external Unsampler/LLM rewrite: preserve the requested action, add the# continuation/dialogue guardrails, then apply MiniMax's official H3 field format.condition_prompt = _add_continuity_and_dialogue_rules(prompt.strip(), prompt.strip())condition_prompt = format_official_h3_prompt(condition_prompt)print(f"[DIAG] OFFICIAL_H3_PROMPT_FORMAT chars={len(condition_prompt)}", flush=True)progress(0.05, desc="Encoding prompt and video reference…")phase_started = time.monotonic()print(f"[DIAG] CONDITIONER_BEGIN requested_frames={num_frames} canvas={canvas} mode=FL2VA_LAST_FRAME", flush=True)try:embeds, tags, metadata, plan = encode_remote(condition_prompt, last_frame_path, canvas, num_frames)print(f"[DIAG] CONDITIONER_OK elapsed={time.monotonic()-phase_started:.1f}s metadata={metadata}", flush=True)except Exception as exc:traceback.print_exc()raise gr.Error(f"Remote conditioner failed ({type(exc).__name__}: {exc}). Check the conditioner Space logs.") from excheight, width, num_frames = (int(metadata[k]) for k in ("height", "width", "num_frames"))progress(0.15, desc="Generating continuation from the exact last frame (HyperFlow, 8 steps)…")print(f"[DIAG] CALL_GPU_GENERATOR frames={num_frames} canvas={width}x{height}", flush=True)try:frames, audio, sampling_rate = _generate(embeds, tags, last_frame_path, height, width, num_frames, int(seed))except BaseException as exc:print(f"[DIAG] GENERATOR_CALL_FAILED exception={type(exc).__name__}: {exc}", flush=True)traceback.print_exc()raiseprint(f"[DIAG] GENERATOR_CALL_OK frames_type={type(frames).__name__} audio_type={type(audio).__name__}", flush=True)from diffusers.utils import encode_videoout_dir = os.path.join(tempfile.gettempdir(), "h3-hyperflow-output")os.makedirs(out_dir, exist_ok=True)stamp = int(time.time() * 1000)segment_path = os.path.join(out_dir, f"hyperflow-continuation-{stamp}.mp4")encode_video(frames, fps=FPS, output_path=segment_path, audio=audio, audio_sample_rate=sampling_rate)full_path = os.path.join(out_dir, f"hyperflow-extended-{stamp}.mp4")final_path = _concat_source_and_segment(video_path, segment_path, full_path, source_has_audio)status = "Completed with HyperFlow's fixed 8-step schedule. The source's final frame is used as the generated segment's first keyframe. The continuation audio is newly generated; source audio is retained only in the joined original section."status += "\n\nPrompt mode: official MiniMax-H3 structured fields (deterministic; no external prompt rewriter)."status += "\n\nConditioning prompt:\n" + condition_promptif final_path == segment_path:status += " The generated continuation is provided separately; automatic joining was skipped or failed."return final_path, segment_path, statuswith gr.Blocks(title="MiniMax H3 HyperFlow Extend") as demo:with gr.Row():with gr.Column():video = gr.Video(label="Source video (MP4, 2–15 seconds)", sources=["upload"])prompt = gr.Textbox(label="What should happen next?", lines=4,value="Continue the same scene naturally from the final moment of the reference video, preserving the characters, appearance, camera angle, lighting, and motion continuity.")canvas = gr.Dropdown(label="Output format", choices=list(CANVASES), value=DEFAULT_CANVAS)duration = gr.Slider(label="Continuation duration (seconds)", minimum=MIN_DURATION, maximum=MAX_DURATION, step=1, value=5)seed = gr.Number(label="Seed", value=42, precision=0)run = gr.Button(f"Extend from last frame · HyperFlow 8 steps · {FPS} fps", variant="primary")with gr.Column():result = gr.Video(label="Extended video (source + continuation when joining succeeds)")segment = gr.Video(label="Generated continuation only")status = gr.Textbox(label="Status", interactive=False)run.click(generate, [video, prompt, canvas, duration, seed], [result, segment, status], api_name="generate")# Load weights at startup so import/download errors are visible in Space logs.load_models()if __name__ == "__main__":demo.launch(show_error=True)
app.py+568-256