From 5418115ddd2ab597d291089e8c506cb2f09088c3 Mon Sep 17 00:00:00 2001
From: hit-cxf <2024111082@stu.hit.edu.cn>
Date: Thu, 14 May 2026 19:57:49 +0800
Subject: [PATCH] 文艺短视频:使用模版生成时支持选择填充图片或视频
---
aigc-director/aigc-claw/backend/pipelines/utils.py | 241 +++++++++++++++++++++++++++++++++-
aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx | 100 ++++++++++++-
aigc-director/aigc-claw/backend/pipelines/standard.py | 67 ++++++++-
aigc-director/aigc-claw/backend/api/schemas/pipelines.py | 1
aigc-director/aigc-claw/backend/api/routers/pipelines.py | 6
aigc-director/aigc-claw/frontend/lib/workflowApi.ts | 1
6 files changed, 384 insertions(+), 32 deletions(-)
diff --git a/aigc-director/aigc-claw/backend/api/routers/pipelines.py b/aigc-director/aigc-claw/backend/api/routers/pipelines.py
index 1774e50..0de58c3 100644
--- a/aigc-director/aigc-claw/backend/api/routers/pipelines.py
+++ b/aigc-director/aigc-claw/backend/api/routers/pipelines.py
@@ -71,15 +71,19 @@
def _render_preview_html(raw: str) -> str:
+ demo_image = _demo_image_data_uri()
replacements = {
**TEMPLATE_FIELD_DEFAULTS,
- "image": _demo_image_data_uri(),
+ "image": demo_image,
+ "media": f'<img class="template-media" style="width:100%;height:100%;object-fit:cover;display:block;" src="{demo_image}" alt="">',
}
def repl(match: re.Match) -> str:
token = match.group(1).strip()
key = token.split(":", 1)[0].split("=", 1)[0].strip()
if key in replacements:
+ if key == "media":
+ return replacements[key]
return replacements[key]
if "=" in token:
return escape(token.split("=", 1)[1].strip())
diff --git a/aigc-director/aigc-claw/backend/api/schemas/pipelines.py b/aigc-director/aigc-claw/backend/api/schemas/pipelines.py
index d0a2df8..63e1467 100644
--- a/aigc-director/aigc-claw/backend/api/schemas/pipelines.py
+++ b/aigc-director/aigc-claw/backend/api/schemas/pipelines.py
@@ -24,6 +24,7 @@
subtitle_render_mode: Literal["postprocess", "image_model"] = "postprocess"
subtitle_template: Optional[str] = None
subtitle_template_fields: Optional[Dict[str, str]] = None
+ template_media_kind: Literal["image", "video"] = "image"
video_duration: int = 5
tts_voice: str = "zh-CN-YunjianNeural"
tts_speed: float = 1.2
diff --git a/aigc-director/aigc-claw/backend/pipelines/standard.py b/aigc-director/aigc-claw/backend/pipelines/standard.py
index 3791cf4..8b76a7d 100644
--- a/aigc-director/aigc-claw/backend/pipelines/standard.py
+++ b/aigc-director/aigc-claw/backend/pipelines/standard.py
@@ -16,6 +16,7 @@
create_static_image_clip,
media_duration_seconds,
render_static_text_image,
+ render_template_media_video,
render_template_text_image,
replace_video_audio,
run_blocking,
@@ -219,13 +220,19 @@
subtitle_template = params.get("subtitle_template")
subtitle_template_fields = params.get("subtitle_template_fields") or {}
template_media = template_media_spec(subtitle_template, video_ratio) if subtitle_template else None
+ template_media_kind = params.get("template_media_kind") or "image"
+ if template_media_kind not in {"image", "video"}:
+ template_media_kind = "image"
+ template_video_mode = bool(subtitle_template and template_media_kind == "video")
+ if template_video_mode and template_media and not template_media.get("supports_video"):
+ raise ValueError(f"Subtitle template does not support video media: {subtitle_template}")
media_video_ratio = template_media["media_ratio"] if template_media else video_ratio
media_resolution = template_media["media_resolution"] if template_media else image_resolution
video_mode = params.get("video_mode") or "image_concat"
dynamic_video = video_mode == "dynamic_video" or bool(params.get("generate_videos", False))
video_model = params.get("video_model")
- if dynamic_video and not video_model:
- raise ValueError("standard pipeline dynamic_video mode requires video_model")
+ if (dynamic_video or template_video_mode) and not video_model:
+ raise ValueError("standard pipeline video generation requires video_model")
video_duration = clamp_segment_count(params.get("video_duration") or params.get("duration") or 5, default=5)
update_task(task_id, progress=9, message="Generating image prompts")
@@ -260,11 +267,12 @@
"mode": mode,
"input_text": text,
"segment_count": len(narrations),
- "video_mode": "dynamic_video" if dynamic_video else "image_concat",
+ "video_mode": "template_video" if template_video_mode else ("dynamic_video" if dynamic_video else "image_concat"),
"style_control": style_control,
"subtitle_render_mode": subtitle_render_mode,
"subtitle_template": subtitle_template,
"subtitle_template_fields": subtitle_template_fields,
+ "template_media_kind": template_media_kind,
"template_media": template_media,
"frames": [
{"index": idx + 1, "narration": narration, "image_prompt": image_prompts[idx]}
@@ -327,12 +335,47 @@
update_task(
task_id,
progress=70 + int(20 * idx / len(images)),
- message=f"{'Generating dynamic video' if dynamic_video else 'Creating static clip'} {idx}/{len(images)}",
+ message=f"{'Rendering template video' if template_video_mode else ('Generating dynamic video' if dynamic_video else 'Creating static clip')} {idx}/{len(images)}",
)
duration = media_duration_seconds(audio_path) or 3.0
clip_image_path = image_path
- if enable_subtitles:
- if subtitle_template:
+ video_path = os.path.join(output_dir, f"video_{idx:02d}.mp4")
+ if enable_subtitles or (subtitle_template and template_video_mode):
+ if subtitle_template and template_video_mode:
+ media_video_path = os.path.join(output_dir, f"template_media_{idx:02d}.mp4")
+ await run_blocking(
+ generate_video_api,
+ prompt=image_prompts[idx - 1],
+ model=video_model,
+ output_path=media_video_path,
+ image_path=image_path,
+ duration=max(video_duration, int(duration + 0.999)),
+ video_ratio=media_video_ratio,
+ )
+ storyboard["frames"][idx - 1]["template_media_video_path"] = media_video_path
+
+ template_video_path = os.path.join(output_dir, f"video_{idx:02d}_template.mp4")
+ await run_blocking(
+ render_template_media_video,
+ media_video_path,
+ template_video_path,
+ poster_image_path=image_path,
+ subtitle=narrations[idx - 1],
+ title=title or None,
+ video_ratio=video_ratio,
+ template_id=subtitle_template,
+ template_values=subtitle_template_fields,
+ index=idx,
+ duration=duration,
+ )
+ storyboard["frames"][idx - 1]["template_video_path"] = template_video_path
+ video_path = await run_blocking(
+ replace_video_audio,
+ template_video_path,
+ audio_path,
+ video_path,
+ )
+ elif subtitle_template:
captioned_image_path = os.path.join(output_dir, f"captioned_image_{idx:02d}.jpg")
clip_image_path = await run_blocking(
render_template_text_image,
@@ -358,13 +401,14 @@
else:
storyboard["frames"][idx - 1]["captioned_image_path"] = clip_image_path
storyboard["frames"][idx - 1]["subtitle_rendered_in_image"] = True
- if subtitle_template or subtitle_render_mode == "postprocess":
+ if not template_video_mode and (subtitle_template or subtitle_render_mode == "postprocess"):
captioned_artifact = artifact(clip_image_path, "image", f"captioned_image_{idx:02d}")
artifacts.append(captioned_artifact)
append_artifact(task_id, captioned_artifact)
storyboard["frames"][idx - 1]["captioned_image_path"] = clip_image_path
- video_path = os.path.join(output_dir, f"video_{idx:02d}.mp4")
- if dynamic_video:
+ if subtitle_template and template_video_mode:
+ pass
+ elif dynamic_video:
video_only_segment_path = os.path.join(output_dir, f"video_{idx:02d}_motion.mp4")
await run_blocking(
generate_video_api,
@@ -421,11 +465,12 @@
"images": images,
"audios": audios,
"videos": videos,
- "video_mode": "dynamic_video" if dynamic_video else "image_concat",
- "video_model": video_model if dynamic_video else None,
+ "video_mode": "template_video" if template_video_mode else ("dynamic_video" if dynamic_video else "image_concat"),
+ "video_model": video_model if (dynamic_video or template_video_mode) else None,
"subtitle_render_mode": subtitle_render_mode,
"subtitle_template": subtitle_template,
"subtitle_template_fields": subtitle_template_fields,
+ "template_media_kind": template_media_kind,
"template_media": template_media,
"video_only_path": video_only_path,
"final_video": final_path,
diff --git a/aigc-director/aigc-claw/backend/pipelines/utils.py b/aigc-director/aigc-claw/backend/pipelines/utils.py
index 08b0a67..d824b7a 100644
--- a/aigc-director/aigc-claw/backend/pipelines/utils.py
+++ b/aigc-director/aigc-claw/backend/pipelines/utils.py
@@ -8,6 +8,7 @@
import shutil
import subprocess
import sys
+import tempfile
from html import escape
from pathlib import Path
from typing import Any, Iterable, Optional
@@ -373,7 +374,21 @@
"media_height": height,
"media_ratio": ratio_from_size(width, height),
"media_resolution": f"{width}*{height}",
+ "supports_video": template_supports_video_media(raw),
}
+
+
+def template_supports_video_media(raw: str) -> bool:
+ visible_raw = re.sub(r"<!--.*?-->", "", raw, flags=re.S)
+ if re.search(r"\{\{\s*media(?:[:=][^{}]*)?\s*\}\}", visible_raw):
+ return True
+ return bool(
+ re.search(
+ r"<img\b[^>]*\bsrc=[\"']\{\{\s*image\s*\}\}[\"'][^>]*>",
+ visible_raw,
+ re.I,
+ )
+ )
def parse_template_placeholders(raw: str) -> list[dict[str, str]]:
@@ -425,17 +440,85 @@
return f"data:{mime};base64,{encoded}"
-def _render_template_html(raw: str, values: dict[str, Any]) -> str:
+def _render_template_html(raw: str, values: dict[str, Any], raw_keys: Optional[set[str]] = None) -> str:
+ raw_keys = raw_keys or set()
+
def repl(match: re.Match) -> str:
token = match.group(1).strip()
key = token.split(":", 1)[0].split("=", 1)[0].strip()
if key in values:
+ if key in raw_keys:
+ return str(values[key] or "")
return escape(str(values[key] or ""), quote=True)
if "=" in token:
return escape(token.split("=", 1)[1].strip(), quote=True)
return ""
return re.sub(r"\{\{\s*([^{}]+?)\s*\}\}", repl, raw)
+
+
+def _media_file_uri(path: str) -> str:
+ if path.startswith(("http://", "https://", "data:", "file:")):
+ return path
+ if not os.path.exists(path):
+ raise FileNotFoundError(f"Media not found: {path}")
+ return Path(path).resolve().as_uri()
+
+
+def _template_media_element(src: str, media_kind: str) -> str:
+ attrs = 'class="template-media" style="width:100%;height:100%;object-fit:cover;display:block;"'
+ if media_kind == "video":
+ return f'<video {attrs} src="{escape(src, quote=True)}" muted playsinline preload="auto"></video>'
+ return f'<img {attrs} src="{escape(src, quote=True)}" alt="">'
+
+
+def _inject_template_media_css(raw: str) -> str:
+ css = (
+ "<style>"
+ ".template-media{width:100%;height:100%;object-fit:cover;display:block;}"
+ "video.template-media{background:#000;}"
+ "</style>"
+ )
+ if "</head>" in raw:
+ return raw.replace("</head>", f"{css}</head>", 1)
+ return css + raw
+
+
+def _prepare_template_media_html(raw: str, *, media_kind: str) -> str:
+ prepared = _inject_template_media_css(raw)
+ if media_kind != "video":
+ return prepared
+ if re.search(r"\{\{\s*media(?:[:=][^{}]*)?\s*\}\}", prepared):
+ return prepared
+ return re.sub(
+ r"<img\b[^>]*\bsrc=[\"']\{\{\s*image\s*\}\}[\"'][^>]*>",
+ "{{media}}",
+ prepared,
+ flags=re.I,
+ )
+
+
+def _template_values(
+ *,
+ image_path: str,
+ subtitle: str,
+ title: Optional[str],
+ template_values: Optional[dict[str, Any]],
+ index: int,
+ media_kind: str = "image",
+ media_path: Optional[str] = None,
+) -> dict[str, Any]:
+ image_uri = _image_data_uri(image_path)
+ media_src = _media_file_uri(media_path) if media_kind == "video" and media_path else image_uri
+ return {
+ **TEMPLATE_FIELD_DEFAULTS,
+ **(template_values or {}),
+ "title": title or TEMPLATE_FIELD_DEFAULTS["title"],
+ "text": subtitle or "",
+ "image": image_uri,
+ "media": _template_media_element(media_src, media_kind),
+ "index": index,
+ }
def _install_playwright_chromium() -> None:
@@ -474,17 +557,17 @@
) -> str:
template_path, width, height = _resolve_template_path(template_id, video_ratio)
with open(template_path, "r", encoding="utf-8") as f:
- raw = f.read()
+ raw = _prepare_template_media_html(f.read(), media_kind="image")
html = _render_template_html(
raw,
- {
- **TEMPLATE_FIELD_DEFAULTS,
- **(template_values or {}),
- "title": title or TEMPLATE_FIELD_DEFAULTS["title"],
- "text": subtitle or "",
- "image": _image_data_uri(image_path),
- "index": index,
- },
+ _template_values(
+ image_path=image_path,
+ subtitle=subtitle,
+ title=title,
+ template_values=template_values,
+ index=index,
+ ),
+ raw_keys={"media"},
)
try:
@@ -508,6 +591,144 @@
return output_path
+def render_template_media_video(
+ media_video_path: str,
+ output_path: str,
+ *,
+ poster_image_path: str,
+ subtitle: str,
+ title: Optional[str] = None,
+ video_ratio: str = "9:16",
+ template_id: str,
+ template_values: Optional[dict[str, Any]] = None,
+ index: int = 1,
+ duration: Optional[float] = None,
+ fps: int = 24,
+) -> str:
+ ffmpeg = shutil.which("ffmpeg")
+ if not ffmpeg:
+ raise RuntimeError("ffmpeg is required to render HTML template videos.")
+ if not os.path.exists(media_video_path):
+ raise FileNotFoundError(f"Template media video not found: {media_video_path}")
+
+ template_path, width, height = _resolve_template_path(template_id, video_ratio)
+ with open(template_path, "r", encoding="utf-8") as f:
+ raw = f.read()
+ if not template_supports_video_media(raw):
+ raise ValueError(f"Template does not support video media: {template_id}")
+
+ raw = _prepare_template_media_html(raw, media_kind="video")
+ html = _render_template_html(
+ raw,
+ _template_values(
+ image_path=poster_image_path,
+ media_kind="image",
+ subtitle=subtitle,
+ title=title,
+ template_values=template_values,
+ index=index,
+ ),
+ raw_keys={"media"},
+ )
+
+ try:
+ from playwright.sync_api import sync_playwright
+ except ImportError as exc:
+ raise RuntimeError(
+ "HTML subtitle templates require Playwright. "
+ "Install backend dependencies again or run `pip install playwright`."
+ ) from exc
+
+ clip_duration = float(duration or media_duration_seconds(media_video_path) or 3.0)
+ frame_count = max(1, int(math.ceil(clip_duration * fps)))
+ os.makedirs(os.path.dirname(output_path), exist_ok=True)
+ frame_dir = tempfile.mkdtemp(prefix="template_frames_", dir=os.path.dirname(output_path))
+ media_frame_dir = tempfile.mkdtemp(prefix="template_media_frames_", dir=os.path.dirname(output_path))
+ frame_pattern = os.path.join(frame_dir, "frame_%05d.jpg")
+ media_frame_pattern = os.path.join(media_frame_dir, "media_%05d.jpg")
+
+ logger.info(
+ "Rendering HTML template video: template=%s media=%s duration=%.2fs fps=%d -> %s",
+ template_id,
+ media_video_path,
+ clip_duration,
+ fps,
+ output_path,
+ )
+ try:
+ extract_cmd = [
+ ffmpeg,
+ "-y",
+ "-i",
+ media_video_path,
+ "-vf",
+ f"fps={fps}",
+ "-q:v",
+ "2",
+ media_frame_pattern,
+ ]
+ subprocess.run(extract_cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ media_frames = sorted(str(path) for path in Path(media_frame_dir).glob("media_*.jpg"))
+ if not media_frames:
+ media_frames = [poster_image_path]
+
+ with sync_playwright() as playwright:
+ browser = _launch_playwright_chromium(playwright)
+ try:
+ page = browser.new_page(viewport={"width": width, "height": height}, device_scale_factor=1)
+ page.set_content(html, wait_until="networkidle", timeout=30000)
+ for frame_index in range(frame_count):
+ media_frame_uri = _image_data_uri(media_frames[frame_index % len(media_frames)])
+ page.evaluate(
+ """async (src) => {
+ const images = Array.from(document.querySelectorAll('img.template-media'));
+ await Promise.all(images.map(async (image) => {
+ image.src = src;
+ if (image.decode) {
+ await image.decode().catch(() => {});
+ }
+ }));
+ await new Promise(resolve => requestAnimationFrame(resolve));
+ }""",
+ media_frame_uri,
+ )
+ page.screenshot(
+ path=os.path.join(frame_dir, f"frame_{frame_index + 1:05d}.jpg"),
+ full_page=False,
+ type="jpeg",
+ quality=92,
+ )
+ finally:
+ browser.close()
+
+ cmd = [
+ ffmpeg,
+ "-y",
+ "-framerate",
+ str(fps),
+ "-i",
+ frame_pattern,
+ "-t",
+ f"{clip_duration:.3f}",
+ "-vf",
+ "format=yuv420p",
+ "-c:v",
+ "libx264",
+ "-preset",
+ "veryfast",
+ "-crf",
+ "18",
+ "-movflags",
+ "+faststart",
+ output_path,
+ ]
+ subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
+ finally:
+ shutil.rmtree(frame_dir, ignore_errors=True)
+ shutil.rmtree(media_frame_dir, ignore_errors=True)
+ return output_path
+
+
def concat_audios(audio_paths: Iterable[str], output_path: str) -> Optional[str]:
paths = [path for path in audio_paths if path and os.path.exists(path)]
if not paths:
diff --git a/aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx b/aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx
index 1d0f7ae..9f0da36 100644
--- a/aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx
+++ b/aigc-director/aigc-claw/frontend/components/pipelines/PipelinePage.tsx
@@ -101,6 +101,47 @@
subtitle: 'subtitle',
};
+const TTS_VOICE_GROUPS: ProviderGroup[] = [
+ {
+ provider: 'zh-cn',
+ label: '普通话',
+ models: [
+ { id: 'zh-CN-XiaoxiaoNeural', label: '晓晓 · 女声' },
+ { id: 'zh-CN-XiaoyiNeural', label: '晓伊 · 女声' },
+ { id: 'zh-CN-YunjianNeural', label: '云健 · 男声', default: true },
+ { id: 'zh-CN-YunxiNeural', label: '云希 · 男声' },
+ { id: 'zh-CN-YunxiaNeural', label: '云夏 · 男声' },
+ { id: 'zh-CN-YunyangNeural', label: '云扬 · 男声' },
+ ],
+ },
+ {
+ provider: 'zh-cn-regional',
+ label: '方言/地区普通话',
+ models: [
+ { id: 'zh-CN-liaoning-XiaobeiNeural', label: '晓北 · 女声 · 东北官话' },
+ { id: 'zh-CN-shaanxi-XiaoniNeural', label: '晓妮 · 女声 · 陕西中原官话' },
+ ],
+ },
+ {
+ provider: 'zh-hk',
+ label: '香港中文/粤语',
+ models: [
+ { id: 'zh-HK-HiuGaaiNeural', label: '晓佳 · 女声 · 粤语' },
+ { id: 'zh-HK-HiuMaanNeural', label: '晓曼 · 女声' },
+ { id: 'zh-HK-WanLungNeural', label: '云龙 · 男声' },
+ ],
+ },
+ {
+ provider: 'zh-tw',
+ label: '台湾中文',
+ models: [
+ { id: 'zh-TW-HsiaoChenNeural', label: '晓臻 · 女声' },
+ { id: 'zh-TW-HsiaoYuNeural', label: '晓雨 · 女声' },
+ { id: 'zh-TW-YunJheNeural', label: '云哲 · 男声' },
+ ],
+ },
+];
+
const STATUS_STYLE: Record<string, string> = {
pending: 'bg-gray-100 text-gray-500',
running: 'bg-blue-50 text-blue-600',
@@ -665,6 +706,7 @@
const [standardMode, setStandardMode] = useState<'inspiration' | 'copy'>('inspiration');
const [standardVideoMode, setStandardVideoMode] = useState<'image_concat' | 'dynamic_video'>('image_concat');
const [templateMode, setTemplateMode] = useState(false);
+ const [templateMediaKind, setTemplateMediaKind] = useState<'image' | 'video'>('image');
const [templates, setTemplates] = useState<StandardTemplateOption[]>([]);
const [selectedTemplateId, setSelectedTemplateId] = useState('');
const [templateFieldValues, setTemplateFieldValues] = useState<Record<string, string>>({});
@@ -711,7 +753,7 @@
})
.catch(() => {});
- if (pipeline !== 'standard' || standardVideoMode === 'dynamic_video') {
+ if (pipeline !== 'standard' || standardVideoMode === 'dynamic_video' || (templateMode && templateMediaKind === 'video')) {
fetchApiModels({ mediaType: 'video', ability: videoAbility, verifiedOnly: true })
.then(models => {
const groups = groupApiModels(models, VIDEO_PROVIDERS);
@@ -725,7 +767,7 @@
})
.catch(() => {});
}
- }, [pipeline, standardVideoMode]);
+ }, [pipeline, standardVideoMode, templateMode, templateMediaKind]);
useEffect(() => {
if (pipeline !== 'standard') return;
@@ -761,10 +803,18 @@
() => templates.find(item => item.id === selectedTemplateId) || null,
[templates, selectedTemplateId]
);
+ const templateVideoEnabled = templateMode && templateMediaKind === 'video';
const selectedTemplateFields = useMemo(
() => selectedTemplate?.fields || [],
[selectedTemplate]
);
+
+ useEffect(() => {
+ if (!templateMode || templateMediaKind !== 'video') return;
+ if (selectedTemplate && !selectedTemplate.supports_video) {
+ setTemplateMediaKind('image');
+ }
+ }, [templateMode, templateMediaKind, selectedTemplate]);
useEffect(() => {
if (!templateMode) return;
@@ -790,10 +840,14 @@
};
const canSubmit = useMemo(() => {
- if (pipeline === 'standard') return text.trim().length > 0 && (!templateMode || Boolean(selectedTemplate));
+ if (pipeline === 'standard') {
+ return text.trim().length > 0
+ && (!templateMode || Boolean(selectedTemplate))
+ && (!templateVideoEnabled || Boolean(selectedTemplate?.supports_video));
+ }
if (pipeline === 'action_transfer') return promptText.trim() && imagePath.trim() && videoPath.trim();
return characterImage.trim() && goodsText.trim();
- }, [pipeline, text, templateMode, selectedTemplate, promptText, imagePath, videoPath, characterImage, goodsText]);
+ }, [pipeline, text, templateMode, selectedTemplate, templateVideoEnabled, promptText, imagePath, videoPath, characterImage, goodsText]);
useEffect(() => {
if (!task || !['pending', 'running'].includes(task.status)) return;
@@ -858,13 +912,14 @@
subtitle_render_mode: !templateMode && enableSubtitles ? subtitleRenderMode : undefined,
subtitle_template: templateMode ? selectedTemplate?.id : undefined,
subtitle_template_fields: templateMode ? templateFieldValues : undefined,
+ template_media_kind: templateMode ? templateMediaKind : undefined,
tts_voice: ttsVoice,
tts_speed: ttsSpeed,
style_control: negativePrompt || undefined,
segment_count: standardMode === 'inspiration' ? standardSegmentCount : undefined,
video_mode: templateMode ? 'image_concat' : standardVideoMode,
- video_model: !templateMode && standardVideoMode === 'dynamic_video' ? videoModel : undefined,
- video_duration: !templateMode && standardVideoMode === 'dynamic_video' ? duration : undefined,
+ video_model: templateVideoEnabled || (!templateMode && standardVideoMode === 'dynamic_video') ? videoModel : undefined,
+ video_duration: templateVideoEnabled || (!templateMode && standardVideoMode === 'dynamic_video') ? duration : undefined,
})
: pipeline === 'action_transfer'
? await startActionTransferPipeline({
@@ -990,6 +1045,27 @@
</div>
</div>
</div>
+ <div className="grid h-10 max-w-sm grid-cols-2 rounded-lg bg-gray-100 p-1 text-sm">
+ {[
+ { id: 'image', label: '图片拼接', disabled: false },
+ { id: 'video', label: '动态视频', disabled: Boolean(selectedTemplate && !selectedTemplate.supports_video) },
+ ].map(item => (
+ <button
+ key={item.id}
+ type="button"
+ disabled={item.disabled}
+ title={item.disabled ? '当前模版不支持动态视频' : undefined}
+ onClick={() => setTemplateMediaKind(item.id as 'image' | 'video')}
+ className={clsx(
+ 'rounded-md transition-colors',
+ templateMediaKind === item.id ? 'bg-white text-blue-600 shadow-sm' : 'text-gray-500',
+ item.disabled && 'cursor-not-allowed opacity-40'
+ )}
+ >
+ {item.label}
+ </button>
+ ))}
+ </div>
</div>
) : (
<div className="grid grid-cols-2 h-10 rounded-lg bg-gray-100 p-1 text-sm max-w-sm">
@@ -1013,7 +1089,11 @@
<span>说明</span>
</div>
<p className="text-sm leading-6 text-yellow-950">
- {standardVideoMode === 'image_concat'
+ {templateMode
+ ? templateMediaKind === 'video'
+ ? '精品模版会先按模版媒体位生成图片,再调用视频模型生成动态媒体,最后逐帧渲染 HTML 模版并合成 TTS 音频。'
+ : '精品模版会按模版媒体位生成图片,再用 HTML 模版精确排版标题、字幕和自定义字段。'
+ : standardVideoMode === 'image_concat'
? '图片拼接会为每个旁白片段生成一张图片,并配合 TTS 音频合成为静态图文短视频。等待时间主要取决于图片生成速度,通常生成每张图片需 10-20 秒。'
: '动态视频会先为每个旁白片段生成图片,再调用视频模型把图片扩展为动态片段,最后合成为完整短片。等待时间更长,通常生成每个视频片段需 1-2 分钟。'}
</p>
@@ -1168,7 +1248,7 @@
{pipeline !== 'action_transfer' && (
<SelectField label="图片模型" value={imageModel} onChange={setImageModel} groups={imageModelGroups} />
)}
- {(pipeline !== 'standard' || standardVideoMode === 'dynamic_video') && (
+ {(pipeline !== 'standard' || standardVideoMode === 'dynamic_video' || templateVideoEnabled) && (
<SelectField label="视频模型" value={videoModel} onChange={setVideoModel} groups={videoModelGroups} />
)}
<label className="flex flex-col gap-1.5">
@@ -1177,12 +1257,12 @@
{VIDEO_RATIOS.map(item => <option key={item.id} value={item.id}>{item.label}</option>)}
</select>
</label>
- {(pipeline === 'action_transfer' || (pipeline === 'standard' && standardVideoMode === 'dynamic_video')) && (
+ {(pipeline === 'action_transfer' || (pipeline === 'standard' && (standardVideoMode === 'dynamic_video' || templateVideoEnabled))) && (
<NumberField label="视频时长" value={duration} onChange={setDuration} min={1} max={10} />
)}
{pipeline !== 'action_transfer' && (
<>
- <TextInput label="TTS 声音" value={ttsVoice} onChange={setTtsVoice} />
+ <SelectField label="TTS 声音" value={ttsVoice} onChange={setTtsVoice} groups={TTS_VOICE_GROUPS} />
<NumberField label="TTS 速度" value={ttsSpeed} onChange={setTtsSpeed} min={0.5} max={2} />
</>
)}
diff --git a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
index 727875e..2ff52bb 100644
--- a/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
+++ b/aigc-director/aigc-claw/frontend/lib/workflowApi.ts
@@ -95,6 +95,7 @@
media_height: number;
media_ratio: string;
media_resolution: string;
+ supports_video?: boolean;
fields: Array<{ key: string; type: string; default: string }>;
preview_url: string;
}
--
Gitblit v1.8.0