Spaces:
Sleeping
Sleeping
refactor: defer model loads inside @spaces.GPU (avoid CPU OOM)
Browse files123456719 unmodified lines272829303132338 unmodified lines4243444546474849505152535455566 unmodified lines6364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710817 unmodified lines1261271281291301311323 unmodified lines13613713813914014114214314414514614714814915015115215315415515615715815916016116216311 unmodified lines1751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602617 unmodified lines2692702712722732742752762772782792802811 unmodified line2832842852862872882892902912922932942951 unmodified line29729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037111 unmodified lines3833843853863873883895 unmodified lines3953963973983994008 unmodified lines4094104114124134144154164174184194204211 unmodified line4234244254264274284291 unmodified line431432433434435436437"""Gradio ZeroGPU Space for LongCat-Video-Avatar 1.5 (single-person AI2V).Loads the INT8-quantized DiT + DMD2 8-step LoRA + Whisper-Large-v3 audio encoderand exposes one inference function: reference image + audio + prompt -> mp4."""# IMPORTANT: spaces must be imported before torch (per HF guide).19 unmodified linesWEIGHTS_DIR.mkdir(parents=True, exist_ok=True)BASE_DIR = WEIGHTS_DIR / "LongCat-Video"AVATAR_DIR = WEIGHTS_DIR / "LongCat-Video-Avatar-1.5"print(f"[boot] WEIGHTS_DIR={WEIGHTS_DIR}")# Make vendored package importablesys.path.insert(0, str(Path(__file__).parent.resolve()))8 unmodified lines# ---------------------------------------------------------------------------# 0) Replace xformers.memory_efficient_attention with a PyTorch-SDPA shim.# xformers wheels for torch 2.12+cu130 aren't available; SDPA is always# in-tree, fast on Blackwell, and matches the inputs the model passes.# ---------------------------------------------------------------------------def _install_sdpa_shim():import xformers.ops # the package exists; only its CUDA ext is broken# Replace BlockDiagonalMask with a thin record so we don't depend on# the xformers internal layout for cumulative seq starts.class _BDShim:def __init__(self, q_seqlen, kv_seqlen):self.q_seqlen = list(q_seqlen)6 unmodified linesxformers.ops.fmha.attn_bias.BlockDiagonalMask = _BDShimdef _meff(q, k, v, attn_bias=None, op=None, **_):# xformers convention: q, k, v are [B, M, H, D]if attn_bias is None:q_ = q.transpose(1, 2).contiguous()k_ = k.transpose(1, 2).contiguous()v_ = v.transpose(1, 2).contiguous()out = F.scaled_dot_product_attention(q_, k_, v_)return out.transpose(1, 2)if isinstance(attn_bias, _BDShim):# Variable-length cross-attention: batch elements concatenated# along seq dim. Loop per-element using SDPA.outs = []q_off = k_off = 0for q_len, k_len in zip(attn_bias.q_seqlen, attn_bias.kv_seqlen):q_b = q[:, q_off:q_off + q_len].transpose(1, 2).contiguous()k_b = k[:, k_off:k_off + k_len].transpose(1, 2).contiguous()v_b = v[:, k_off:k_off + k_len].transpose(1, 2).contiguous()o = F.scaled_dot_product_attention(q_b, k_b, v_b)outs.append(o.transpose(1, 2))q_off += q_lenk_off += k_lenreturn torch.cat(outs, dim=1)raise NotImplementedError(f"Unsupported attn_bias in SDPA shim: {type(attn_bias)}")xformers.ops.memory_efficient_attention = _meffprint("[boot] installed xformers→SDPA shim")_install_sdpa_shim()# ---------------------------------------------------------------------------# 1) Download weights (one-time per container if /data is persistent)# ---------------------------------------------------------------------------def _ensure_weights():token = os.environ.get("HF_TOKEN")# We only need text_encoder / vae / tokenizer from the base LongCat-Video repo.base_marker = BASE_DIR / "vae" / "config.json"if not base_marker.exists():print("[boot] downloading LongCat-Video (vae/text_encoder/tokenizer)…")snapshot_download("meituan-longcat/LongCat-Video",local_dir=str(BASE_DIR),17 unmodified linesavatar_marker = AVATAR_DIR / "base_model_int8" / "config.json"if not avatar_marker.exists():print("[boot] downloading LongCat-Video-Avatar-1.5 (INT8 + lora + whisper + vocal_separator)…")snapshot_download("meituan-longcat/LongCat-Video-Avatar-1.5",local_dir=str(AVATAR_DIR),3 unmodified lines"lora/*","scheduler/*","vocal_separator/*",# Whisper-Large-v3: only the bf16 safetensors + tokenizer/config files"whisper-large-v3/model.safetensors","whisper-large-v3/*.json","whisper-large-v3/*.txt",],ignore_patterns=[# Drop the fp32 sharded copies, flax, TF, and pickled legacy weights"whisper-large-v3/model.fp32*","whisper-large-v3/flax_model*","whisper-large-v3/tf_model*","whisper-large-v3/pytorch_model*",],)print("[boot] weights ready.")_ensure_weights()# ---------------------------------------------------------------------------# 2) Patch DiT config: prefer xformers, disable flash-attn (not buildable on# ZeroGPU's Blackwell sm_120). Both base and int8 configs share these flags.# ---------------------------------------------------------------------------def _patch_dit_config():11 unmodified lineschanged = Trueif changed:cfg_path.write_text(json.dumps(cfg, indent=2))print(f"[boot] patched {cfg_path.name} -> xformers backend")_patch_dit_config()# ---------------------------------------------------------------------------# 3) Load models on CPU at module level (spaces moves them to GPU on demand)# ---------------------------------------------------------------------------from transformers import AutoTokenizer, UMT5EncoderModel # noqa: E402from longcat_video.pipeline_longcat_video_avatar import LongCatVideoAvatarPipeline # noqa: E402from longcat_video.modules.scheduling_flow_match_euler_discrete import ( # noqa: E402FlowMatchEulerDiscreteScheduler,)from longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWan # noqa: E402from longcat_video.modules.quantization import load_quantized_dit # noqa: E402from longcat_video.audio_process import ( # noqa: E402get_audio_encoder,get_audio_feature_extractor,)from longcat_video.audio_process.torch_utils import save_video_ffmpeg # noqa: E402CP_SPLIT_HW = [1, 1] # single-GPU, no context-parallel splitprint("[boot] loading tokenizer + text_encoder (UMT5-XXL)…")tokenizer = AutoTokenizer.from_pretrained(str(BASE_DIR), subfolder="tokenizer")text_encoder = UMT5EncoderModel.from_pretrained(str(BASE_DIR),subfolder="text_encoder",torch_dtype=torch.bfloat16,low_cpu_mem_usage=True,)print("[boot] loading VAE (Wan)…")vae = AutoencoderKLWan.from_pretrained(str(BASE_DIR), subfolder="vae", torch_dtype=torch.bfloat16)print("[boot] loading scheduler…")scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(str(AVATAR_DIR), subfolder="scheduler")print("[boot] loading INT8 DiT + DMD2 LoRA…")dit = load_quantized_dit(str(AVATAR_DIR), subfolder="base_model_int8", cp_split_hw=CP_SPLIT_HW)_lora_path = AVATAR_DIR / "lora" / "dmd_lora.safetensors"if _lora_path.exists():dit.load_lora(str(_lora_path), "dmd", multiplier=1.0, lora_network_dim=128, lora_network_alpha=64)dit.enable_loras(["dmd"])print("[boot] DMD2 LoRA enabled (8-step distillation)")print("[boot] loading Whisper-Large-v3 audio encoder…")audio_encoder = get_audio_encoder(str(AVATAR_DIR / "whisper-large-v3"), "avatar-v1.5")audio_feature_extractor = get_audio_feature_extractor(str(AVATAR_DIR / "whisper-large-v3"), "avatar-v1.5")print("[boot] loading vocal separator (Kim_Vocal_2)…")from audio_separator.separator import Separator # noqa: E402VOCAL_TMP = Path("/tmp/vocal_out")VOCAL_TMP.mkdir(parents=True, exist_ok=True)vocal_separator = Separator(output_dir=str(VOCAL_TMP / "vocals"),output_single_stem="vocals",model_file_dir=str(AVATAR_DIR / "vocal_separator"),)vocal_separator.load_model("Kim_Vocal_2.onnx")print("[boot] assembling pipeline…")pipe = LongCatVideoAvatarPipeline(tokenizer=tokenizer,text_encoder=text_encoder,vae=vae,scheduler=scheduler,dit=dit,audio_encoder=audio_encoder,audio_feature_extractor=audio_feature_extractor,model_type="avatar-v1.5",)print("[boot] ready.")# ---------------------------------------------------------------------------# 4) Inference helpers# ---------------------------------------------------------------------------NEGATIVE_PROMPT = (7 unmodified linesdef _extract_vocal(src: str) -> str:"""Run the vocal separator; return path to vocals-only wav, or src if it fails."""try:outputs = vocal_separator.separate(src)if outputs:return str((VOCAL_TMP / "vocals" / outputs[0]).resolve())except Exception as e:print(f"[vocal] separation failed, using raw audio: {e}")return src1 unmodified line# 5) GPU-bound inference function# ---------------------------------------------------------------------------@spaces.GPU(duration=300)def generate(image_path: str,audio_path: str,prompt: str,resolution: str,audio_cfg: float,seed: int,progress=gr.Progress(track_tqdm=True),):1 unmodified lineraise gr.Error("Please upload a reference image.")if not audio_path:raise gr.Error("Please upload an audio clip.")if not prompt or not prompt.strip():prompt = "A person is talking naturally."# Move pipeline onto GPU for the duration of this call.# NB: pipe.to() moves dit / text_encoder / vae but not audio_encoder,# so we move Whisper explicitly here.pipe.to("cuda")audio_encoder.to("cuda")width, height = (832, 480) if resolution == "480p" else (1280, 768)save_fps = 25audio_stride = 1num_frames = 93 # one 93-frame segment (~3.7s @ 25fps)import librosa # local import to keep boot fast# 1) Vocal isolationprogress(0.05, desc="Isolating vocals…")vocal_path = _extract_vocal(audio_path)# 2) Pad audio to required durationspeech, sr = librosa.load(vocal_path, sr=16000)target_duration = num_frames / save_fpspad = math.ceil((target_duration - len(speech) / sr) * sr)if pad > 0:speech = np.concatenate([speech, np.zeros(pad, dtype=speech.dtype)])# 3) Whisper audio embeddingprogress(0.15, desc="Encoding audio (Whisper-Large-v3)…")full_audio_emb = pipe.get_audio_embedding(speech, fps=save_fps * audio_stride, device="cuda", sample_rate=sr, model_type="avatar-v1.5")if torch.isnan(full_audio_emb).any():raise gr.Error("Audio embedding contains NaN — try a cleaner audio clip.")# 4) Build per-frame windowed audio tensor: [1, T, 5, 5, D]indices = torch.arange(2 * 2 + 1) - 2 # 5-frame window centered on each latent framecenter = torch.arange(0, audio_stride * num_frames, audio_stride).unsqueeze(1) + indices.unsqueeze(0)center = torch.clamp(center, min=0, max=full_audio_emb.shape[0] - 1)audio_emb = full_audio_emb[center][None, ...].to("cuda")# 5) Run AI2V generation (8 steps thanks to DMD2 LoRA)progress(0.30, desc="Generating video (DMD2 8-step)…")image = Image.open(image_path).convert("RGB")generator = torch.Generator(device="cuda").manual_seed(int(seed))output, _latent = pipe.generate_ai2v(image=image,prompt=prompt.strip(),negative_prompt=NEGATIVE_PROMPT,resolution=resolution,num_frames=num_frames,num_inference_steps=8,text_guidance_scale=1.0,audio_guidance_scale=float(audio_cfg),output_type="both",generator=generator,audio_emb=audio_emb,use_distill=True,)# 6) Save with audioprogress(0.92, desc="Muxing audio + video…")frames = (output[0] * 255).astype(np.uint8)out_tensor = torch.from_numpy(frames)out_base = Path(tempfile.gettempdir()) / f"longcat_{uuid.uuid4().hex[:8]}"save_video_ffmpeg(out_tensor, str(out_base), audio_path, fps=save_fps, quality=5)out_path = f"{out_base}.mp4"print(f"[gen] wrote {out_path}")return out_path11 unmodified lines"their mouth. Wearing a vibrant red jacket with gold embroidery, the singer is speaking ""while smoke swirls around them, creating a dynamic and atmospheric scene.","480p",4.0,42,])5 unmodified linesUpload a **reference image** + **audio clip** + a short **text prompt**.The model generates a ~3.7-second lip-synced video using Meituan'sLongCat-Video-Avatar 1.5 (INT8 DiT + DMD2 8-step distilled).""")with gr.Row():8 unmodified lineswith gr.Row():resolution = gr.Radio(["480p", "720p"], value="480p", label="Resolution")seed = gr.Number(value=42, precision=0, label="Seed")audio_cfg = gr.Slider(1.0,6.0,value=4.0,step=0.5,label="Audio CFG (higher = stronger lip sync, 3–5 recommended)",)go = gr.Button("Generate", variant="primary")with gr.Column():video_out = gr.Video(label="Output", autoplay=True)1 unmodified lineif EXAMPLES:gr.Examples(examples=EXAMPLES,inputs=[image_in, audio_in, prompt, resolution, audio_cfg, seed],outputs=video_out,fn=generate,cache_examples=False,1 unmodified linego.click(generate,inputs=[image_in, audio_in, prompt, resolution, audio_cfg, seed],outputs=video_out,)123456719 unmodified lines272829303132338 unmodified lines424344454647484950515253546 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697989910017 unmodified lines1181191201211221231243 unmodified lines12812913013113213313413513613713813914014114214314414514614714814915015115211 unmodified lines1641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492507 unmodified lines2582592602612622632642652662672682692702711 unmodified line2732742752762772782792802812822832841 unmodified line28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735811 unmodified lines3703713723733743755 unmodified lines3813823833843853863873888 unmodified lines3973983994004014021 unmodified line4044054064074084094101 unmodified line412413414415416417418"""Gradio ZeroGPU Space for LongCat-Video-Avatar 1.5 (single-person AI2V).Lazy-loads the INT8 DiT + DMD2 8-step LoRA + Whisper-Large-v3 inside the first@spaces.GPU call (CPU RAM on ZeroGPU is too small for 22GB UMT5-XXL + 14GB DiT)."""# IMPORTANT: spaces must be imported before torch (per HF guide).19 unmodified linesWEIGHTS_DIR.mkdir(parents=True, exist_ok=True)BASE_DIR = WEIGHTS_DIR / "LongCat-Video"AVATAR_DIR = WEIGHTS_DIR / "LongCat-Video-Avatar-1.5"print(f"[boot] WEIGHTS_DIR={WEIGHTS_DIR}", flush=True)# Make vendored package importablesys.path.insert(0, str(Path(__file__).parent.resolve()))8 unmodified lines# ---------------------------------------------------------------------------# 0) Replace xformers.memory_efficient_attention with a PyTorch-SDPA shim.# xformers wheels for torch 2.12+cu130 aren't published; SDPA is always# in-tree and matches the inputs the model passes.# ---------------------------------------------------------------------------def _install_sdpa_shim():import xformers.opsclass _BDShim:def __init__(self, q_seqlen, kv_seqlen):self.q_seqlen = list(q_seqlen)6 unmodified linesxformers.ops.fmha.attn_bias.BlockDiagonalMask = _BDShimdef _meff(q, k, v, attn_bias=None, op=None, **_):# xformers convention: [B, M, H, D]; SDPA wants [B, H, M, D].if attn_bias is None:q_ = q.transpose(1, 2).contiguous()k_ = k.transpose(1, 2).contiguous()v_ = v.transpose(1, 2).contiguous()return F.scaled_dot_product_attention(q_, k_, v_).transpose(1, 2)if isinstance(attn_bias, _BDShim):outs, q_off, k_off = [], 0, 0for q_len, k_len in zip(attn_bias.q_seqlen, attn_bias.kv_seqlen):q_b = q[:, q_off:q_off + q_len].transpose(1, 2).contiguous()k_b = k[:, k_off:k_off + k_len].transpose(1, 2).contiguous()v_b = v[:, k_off:k_off + k_len].transpose(1, 2).contiguous()outs.append(F.scaled_dot_product_attention(q_b, k_b, v_b).transpose(1, 2))q_off += q_lenk_off += k_lenreturn torch.cat(outs, dim=1)raise NotImplementedError(f"Unsupported attn_bias in SDPA shim: {type(attn_bias)}")xformers.ops.memory_efficient_attention = _meffprint("[boot] installed xformers→SDPA shim", flush=True)_install_sdpa_shim()# ---------------------------------------------------------------------------# 1) Download weights (one-time per container thanks to /data bucket)# ---------------------------------------------------------------------------def _ensure_weights():token = os.environ.get("HF_TOKEN")base_marker = BASE_DIR / "vae" / "config.json"if not base_marker.exists():print("[boot] downloading LongCat-Video (vae/text_encoder/tokenizer)…", flush=True)snapshot_download("meituan-longcat/LongCat-Video",local_dir=str(BASE_DIR),17 unmodified linesavatar_marker = AVATAR_DIR / "base_model_int8" / "config.json"if not avatar_marker.exists():print("[boot] downloading LongCat-Video-Avatar-1.5 (INT8 + lora + whisper + vocal_separator)…", flush=True)snapshot_download("meituan-longcat/LongCat-Video-Avatar-1.5",local_dir=str(AVATAR_DIR),3 unmodified lines"lora/*","scheduler/*","vocal_separator/*","whisper-large-v3/model.safetensors","whisper-large-v3/*.json","whisper-large-v3/*.txt",],ignore_patterns=["whisper-large-v3/model.fp32*","whisper-large-v3/flax_model*","whisper-large-v3/tf_model*","whisper-large-v3/pytorch_model*",],)print("[boot] weights ready.", flush=True)_ensure_weights()# ---------------------------------------------------------------------------# 2) Patch DiT config: prefer xformers (now our SDPA shim) over flash-attn.# ---------------------------------------------------------------------------def _patch_dit_config():11 unmodified lineschanged = Trueif changed:cfg_path.write_text(json.dumps(cfg, indent=2))print(f"[boot] patched {cfg_path.name} -> xformers/SDPA backend", flush=True)_patch_dit_config()# ---------------------------------------------------------------------------# 3) Lazy pipeline cache. Built inside the first @spaces.GPU call.# ---------------------------------------------------------------------------_PIPE = None_VOCAL = Nonedef _build_pipeline():"""Construct the whole pipeline directly on the GPU (avoids CPU RAM cap)."""global _PIPEprint("[load] building pipeline (first call may take ~60s)…", flush=True)t0 = time.time()from transformers import AutoTokenizer, UMT5EncoderModelfrom longcat_video.pipeline_longcat_video_avatar import LongCatVideoAvatarPipelinefrom longcat_video.modules.scheduling_flow_match_euler_discrete import FlowMatchEulerDiscreteSchedulerfrom longcat_video.modules.autoencoder_kl_wan import AutoencoderKLWanfrom longcat_video.modules.quantization import load_quantized_ditfrom longcat_video.audio_process import get_audio_encoder, get_audio_feature_extractorcp_split_hw = [1, 1]dtype = torch.bfloat16tokenizer = AutoTokenizer.from_pretrained(str(BASE_DIR), subfolder="tokenizer")text_encoder = UMT5EncoderModel.from_pretrained(str(BASE_DIR), subfolder="text_encoder", torch_dtype=dtype, device_map="cuda")vae = AutoencoderKLWan.from_pretrained(str(BASE_DIR), subfolder="vae", torch_dtype=dtype).to("cuda")scheduler = FlowMatchEulerDiscreteScheduler.from_pretrained(str(AVATAR_DIR), subfolder="scheduler")dit = load_quantized_dit(str(AVATAR_DIR), subfolder="base_model_int8", cp_split_hw=cp_split_hw).to("cuda")lora_path = AVATAR_DIR / "lora" / "dmd_lora.safetensors"if lora_path.exists():dit.load_lora(str(lora_path), "dmd", multiplier=1.0, lora_network_dim=128, lora_network_alpha=64)dit.enable_loras(["dmd"])print("[load] DMD2 8-step LoRA enabled", flush=True)audio_encoder = get_audio_encoder(str(AVATAR_DIR / "whisper-large-v3"), "avatar-v1.5").to("cuda", dtype=dtype)audio_feature_extractor = get_audio_feature_extractor(str(AVATAR_DIR / "whisper-large-v3"), "avatar-v1.5")_PIPE = LongCatVideoAvatarPipeline(tokenizer=tokenizer,text_encoder=text_encoder,vae=vae,scheduler=scheduler,dit=dit,audio_encoder=audio_encoder,audio_feature_extractor=audio_feature_extractor,model_type="avatar-v1.5",)_PIPE.device = "cuda"print(f"[load] pipeline ready in {time.time() - t0:.1f}s", flush=True)def _build_vocal_separator():"""Vocal separator is ONNX (CPU); build lazily as well so /data hits late."""global _VOCALfrom audio_separator.separator import Separatorvocal_tmp = Path("/tmp/vocal_out")(vocal_tmp / "vocals").mkdir(parents=True, exist_ok=True)_VOCAL = Separator(output_dir=str(vocal_tmp / "vocals"),output_single_stem="vocals",model_file_dir=str(AVATAR_DIR / "vocal_separator"),)_VOCAL.load_model("Kim_Vocal_2.onnx")print("[load] vocal separator ready", flush=True)# ---------------------------------------------------------------------------# 4) Inference helper# ---------------------------------------------------------------------------NEGATIVE_PROMPT = (7 unmodified linesdef _extract_vocal(src: str) -> str:if _VOCAL is None:return srctry:outputs = _VOCAL.separate(src)if outputs:return str((Path("/tmp/vocal_out") / "vocals" / outputs[0]).resolve())except Exception as e:print(f"[vocal] separation failed, using raw audio: {e}", flush=True)return src1 unmodified line# 5) GPU-bound inference function# ---------------------------------------------------------------------------@spaces.GPU(duration=420)def generate(image_path: str,audio_path: str,prompt: str,resolution: str,seed: int,progress=gr.Progress(track_tqdm=True),):1 unmodified lineraise gr.Error("Please upload a reference image.")if not audio_path:raise gr.Error("Please upload an audio clip.")prompt = (prompt or "A person is talking naturally.").strip()progress(0.02, desc="Warming up models (one-time on cold start)…")if _PIPE is None:_build_pipeline()if _VOCAL is None:_build_vocal_separator()from longcat_video.audio_process.torch_utils import save_video_ffmpegimport librosasave_fps = 25audio_stride = 1num_frames = 93# 1) Vocal isolationprogress(0.10, desc="Isolating vocals…")vocal_path = _extract_vocal(audio_path)# 2) Pad audio to target durationspeech, sr = librosa.load(vocal_path, sr=16000)pad = math.ceil((num_frames / save_fps - len(speech) / sr) * sr)if pad > 0:speech = np.concatenate([speech, np.zeros(pad, dtype=speech.dtype)])# 3) Whisper audio embeddingprogress(0.20, desc="Encoding audio (Whisper-Large-v3)…")full_audio_emb = _PIPE.get_audio_embedding(speech, fps=save_fps * audio_stride, device="cuda", sample_rate=sr, model_type="avatar-v1.5")if torch.isnan(full_audio_emb).any():raise gr.Error("Audio embedding contains NaN — try a different audio clip.")# 4) Build windowed audio tensor: [1, T, 5, 5, D]indices = torch.arange(2 * 2 + 1) - 2center = torch.arange(0, audio_stride * num_frames, audio_stride).unsqueeze(1) + indices.unsqueeze(0)center = torch.clamp(center, min=0, max=full_audio_emb.shape[0] - 1)audio_emb = full_audio_emb[center][None, ...].to("cuda")# 5) Generate (8-step distilled, both CFG=1.0 → 1 forward per step)progress(0.30, desc="Generating video (DMD2 8-step)…")image = Image.open(image_path).convert("RGB")generator = torch.Generator(device="cuda").manual_seed(int(seed))output, _ = _PIPE.generate_ai2v(image=image,prompt=prompt,negative_prompt=NEGATIVE_PROMPT,resolution=resolution,num_frames=num_frames,num_inference_steps=8,text_guidance_scale=1.0,audio_guidance_scale=1.0,output_type="both",generator=generator,audio_emb=audio_emb,use_distill=True,)# 6) Mux + saveprogress(0.92, desc="Muxing audio + video…")frames = (output[0] * 255).astype(np.uint8)out_tensor = torch.from_numpy(frames)out_base = Path(tempfile.gettempdir()) / f"longcat_{uuid.uuid4().hex[:8]}"save_video_ffmpeg(out_tensor, str(out_base), audio_path, fps=save_fps, quality=5)out_path = f"{out_base}.mp4"print(f"[gen] wrote {out_path}", flush=True)return out_path11 unmodified lines"their mouth. Wearing a vibrant red jacket with gold embroidery, the singer is speaking ""while smoke swirls around them, creating a dynamic and atmospheric scene.","480p",42,])5 unmodified linesUpload a **reference image** + **audio clip** + a short **text prompt**.The model generates a ~3.7-second lip-synced video using Meituan'sLongCat-Video-Avatar 1.5 (INT8 DiT + DMD2 8-step distilled).*First call is slow: ~60s to warm up models on GPU.*""")with gr.Row():8 unmodified lineswith gr.Row():resolution = gr.Radio(["480p", "720p"], value="480p", label="Resolution")seed = gr.Number(value=42, precision=0, label="Seed")go = gr.Button("Generate", variant="primary")with gr.Column():video_out = gr.Video(label="Output", autoplay=True)1 unmodified lineif EXAMPLES:gr.Examples(examples=EXAMPLES,inputs=[image_in, audio_in, prompt, resolution, seed],outputs=video_out,fn=generate,cache_examples=False,1 unmodified linego.click(generate,inputs=[image_in, audio_in, prompt, resolution, seed],outputs=video_out,)
app.py+116-135