Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

feat: 科普 Seedance 内置口播,画布预览框按图比例自适应

yi01e934d908a8
diff --git a/backend/.env.example b/backend/.env.example
index c7ea528..d6237dd 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -54,6 +54,9 @@ MODEL_VIDEO=doubao-seedance-2-5-260628
SEEDANCE_DURATION_MIN=4
SEEDANCE_DURATION_MAX=30
# 科普 Seedance 仍出音轨:只要键盘/点击等操作环境音,不要口播与 BGM
+# 科普 full 默认用 Seedance 视频内置口播;关则回退到外部 TTS
+KEPU_SEEDANCE_NATIVE_AUDIO=true
+# 仅当 NATIVE_AUDIO=false 时:Seedance 只要操作音效 + 后期 TTS(建议保持 true)
KEPU_SEEDANCE_SFX_AUDIO=true
# 音频/TTS 上游模型 ID(TokenFree 目录现用 qwen-tts;seed-tts-2.0 已下线)
MODEL_AUDIO=qwen-tts-2025-05-22
diff --git a/backend/app/config.py b/backend/app/config.py
index 4ebcb0b..3312d00 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -75,7 +75,9 @@ class Settings(BaseSettings):
drama_user_video_job_limit: int = 12
# 单个分镜视频最大尝试次数;超过后直接失败,避免长时间卡在同一镜
drama_fragment_max_attempts: int = 3
- # 科普 Seedance 仍出音轨:只要操作/环境音效,不要口播与 BGM
+ # 科普 full:Seedance 视频内置口播+环境音,后期不再叠外部 TTS
+ kepu_seedance_native_audio: bool = True
+ # 仅当 native_audio=false 时生效:Seedance 只要操作音效,口播改后期 TTS(默认开)
kepu_seedance_sfx_audio: bool = True
ark_mock: bool = False
diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.py
index 8af9958..3546570 100644
--- a/backend/app/services/ffmpeg_compose.py
+++ b/backend/app/services/ffmpeg_compose.py
@@ -61,8 +61,10 @@ class ComposeOptions:
# Optional continuous BGM under narration
bgm_path: Path | None = None
bgm_volume: float = 0.22
- # 保留镜头视频里的操作音效,后期与 TTS 叠轨(科普 full)
+ # 保留镜头视频里的操作音效,后期与 TTS 叠轨(科普 full 回退模式)
keep_video_sfx: bool = False
+ # Seedance 内置口播:直接保留视频音轨,不叠外部 TTS
+ prefer_video_audio: bool = False
sfx_volume: float = 0.22
@@ -1115,6 +1117,9 @@ def compose_project(
segment_paths: list[Path] = []
continuous = bool(opts.full_audio_path and opts.full_audio_path.exists())
keep_sfx = bool(opts.keep_video_sfx)
+ prefer_va = bool(opts.prefer_video_audio)
+ # 内置口播或叠音效时,垫片/烧字幕需保留视频音轨
+ keep_clip_audio = keep_sfx or prefer_va
sfx_vol = float(opts.sfx_volume or 0.22)
for shot in shots:
@@ -1176,7 +1181,7 @@ def compose_project(
shot.duration,
w=w,
h=h,
- keep_audio=keep_sfx,
+ keep_audio=keep_clip_audio,
)
_burn_captions_on_video(
raw_v,
@@ -1192,7 +1197,7 @@ def compose_project(
subtitle_layout=opts.subtitle_layout or "top",
title_scale=opts.title_scale,
sub_scale=opts.sub_scale,
- keep_audio=keep_sfx,
+ keep_audio=keep_clip_audio,
)
elif shot.image_path and shot.image_path.exists():
_image_to_video(shot.image_path, shot.duration, video, w=w, h=h)
@@ -1230,7 +1235,37 @@ def compose_project(
]
)
- if continuous and keep_sfx and _probe_has_audio(video):
+ if prefer_va and _probe_has_audio(video):
+ # Seedance 内置口播:直接保留视频音轨
+ _copy_fitted_clip(video, shot.duration, seg)
+ elif prefer_va and shot.audio_path and shot.audio_path.exists():
+ # 隐私跳过/无 a 轨:回退单镜 TTS(若有)
+ logger.warning(
+ "compose shot %s: no video audio, falling back to shot TTS",
+ shot.shot_no,
+ )
+ _mux_shot(
+ video,
+ audio,
+ shot.duration,
+ seg,
+ mix_video_sfx=False,
+ sfx_volume=sfx_vol,
+ )
+ elif prefer_va:
+ logger.warning(
+ "compose shot %s: no video audio and no shot TTS; silent segment",
+ shot.shot_no,
+ )
+ _mux_shot(
+ video,
+ audio,
+ shot.duration,
+ seg,
+ mix_video_sfx=False,
+ sfx_volume=sfx_vol,
+ )
+ elif continuous and keep_sfx and _probe_has_audio(video):
_copy_fitted_clip(video, shot.duration, seg)
else:
_mux_shot(
@@ -1238,7 +1273,7 @@ def compose_project(
audio,
shot.duration,
seg,
- mix_video_sfx=keep_sfx and not continuous,
+ mix_video_sfx=keep_sfx and not continuous and not prefer_va,
sfx_volume=sfx_vol,
)
segment_paths.append(seg)
diff --git a/backend/app/services/kepu_stages.py b/backend/app/services/kepu_stages.py
index 8b1aaa4..dc9bf4a 100644
--- a/backend/app/services/kepu_stages.py
+++ b/backend/app/services/kepu_stages.py
@@ -49,7 +49,17 @@ def continuous_narration_ok(project_id: int) -> bool:
def project_audio_ready(project: Any) -> bool:
- """项目旁白是否就绪:整片文件 OK,或全部镜头旁白文件 OK。"""
+ """项目旁白是否就绪:视频内置口播无需外部 TTS;否则整片/分镜旁白文件 OK。"""
+ # full + Seedance 内置口播:assets 阶段不强制外部配音
+ if not _is_image_text(project):
+ try:
+ from app.config import get_settings
+
+ if bool(getattr(get_settings(), "kepu_seedance_native_audio", True)):
+ return True
+ except Exception: # noqa: BLE001
+ # 配置异常时不 fail-open,避免误跳过外部 TTS
+ pass
project_id = getattr(project, "id", None)
if project_id is not None and continuous_narration_ok(int(project_id)):
return True
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index 2207627..1938069 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -177,13 +177,27 @@ def _is_image_text(project: Project) -> bool:
return (project.pipeline_mode or "full") == "image_text"
+def _kepu_seedance_native_audio(project: Project | None = None) -> bool:
+ """科普 full:Seedance 视频内置口播,不走外部 TTS。"""
+ if project is not None and _is_image_text(project):
+ return False
+ return bool(getattr(get_settings(), "kepu_seedance_native_audio", True))
+
+
def _kepu_seedance_sfx_audio(project: Project | None = None) -> bool:
- """科普 full:向 Seedance 要操作/环境音效(不含口播与 BGM)。"""
+ """科普 full 回退:Seedance 只要操作音效,口播改后期 TTS。"""
+ if _kepu_seedance_native_audio(project):
+ return False
if project is not None and _is_image_text(project):
return False
return bool(get_settings().kepu_seedance_sfx_audio)
+def _kepu_seedance_generate_audio(project: Project | None = None) -> bool:
+ """是否向 Seedance 要音轨(内置口播或仅音效)。"""
+ return _kepu_seedance_native_audio(project) or _kepu_seedance_sfx_audio(project)
+
+
def _project_output_ratio(project: Project) -> str:
"""User-selected output ratio, else template default, else 16:9."""
allowed = {"16:9", "9:16", "1:1", "4:3", "21:9"}
@@ -236,6 +250,7 @@ def _kepu_video_prompt(
motion_bias: str,
camera: str,
ambient_only: bool,
+ no_bgm: bool = False,
) -> str:
"""科普提交 Seedance:后期叠字,禁止模型烧录字幕。"""
return segplan.build_seedance_prompt(
@@ -245,6 +260,7 @@ def _kepu_video_prompt(
camera=camera,
ambient_only=ambient_only,
burn_subtitles=False,
+ no_bgm=no_bgm,
)
@@ -902,8 +918,10 @@ async def _parallel_image_and_audio(project_id: int) -> None:
img_sem = asyncio.Semaphore(max(1, cfg.pipeline_image_concurrency))
done_img = 0
progress_lock = asyncio.Lock()
- # 静图成片与完整模式都合成连贯旁白;已有音轨则跳过
- need_audio = not _continuous_audio_ok(project_id)
+ # 静图成片仍走外部 TTS;full + Seedance 内置口播则跳过
+ need_audio = (not _kepu_seedance_native_audio(project)) and (
+ not _continuous_audio_ok(project_id)
+ )
async def bump_images() -> None:
nonlocal done_img
@@ -1094,9 +1112,10 @@ async def _parallel_videos(project_id: int) -> None:
)
project = result.scalar_one()
tpl = project.template
- # 科普 full:Seedance 出操作音效,口播改后期 TTS
- generate_audio = _kepu_seedance_sfx_audio(project)
- ambient_only = generate_audio
+ # 科普 full:默认 Seedance 内置口播;回退模式才 ambient_only + 后期 TTS
+ generate_audio = _kepu_seedance_generate_audio(project)
+ ambient_only = _kepu_seedance_sfx_audio(project)
+ no_bgm = _kepu_seedance_native_audio(project)
consistency = template_consistency_mode(tpl) == "character" and bool(
tpl.seedance_config.get("character_consistency", True)
)
@@ -1188,6 +1207,7 @@ async def _parallel_videos(project_id: int) -> None:
motion_bias=motion,
camera=str(meta.get("camera") or ""),
ambient_only=ambient_only,
+ no_bgm=no_bgm,
)
dur = segplan.resolve_api_duration(
script,
@@ -1376,7 +1396,6 @@ async def _compose_stage(project_id: int) -> None:
mode = project.pipeline_mode or "full"
# full 模式:成片节奏跟镜头视频真实时长,勿被整片旁白重分配后的短 duration 裁掉画面
- # (@duration/出视频约 76s,TTS 仅 ~33s 时,旧逻辑会把成片压成旁白长)
if mode == "full":
for item in media:
if not item.video_path:
@@ -1385,9 +1404,13 @@ async def _compose_stage(project_id: int) -> None:
if probed and probed > 0.5:
item.duration = float(probed)
- full_audio = _full_narration_path(project_id)
- if not full_audio.exists():
- full_audio = None
+ native_audio = _kepu_seedance_native_audio(project)
+ # 视频内置口播:不叠外部 full_narration;回退/静图仍可用整片 TTS
+ full_audio = None
+ if not native_audio:
+ full_audio = _full_narration_path(project_id)
+ if not full_audio.exists():
+ full_audio = None
sub_cfg = _merge_subtitle_preset(
(project.template.subtitle_config if project.template else None) or {},
@@ -1411,7 +1434,7 @@ async def _compose_stage(project_id: int) -> None:
if not bgm_mood and project.template and isinstance(project.template.audio_config, dict):
bgm_mood = str(project.template.audio_config.get("bgm_mood") or "").strip()
bgm_path = resolve_bgm_path(bgm_mood)
- keep_video_sfx = _kepu_seedance_sfx_audio(project)
+ keep_video_sfx = native_audio or _kepu_seedance_sfx_audio(project)
await _run_ffmpeg_compose_with_retry(
project_id,
@@ -1430,6 +1453,7 @@ async def _compose_stage(project_id: int) -> None:
bgm_path=bgm_path,
bgm_volume=0.22,
keep_video_sfx=keep_video_sfx,
+ prefer_video_audio=native_audio,
sfx_volume=0.22,
),
),
@@ -1577,7 +1601,9 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
shot = next((s for s in project.shots if s.id == shot_id), None)
if not shot or not (shot.image_url or shot.image_ark_url):
raise ValueError("shot image required")
- generate_audio = _kepu_seedance_sfx_audio(project)
+ generate_audio = _kepu_seedance_generate_audio(project)
+ ambient_only = _kepu_seedance_sfx_audio(project)
+ no_bgm = _kepu_seedance_native_audio(project)
motion = str(project.template.seedance_config.get("motion_bias", ""))
consistency = template_consistency_mode(project.template) == "character" and bool(
project.template.seedance_config.get("character_consistency", True)
@@ -1591,7 +1617,8 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
style_prefix=_effective_style(project),
motion_bias=motion,
camera=shot.camera or "",
- ambient_only=generate_audio,
+ ambient_only=ambient_only,
+ no_bgm=no_bgm,
)
dur = segplan.resolve_api_duration(
script,
@@ -1663,6 +1690,8 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:
.options(selectinload(Project.template), selectinload(Project.shots))
)
project = result.scalar_one()
+ if _kepu_seedance_native_audio(project):
+ raise ValueError("当前为视频内置配音,请重绘该镜视频以更新口播")
shot = next((s for s in project.shots if s.id == shot_id), None)
if not shot:
raise ValueError("shot not found")
@@ -1713,32 +1742,44 @@ async def regen_project_audio_and_compose(project_id: int) -> None:
.options(selectinload(Project.template), selectinload(Project.shots))
)
project = result.scalar_one()
+ native_audio = _kepu_seedance_native_audio(project)
voice = _project_voice(project)
shots = sorted(project.shots, key=lambda s: s.shot_no)
project.final_video_url = None
await db.commit()
- await publish_progress(
- project_id,
- {
- "event": "progress",
- "stage": "AUDIOING",
- "percent": 82,
- "message": "整片连贯配音中…",
- },
- )
- await _synthesize_continuous_audio(
- project_id, voice=voice, shot_rows=shots, force=True
- )
- await publish_progress(
- project_id,
- {
- "event": "progress",
- "stage": "AUDIOING",
- "percent": 90,
- "message": "整片配音完成,开始合成",
- },
- )
+ if native_audio:
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "AUDIOING",
+ "percent": 90,
+ "message": "使用视频内置配音,开始合成",
+ },
+ )
+ else:
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "AUDIOING",
+ "percent": 82,
+ "message": "整片连贯配音中…",
+ },
+ )
+ await _synthesize_continuous_audio(
+ project_id, voice=voice, shot_rows=shots, force=True
+ )
+ await publish_progress(
+ project_id,
+ {
+ "event": "progress",
+ "stage": "AUDIOING",
+ "percent": 90,
+ "message": "整片配音完成,开始合成",
+ },
+ )
try:
await _compose_stage(project_id)
diff --git a/backend/app/services/seedance_segments.py b/backend/app/services/seedance_segments.py
index 9780444..b57a24b 100644
--- a/backend/app/services/seedance_segments.py
+++ b/backend/app/services/seedance_segments.py
@@ -449,10 +449,13 @@ def build_seedance_production_section(
ambient_only: bool = False,
burn_subtitles: bool = True,
character_intro: bool = True,
+ no_bgm: bool = False,
) -> str:
"""组装 Seedance 音频/字幕/BGM 强制约束(科普旁白 / 漫剧画面+对白混排)。
- ambient_only:科普后期 TTS 模式——模型只出操作环境音,禁止口播与 BGM。
+ ambient_only:回退模式——模型只出操作环境音,禁止口播与 BGM(口播由后期 TTS)。
+ 默认科普 full 为环境音+口播同出(ambient_only=False)。
+ no_bgm:禁止模型出 BGM(科普内置口播时由后期叠可控 BGM)。
burn_subtitles=False:成片后再烧 SRT——保留口播,禁止画面内字幕。
character_intro=False:禁止人物介绍叠字/字卡(与字幕开关独立)。
"""
@@ -480,6 +483,16 @@ def build_seedance_production_section(
"口播仅出声,文字叠字由后期完成。"
)
+ def _bgm_line(idx: int) -> str:
+ if no_bgm:
+ return (
+ f"{idx}. 背景音乐:禁止任何 BGM、配乐、旋律、哼唱垫乐;"
+ "BGM 由后期统一叠加,视频内只保留口播与环境音效。"
+ )
+ return (
+ f"{idx}. 背景音乐:{bgm_mood};BGM 音量低于人声约 30%,不得盖过旁白与关键音效。"
+ )
+
if drama_mixed:
lines = [
"1. 配音范围:仅【旁白·…】【对白·…】标记的段落需要口播;"
@@ -513,11 +526,10 @@ def build_seedance_production_section(
)
else:
lines.append(
- "4. 人声:本镜若无旁白/对白标记,则全程无口播,仅环境音与 BGM。"
+ "4. 人声:本镜若无旁白/对白标记,则全程无口播,仅环境音"
+ + ("。" if no_bgm else "与 BGM。")
)
- lines.append(
- f"5. 背景音乐:{bgm_mood};BGM 音量低于人声约 30%。"
- )
+ lines.append(_bgm_line(5))
lines.append(
"6. 音效:环境音与动作音效与画面同步,层次低于人声。"
)
@@ -559,9 +571,7 @@ def build_seedance_production_section(
+ (";口播仅出声,画面不叠字幕;" if not burn_subtitles else ",并同步烧录字幕;")
+ "视频内不要自行添加嘈杂对白。"
)
- lines.append(
- f"4. 背景音乐:{bgm_mood};BGM 音量低于人声约 30%,不得盖过旁白与关键音效。"
- )
+ lines.append(_bgm_line(4))
lines.append(
"5. 音效:环境音与动作音效与画面同步,层次低于人声。"
)
@@ -831,6 +841,7 @@ def build_seedance_prompt(
ambient_only: bool = False,
burn_subtitles: bool = True,
character_intro: bool = True,
+ no_bgm: bool = False,
) -> str:
"""Assemble final Seedance text: style lock + production constraints + timed body."""
parts: list[str] = []
@@ -851,6 +862,7 @@ def build_seedance_prompt(
ambient_only=ambient_only,
burn_subtitles=burn_subtitles and not ambient_only,
character_intro=character_intro and not ambient_only,
+ no_bgm=no_bgm and not ambient_only,
)
)
parts.append(
diff --git a/backend/tests/test_kepu_native_audio.py b/backend/tests/test_kepu_native_audio.py
new file mode 100644
index 0000000..6fdadb7
--- /dev/null
+++ b/backend/tests/test_kepu_native_audio.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+"""科普 full:Seedance 视频内置口播,跳过外部 TTS。"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from app.config import get_settings
+from app.services.kepu_stages import project_audio_ready
+from app.services.pipeline import (
+ _kepu_seedance_generate_audio,
+ _kepu_seedance_native_audio,
+ _kepu_seedance_sfx_audio,
+)
+
+
+def test_native_audio_default_on_for_full() -> None:
+ project = SimpleNamespace(pipeline_mode="full")
+ assert _kepu_seedance_native_audio(project) is True
+ assert _kepu_seedance_sfx_audio(project) is False
+ assert _kepu_seedance_generate_audio(project) is True
+
+
+def test_native_audio_off_for_image_text() -> None:
+ project = SimpleNamespace(pipeline_mode="image_text")
+ assert _kepu_seedance_native_audio(project) is False
+ assert _kepu_seedance_generate_audio(project) is False
+
+
+def test_project_audio_ready_true_when_native(monkeypatch) -> None:
+ settings = get_settings()
+ monkeypatch.setattr(settings, "kepu_seedance_native_audio", True)
+ project = SimpleNamespace(id=1, pipeline_mode="full", shots=[SimpleNamespace()])
+ assert project_audio_ready(project) is True
+
+
+def test_sfx_fallback_when_native_off(monkeypatch) -> None:
+ settings = get_settings()
+ monkeypatch.setattr(settings, "kepu_seedance_native_audio", False)
+ monkeypatch.setattr(settings, "kepu_seedance_sfx_audio", True)
+ project = SimpleNamespace(pipeline_mode="full")
+ assert _kepu_seedance_native_audio(project) is False
+ assert _kepu_seedance_sfx_audio(project) is True
+ assert _kepu_seedance_generate_audio(project) is True
diff --git a/backend/tests/test_kepu_phase_billing.py b/backend/tests/test_kepu_phase_billing.py
index dd7715c..d1f4923 100644
--- a/backend/tests/test_kepu_phase_billing.py
+++ b/backend/tests/test_kepu_phase_billing.py
@@ -65,8 +65,16 @@ def test_resolve_phase_videos_when_continuous_audio_ok(monkeypatch) -> None:
assert resolve_kepu_billing_phase(_project(shots)) == "videos"
+def test_resolve_phase_videos_when_native_audio_and_images() -> None:
+ """Seedance 内置口播:有图即可进 videos,不依赖外部 TTS 文件。"""
+ shots = [_shot(image_url="/i.png") for _ in range(3)]
+ assert resolve_kepu_billing_phase(_project(shots)) == "videos"
+
+
def test_resolve_phase_assets_when_audio_url_but_file_bad(monkeypatch) -> None:
- """仅有 audio_url 字符串但文件不可用时,仍应留在 assets,避免误冻视频款。"""
+ """回退外部 TTS 时:仅有 audio_url 但文件不可用,仍留在 assets。"""
+ settings = get_settings()
+ monkeypatch.setattr(settings, "kepu_seedance_native_audio", False)
monkeypatch.setattr(
"app.services.kepu_stages.continuous_narration_ok",
lambda _pid: False,
diff --git a/backend/tests/test_seedance_segments.py b/backend/tests/test_seedance_segments.py
index fc33bc0..0a883f6 100644
--- a/backend/tests/test_seedance_segments.py
+++ b/backend/tests/test_seedance_segments.py
@@ -218,6 +218,21 @@ def test_build_seedance_production_section_ambient_only():
assert "轻快专业" not in section
+def test_build_seedance_production_section_no_bgm_keeps_vo():
+ """内置口播:保留旁白约束,禁止模型 BGM。"""
+ script = build_segment_script(
+ [
+ SegmentBeat(duration=5, kind="narration", text="诺贝尔发明了炸药"),
+ ],
+ bgm_mood="轻快专业",
+ )
+ section = build_seedance_production_section(script, ambient_only=False, no_bgm=True)
+ assert "禁止任何 BGM" in section
+ assert "旁白" in section
+ assert "后期外部 TTS" not in section
+ assert "轻快专业" not in section
+
+
def test_build_seedance_prompt_ambient_only_rewrites_narration():
from app.services.seedance_segments import seedance_timeline_without_voice
diff --git a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
index 866bf80..306729e 100644
--- a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
@@ -1,6 +1,22 @@
/** 画布资产自定义节点:类型图标 + 媒体卡片 + 选中工具栏 */
-import { memo, useCallback, useState, type ChangeEvent, type KeyboardEvent, type MouseEvent } from 'react'
-import { Handle, NodeToolbar, Position, type Node, type NodeProps } from '@xyflow/react'
+import {
+ memo,
+ useCallback,
+ useEffect,
+ useState,
+ type ChangeEvent,
+ type KeyboardEvent,
+ type MouseEvent,
+ type SyntheticEvent,
+} from 'react'
+import {
+ Handle,
+ NodeToolbar,
+ Position,
+ useUpdateNodeInternals,
+ type Node,
+ type NodeProps,
+} from '@xyflow/react'
import { AudioLines, Image as ImageIcon, Landmark, Loader2, Maximize2, Play, UserRound } from 'lucide-react'
import { resolveDramaMediaUrl } from '../../../api/drama'
import { isAudioUrl, isPlayableVideoUrl } from '../../../lib/canvasNodeMedia'
@@ -9,6 +25,7 @@ import {
CANVAS_GENERATABLE_KINDS,
CANVAS_NODE_OPTION_BY_KIND,
CANVAS_UPLOADABLE_KINDS,
+ canvasMediaFrameSize,
type CanvasAssetNodeData,
} from './canvasTypes'
import { CanvasNodeGeneratePanel } from './nodes/CanvasNodeGeneratePanel'
@@ -17,10 +34,28 @@ import { CanvasNodeUploadBar } from './nodes/CanvasNodeUploadBar'
import { DRAMA_VOICE_BINDING_ENABLED } from '../../../lib/dramaVoiceBinding'
/** 画布视频缩略:仅展示封面,不拦截单击(单击要选中并显示提示词面板) */
-function CanvasAssetVideoPreview({ src }: { src: string }) {
+function CanvasAssetVideoPreview({
+ src,
+ onAspect,
+}: {
+ src: string
+ onAspect?: (aspect: number) => void
+}) {
return (
<div className="fc-asset-video">
- <video className="fc-asset-media" src={src} muted playsInline preload="metadata" />
+ <video
+ className="fc-asset-media"
+ src={src}
+ muted
+ playsInline
+ preload="metadata"
+ onLoadedMetadata={(event) => {
+ const el = event.currentTarget
+ if (el.videoWidth > 0 && el.videoHeight > 0) {
+ onAspect?.(el.videoWidth / el.videoHeight)
+ }
+ }}
+ />
<span className="fc-asset-video-play" aria-hidden>
<Play size={22} strokeWidth={2.2} fill="currentColor" />
</span>
@@ -42,6 +77,7 @@ function PlaceholderIcon({ kind }: { kind: CanvasAssetNodeData['kind'] }) {
/** 渲染单个画布资产节点 */
function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasAssetNodeData>>) {
const { updateNodeTextContent, renameNode } = useCanvasStore()
+ const updateNodeInternals = useUpdateNodeInternals()
const option = CANVAS_NODE_OPTION_BY_KIND[data.kind]
const Icon = option.icon
const isText = data.kind === 'text'
@@ -68,12 +104,44 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA
// renaming 是否正在编辑节点名称
// draftName 编辑中的名称草稿
// previewOpen 是否打开大屏预览
+ // mediaAspect 媒体宽高比(宽/高),用于预览框横竖自适应
const [renaming, setRenaming] = useState(false)
const [draftName, setDraftName] = useState(displayName)
const [previewOpen, setPreviewOpen] = useState(false)
+ const [mediaAspect, setMediaAspect] = useState<number | null>(null)
const audioSrc = resolveDramaMediaUrl(voiceUrl || (data.kind === 'audio' ? mediaSrc : ''))
const textContent = typeof data.textContent === 'string' ? data.textContent : ''
const canPreview = Boolean(mediaSrc || audioSrc || textContent.trim())
+ const frameSize = canvasMediaFrameSize(data.kind, mediaSrc ? mediaAspect : null)
+ const orientationClass =
+ mediaSrc && mediaAspect
+ ? mediaAspect > 1.05
+ ? ' is-landscape'
+ : mediaAspect < 0.95
+ ? ' is-portrait'
+ : ' is-square'
+ : ''
+
+ useEffect(() => {
+ setMediaAspect(null)
+ }, [mediaSrc])
+
+ useEffect(() => {
+ updateNodeInternals(id)
+ }, [id, frameSize.width, frameSize.height, updateNodeInternals])
+
+ /** 图片加载后按自然尺寸更新预览框比例 */
+ const handleImageLoad = useCallback((event: SyntheticEvent<HTMLImageElement>) => {
+ const el = event.currentTarget
+ if (el.naturalWidth > 0 && el.naturalHeight > 0) {
+ setMediaAspect(el.naturalWidth / el.naturalHeight)
+ }
+ }, [])
+
+ /** 视频 metadata 就绪后更新预览框比例 */
+ const handleVideoAspect = useCallback((aspect: number) => {
+ if (aspect > 0) setMediaAspect(aspect)
+ }, [])
const handleTextChange = useCallback(
(event: ChangeEvent<HTMLTextAreaElement>) => {
@@ -170,7 +238,14 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA
title={canPreview ? '双击放大预览' : undefined}
onDoubleClick={handleCardDoubleClick}
>
- <div className={`fc-asset-body is-${data.kind}`}>
+ <div
+ className={`fc-asset-body is-${data.kind}${orientationClass}`}
+ style={
+ data.kind === 'text' || data.kind === 'audio'
+ ? undefined
+ : { width: frameSize.width, height: frameSize.height }
+ }
+ >
{isText ? (
selected ? (
<textarea
@@ -189,7 +264,7 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA
<span>生成中…</span>
</div>
) : mediaSrc && data.kind === 'video' && isPlayableVideoUrl(mediaSrc) ? (
- <CanvasAssetVideoPreview src={mediaSrc} />
+ <CanvasAssetVideoPreview src={mediaSrc} onAspect={handleVideoAspect} />
) : mediaSrc && (data.kind === 'audio' || isAudioUrl(mediaSrc)) ? (
<div className="fc-asset-audio-thumb">
<AudioLines size={28} strokeWidth={1.6} />
@@ -204,6 +279,7 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA
src={mediaSrc}
alt={displayName}
draggable={false}
+ onLoad={handleImageLoad}
/>
) : (
<PlaceholderIcon kind={data.kind} />
diff --git a/frontend/src/pages/drama/canvas/CanvasStore.tsx b/frontend/src/pages/drama/canvas/CanvasStore.tsx
index b38e18c..ae334da 100644
--- a/frontend/src/pages/drama/canvas/CanvasStore.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasStore.tsx
@@ -39,6 +39,7 @@ import {
import { mergeAssetsWithCanvasLayout, buildNodeDataFromAsset } from './assetsToCanvasNodes'
import {
CANVAS_NODE_DEFAULT_LABEL,
+ nextCanvasNodeLabel,
canvasKindToAssetType,
type CanvasAssetNodeData,
type CanvasNodeKind,
@@ -133,6 +134,8 @@ export function CanvasStoreProvider({ projectId, children }: CanvasStoreProvider
const edgesRef = useRef(edges)
const historyRef = useRef(history)
const freeCanvasModeRef = useRef(freeCanvasMode)
+ /** 串行化新建节点,避免连点并发同名命中去重 */
+ const addNodeChainRef = useRef(Promise.resolve())
const flushRef = useRef<
(override?: { nodes: Node<CanvasAssetNodeData>[]; edges: Edge[] }) => Promise<void>
>(async () => undefined)
@@ -336,55 +339,93 @@ export function CanvasStoreProvider({ projectId, children }: CanvasStoreProvider
const addNodeOfKind = useCallback(
async (kind: CanvasNodeKind, position: { x: number; y: number }) => {
- const label = CANVAS_NODE_DEFAULT_LABEL[kind]
- let assetId: number | undefined
- try {
- const asset = await dramaApi.createAsset({
- project_id: projectId,
- type: kind,
- asset_type: canvasKindToAssetType(kind),
- name: label,
- params: { on_canvas: true },
- })
- assetId = asset.id
- } catch (err) {
- setErrorMessage(err instanceof Error ? err.message : '创建资产失败')
- return
- }
+ const run = async () => {
+ /* 唯一名避免同类型同名去重复用资产;错开落点避免叠在同一位置 */
+ let label = nextCanvasNodeLabel(kind, nodesRef.current)
+ const stagger = nodesRef.current.length * 24
+ const placed = { x: position.x + stagger, y: position.y + stagger }
+ let assetId: number | undefined
+ try {
+ const asset = await dramaApi.createAsset({
+ project_id: projectId,
+ type: kind,
+ asset_type: canvasKindToAssetType(kind),
+ name: label,
+ params: { on_canvas: true },
+ })
+ assetId = asset.id
+ /* 若仍命中旧资产(兼容库内同名卡),换名再试一次 */
+ const usedIds = new Set(
+ nodesRef.current
+ .map((n) => n.data.assetId)
+ .filter((id): id is number => typeof id === 'number' && id > 0),
+ )
+ if (usedIds.has(assetId)) {
+ label = `${label} ${Date.now().toString(36)}`
+ const retry = await dramaApi.createAsset({
+ project_id: projectId,
+ type: kind,
+ asset_type: canvasKindToAssetType(kind),
+ name: label,
+ params: { on_canvas: true },
+ })
+ if (usedIds.has(retry.id)) {
+ setErrorMessage('创建节点失败:资产已存在于画布')
+ return
+ }
+ assetId = retry.id
+ }
+ } catch (err) {
+ setErrorMessage(err instanceof Error ? err.message : '创建资产失败')
+ return
+ }
- const id = `asset-${assetId}`
- const node: Node<CanvasAssetNodeData> = {
- id,
- type: 'asset',
- position,
- data: {
- kind,
- label,
- assetId,
- textContent: kind === 'text' ? '' : undefined,
- mediaUrl: null,
- },
- }
- /* 回写 canvas_node_id,刷新后仍能识别为画布节点 */
- void dramaApi
- .updateAsset(assetId, { params: { canvas_node_id: id, on_canvas: true } })
- .catch(() => undefined)
+ const id = `asset-${assetId}`
+ const node: Node<CanvasAssetNodeData> = {
+ id,
+ type: 'asset',
+ position: placed,
+ data: {
+ kind,
+ label,
+ assetId,
+ textContent: kind === 'text' ? '' : undefined,
+ mediaUrl: null,
+ },
+ }
+ /* 回写 canvas_node_id,刷新后仍能识别为画布节点 */
+ void dramaApi
+ .updateAsset(assetId, { params: { canvas_node_id: id, on_canvas: true } })
+ .catch(() => undefined)
- setHistory((prev) =>
- pushHistory(prev, {
- nodes: nodesRef.current,
+ setHistory((prev) =>
+ pushHistory(prev, {
+ nodes: nodesRef.current,
+ edges: edgesRef.current,
+ }),
+ )
+ const nextNodes = [...nodesRef.current, node]
+ nodesRef.current = nextNodes
+ setNodes(nextNodes)
+ markDirty()
+ /* 立刻落盘,避免刷新丢失新建节点 */
+ void flushRef.current({
+ nodes: nextNodes,
edges: edgesRef.current,
- }),
- )
- const nextNodes = [...nodesRef.current, node]
- nodesRef.current = nextNodes
- setNodes(nextNodes)
- markDirty()
- /* 立刻落盘,避免刷新丢失新建节点 */
- void flushRef.current({
- nodes: nextNodes,
- edges: edgesRef.current,
+ })
+ }
+
+ const prev = addNodeChainRef.current
+ let release!: () => void
+ addNodeChainRef.current = new Promise<void>((resolve) => {
+ release = resolve
})
+ await prev
+ try {
+ await run()
+ } finally {
+ release()
+ }
},
[markDirty, projectId],
)
diff --git a/frontend/src/pages/drama/canvas/canvas.css b/frontend/src/pages/drama/canvas/canvas.css
index 4a220da..072475a 100644
--- a/frontend/src/pages/drama/canvas/canvas.css
+++ b/frontend/src/pages/drama/canvas/canvas.css
@@ -842,12 +842,14 @@
.fc-asset-body.is-scene {
width: 200px;
height: 240px;
+ transition: width 0.18s ease, height 0.18s ease;
}
.fc-asset-body.is-image,
.fc-asset-body.is-video {
width: 160px;
height: 220px;
+ transition: width 0.18s ease, height 0.18s ease;
}
.fc-asset-body.is-audio {
diff --git a/frontend/src/pages/drama/canvas/canvasTypes.ts b/frontend/src/pages/drama/canvas/canvasTypes.ts
index b0e7e7a..1944d15 100644
--- a/frontend/src/pages/drama/canvas/canvasTypes.ts
+++ b/frontend/src/pages/drama/canvas/canvasTypes.ts
@@ -87,7 +87,27 @@ export const CANVAS_NODE_DEFAULT_LABEL: Record<CanvasNodeKind, string> = {
audio: '新音频',
}
-/** 节点卡片尺寸(宽 × 高,用于落点居中) */
+/**
+ * 为新建画布节点生成不与现有节点冲突的名称。
+ * 后端同类型同名会去重复用资产,导致 asset-{id} 冲突并覆盖旧节点。
+ */
+export function nextCanvasNodeLabel(
+ kind: CanvasNodeKind,
+ existing: Array<{ data: { kind: CanvasNodeKind; label?: string } }>,
+): string {
+ const base = CANVAS_NODE_DEFAULT_LABEL[kind]
+ const used = new Set(
+ existing
+ .filter((n) => n.data.kind === kind)
+ .map((n) => (typeof n.data.label === 'string' ? n.data.label.trim() : '')),
+ )
+ if (!used.has(base)) return base
+ let i = 2
+ while (used.has(`${base} ${i}`)) i += 1
+ return `${base} ${i}`
+}
+
+/** 节点卡片尺寸(宽 × 高,用于落点居中;含页脚约 +40) */
export const CANVAS_NODE_SIZE: Record<CanvasNodeKind, { width: number; height: number }> = {
character: { width: 200, height: 280 },
scene: { width: 200, height: 280 },
@@ -97,6 +117,46 @@ export const CANVAS_NODE_SIZE: Record<CanvasNodeKind, { width: number; height: n
audio: { width: 200, height: 100 },
}
+/** 预览区默认尺寸(不含页脚;无媒体时用竖屏占位) */
+export const CANVAS_MEDIA_BODY_SIZE: Record<
+ Exclude<CanvasNodeKind, 'text' | 'audio'>,
+ { width: number; height: number }
+> = {
+ character: { width: 200, height: 240 },
+ scene: { width: 200, height: 240 },
+ video: { width: 160, height: 220 },
+ image: { width: 160, height: 220 },
+}
+
+/**
+ * 按媒体宽高比计算预览框尺寸:横屏变宽、竖屏保持竖向。
+ * aspect = naturalWidth / naturalHeight
+ */
+export function canvasMediaFrameSize(
+ kind: CanvasNodeKind,
+ aspect: number | null | undefined,
+): { width: number; height: number } {
+ if (kind === 'text') return { width: 280, height: 100 }
+ if (kind === 'audio') return { width: 200, height: 72 }
+ const fallback = CANVAS_MEDIA_BODY_SIZE[kind]
+ if (!aspect || !Number.isFinite(aspect) || aspect <= 0) return { ...fallback }
+
+ const a = Math.min(Math.max(aspect, 9 / 21), 21 / 9)
+ const shortSide = kind === 'character' || kind === 'scene' ? 200 : 160
+ const maxLong = kind === 'character' || kind === 'scene' ? 320 : 280
+
+ if (a >= 1) {
+ // 横屏 / 正方形:以短边为高
+ const height = shortSide
+ const width = Math.min(maxLong, Math.round(height * a))
+ return { width, height: Math.max(120, Math.round(width / a)) }
+ }
+ // 竖屏:以短边为宽
+ const width = shortSide
+ const height = Math.min(maxLong, Math.round(width / a))
+ return { width, height: Math.max(140, height) }
+}
+
/** 网格吸附步长 */
export const CANVAS_SNAP_GRID: [number, number] = [20, 20]