使用 ComfyUI API 實作 MiniMax-H3 多模態影片與音訊生成流程

2026年8月11日 05:44
站內 AI 整理稿

In this tutorial, we implement an end-to-end MiniMax-H3 video generation workflow using ComfyUI as a headless inference backend.

We configure the environment around GPU memory, disk capacity, model precision, resolution, duration, sampling strategy, and multiple generation modes, while dynamically selecting an appropriate weight profile based on the available hardware.

We install and launch ComfyUI programmatically, download the required diffusion, text-encoder, video-VAE, and audio-VAE weights from Hugging Face, and communicate with the running server through its HTTP and WebSocket APIs.

We also construct the ComfyUI execution graph directly in Python, validate node schemas against the live /objectinfo endpoint, and support text-to-video, first- and last-frame-conditioned generation, and reference-image-conditioned generation.

By combining automated model setup, schema-aware graph construction, joint video-audio decoding, progress monitoring, and output collection, we create a reproducible pipeline for experimenting with MiniMax-H3 without relying on the graphical ComfyUI interface.

Copy CodeCopiedUse a different Browserimport json, os, re, shutil, subprocess, sys, time, uuid, urllib.request, urllib.error from pathlib import Path CFG = { "MODE": "t2v", "PROMPT": ( "Realistic live-action cinematic look.

A lone lighthouse keeper on a storm-lashed " "cliff at dusk, anamorphic lens, shallow depth of field, film grain, volumetric sea spray.\n" "[0s-2s] Wide shot: waves detonate against black rock, the lighthouse beam sweeps the frame.

\n" "[2s-4s] Medium shot: the keeper braces against the wind, coat snapping, rain on his face.\n" "[4s-5s] Close up: he squints into the dark and says \"She's holding.\"\n" "Camera: hard cuts between shots, slight handheld jitter, no dissolves.

\n" "Audio: roaring surf and howling wind throughout, low cello drone underneath, " "a heavy wave impact on each cut, the line delivered clearly over the storm.\n" "No text, subtitles, logos or watermarks." ), "ASPECT": (16, 9), "MEGAPIXELS": 0.4, "SECONDS": 5.

0, "SEED": 556589502035082, "STEPS": 20, "SAMPLER": "resmultistep", "SCHEDULER": "simple", "FIRSTFRAME": None, "LASTFRAME": None, "REFIMAGES": [], "REFIMAGESIZE": "match", "SIGMASHIFT": None, "TURBOLORA": False, "TURBOSTEPS": 8, "TURBOSAMPLER": "euler", "TURBOSCHEDULER": "beta", "COMFYDIR": "/content/ComfyUI", "OUTDIR": "/content/outputs", "MODELSROOT": "/content/models", "PORT": 8188, "HFTOKEN": os.

environ.get("HFTOKEN", ""), "SKIPINSTALL": False, } REPO = "Comfy-Org/MiniMax-H3" API = f"http://127.0.0.1:{CFG['PORT']}" PROFILES = [ dict(name="quality", minvram=70, unetfl="minimaxh3fl2vabf16.safetensors", unetref="minimaxh3ref2vabf16.safetensors", te="qwen3vl32bminimaxh3int8convrot.

safetensors", flags=["--normalvram"]), dict(name="balanced", minvram=38, unetfl="minimaxh3fl2vaprunedint8convrot.safetensors", unetref="minimaxh3ref2vaprunedint8convrot.safetensors", te="qwen3vl32bminimaxh3nvfp4awq.

safetensors", flags=["--normalvram", "--cache-none"]), dict(name="squeeze", minvram=20, unetfl="minimaxh3fl2vaprunedfp8scaled.safetensors", unetref="minimaxh3ref2vaprunedfp8scaled.safetensors", te="qwen3vl32bminimaxh3nvfp4awq.

safetensors", flags=["--lowvram", "--cache-none", "--disable-smart-memory"]), ] VAEVIDEO = "minimaxh3videovaefp16.safetensors" VAEAUDIO = "minimaxh3audiovaefp32.safetensors" def sh(cmd, cwd=None, check=True, quiet=False): """Run a shell command, streaming output.""" print(f"$ {cmd}") p = subprocess.

run(cmd, shell=True, cwd=cwd, stdout=subprocess.DEVNULL if quiet else None, stderr=subprocess.STDOUT if quiet else None) if check and p.returncode != 0: raise RuntimeError(f"command failed ({p.returncode}): {cmd}") def getjson(path, payload=None, timeout=30): url = f"{API}{path}" data = json.

dumps(payload).encode() if payload is not None else None req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=timeout) as r: body = r.read() return json.

loads(body) if body else {} def alignframes(seconds, fps=24): """H3 consumes frame counts on the 17k+5 grid.Snap upward.""" n = max(5, int(round(seconds fps))) while n % 17 != 5: n += 1 return n def h3canvas(aspect=(16, 9), megapixels=0.

98, multiple=32): """Mirror of ComfyUI's ResolutionSelector + H3's 7681344 area cap.""" ar = aspect[0] / aspect[1] total = megapixels 1e6 h = (total / ar) 0.5 w = ar h cap = 768 1344 if w h > cap: s = (cap / (w h)) 0.

5 w, h = w s, h s r = lambda v: max(multiple, int(round(v / multiple)) multiple) return r(w), r(h) def preflight(): try: import torch except ImportError: raise SystemExit("PyTorch missing — run this in a Colab GPU runtime.") if not torch.cuda.isavailable(): raise SystemExit("No CUDA device.

Runtime > Change runtime type > GPU (A100).") name = torch.cuda.getdevicename(0) vram = torch.cuda.getdeviceproperties(0).totalmemory / 1e9 freedisk = shutil.diskusage("/content").free / 1e9 bf16 = torch.cuda.isbf16supported() print(f"GPU : {name} ({vram:.

1f} GB VRAM, bf16={bf16})") print(f"Free disk : {freedisk:.1f} GB") if not bf16: raise SystemExit( "This GPU has no bf16 support (T4/K80).MiniMax-H3 will not run here.\n" "Switch to an A100/L4/H100 runtime.

" ) profile = next((p for p in PROFILES if vram >= p["minvram"]), None) if profile is None: raise SystemExit( f"{vram:.0f} GB VRAM is below the ~20 GB floor for the smallest H3 build." ) if freedisk < 45: print("WARNING: <45 GB free.Point MODELSROOT at Drive or expect a disk-full error.

") print(f"Profile : {profile['name']} (unet={profile['unetfl']}, te={profile['te']})") return profile We define the core MiniMax-H3 configuration, model profiles, generation parameters, and shared utility functions used throughout the workflow.

We calculate valid frame counts and canvas dimensions while checking GPU capability, available VRAM, BF16 support, and disk space before inference begins.We also automatically select the most appropriate model profile so the pipeline matches the hardware available in our Colab runtime.

Copy CodeCopiedUse a different Browserdef installcomfy(): comfy = Path(CFG["COMFYDIR"]) if CFG["SKIPINSTALL"] and comfy.exists(): print("Skipping install (SKIPINSTALL=True).") return sh("pip install -q -U 'huggingfacehub[hfxet]' hftransfer websocket-client") if not comfy.

exists(): sh(f"git clone --depth 1 https://github.com/comfyanonymous/ComfyUI {comfy}") sh(f"pip install -q -r {comfy}/requirements.txt") ver = (comfy / "comfyuiversion.py") if ver.exists(): print("ComfyUI:", ver.readtext().strip()) if not (comfy / "comfyextras" / "nodesminimaxh3.py").

exists(): raise SystemExit("This ComfyUI checkout lacks native MiniMax-H3 nodes — update it.") root = Path(CFG["MODELSROOT"]) for sub in ("diffusionmodels", "textencoders", "vae", "loras"): (root / sub).mkdir(parents=True, existok=True) (comfy / "extramodelpaths.yaml").

writetext( "minimaxh3:\n" f" basepath: {root}\n" " diffusionmodels: diffusionmodels\n" " textencoders: textencoders\n" " vae: vae\n" " loras: loras\n" ) Path(CFG["OUTDIR"]).mkdir(parents=True, existok=True) def fetch(repoid, filename, subdir): from huggingfacehub import hfhubdownload os.

environ["HFHUBENABLEHFTRANSFER"] = "1" dest = Path(CFG["MODELSROOT"]) / subdir target = dest / Path(filename).name if target.exists() and target.stat().stsize > 1000000: print(f"cached {target.name} ({target.stat().stsize/1e9:.

1f} GB)") return target print(f"pulling {filename} -> {dest}") try: p = hfhubdownload(repoid=repoid, filename=filename, localdir=str(dest), token=CFG["HFTOKEN"] or None) except Exception as e: if "401" in str(e) or "403" in str(e) or "gated" in str(e).

lower(): raise SystemExit( f"Access denied for {repoid}.Accept the MiniMax-H3 community license on the " "model page, create a read token, then set CFG['HFTOKEN']." ) from e raise p = Pat

Related

相關文章

量子位生成式AI

阿里視頻大模型Wan3.0正式上線,行業評價“穩定、真實、有質感”

阿里巴巴影片生成大模型Wan3.0正式上線,單次可生成30秒影片,並首次支援doc、xls、ppt、pdf、md等文檔輸入。企業用戶普遍評價其「穩定、真實、有質感」,能穩定保持角色與場景一致性,並已進入短劇、影視、廣告等生產流程。即日起可於阿里雲百鍊、千問等平台體驗,標準版並推出限時7折優惠。

剛剛
IT之家生成式AI

阿里雲視頻生成模型 Wan3.0 正式上線,支持單次生成 30 秒視頻、文檔輸入

作者:遠洋 責編:遠洋 評論: 8 月 24 日消息,阿里雲消息,今天,視頻生成模型 Wan3.0 正式上線。官方稱,Wan3.0 在生成時長、萬能創作、全能參考以及真實世界還原等維度全面升級,單次可生成 30 秒視頻,並首次支持 doc、xls、ppt、pdf、md 等文檔格式輸入,力求準確還原真實世界。

剛剛
全天候科技生成式AI

企業AI最後一公里:三路人馬在此交鋒

鄭敏芳 發表於 2026年08月24日 03:09 摘要:尋找自己的位置 2026年世界機器人大會現場,談到這一輪突然走紅的FDE(前線部署工程師),明略科技CEO吳明輝先把時間往回撥了十多年。“12年前我們就在非常認真地研究。”當華爾街見聞·問及FDE與傳統軟件部署有什麼區別時,吳明輝說,兩者都會進入客戶現場,但今天的FDE需要做得更深:一邊把Agent接進真實業務,一邊把現場形成的能力繼續沉澱回後臺。

剛剛