cpuai commited on
Commit
4a8de12
·
verified ·
1 Parent(s): d4347e6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +525 -0
app.py ADDED
@@ -0,0 +1,525 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # HuggingFace Spaces (Gradio + ZeroGPU) 单文件示例:
3
+ # - 自动下载 LongCat-Video GitHub 代码(zip)
4
+ # - 自动下载 LongCat-Video / LongCat-Video-Avatar 权重(HF Hub)
5
+ # - 通过 spaces.GPU 在 ZeroGPU 环境下按需申请 GPU 执行推理
6
+ # - 支持单人:AT2V / AI2V
7
+ #
8
+ # 说明:
9
+ # 1) 官方示例使用 torchrun nproc=2(多进程/可能更快):
10
+ # 这里默认改为 nproc=1 + context_parallel_size=1,更适合 Spaces。
11
+ # 2) FlashAttention 默认在 config 开启,但在 Spaces 上未必能顺利安装;
12
+ # 本示例会尝试把 config 里所有包含 "flash" 的 attention backend 字段递归替换为 "sdpa"。
13
+ #
14
+ # 参考:
15
+ # - ZeroGPU 官方用法:@spaces.GPU(duration=...) :contentReference[oaicite:5]{index=5}(用户侧不需要引用,代码内不写引用)
16
+ # - LongCat-Video-Avatar 模型卡:推理命令/参数/权重目录结构 :contentReference[oaicite:6]{index=6}
17
+
18
+ import os
19
+ import re
20
+ import sys
21
+ import json
22
+ import time
23
+ import shutil
24
+ import zipfile
25
+ import hashlib
26
+ import subprocess
27
+ from pathlib import Path
28
+ from datetime import datetime
29
+ from typing import Any, Dict, Tuple, Optional
30
+
31
+ # ----------------------------
32
+ # 运行时“尽量单文件”的依赖安装
33
+ # ----------------------------
34
+ def _pip_install(pkgs):
35
+ """在 Spaces 里尽量避免反复安装:用一个标记文件 + 简单 import 探测。"""
36
+ cmd = [sys.executable, "-m", "pip", "install", "-U"] + pkgs
37
+ print("[pip]", " ".join(cmd))
38
+ subprocess.check_call(cmd)
39
+
40
+ def _ensure_imports():
41
+ """
42
+ 只安装本 app 直接需要的包。
43
+ LongCat-Video 自身依赖很多(官方 requirements),这里不强制全量预装,
44
+ 而是交给官方脚本在运行时 import;若缺包会在日志里体现,再按需加到下面列表。
45
+ """
46
+ try:
47
+ import gradio as gr # noqa
48
+ except Exception:
49
+ _pip_install(["gradio>=4.0.0"])
50
+
51
+ try:
52
+ import requests # noqa
53
+ except Exception:
54
+ _pip_install(["requests>=2.31.0"])
55
+
56
+ try:
57
+ from huggingface_hub import snapshot_download # noqa
58
+ except Exception:
59
+ _pip_install(["huggingface_hub[cli]>=0.24.0"])
60
+
61
+ # ZeroGPU 推荐的 spaces 包:多数 ZeroGPU 环境自带;没有就装
62
+ try:
63
+ import spaces # noqa
64
+ except Exception:
65
+ _pip_install(["spaces>=0.27.0"])
66
+
67
+ _ensure_imports()
68
+
69
+ import gradio as gr
70
+ import requests
71
+ from huggingface_hub import snapshot_download
72
+
73
+ # spaces 在非 ZeroGPU 环境也应可安全使用;若导入失败已在上面安装
74
+ import spaces
75
+
76
+
77
+ # ----------------------------
78
+ # 配置区(可按需改)
79
+ # ----------------------------
80
+ GITHUB_ZIP_URL = "https://github.com/meituan-longcat/LongCat-Video/archive/refs/heads/main.zip"
81
+
82
+ # HF 权重(模型卡说明的目录) :contentReference[oaicite:7]{index=7}
83
+ HF_MODEL_LONGCAT_VIDEO = "meituan-longcat/LongCat-Video"
84
+ HF_MODEL_LONGCAT_AVATAR = "meituan-longcat/LongCat-Video-Avatar"
85
+
86
+ # 本地缓存目录:Spaces 上建议放到 /home/user 或当前目录
87
+ BASE_DIR = Path(__file__).parent.resolve()
88
+ CACHE_DIR = BASE_DIR / "_cache"
89
+ REPO_DIR = CACHE_DIR / "LongCat-Video-main" # zip 解压后的目录名
90
+ WEIGHTS_DIR = CACHE_DIR / "weights"
91
+ WEIGHTS_LONGCAT_VIDEO = WEIGHTS_DIR / "LongCat-Video"
92
+ WEIGHTS_LONGCAT_AVATAR = WEIGHTS_DIR / "LongCat-Video-Avatar"
93
+ OUTPUT_DIR = CACHE_DIR / "outputs"
94
+ TMP_DIR = CACHE_DIR / "tmp"
95
+
96
+ # 为了减少 torch CUDA 内存碎片(有时有用)
97
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
98
+
99
+
100
+ # ----------------------------
101
+ # 工具函数
102
+ # ----------------------------
103
+ def _sha1(s: str) -> str:
104
+ return hashlib.sha1(s.encode("utf-8")).hexdigest()[:10]
105
+
106
+ def _run(cmd, cwd: Optional[Path] = None, env: Optional[Dict[str, str]] = None) -> Tuple[int, str]:
107
+ """运行命令并返回 (code, stdout+stderr)。"""
108
+ print("[run]", " ".join(cmd))
109
+ p = subprocess.Popen(
110
+ cmd,
111
+ cwd=str(cwd) if cwd else None,
112
+ env=env,
113
+ stdout=subprocess.PIPE,
114
+ stderr=subprocess.STDOUT,
115
+ text=True,
116
+ bufsize=1,
117
+ universal_newlines=True,
118
+ )
119
+ out_lines = []
120
+ while True:
121
+ line = p.stdout.readline()
122
+ if not line and p.poll() is not None:
123
+ break
124
+ if line:
125
+ out_lines.append(line)
126
+ code = p.wait()
127
+ return code, "".join(out_lines)
128
+
129
+ def _download_and_extract_repo():
130
+ """下载并解压 GitHub zip 到 CACHE_DIR。"""
131
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
132
+ zip_path = CACHE_DIR / "LongCat-Video-main.zip"
133
+
134
+ if REPO_DIR.exists() and (REPO_DIR / "run_demo_avatar_single_audio_to_video.py").exists():
135
+ return
136
+
137
+ # 清理旧目录
138
+ if REPO_DIR.exists():
139
+ shutil.rmtree(REPO_DIR, ignore_errors=True)
140
+
141
+ # 下载 zip
142
+ if not zip_path.exists():
143
+ r = requests.get(GITHUB_ZIP_URL, stream=True, timeout=120)
144
+ r.raise_for_status()
145
+ with open(zip_path, "wb") as f:
146
+ for chunk in r.iter_content(chunk_size=1024 * 1024):
147
+ if chunk:
148
+ f.write(chunk)
149
+
150
+ # 解压
151
+ with zipfile.ZipFile(zip_path, "r") as zf:
152
+ zf.extractall(CACHE_DIR)
153
+
154
+ # 基本校验
155
+ if not (REPO_DIR / "run_demo_avatar_single_audio_to_video.py").exists():
156
+ raise RuntimeError("仓库解压后未找到 run_demo_avatar_single_audio_to_video.py,可能 GitHub 结构变化。")
157
+
158
+ def _download_weights():
159
+ """下载 HF 权重到 WEIGHTS_DIR。"""
160
+ WEIGHTS_DIR.mkdir(parents=True, exist_ok=True)
161
+
162
+ # 使用 token(若你在 Space Secrets 里配置了 HF_TOKEN)
163
+ token = os.environ.get("HF_TOKEN", None)
164
+
165
+ if not WEIGHTS_LONGCAT_VIDEO.exists():
166
+ snapshot_download(
167
+ repo_id=HF_MODEL_LONGCAT_VIDEO,
168
+ local_dir=str(WEIGHTS_LONGCAT_VIDEO),
169
+ token=token,
170
+ local_dir_use_symlinks=False,
171
+ )
172
+
173
+ if not WEIGHTS_LONGCAT_AVATAR.exists():
174
+ snapshot_download(
175
+ repo_id=HF_MODEL_LONGCAT_AVATAR,
176
+ local_dir=str(WEIGHTS_LONGCAT_AVATAR),
177
+ token=token,
178
+ local_dir_use_symlinks=False,
179
+ )
180
+
181
+ def _recursive_patch_attention_backend(obj: Any) -> Any:
182
+ """
183
+ 递归把 config 里疑似 flash-attn backend 的字段替换为 sdpa。
184
+ 不依赖具体 key 名,尽量“宽松匹配”:
185
+ - key 或 value 里出现 flash / flashattn / flash_attn => 改成 "sdpa"
186
+ """
187
+ if isinstance(obj, dict):
188
+ new = {}
189
+ for k, v in obj.items():
190
+ lk = str(k).lower()
191
+ if any(x in lk for x in ["attn", "attention", "backend"]):
192
+ # 先递归处理 value
193
+ vv = _recursive_patch_attention_backend(v)
194
+ # 再判断是否需要替换
195
+ if isinstance(vv, str) and ("flash" in vv.lower() or "flash_attn" in vv.lower() or "flashattn" in vv.lower()):
196
+ new[k] = "sdpa"
197
+ else:
198
+ new[k] = vv
199
+ else:
200
+ new[k] = _recursive_patch_attention_backend(v)
201
+ return new
202
+ elif isinstance(obj, list):
203
+ return [_recursive_patch_attention_backend(x) for x in obj]
204
+ else:
205
+ # 普通标量
206
+ if isinstance(obj, str):
207
+ lo = obj.lower()
208
+ if "flash_attn" in lo or "flashattn" in lo or lo.strip() == "flash" or "flash" == lo.strip():
209
+ return "sdpa"
210
+ return obj
211
+
212
+ def _try_patch_avatar_configs():
213
+ """
214
+ 官方说明:avatar_single/config.json 和 avatar_multi/config.json 默认启用 FlashAttention-2 :contentReference[oaicite:8]{index=8}
215
+ 这里尽量替换为 sdpa,避免必须安装 flash-attn。
216
+ """
217
+ cfgs = [
218
+ WEIGHTS_LONGCAT_AVATAR / "avatar_single" / "config.json",
219
+ WEIGHTS_LONGCAT_AVATAR / "avatar_multi" / "config.json",
220
+ ]
221
+ for cfg in cfgs:
222
+ if not cfg.exists():
223
+ continue
224
+ try:
225
+ raw = json.loads(cfg.read_text(encoding="utf-8"))
226
+ patched = _recursive_patch_attention_backend(raw)
227
+ if patched != raw:
228
+ cfg.write_text(json.dumps(patched, ensure_ascii=False, indent=2), encoding="utf-8")
229
+ except Exception as e:
230
+ print(f"[warn] patch config failed: {cfg} -> {e}")
231
+
232
+ def _load_template_json(template_path: Path) -> Dict[str, Any]:
233
+ data = json.loads(template_path.read_text(encoding="utf-8"))
234
+ if not isinstance(data, dict):
235
+ raise ValueError("模板 JSON 不是 dict 结构,无法安全修改。")
236
+ return data
237
+
238
+ def _recursive_replace_first_match(data: Any, key_pred, value_pred, new_value) -> Tuple[Any, bool]:
239
+ """
240
+ 在任意 JSON 结构中,找到第一个满足条件的 (key, value) 并替换 value。
241
+ 返回 (new_data, replaced?)
242
+ """
243
+ if isinstance(data, dict):
244
+ out = {}
245
+ replaced = False
246
+ for k, v in data.items():
247
+ if (not replaced) and key_pred(k) and value_pred(v):
248
+ out[k] = new_value
249
+ replaced = True
250
+ else:
251
+ nv, r = _recursive_replace_first_match(v, key_pred, value_pred, new_value)
252
+ out[k] = nv
253
+ replaced = replaced or r
254
+ return out, replaced
255
+ elif isinstance(data, list):
256
+ out_list = []
257
+ replaced = False
258
+ for item in data:
259
+ if replaced:
260
+ out_list.append(item)
261
+ continue
262
+ nv, r = _recursive_replace_first_match(item, key_pred, value_pred, new_value)
263
+ out_list.append(nv)
264
+ replaced = replaced or r
265
+ return out_list, replaced
266
+ else:
267
+ return data, False
268
+
269
+ def _build_input_json_single(
270
+ mode: str,
271
+ audio_path: Path,
272
+ prompt: str,
273
+ ref_image_path: Optional[Path],
274
+ seed: int,
275
+ resolution: str
276
+ ) -> Path:
277
+ """
278
+ 基于 assets/avatar/single_example_1.json 模板生成 input_json。
279
+ 官方脚本以 --input_json 读取参数 :contentReference[oaicite:9]{index=9}
280
+ """
281
+ template = REPO_DIR / "assets" / "avatar" / "single_example_1.json"
282
+ if not template.exists():
283
+ raise RuntimeError("未找到模板 assets/avatar/single_example_1.json(仓库结构可能变化)。")
284
+
285
+ data = _load_template_json(template)
286
+
287
+ # 替换 prompt:优先找 key 包含 prompt/text 之类
288
+ data, _ = _recursive_replace_first_match(
289
+ data,
290
+ key_pred=lambda k: "prompt" in str(k).lower() or "text" in str(k).lower(),
291
+ value_pred=lambda v: isinstance(v, str),
292
+ new_value=prompt.strip() if prompt else "A person is talking."
293
+ )
294
+
295
+ # 替换 audio path:找 key 包含 audio 且 value 是字符串
296
+ data, _ = _recursive_replace_first_match(
297
+ data,
298
+ key_pred=lambda k: "audio" in str(k).lower(),
299
+ value_pred=lambda v: isinstance(v, str),
300
+ new_value=str(audio_path)
301
+ )
302
+
303
+ # 替换 image path(仅 AI2V)
304
+ if mode == "ai2v" and ref_image_path is not None:
305
+ data, _ = _recursive_replace_first_match(
306
+ data,
307
+ key_pred=lambda k: ("image" in str(k).lower()) or ("ref" in str(k).lower()),
308
+ value_pred=lambda v: isinstance(v, str),
309
+ new_value=str(ref_image_path)
310
+ )
311
+
312
+ # seed(若模板里有)
313
+ data, _ = _recursive_replace_first_match(
314
+ data,
315
+ key_pred=lambda k: "seed" in str(k).lower(),
316
+ value_pred=lambda v: isinstance(v, (int, float, str)),
317
+ new_value=int(seed)
318
+ )
319
+
320
+ # resolution(若模板里有)
321
+ data, _ = _recursive_replace_first_match(
322
+ data,
323
+ key_pred=lambda k: "resolution" in str(k).lower(),
324
+ value_pred=lambda v: isinstance(v, str),
325
+ new_value=str(resolution)
326
+ )
327
+
328
+ TMP_DIR.mkdir(parents=True, exist_ok=True)
329
+ out_path = TMP_DIR / f"single_{mode}_{_sha1(str(audio_path) + prompt + str(seed) + str(time.time()))}.json"
330
+ out_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
331
+ return out_path
332
+
333
+ def _find_latest_mp4(since_ts: float) -> Optional[Path]:
334
+ if not OUTPUT_DIR.exists():
335
+ return None
336
+ candidates = []
337
+ for p in OUTPUT_DIR.rglob("*.mp4"):
338
+ try:
339
+ if p.stat().st_mtime >= since_ts - 2:
340
+ candidates.append(p)
341
+ except Exception:
342
+ pass
343
+ if not candidates:
344
+ return None
345
+ candidates.sort(key=lambda x: x.stat().st_mtime, reverse=True)
346
+ return candidates[0]
347
+
348
+ def _ensure_ready() -> str:
349
+ """
350
+ 准备:
351
+ - 下载 repo
352
+ - 下载权重
353
+ - 尝试 patch attention backend
354
+ """
355
+ _download_and_extract_repo()
356
+ _download_weights()
357
+ _try_patch_avatar_configs()
358
+
359
+ # 输出目录
360
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
361
+
362
+ return "准备完成:代码与权重已就绪。"
363
+
364
+
365
+ # ----------------------------
366
+ # GPU 推理函数(ZeroGPU 核心)
367
+ # ----------------------------
368
+ @spaces.GPU(duration=900) # 生成视频通常 >60s,给足时间;你可视情况调小/调大 :contentReference[oaicite:10]{index=10}
369
+ def generate_single(
370
+ mode: str,
371
+ audio_file: str,
372
+ prompt: str,
373
+ ref_image_file: Optional[str],
374
+ seed: int,
375
+ resolution: str,
376
+ num_segments: int,
377
+ ref_img_index: int,
378
+ mask_frame_range: int,
379
+ ) -> Tuple[Optional[str], str]:
380
+ """
381
+ 返回:(mp4路径 or None, 日志文本)
382
+ """
383
+ t0 = time.time()
384
+
385
+ # 文件落盘路径(Gradio 传入的是本地临时文件路径字符串)
386
+ audio_path = Path(audio_file).resolve()
387
+ ref_image_path = Path(ref_image_file).resolve() if ref_image_file else None
388
+
389
+ # 构造 input_json
390
+ input_json = _build_input_json_single(
391
+ mode=mode,
392
+ audio_path=audio_path,
393
+ prompt=prompt,
394
+ ref_image_path=ref_image_path,
395
+ seed=seed,
396
+ resolution=resolution,
397
+ )
398
+
399
+ # 运行官方脚本(单进程 torchrun)
400
+ # 官方示例:torchrun --nproc_per_node=2 ... --context_parallel_size=2 ... :contentReference[oaicite:11]{index=11}
401
+ # 这里适配 Space:nproc=1, context_parallel_size=1
402
+ cmd = [
403
+ sys.executable, "-m", "torch.distributed.run",
404
+ "--nproc_per_node=1",
405
+ "run_demo_avatar_single_audio_to_video.py",
406
+ "--context_parallel_size=1",
407
+ f"--checkpoint_dir={WEIGHTS_LONGCAT_AVATAR}",
408
+ f"--stage_1={mode}",
409
+ f"--input_json={input_json}",
410
+ f"--resolution={resolution}",
411
+ ]
412
+
413
+ # 续写参数(用户设置 >1 才启用)
414
+ if num_segments and int(num_segments) > 1:
415
+ cmd += [
416
+ f"--num_segments={int(num_segments)}",
417
+ f"--ref_img_index={int(ref_img_index)}",
418
+ f"--mask_frame_range={int(mask_frame_range)}",
419
+ ]
420
+
421
+ # 环境变量:让脚本能找到模块
422
+ env = dict(os.environ)
423
+ env["PYTHONPATH"] = str(REPO_DIR) + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
424
+ env["HF_HOME"] = str(CACHE_DIR / "hf_home")
425
+ env["TORCH_HOME"] = str(CACHE_DIR / "torch_home")
426
+
427
+ # 约定输出目录(若脚本支持/或脚本默认输出在当前目录下的 outputs)
428
+ # 我们用 cwd + 输出扫描兜底
429
+ env["OUTPUT_DIR"] = str(OUTPUT_DIR)
430
+
431
+ code, log = _run(cmd, cwd=REPO_DIR, env=env)
432
+
433
+ # 尝试找到最新 mp4
434
+ mp4 = _find_latest_mp4(t0)
435
+ if mp4 is None:
436
+ # 兜底:在 repo 内也扫一下
437
+ repo_candidates = list(REPO_DIR.rglob("*.mp4"))
438
+ repo_candidates.sort(key=lambda x: x.stat().st_mtime, reverse=True)
439
+ if repo_candidates and repo_candidates[0].stat().st_mtime >= t0 - 2:
440
+ mp4 = repo_candidates[0]
441
+
442
+ if code != 0:
443
+ return None, f"执行失败(exit={code})。日志如下:\n\n{log}"
444
+
445
+ if mp4 is None or not mp4.exists():
446
+ return None, f"执行完成,但未找到 mp4 输出文件。日志如下:\n\n{log}"
447
+
448
+ return str(mp4), f"执行成功:{mp4}\n\n日志如下:\n\n{log}"
449
+
450
+
451
+ # ----------------------------
452
+ # Gradio UI
453
+ # ----------------------------
454
+ def ui_prepare() -> str:
455
+ try:
456
+ return _ensure_ready()
457
+ except Exception as e:
458
+ return f"准备失败:{e}"
459
+
460
+ with gr.Blocks(title="LongCat-Video-Avatar (ZeroGPU) - Single File Space") as demo:
461
+ gr.Markdown(
462
+ """
463
+ # LongCat-Video-Avatar(ZeroGPU / 单文件 Space)
464
+
465
+ - 单人模式:**AT2V(音频+文本)** / **AI2V(音频+图片)**
466
+ - 续写(Video Continuation):把 **num_segments** 设为 > 1 即可(官方参数:ref_img_index / mask_frame_range)
467
+ - 提示:为了更自然的口型,prompt 里建议包含 talking/speaking 等动作词(模型卡建议)
468
+ """
469
+ )
470
+
471
+ with gr.Row():
472
+ btn_prepare = gr.Button("一键准备(下载代码+权重)", variant="primary")
473
+ prep_status = gr.Textbox(label="准备状态", value="尚未准备。首次准备会下载较大权重。", lines=2)
474
+
475
+ btn_prepare.click(fn=ui_prepare, outputs=prep_status)
476
+
477
+ with gr.Row():
478
+ mode = gr.Radio(
479
+ choices=[("Audio-Text-to-Video (AT2V)", "at2v"), ("Audio-Image-to-Video (AI2V)", "ai2v")],
480
+ value="at2v",
481
+ label="模式"
482
+ )
483
+
484
+ with gr.Row():
485
+ audio_in = gr.Audio(label="输入音频(wav/mp3等)", type="filepath")
486
+ ref_img = gr.Image(label="参考图(仅 AI2V 需要)", type="filepath")
487
+
488
+ prompt = gr.Textbox(
489
+ label="Prompt(建议包含 talking/speaking 等动作词)",
490
+ value="A young person is talking naturally, realistic style.",
491
+ lines=2
492
+ )
493
+
494
+ with gr.Row():
495
+ seed = gr.Number(label="Seed", value=0, precision=0)
496
+ resolution = gr.Dropdown(label="分辨率", choices=["480P", "720P"], value="480P")
497
+
498
+ with gr.Accordion("高级参数(续写/一致性/防重复)", open=False):
499
+ num_segments = gr.Slider(label="num_segments(>1 启用续写)", minimum=1, maximum=8, step=1, value=1)
500
+ ref_img_index = gr.Slider(label="ref_img_index(默认 10)", minimum=-30, maximum=60, step=1, value=10)
501
+ mask_frame_range = gr.Slider(label="mask_frame_range(默认 3)", minimum=1, maximum=12, step=1, value=3)
502
+
503
+ btn = gr.Button("生成视频", variant="primary")
504
+
505
+ out_video = gr.Video(label="输出视频(mp4)")
506
+ out_log = gr.Textbox(label="运行日志", lines=18)
507
+
508
+ def _validate(mode_v, audio_fp, img_fp):
509
+ if not audio_fp:
510
+ raise gr.Error("请先上传音频。")
511
+ if mode_v == "ai2v" and not img_fp:
512
+ raise gr.Error("AI2V 模式必须上传参考图。")
513
+
514
+ def run(mode_v, audio_fp, prompt_v, img_fp, seed_v, res_v, seg_v, idx_v, mask_v):
515
+ _validate(mode_v, audio_fp, img_fp)
516
+ # seed=0 时也允许;如果想随机可自己改成 random
517
+ return generate_single(mode_v, audio_fp, prompt_v, img_fp, int(seed_v), res_v, int(seg_v), int(idx_v), int(mask_v))
518
+
519
+ btn.click(
520
+ fn=run,
521
+ inputs=[mode, audio_in, prompt, ref_img, seed, resolution, num_segments, ref_img_index, mask_frame_range],
522
+ outputs=[out_video, out_log],
523
+ )
524
+
525
+ demo.queue(max_size=12).launch()