Skip to content

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

Ship drama fragment planning, voice design/reference audio, and episode canvas UX.

yi3b63145a6b2e
diff --git a/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.py b/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.py
index e812dff..a876115 100644
--- a/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.py
+++ b/.cursor/skills/kepu-batch-opensource/scripts/batch_submit.py
@@ -66,13 +66,22 @@ def build_runner() -> str:
"output_ratio": it["output_ratio"],
"voice_id": it["voice_id"],
}}
+ if it.get("character_prompt"):
+ body["character_prompt"] = it["character_prompt"]
+ if it.get("extra_prompt"):
+ body["extra_prompt"] = it["extra_prompt"]
p = api("POST", "/api/projects", body, token=tok)
pid = p["id"]
- api("PATCH", f"/api/projects/{{pid}}", {{
+ patch = {{
"output_ratio": it["output_ratio"],
"voice_id": it["voice_id"],
"pipeline_mode": it.get("pipeline_mode", "full"),
- }}, token=tok)
+ }}
+ if it.get("character_prompt"):
+ patch["character_prompt"] = it["character_prompt"]
+ if it.get("extra_prompt"):
+ patch["extra_prompt"] = it["extra_prompt"]
+ api("PATCH", f"/api/projects/{{pid}}", patch, token=tok)
gen = api("POST", f"/api/projects/{{pid}}/generate", token=tok)
row = {{
"id": pid,
diff --git a/backend/.env.example b/backend/.env.example
index 99de916..e15b789 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -63,10 +63,16 @@ KEPU_SEEDANCE_GENERATE_AUDIO=true
MODEL_AUDIO=seed-tts-2.0
# 豆包语音合成(openspeech,与方舟 Key 不同)。不配则自动用 edge-tts 兜底
+# 新版控制台 API Key(ai-manju 项目里同名 SPEECH_API_KEY)
+# VOLC_TTS_API_KEY=
+# 旧版控制台(可选回退)
# VOLC_TTS_APP_ID=
# VOLC_TTS_ACCESS_KEY=
# VOLC_TTS_RESOURCE_ID=seed-tts-2.0
# VOLC_TTS_SPEAKER=zh_female_cancan_uranus_bigtts
+# 漫剧角色音色设计(需控制台购买 S_ 槽位):https://docs.volcengine.com/docs/6561/2277844
+# VOLC_TTS_VOICE_DESIGN_SPEAKER_IDS=S_xxx,S_yyy
+# VOLC_TTS_VOICE_DESIGN_URL=https://openspeech.bytedance.com/api/v3/tts/voice_design
ARK_IMAGE_SIZE=2k
ARK_VIDEO_RESOLUTION=480p
@@ -74,7 +80,7 @@ ARK_VIDEO_RATIO=16:9
ARK_VIDEO_POLL_INTERVAL=8
ARK_VIDEO_POLL_TIMEOUT=900
PIPELINE_IMAGE_CONCURRENCY=3
-PIPELINE_VIDEO_CONCURRENCY=2
+PIPELINE_VIDEO_CONCURRENCY=10
PIPELINE_AUDIO_CONCURRENCY=4
# Aliyun OSS(成片/分镜上传;FFmpeg 仍用本地文件。前端 dist 见 deploy/scripts/upload_oss_web.py)
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index 8970ad8..5d15b0c 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -17,11 +17,17 @@ from app.schemas_drama import (
DramaEpisodeOut,
DramaFragmentOut,
DramaGenerateRequest,
+ DramaPlanFragmentsRequest,
DramaSaveFragmentsRequest,
)
from app.services.drama.access import get_owned_drama_project, get_owned_episode
from app.services.drama.generation import fragment_generation_status
-from app.services.drama.jobs import dispatch_episode_generate_job
+from app.services.drama.jobs import (
+ cancel_all_episode_video_jobs,
+ cancel_episode_video_jobs,
+ dispatch_episode_fragment_plan_job,
+ dispatch_episode_generate_job,
+)
from app.services.drama.seed import seed_episodes_from_script
router = APIRouter()
@@ -82,6 +88,62 @@ async def get_episode(
return _episode_out(ep)
[email protected]("/episodes/{episode_id}/plan_fragments", response_model=DramaEpisodeOut)
+async def plan_episode_fragments(
+ episode_id: int,
+ body: DramaPlanFragmentsRequest | None = None,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> DramaEpisodeOut:
+ # 入队单集 LLM 分镜;前端轮询 episode.params.fragment_plan_status
+ req = body or DramaPlanFragmentsRequest()
+ ep = await get_owned_episode(db, episode_id, user)
+ await get_owned_drama_project(db, ep.project_id, user)
+
+ params = dict(ep.params or {})
+ existing = str(params.get("fragment_plan_status") or "")
+ # force 时允许重入队(避免 Celery 丢任务后卡在 generating)
+ if existing == "generating" and not req.force:
+ logger.info("单集分镜已在进行中 episode_id=%s", episode_id)
+ return _episode_out(ep)
+ if existing == "generating" and req.force:
+ logger.warning("单集分镜强制重入队 episode_id=%s prev_status=generating", episode_id)
+
+ if not req.force:
+ # 非 force:有保护分镜则拒绝
+ protected = any(
+ (f.video or "").strip()
+ or (isinstance(f.params, dict) and f.params.get("user_edited"))
+ for f in (ep.fragments or [])
+ )
+ if protected:
+ raise HTTPException(
+ status_code=409,
+ detail="本集含已生成视频或手改分镜,请确认后强制重新分镜",
+ )
+
+ params["fragment_plan_status"] = "generating"
+ params.pop("fragment_plan_error", None)
+ params["fragment_plan_mode"] = "llm"
+ ep.params = params
+ await db.commit()
+ await db.refresh(ep)
+
+ task_id = dispatch_episode_fragment_plan_job(
+ episode_id,
+ fallback_rules=bool(req.fallback_rules),
+ )
+ logger.info(
+ "已入队单集 LLM 分镜 episode_id=%s force=%s task_id=%s",
+ episode_id,
+ req.force,
+ task_id,
+ )
+ # 再取一次带 fragments 的 episode
+ ep = await get_owned_episode(db, episode_id, user)
+ return _episode_out(ep)
+
+
@router.post("/episodes/seed_from_script", response_model=list[DramaEpisodeOut])
async def seed_episodes(
project_id: int,
@@ -165,13 +227,27 @@ async def generate_episode(
# 入队 Celery / 进程内任务,前端用 generate_status 轮询
ep = await get_owned_episode(db, episode_id, user)
await get_owned_drama_project(db, ep.project_id, user)
- frags = sorted(ep.fragments or [], key=lambda f: f.sort_order)
+ all_frags = sorted(ep.fragments or [], key=lambda f: f.sort_order)
if body.fragment_ids:
id_set = set(body.fragment_ids)
- frags = [f for f in frags if f.id in id_set]
+ frags = [f for f in all_frags if f.id in id_set]
+ else:
+ frags = list(all_frags)
if not frags:
raise HTTPException(status_code=400, detail="没有可生成的分镜")
+ # 已有分镜在排队/生成时,仅禁止重复提交同一分镜
+ busy_same = [
+ f.id
+ for f in frags
+ if fragment_generation_status(f).get("status") in {"queued", "running"}
+ ]
+ if busy_same:
+ raise HTTPException(
+ status_code=409,
+ detail="所选分镜正在生成,请等待完成后再试",
+ )
+
frag_ids = [f.id for f in frags]
for f in frags:
params = dict(f.params or {})
@@ -224,3 +300,32 @@ async def generate_status(
"total": len(items),
"fragments": items,
}
+
+
[email protected]("/episodes/{episode_id}/cancel_generate")
+async def cancel_generate_episode(
+ episode_id: int,
+ db: AsyncSession = Depends(get_db),
+ user: User = Depends(get_current_user),
+) -> dict:
+ """取消本集全部分镜视频生成(排队/进行中)。"""
+ ep = await get_owned_episode(db, episode_id, user)
+ await get_owned_drama_project(db, ep.project_id, user)
+ result = await cancel_episode_video_jobs(episode_id)
+ logger.info(
+ "已取消分集视频 episode_id=%s project_id=%s result=%s",
+ episode_id,
+ ep.project_id,
+ result,
+ )
+ return result
+
+
[email protected]("/cancel_video_jobs")
+async def cancel_all_video_jobs(
+ user: User = Depends(get_current_user),
+) -> dict:
+ """取消当前用户触发的全部漫剧分镜视频任务。"""
+ result = await cancel_all_episode_video_jobs()
+ logger.info("已取消全部视频任务 user_id=%s result=%s", user.id, result)
+ return result
diff --git a/backend/app/api/drama/generation.py b/backend/app/api/drama/generation.py
index 05f490b..bb07739 100644
--- a/backend/app/api/drama/generation.py
+++ b/backend/app/api/drama/generation.py
@@ -102,14 +102,21 @@ async def suggest_voice_prompt(
if (asset.type or "").lower() != "character":
raise HTTPException(status_code=400, detail="仅支持角色资产")
- prompt = await suggest_voice_prompt_for_character(asset, project)
+ voice_prompt, speaker, sample_text = await suggest_voice_prompt_for_character(asset, project)
logger.info(
- "音色提示词已生成 project_id=%s asset_id=%s len=%s",
+ "音色提示词已生成 project_id=%s asset_id=%s len=%s speaker=%s",
project.id,
asset.id,
- len(prompt),
+ len(voice_prompt),
+ speaker,
)
- return {"ok": True, "voice_prompt": prompt, "asset_id": asset.id}
+ return {
+ "ok": True,
+ "voice_prompt": voice_prompt,
+ "speaker": speaker,
+ "sample_text": sample_text,
+ "asset_id": asset.id,
+ }
@router.post("/generation/voice")
@@ -148,6 +155,14 @@ async def generate_voice(
await db.commit()
await db.refresh(asset)
+ character_asset = None
+ if body.character_asset_id:
+ character_asset = await db.get(DramaAsset, body.character_asset_id)
+ if not character_asset or character_asset.project_id != project.id:
+ raise HTTPException(status_code=404, detail="角色资产不存在")
+ if (character_asset.type or "").lower() != "character":
+ raise HTTPException(status_code=400, detail="character_asset_id 须为角色资产")
+
try:
updated = await generate_voice_asset_audio(
db,
@@ -157,6 +172,7 @@ async def generate_voice(
voice_prompt=prompt,
sample_text=body.sample_text,
speaker=body.speaker,
+ character_asset=character_asset,
)
except Exception as exc: # noqa: BLE001
params = dict(asset.params or {})
diff --git a/backend/app/config.py b/backend/app/config.py
index 7635e76..365da43 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -37,6 +37,11 @@ class Settings(BaseSettings):
volc_tts_resource_id: str = "seed-tts-2.0"
volc_tts_speaker: str = "zh_female_cancan_uranus_bigtts"
volc_tts_url: str = "https://openspeech.bytedance.com/api/v3/tts/unidirectional"
+ # 新版控制台 API Key(与 app_id/access_key 二选一,优先 api_key)
+ volc_tts_api_key: str = ""
+ # 音色设计:控制台购买的 S_ 槽位,逗号分隔;配了且鉴权齐全则漫剧走 voice_design
+ volc_tts_voice_design_url: str = "https://openspeech.bytedance.com/api/v3/tts/voice_design"
+ volc_tts_voice_design_speaker_ids: str = ""
# Seedream: 2k|3k|4k or WIDTHxHEIGHT,且总像素 >= 3686400(约 2560x1440)
ark_image_size: str = "2k"
ark_video_resolution: str = "480p"
@@ -45,7 +50,8 @@ class Settings(BaseSettings):
ark_video_poll_timeout: float = 900.0
# Parallel generation concurrency (per project)
pipeline_image_concurrency: int = 3
- pipeline_video_concurrency: int = 2
+ # Seedance 2.5 官方并发上限约 10
+ pipeline_video_concurrency: int = 10
pipeline_audio_concurrency: int = 4
# 科普 full:Seedance generate_audio 配音,跳过 TTS + 重合成,仅拼接镜头
kepu_seedance_generate_audio: bool = True
diff --git a/backend/app/schemas_drama.py b/backend/app/schemas_drama.py
index b06aa72..c4e2365 100644
--- a/backend/app/schemas_drama.py
+++ b/backend/app/schemas_drama.py
@@ -175,6 +175,10 @@ class DramaVoiceGenerateRequest(BaseModel):
voice_prompt: str = Field(description="音色描述,用于 TTS 试听与 Seedance reference_audio")
sample_text: str | None = Field(default=None, description="试听台词,缺省自动生成")
speaker: str | None = Field(default=None, description="可选 TTS speaker 覆盖")
+ character_asset_id: int | None = Field(
+ default=None,
+ description="关联角色资产 ID,用于 voice_design image_prompt",
+ )
class DramaFragmentSaveItem(BaseModel):
@@ -196,6 +200,13 @@ class DramaGenerateRequest(BaseModel):
fragment_ids: list[int] | None = None
+class DramaPlanFragmentsRequest(BaseModel):
+ # force 是否覆盖已有视频/手改分镜(单集 AI 重切默认 true)
+ force: bool = True
+ # fallback_rules LLM 失败时是否回退规则切分
+ fallback_rules: bool = True
+
+
class DramaCanvasSaveRequest(BaseModel):
project_id: int
nodes: list[dict[str, Any]] = Field(default_factory=list)
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 82ed706..be1beeb 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -142,9 +142,32 @@ class StoryboardResult:
class TaskResult:
status: str # pending | running | succeeded | failed
url: str | None = None
+ last_frame_url: str | None = None
error: str | None = None
+# 从 Seedance 任务成功响应中提取尾帧 URL
+def _extract_seedance_last_frame_url(data: dict[str, Any]) -> str | None:
+ content = data.get("content")
+ if isinstance(content, dict):
+ for key in ("last_frame_url", "last_frame_image_url", "lastFrameUrl"):
+ value = content.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ nested = content.get("last_frame")
+ if isinstance(nested, dict):
+ nested_url = nested.get("url")
+ if isinstance(nested_url, str) and nested_url.strip():
+ return nested_url.strip()
+ if isinstance(nested, str) and nested.strip():
+ return nested.strip()
+ for key in ("last_frame_url", "last_frame_image_url", "lastFrameUrl"):
+ value = data.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return None
+
+
@dataclass
class ImageResult:
local_url: str
@@ -613,7 +636,12 @@ class ArkGateway:
"""解析图片/音频 URL 供 Seedance 拉取。"""
return await self._resolve_image_ref(media_url, prefer_https=prefer_https)
- async def _resolve_seedance_content_items(self, items: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ async def _resolve_seedance_content_items(
+ self,
+ items: list[dict[str, Any]],
+ *,
+ project_id: int = 0,
+ ) -> list[dict[str, Any]]:
resolved: list[dict[str, Any]] = []
for item in items:
copy = dict(item)
@@ -630,7 +658,12 @@ class ArkGateway:
resolved.append(copy)
return resolved
- async def gen_video_seedance_body(self, body: dict[str, Any]) -> str:
+ async def gen_video_seedance_body(
+ self,
+ body: dict[str, Any],
+ *,
+ project_id: int = 0,
+ ) -> str:
"""提交 Seedance 多模态请求体(参考图 + reference_audio)。"""
if self.mock:
digest = hashlib.md5(json.dumps(body, sort_keys=True, default=str).encode()).hexdigest()[
@@ -641,7 +674,10 @@ class ArkGateway:
payload = dict(body)
content = payload.get("content")
if isinstance(content, list):
- payload["content"] = await self._resolve_seedance_content_items(content)
+ payload["content"] = await self._resolve_seedance_content_items(
+ content,
+ project_id=project_id,
+ )
payload["duration"] = self._seedance_duration(payload.get("duration", 8))
logger.info(
@@ -673,20 +709,26 @@ class ArkGateway:
project_id: int,
shot_no: int,
max_attempts: int = 2,
- ) -> str:
- """创建 Seedance 多模态任务并等待完成。"""
+ ) -> tuple[str, str | None]:
+ """创建 Seedance 多模态任务并等待完成;返回 (本地视频 URL, 可选本地尾帧 URL)。"""
last_err: Exception | None = None
for _attempt in range(max_attempts):
try:
- task_id = await self.gen_video_seedance_body(body)
- return await self.wait_video(task_id, project_id=project_id, shot_no=shot_no)
+ task_id = await self.gen_video_seedance_body(body, project_id=project_id)
+ return await self.wait_video_assets(
+ task_id, project_id=project_id, shot_no=shot_no
+ )
except Exception as exc: # noqa: BLE001
last_err = exc
raise RuntimeError(str(last_err) if last_err else "Seedance multimodal failed")
async def poll_task(self, task_id: str) -> TaskResult:
if self.mock or task_id.startswith("mock-task-"):
- return TaskResult(status="succeeded", url=f"/static/mock/video_{task_id[-8:]}.mp4")
+ return TaskResult(
+ status="succeeded",
+ url=f"/static/mock/video_{task_id[-8:]}.mp4",
+ last_frame_url=f"/static/mock/last_{task_id[-8:]}.jpg",
+ )
deadline = time.monotonic() + self.settings.ark_video_poll_timeout
async with httpx.AsyncClient(timeout=60.0) as client:
@@ -706,28 +748,65 @@ class ArkGateway:
url = content.get("video_url")
if not url:
url = data.get("video_url")
- return TaskResult(status="succeeded", url=url)
+ return TaskResult(
+ status="succeeded",
+ url=url,
+ last_frame_url=_extract_seedance_last_frame_url(data),
+ )
if status in {"failed", "cancelled", "canceled", "expired"}:
err = data.get("error") or data.get("message") or status
return TaskResult(status="failed", error=str(err))
await asyncio.sleep(self.settings.ark_video_poll_interval)
return TaskResult(status="failed", error="poll timeout")
- async def wait_video(
+ async def wait_video_assets(
self,
task_id: str,
*,
project_id: int,
shot_no: int,
- ) -> str:
+ ) -> tuple[str, str | None]:
+ """等待任务完成并落盘视频;若有尾帧则一并落盘。"""
result = await self.poll_task(task_id)
if result.status != "succeeded" or not result.url:
raise RuntimeError(result.error or "video generation failed")
+
if result.url.startswith("/static/"):
- return result.url
- dest = storage.project_dir(project_id) / f"shot_{shot_no:03d}.mp4"
- await storage.download_to(result.url, dest)
- return storage.publish_local(dest)
+ video_local = result.url
+ else:
+ dest = storage.project_dir(project_id) / f"shot_{shot_no:03d}.mp4"
+ await storage.download_to(result.url, dest)
+ video_local = storage.publish_local(dest)
+
+ last_local: str | None = None
+ if result.last_frame_url:
+ try:
+ if result.last_frame_url.startswith("/static/"):
+ last_local = result.last_frame_url
+ else:
+ frame_dest = storage.project_dir(project_id) / f"shot_{shot_no:03d}_last.jpg"
+ await storage.download_to(result.last_frame_url, frame_dest)
+ last_local = storage.publish_local(frame_dest)
+ except Exception as exc: # noqa: BLE001
+ logger.warning(
+ "Seedance last frame download failed shot_no=%s err=%s",
+ shot_no,
+ exc,
+ )
+ last_local = None
+ return video_local, last_local
+
+ async def wait_video(
+ self,
+ task_id: str,
+ *,
+ project_id: int,
+ shot_no: int,
+ ) -> str:
+ video_local, _last = await self.wait_video_assets(
+ task_id, project_id=project_id, shot_no=shot_no
+ )
+ return video_local
async def gen_and_wait_video(
self,
@@ -783,6 +862,25 @@ class ArkGateway:
await asyncio.sleep(1.5 * (attempt + 1))
raise RuntimeError(str(last_err) if last_err else "video generation failed")
+ def _openspeech_configured(self) -> bool:
+ """豆包 openspeech 是否已配置(新版 API Key 或旧版 AppId + AccessKey)。"""
+ if (self.settings.volc_tts_api_key or "").strip():
+ return True
+ return bool(self.settings.volc_tts_app_id and self.settings.volc_tts_access_key)
+
+ @staticmethod
+ def _build_tts_additions(speaker: str, emotion_hint: str | None) -> str | None:
+ """组装 openspeech additions(S_ 克隆 + 语气 context_texts)。"""
+ additions: dict[str, Any] = {}
+ if speaker.startswith("S_"):
+ additions["model_type"] = 4
+ hint = (emotion_hint or "").strip()
+ if hint:
+ additions["context_texts"] = [f"用「{hint}」的语气朗读"]
+ if not additions:
+ return None
+ return json.dumps(additions, ensure_ascii=False)
+
async def tts(
self,
text: str,
@@ -791,6 +889,7 @@ class ArkGateway:
project_id: int | None = None,
shot_no: int | None = None,
duration_hint: float = 4.0,
+ emotion_hint: str | None = None,
) -> str:
voice_map = {
"narrator_calm": "zh_female_cancan_uranus_bigtts",
@@ -826,10 +925,10 @@ class ArkGateway:
return None
return storage.publish_local(dest)
- # 1) 豆包 openspeech(需 APP ID + Access Key)
- if self.settings.volc_tts_app_id and self.settings.volc_tts_access_key:
+ # 1) 豆包 openspeech(X-Api-Key 或 AppId + AccessKey)
+ if self._openspeech_configured():
try:
- ok = await self._tts_openspeech(clean, speaker, dest)
+ ok = await self._tts_openspeech(clean, speaker, dest, emotion_hint=emotion_hint)
if ok:
url = await _accept_if_audible("openspeech")
if url:
@@ -881,14 +980,25 @@ class ArkGateway:
return self.settings.volc_tts_resource_id or "seed-tts-2.0"
return "seed-tts-1.0"
- async def _tts_openspeech(self, text: str, speaker: str, dest: Path) -> bool:
+ async def _tts_openspeech(
+ self,
+ text: str,
+ speaker: str,
+ dest: Path,
+ *,
+ emotion_hint: str | None = None,
+ ) -> bool:
resource = self._tts_resource_id(speaker)
- headers = {
+ headers: dict[str, str] = {
"Content-Type": "application/json",
- "X-Api-App-Id": self.settings.volc_tts_app_id,
- "X-Api-Access-Key": self.settings.volc_tts_access_key,
"X-Api-Resource-Id": resource,
}
+ api_key = (self.settings.volc_tts_api_key or "").strip()
+ if api_key:
+ headers["X-Api-Key"] = api_key
+ else:
+ headers["X-Api-App-Id"] = self.settings.volc_tts_app_id
+ headers["X-Api-Access-Key"] = self.settings.volc_tts_access_key
body: dict[str, Any] = {
"user": {"uid": "framecut"},
"req_params": {
@@ -897,8 +1007,9 @@ class ArkGateway:
"audio_params": {"format": "mp3", "sample_rate": 24000},
},
}
- if speaker.startswith("S_"):
- body["req_params"]["additions"] = json.dumps({"model_type": 4}, ensure_ascii=False)
+ additions = self._build_tts_additions(speaker, emotion_hint)
+ if additions:
+ body["req_params"]["additions"] = additions
async with httpx.AsyncClient(timeout=120.0) as client:
resp = await client.post(self.settings.volc_tts_url, headers=headers, json=body)
@@ -986,11 +1097,15 @@ class ArkGateway:
):
return raw
if prefer_https:
- # Seedance 2.0: avoid data URI (often Invalid base64 / odd BodyFormat)
+ # Seedance 2.0: 需要公网 https;本地 /static 先同步上 OSS
local = storage.local_path_from_url(raw)
if local and local.exists():
+ public = storage.republish_url(raw, sync=True)
+ if public and str(public).startswith("https://"):
+ return str(public)
raise RuntimeError(
- "Seedance 需要公网可访问的图片 URL(image_ark_url),本地图无法提交"
+ "Seedance 需要公网可访问的图片 URL(请启用 OSS 并确保参考图已上传),"
+ "本地 /static 图无法被方舟拉取"
)
if raw.startswith("data:"):
raise RuntimeError("Seedance 不支持 data URI 图片,请使用 Ark CDN https 链接")
diff --git a/backend/app/services/drama/build_fragments.py b/backend/app/services/drama/build_fragments.py
index f9cef1d..60191b1 100644
--- a/backend/app/services/drama/build_fragments.py
+++ b/backend/app/services/drama/build_fragments.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import re
from typing import Any
+from app.services.seedance_segments import DRAMA_SUBTITLE_CUE, DIALOGUE_PREFIX, VISUAL_PREFIX
+
# 场次标题:### 场1-2 / ### 场景1-2
SCENE_HEADER_RE = re.compile(r"^###\s*场(?:景)?\s*\d+\s*[--—]\s*\d+\s*$")
# 兼容无空格、或标题后带说明
@@ -24,6 +26,31 @@ FRAGMENT_SOFT_MAX = 20
# 单分镜总时长硬上限(Seedance 2.5 支持至 30s)
FRAGMENT_TOTAL_MAX = 30
+# 重要角色:roleType / title / tags 命中则需要人物介绍叠字
+IMPORTANT_ROLE_RE = re.compile(r"主角|男主|女主|重要|反派|BOSS|核心|主人公")
+# 次要定位:默认不介绍
+MINOR_ROLE_RE = re.compile(r"群演|路人|群众|龙套|配角|出场人物|兵丁|侍卫|士兵")
+# 群体/无名角色名:不介绍
+MINOR_NAME_RE = re.compile(r"(兵|百姓|群众|路人|侍从|侍卫|士兵|甲|乙|众人|百姓们)$")
+# 无意义 intro 占位文案
+GENERIC_INTRO_TEXTS = frozenset({"出场人物", "配角", "角色", "群演", "路人", "-"})
+# stub 资产默认身份背景等占位句式
+STUB_CAST_INTRO_RE = re.compile(r"剧本分集出场人物|出场\s*->\s*卷入")
+# 已写入分镜的人物介绍叠字行(兼容旧「·画面叠字」与现行「·角色身旁」)
+CHARACTER_INTRO_CUE = "【人物介绍·画面叠字·角色身旁】"
+CHARACTER_INTRO_LINE_RE = re.compile(
+ r"^【人物介绍·画面叠字(?:·角色身旁)?】\s*([^|\|\n]+?)(?:\s*[||].*)?$"
+)
+LEGACY_CHARACTER_INTRO_CUE = "【人物介绍·画面叠字】"
+# 纯画面/空镜标签(冒号前):禁止当成「角色名:对白」
+VISUAL_SHOT_LABEL_RE = re.compile(
+ r"^(?:"
+ r"空镜|画面|远景|近景|中景|全景|特写|大特写|"
+ r"跟拍|俯拍|仰拍|航拍|推镜|拉镜|摇镜|环境|镜头|动作|转场|闪回|"
+ r"建立镜头|气氛镜头"
+ r")\s*[::]"
+)
+
def normalize_scene_location_name(raw: str) -> str:
# 去掉斜杠说明、压缩空白
@@ -54,6 +81,55 @@ def parse_cast_names(raw: str) -> list[str]:
return out
+def extract_introduced_names_from_content(content: str) -> list[str]:
+ # 从分镜正文提取已写入的人物介绍角色名(保序)
+ names: list[str] = []
+ seen: set[str] = set()
+ for line in (content or "").replace("\r\n", "\n").split("\n"):
+ match = CHARACTER_INTRO_LINE_RE.match(line.strip())
+ if not match:
+ continue
+ name = match.group(1).strip()
+ if name and name not in seen:
+ seen.add(name)
+ names.append(name)
+ return names
+
+
+def collect_series_introduced_names(
+ episodes: list[Any],
+ *,
+ before_episode_number: int | None = None,
+ exclude_episode_id: int | None = None,
+) -> set[str]:
+ """
+ 汇总本剧更早分集里已做过人物介绍的角色名。
+ before_episode_number:只统计集号更小的分集;None 则按 exclude 排除当前集。
+ """
+ # rows (ep_no, ep_id, episode) 排序用
+ rows: list[tuple[int, int, Any]] = []
+ for ep in episodes:
+ params = getattr(ep, "params", None) or {}
+ if not isinstance(params, dict):
+ params = {}
+ ep_no = int(params.get("episodeNumber") or 0)
+ ep_id = int(getattr(ep, "id", 0) or 0)
+ if exclude_episode_id is not None and ep_id == int(exclude_episode_id):
+ continue
+ if before_episode_number is not None and before_episode_number > 0:
+ if ep_no <= 0 or ep_no >= int(before_episode_number):
+ continue
+ rows.append((ep_no or 10**9, ep_id, ep))
+ rows.sort(key=lambda x: (x[0], x[1]))
+
+ introduced: set[str] = set()
+ for _, _, ep in rows:
+ for frag in getattr(ep, "fragments", None) or []:
+ for name in extract_introduced_names_from_content(getattr(frag, "content", None) or ""):
+ introduced.add(name)
+ return introduced
+
+
def split_episode_content_into_scenes(content: str) -> list[dict[str, str]]:
# 按 ### 场X-Y 拆分;无场头时整集一场
lines = (content or "").replace("\r\n", "\n").split("\n")
@@ -144,36 +220,79 @@ def _strip_screenplay_meta(body: str) -> tuple[str | None, list[str]]:
return location_line, narrative
+def _strip_production_prefix(line: str) -> str:
+ # 去掉已有【…】生产前缀,便于二次分类
+ return re.sub(r"^【[^】]*】\s*", "", (line or "").strip()).strip()
+
+
+def _is_visual_description_line(line: str) -> bool:
+ # 空镜/景别/纯画面描写:不得配音、不得烧字幕
+ trimmed = (line or "").strip()
+ if not trimmed:
+ return False
+ if trimmed.startswith("【画面") or trimmed.startswith(VISUAL_PREFIX):
+ return True
+ if trimmed.startswith("【空镜"):
+ return True
+ if trimmed.startswith("△") or trimmed.startswith("Δ"):
+ return True
+ body = _strip_production_prefix(trimmed)
+ if not body:
+ return False
+ if VISUAL_SHOT_LABEL_RE.match(body):
+ return True
+ if body.startswith("空镜") or body.startswith("△"):
+ return True
+ return False
+
+
def _format_narrative_line(line: str) -> str:
+ # 将场记行标成画面/旁白/对白;空镜类必须走无配音前缀
trimmed = line.strip()
if not trimmed:
return trimmed
+ if trimmed.startswith("【画面") or trimmed.startswith("【旁白") or trimmed.startswith("【对白"):
+ # 已打标但仍可能是误判的「对白·空镜:…」→ 纠正为画面
+ if trimmed.startswith("【对白") and _is_visual_description_line(trimmed):
+ return f"{VISUAL_PREFIX}{_strip_production_prefix(trimmed)}"
+ if trimmed.startswith("【旁白") and _is_visual_description_line(trimmed):
+ return f"{VISUAL_PREFIX}{_strip_production_prefix(trimmed)}"
+ return trimmed
+ if trimmed.startswith("【空镜"):
+ return f"【空镜·可仅环境音与 BGM】{trimmed}"
+ if _is_visual_description_line(trimmed):
+ if trimmed.startswith("△") or trimmed.startswith("Δ"):
+ body = trimmed.replace("Δ", "△", 1) if trimmed.startswith("Δ") else trimmed
+ return f"{VISUAL_PREFIX}{body}"
+ return f"{VISUAL_PREFIX}{trimmed}"
if re.search(r"[((](?:vo|VO|旁白)[))]", trimmed):
return f"【旁白·慢速清晰·同步字幕】{trimmed}"
if re.search(r"[((](?:os|OS)[))]", trimmed):
return f"【内心独白·同步字幕】{trimmed}"
- if re.match(r"^[^((::\n]{1,16}[((][^))]*[))]\s*[::].+", trimmed) or re.match(
- r"^[^::\n]{1,16}[::].+", trimmed
- ):
- return f"【对白·慢速清晰·同步字幕】{trimmed}"
- if trimmed.startswith("△") or trimmed.startswith("Δ"):
- return trimmed.replace("Δ", "△", 1) if trimmed.startswith("Δ") else trimmed
- if trimmed.startswith("【空镜"):
- return f"【空镜·可仅环境音与 BGM】{trimmed}"
- return trimmed
+ # 角色对白:排除空镜/景别等冒号标签,避免「空镜:…」被当成「角色名:台词」
+ if re.match(r"^[^((::\n]{1,16}[((][^))]*[))]\s*[::].+", trimmed):
+ return f"{DIALOGUE_PREFIX}{trimmed}"
+ colon_speaker = re.match(r"^([^::\n]{1,16})[::](.+)$", trimmed)
+ if colon_speaker and not VISUAL_SHOT_LABEL_RE.match(trimmed):
+ return f"{DIALOGUE_PREFIX}{trimmed}"
+ # 纯画面/动作描述:明确禁止配音,避免被全局字幕 cue 误读为旁白
+ return f"{VISUAL_PREFIX}{trimmed}"
def _estimate_line_duration(line: str) -> int:
trimmed = line.strip()
if not trimmed:
return 0
+ if trimmed.startswith("【画面") or trimmed.startswith(VISUAL_PREFIX):
+ body = re.sub(r"^【[^】]*】", "", trimmed).strip()
+ return min(6, max(2, len(re.sub(r"\s+", "", body)) // 12))
if trimmed.startswith("△"):
return 2
if trimmed.startswith("【空镜"):
return 4
- if "旁白" in trimmed:
+ if "旁白" in trimmed and trimmed.startswith("【旁白"):
return min(8, max(3, len(re.sub(r"\s+", "", trimmed)) // 8))
- if "对白" in trimmed or "内心独白" in trimmed:
+ if trimmed.startswith("【对白") or "内心独白" in trimmed:
return min(8, max(3, len(re.sub(r"\s+", "", trimmed)) // 10))
return min(6, max(2, len(re.sub(r"\s+", "", trimmed)) // 12))
@@ -234,15 +353,272 @@ def _infer_bgm_mood(hints: str) -> str:
return "贴合剧情氛围的轻量配乐,情绪随画面起伏"
+def _is_generic_intro_text(text: str) -> bool:
+ cleaned = re.sub(r"\s+", "", (text or "").strip())
+ if not cleaned:
+ return True
+ if cleaned in GENERIC_INTRO_TEXTS:
+ return True
+ if cleaned.startswith("出场人物"):
+ return True
+ if STUB_CAST_INTRO_RE.search(cleaned):
+ return True
+ return False
+
+
+def _shorten_intro(text: str, max_len: int = 24) -> str:
+ # 叠字描述截断:去空白、取首句、限长
+ cleaned = re.sub(r"\s+", "", (text or "").strip())
+ if not cleaned:
+ return ""
+ first = re.split(r"[。!?;;]", cleaned, maxsplit=1)[0].strip()
+ if len(first) > max_len:
+ return first[: max_len - 1] + "…"
+ return first
+
+
+def _resolve_character_intro_text(params: dict[str, Any] | None) -> str | None:
+ # 优先 title,其次身份背景首句 / roleType / 标签;跳过占位文案
+ if not isinstance(params, dict):
+ return None
+ title = str(params.get("title") or "").strip()
+ role = str(params.get("roleType") or "").strip()
+ identity = str(params.get("identityBackground") or "").strip()
+ tags = str(params.get("coreTags") or "").strip()
+ personality = str(params.get("personality") or "").strip()
+
+ if title and not _is_generic_intro_text(title):
+ return _shorten_intro(title)
+ if identity:
+ shortened = _shorten_intro(identity)
+ if shortened and not _is_generic_intro_text(shortened):
+ return shortened
+ if role and not _is_generic_intro_text(role):
+ if title and not _is_generic_intro_text(title):
+ return _shorten_intro(f"{role}·{title}")
+ return _shorten_intro(role)
+ if personality:
+ shortened = _shorten_intro(personality)
+ if shortened and not _is_generic_intro_text(shortened):
+ return shortened
+ if tags:
+ first_tag = re.split(r"[、,,/|]", tags)[0].strip()
+ if first_tag and not _is_generic_intro_text(first_tag):
+ return _shorten_intro(first_tag)
+ return None
+
+
+def _extract_intro_sentence_for_name(name: str, text: str) -> str | None:
+ # 从梗概/分集正文截取含该角色的句子作叠字介绍
+ char_name = (name or "").strip()
+ blob = (text or "").strip()
+ if not char_name or char_name not in blob:
+ return None
+ candidates: list[str] = []
+ for sent in re.split(r"[。!?\n]", blob):
+ if char_name not in sent:
+ continue
+ cleaned = re.sub(r"\s+", "", sent.strip())
+ if len(cleaned) < 6:
+ continue
+ if CAST_LINE_RE.match(cleaned) or cleaned.startswith("出场人物"):
+ continue
+ if cleaned.startswith("###"):
+ continue
+ candidates.append(cleaned)
+ if not candidates:
+ return None
+ # 叠字宜短:优先 12~36 字的句子
+ best = min(candidates, key=lambda s: abs(len(s) - 22))
+ return _shorten_intro(best, max_len=28)
+
+
+def _resolve_intro_from_summary_narrative(
+ name: str,
+ summary: dict[str, Any] | None,
+) -> str | None:
+ char_name = (name or "").strip()
+ if not char_name or not isinstance(summary, dict):
+ return None
+ for field in ("synopsis", "oneLineStory", "coreHook"):
+ text = str(summary.get(field) or "").strip()
+ intro = _extract_intro_sentence_for_name(char_name, text)
+ if intro:
+ return intro
+ return None
+
+
+def infer_character_intro_text(
+ name: str,
+ params: dict[str, Any] | None = None,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
+) -> str | None:
+ """人物介绍叠字文案:override → 资产字段 → 摘要梗概 → 分集剧本正文。"""
+ char_name = (name or "").strip()
+ if char_name and intro_overrides:
+ override = str(intro_overrides.get(char_name) or "").strip()
+ if override and not _is_generic_intro_text(override):
+ return _shorten_intro(override, max_len=28)
+ intro = _resolve_character_intro_text(params)
+ if intro and not _is_generic_intro_text(intro):
+ return intro
+ intro = _resolve_intro_from_summary_narrative(name, summary)
+ if intro:
+ return intro
+ for body in episode_bodies or []:
+ intro = _extract_intro_sentence_for_name(name, body)
+ if intro:
+ return intro
+ if isinstance(params, dict):
+ for field in ("relationships", "growthExperience", "growthArc"):
+ val = str(params.get(field) or "").strip()
+ if not val or _is_generic_intro_text(val):
+ continue
+ shortened = _shorten_intro(val)
+ if shortened and not _is_generic_intro_text(shortened):
+ return shortened
+ return None
+
+
+def build_summary_character_lookup(summary: dict[str, Any] | None) -> dict[str, dict[str, Any]]:
+ # 剧本摘要 characters[] 按名索引(保序,供 stub 资产补全小传)
+ lookup: dict[str, dict[str, Any]] = {}
+ if not isinstance(summary, dict):
+ return lookup
+ for item in summary.get("characters") or []:
+ if not isinstance(item, dict):
+ continue
+ name = str(item.get("name") or "").strip()
+ if name and name not in lookup:
+ lookup[name] = item
+ return lookup
+
+
+def _find_summary_character(
+ lookup: dict[str, dict[str, Any]],
+ name: str,
+) -> dict[str, Any] | None:
+ target = (name or "").strip()
+ if not target or not lookup:
+ return None
+ if target in lookup:
+ return lookup[target]
+ for key, item in lookup.items():
+ if key and (target in key or key in target):
+ return item
+ return None
+
+
+def _merge_params_with_summary(
+ params: dict[str, Any] | None,
+ summary_char: dict[str, Any] | None,
+) -> dict[str, Any]:
+ # 资产 params 为 stub 时,用摘要人物字段补全
+ merged = dict(params or {})
+ if not summary_char:
+ return merged
+ for key in ("roleType", "title", "coreTags", "identityBackground", "personality"):
+ summary_val = str(summary_char.get(key) or "").strip()
+ if not summary_val:
+ continue
+ existing = str(merged.get(key) or "").strip()
+ if not existing or _is_generic_intro_text(existing):
+ merged[key] = summary_val
+ return merged
+
+
+def _character_mentioned_in_summary(name: str, summary: dict[str, Any] | None) -> bool:
+ char_name = (name or "").strip()
+ if not char_name or not isinstance(summary, dict):
+ return False
+ if _find_summary_character(build_summary_character_lookup(summary), char_name):
+ return True
+ blob = " ".join(
+ str(summary.get(k) or "")
+ for k in ("synopsis", "oneLineStory", "coreHook")
+ )
+ return char_name in blob
+
+
+def build_character_binding(
+ character_name: str,
+ character_asset: Any,
+ *,
+ summary_lookup: dict[str, dict[str, Any]] | None = None,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
+) -> dict[str, Any]:
+ # 组装单角色 binding:重要度 + 介绍文案(摘要优先于 stub 资产)
+ name = str(character_name or "").strip()
+ params = getattr(character_asset, "params", None) or {}
+ if not isinstance(params, dict):
+ params = {}
+ lookup = summary_lookup if summary_lookup is not None else build_summary_character_lookup(summary)
+ summary_char = _find_summary_character(lookup, name)
+ merged = _merge_params_with_summary(params, summary_char)
+ role_type = str(merged.get("roleType") or "").strip() or None
+ title = str(merged.get("title") or "").strip() or None
+ core_tags = str(merged.get("coreTags") or "").strip() or None
+ intro = infer_character_intro_text(
+ name,
+ merged,
+ summary,
+ episode_bodies=episode_bodies,
+ intro_overrides=intro_overrides,
+ )
+ important = _is_important_character(
+ name,
+ role_type=role_type,
+ title=title,
+ core_tags=core_tags,
+ )
+ if not important and _character_mentioned_in_summary(name, summary):
+ important = True
+ return {
+ "name": name,
+ "assetId": int(character_asset.id),
+ "introText": intro,
+ "important": important,
+ }
+
+
+def _is_important_character(
+ name: str,
+ *,
+ role_type: str | None = None,
+ title: str | None = None,
+ core_tags: str | None = None,
+) -> bool:
+ # 仅重要角色做人物介绍:群体名 / 纯配角 stub 跳过
+ char_name = (name or "").strip()
+ if not char_name or MINOR_NAME_RE.search(char_name):
+ return False
+ role = (role_type or "").strip()
+ ttl = (title or "").strip()
+ tags = (core_tags or "").strip()
+ blob = f"{role} {ttl} {tags}"
+ if IMPORTANT_ROLE_RE.search(blob):
+ return True
+ if ttl and not _is_generic_intro_text(ttl):
+ # 有具体身份头衔(如「治水英雄」「四岳首领」)视为可介绍
+ return True
+ if MINOR_ROLE_RE.search(role) or role in GENERIC_INTRO_TEXTS or not role:
+ return False
+ return True
+
+
def _build_production_cues(
location_line: str | None,
narrative_lines: list[str],
character_intro_lines: list[str],
) -> list[str]:
- # 字幕 / BGM / 人物介绍前置提示
+ # 字幕 / BGM / 人物介绍前置提示(字幕 cue 不含「旁白」字样,避免 Seedance 整镜念白)
hint = " ".join(filter(None, [location_line or "", *narrative_lines[:3]]))
lines = [
- "【字幕:底部居中·简体中文·对白旁白同步】",
+ DRAMA_SUBTITLE_CUE,
f"【BGM:{_infer_bgm_mood(hint)};音量低于人声】",
]
lines.extend(character_intro_lines)
@@ -250,15 +626,38 @@ def _build_production_cues(
def _build_character_intro_lines(character_bindings: list[dict[str, Any]]) -> list[str]:
- # 本场人物介绍叠字行
- return [
- (
- f"【人物介绍·画面叠字】{b['name']}|{b['introText']}"
- if b.get("introText")
- else f"【人物介绍·画面叠字】{b['name']}"
- )
- for b in character_bindings
- ]
+ # 人物介绍叠字:贴在对应角色身旁,非口播
+ lines: list[str] = []
+ for b in character_bindings:
+ name = str(b.get("name") or "").strip()
+ intro = str(b.get("introText") or "").strip()
+ if not name or not intro:
+ continue
+ lines.append(f"{CHARACTER_INTRO_CUE}{name}|{intro}")
+ return lines
+
+
+def _bindings_mentioned_in_text(
+ text: str,
+ bindings: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ # 正文或 @asset 引用中首次点名的角色(保序)
+ if not text or not bindings:
+ return []
+ hit: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for binding in bindings:
+ name = str(binding.get("name") or "").strip()
+ if not name or name in seen:
+ continue
+ asset_id = binding.get("assetId")
+ mentioned = name in text
+ if not mentioned and asset_id is not None:
+ mentioned = bool(re.search(rf"@asset:{int(asset_id)}(?!\d)", text))
+ if mentioned:
+ seen.add(name)
+ hit.append(binding)
+ return hit
def _flush_fragment_chunk(
@@ -275,20 +674,50 @@ def _flush_fragment_chunk(
return "\n".join(planned).strip(), duration
+def _pick_intros_for_fragment(
+ body_lines: list[str],
+ intro_candidates: list[dict[str, Any]],
+ introduced: set[str],
+ *,
+ flush_remaining: bool = False,
+) -> list[dict[str, Any]]:
+ # 本镜首次出场的重要角色;末镜可兜底介绍本场剩余候选
+ pending = [b for b in intro_candidates if str(b.get("name") or "") not in introduced]
+ if not pending:
+ return []
+ body_text = "\n".join(body_lines)
+ mentioned = _bindings_mentioned_in_text(body_text, pending)
+ if flush_remaining:
+ # 末镜:点名优先,其余未出场候选一并介绍,避免重要角色漏介绍
+ mentioned_names = {str(b.get("name") or "") for b in mentioned}
+ extras = [b for b in pending if str(b.get("name") or "") not in mentioned_names]
+ return [*mentioned, *extras]
+ return mentioned
+
+
def plan_fragments_from_scene(
body: str,
meta: dict[str, Any],
scene_asset_id: int | None,
character_bindings: list[dict[str, Any]],
+ introduced: set[str] | None = None,
) -> list[tuple[str, int]]:
"""
规划单场视频向分镜正文;超软上限时拆成多条,避免截断后半场。
+ 人物介绍仅注入「重要且本剧首次出场」的角色,落到其首次出现的分镜。
+ introduced 跨集/跨场共享的已介绍角色名集合(会被原地更新)。
返回 [(content, duration_sec), ...]
"""
+ # introduced_names 本剧已介绍过的角色
+ introduced_names = introduced if introduced is not None else set()
location_line, narrative_lines = _strip_screenplay_meta(body)
- intro_lines = _build_character_intro_lines(character_bindings)
- first_cues = _build_production_cues(location_line, narrative_lines, intro_lines)
- cont_cues = _build_production_cues(location_line, narrative_lines, [])
+ # intro_candidates 本场可介绍的重要角色(须有简短描述)
+ intro_candidates = [
+ b
+ for b in character_bindings
+ if b.get("important") and b.get("introText") and str(b.get("name") or "").strip()
+ ]
+ base_cues = _build_production_cues(location_line, narrative_lines, [])
# timed_blocks 待打包的 (时长, 文本行列表)
timed_blocks: list[tuple[int, list[str]]] = []
@@ -315,29 +744,45 @@ def plan_fragments_from_scene(
timed_blocks.append((line_dur, [f"@duration:{line_dur}", formatted]))
if not timed_blocks:
- return [_flush_fragment_chunk(first_cues, [], 0)]
+ to_intro = _pick_intros_for_fragment([], intro_candidates, introduced_names, flush_remaining=True)
+ cues = _build_production_cues(
+ location_line,
+ narrative_lines,
+ _build_character_intro_lines(to_intro),
+ )
+ for b in to_intro:
+ introduced_names.add(str(b["name"]))
+ return [_flush_fragment_chunk(cues, [], 0)]
fragments: list[tuple[str, int]] = []
body_lines: list[str] = []
used = 0
- is_first = True
+
+ def flush_current(*, is_last: bool) -> None:
+ # 落盘当前镜并注入本镜首次出场介绍
+ nonlocal body_lines, used
+ to_intro = _pick_intros_for_fragment(
+ body_lines,
+ intro_candidates,
+ introduced_names,
+ flush_remaining=is_last,
+ )
+ intro_lines = _build_character_intro_lines(to_intro)
+ cues = [*base_cues, *intro_lines] if intro_lines else list(base_cues)
+ fragments.append(_flush_fragment_chunk(cues, body_lines, used))
+ for b in to_intro:
+ introduced_names.add(str(b["name"]))
+ body_lines = []
+ used = 0
for block_dur, block_lines in timed_blocks:
# 已达软上限且本块放不下 → 先落盘当前镜
if used > 0 and used >= FRAGMENT_SOFT_MAX and used + block_dur > FRAGMENT_SOFT_MAX:
- cues = first_cues if is_first else cont_cues
- fragments.append(_flush_fragment_chunk(cues, body_lines, used))
- body_lines = []
- used = 0
- is_first = False
+ flush_current(is_last=False)
# 硬上限:本块放不下则开新镜;单块超过硬上限则截断到硬上限
if used > 0 and used + block_dur > FRAGMENT_TOTAL_MAX:
- cues = first_cues if is_first else cont_cues
- fragments.append(_flush_fragment_chunk(cues, body_lines, used))
- body_lines = []
- used = 0
- is_first = False
+ flush_current(is_last=False)
take_dur = block_dur
if take_dur > FRAGMENT_TOTAL_MAX:
@@ -345,11 +790,7 @@ def plan_fragments_from_scene(
if used + take_dur > FRAGMENT_TOTAL_MAX:
take_dur = FRAGMENT_TOTAL_MAX - used
if take_dur <= 0:
- cues = first_cues if is_first else cont_cues
- fragments.append(_flush_fragment_chunk(cues, body_lines, used))
- body_lines = []
- used = 0
- is_first = False
+ flush_current(is_last=False)
take_dur = min(block_dur, FRAGMENT_TOTAL_MAX)
if take_dur != block_dur:
@@ -361,12 +802,96 @@ def plan_fragments_from_scene(
used += take_dur
if body_lines or not fragments:
- cues = first_cues if is_first else cont_cues
- fragments.append(_flush_fragment_chunk(cues, body_lines, used))
+ flush_current(is_last=True)
return fragments
+# 解析已有分镜正文:片头 cue + (@duration + 正文) 块
+def parse_fragment_timed_blocks(content: str) -> tuple[list[str], list[tuple[int, list[str]]]]:
+ lines = (content or "").replace("\r\n", "\n").split("\n")
+ header: list[str] = []
+ blocks: list[tuple[int, list[str]]] = []
+ i = 0
+ while i < len(lines):
+ raw = lines[i]
+ stripped = raw.strip()
+ if stripped.startswith("@duration:"):
+ break
+ header.append(raw)
+ i += 1
+ while i < len(lines):
+ stripped = lines[i].strip()
+ m = re.match(r"^@duration:(\d+)\s*$", stripped)
+ if not m:
+ i += 1
+ continue
+ dur = int(m.group(1))
+ block_lines = [f"@duration:{dur}"]
+ i += 1
+ while i < len(lines) and not lines[i].strip().startswith("@duration:"):
+ block_lines.append(lines[i])
+ i += 1
+ if dur > 0:
+ blocks.append((dur, block_lines))
+ return header, blocks
+
+
+# 将已有超长分镜正文按软/硬上限拆成多条 content(保留片头 cue)
+def split_overlong_fragment_content(
+ content: str,
+ *,
+ soft_max: int = FRAGMENT_SOFT_MAX,
+ hard_max: int = FRAGMENT_TOTAL_MAX,
+) -> list[tuple[str, int]]:
+ header, blocks = parse_fragment_timed_blocks(content)
+ if not blocks:
+ return []
+ total = sum(d for d, _ in blocks)
+ if total <= hard_max:
+ used = total
+ text = "\n".join([*header, *[ln for _, rows in blocks for ln in rows]]).strip()
+ return [(text, used)] if text else []
+
+ chunks: list[tuple[str, int]] = []
+ body: list[str] = []
+ used = 0
+
+ def flush() -> None:
+ nonlocal body, used
+ if not body:
+ return
+ text = "\n".join([*header, *body]).strip()
+ chunks.append((text, used))
+ body = []
+ used = 0
+
+ for block_dur, block_lines in blocks:
+ if used > 0 and used >= soft_max and used + block_dur > soft_max:
+ flush()
+ if used > 0 and used + block_dur > hard_max:
+ flush()
+ take = block_dur
+ if take > hard_max:
+ take = hard_max
+ if used + take > hard_max:
+ take = hard_max - used
+ if take <= 0:
+ flush()
+ take = min(block_dur, hard_max)
+ if take != block_dur:
+ rewritten = [
+ f"@duration:{take}" if ln.strip().startswith("@duration:") else ln
+ for ln in block_lines
+ ]
+ body.extend(rewritten)
+ else:
+ body.extend(block_lines)
+ used += take
+ flush()
+ return chunks
+
+
def plan_fragment_content_from_scene(
body: str,
meta: dict[str, Any],
@@ -395,14 +920,24 @@ def is_raw_screenplay_fragment(content: str) -> bool:
def build_fragments_from_episode_body(
content: str,
assets: list[Any],
+ already_introduced: set[str] | None = None,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
) -> list[dict[str, Any]]:
"""
将一集正文拆成多场分镜草稿。
+ already_introduced:本剧更早分集已介绍过的角色(跨集去重)。
+ summary:剧本摘要,用于 stub 资产补全人物介绍文案。
返回 [{content, duration_sec, asset_ids, scene_name, character_names}, ...]
"""
character_assets = [a for a in assets if getattr(a, "type", "") == "character"]
scene_assets = [a for a in assets if getattr(a, "type", "") == "scene"]
scenes = split_episode_content_into_scenes(content)
+ summary_lookup = build_summary_character_lookup(summary)
+ script_bodies = list(episode_bodies or [])
+ if content and content not in script_bodies:
+ script_bodies.append(content)
if not scenes:
return [
@@ -415,6 +950,8 @@ def build_fragments_from_episode_body(
}
]
+ # introduced 本剧已做过人物介绍的角色名(含更早分集 + 本集跨场)
+ introduced: set[str] = set(already_introduced or ())
fragments: list[dict[str, Any]] = []
for scene in scenes:
meta = extract_scene_meta(scene["body"])
@@ -432,26 +969,26 @@ def build_fragments_from_episode_body(
character_asset = _find_asset_by_name(character_assets, str(character_name))
if character_asset is None:
continue
- intro = None
- params = getattr(character_asset, "params", None) or {}
- if isinstance(params, dict):
- intro = params.get("title") or params.get("roleType") or params.get("coreTags")
character_bindings.append(
- {
- "name": str(character_name),
- "assetId": int(character_asset.id),
- "introText": str(intro).strip() if intro else None,
- }
+ build_character_binding(
+ str(character_name),
+ character_asset,
+ summary_lookup=summary_lookup,
+ summary=summary,
+ episode_bodies=script_bodies,
+ intro_overrides=intro_overrides,
+ )
)
if character_asset.id not in matched_ids:
matched_ids.append(int(character_asset.id))
- # 一场可拆多条分镜(按时长软/硬上限)
+ # 一场可拆多条分镜(按时长软/硬上限);介绍落在首次出场镜
for planned, duration in plan_fragments_from_scene(
scene["body"],
meta,
scene_asset_id,
character_bindings,
+ introduced,
):
fragments.append(
{
diff --git a/backend/app/services/drama/build_seedance_generate_body.py b/backend/app/services/drama/build_seedance_generate_body.py
index 3a47863..df752bd 100644
--- a/backend/app/services/drama/build_seedance_generate_body.py
+++ b/backend/app/services/drama/build_seedance_generate_body.py
@@ -13,7 +13,10 @@ from app.services.drama.fragment_content_duration import (
resolve_seedance_duration_from_content,
)
from app.services.drama.image_styles import resolve_image_style_prompt
-from app.services.seedance_segments import build_seedance_production_section
+from app.services.seedance_segments import (
+ build_seedance_production_section,
+ rewrite_misclassified_visual_voice_lines,
+)
ASSET_MENTION_TOKEN_PATTERN = re.compile(r"@asset:(\d+)")
WHITESPACE_PATTERN = re.compile(r"\s+")
@@ -26,6 +29,10 @@ SEEDANCE_CHARACTER_VOICE_SECTION_HEADER = (
"【强制约束:角色音色】以下角色说话的音色、语气、节奏与发声质感必须与对应参考音频严格一致,"
"语速自然偏慢、吐字清晰,严禁加速赶词、替换、混用其他声线或自行改写:"
)
+SEEDANCE_NARRATION_VOICE_SECTION_HEADER = (
+ "【强制约束:旁白音色】以下旁白说话的音色、语气、节奏与发声质感必须与对应参考音频严格一致,"
+ "语速自然偏慢、吐字清晰,严禁加速赶词、替换、混用其他声线或自行改写:"
+)
SEEDANCE_CHARACTER_APPEARANCE_SECTION_HEADER = (
"【强制约束:角色形象】以下角色的面容、体型、发型、服饰与整体气质必须与对应参考图严格一致,"
"严禁换脸、形象漂移或重绘为其他人物:"
@@ -44,6 +51,8 @@ class BuildSeedanceGenerateBodyInput(TypedDict, total=False):
resolution: str | None
video_style_id: str | None
duration_fallback: int | None
+ # 上一镜尾帧公网/本地 URL;有参考媒体时作 reference_image(不可与 first_frame 混用)
+ continuity_first_frame_url: str | None
@dataclass
@@ -122,6 +131,10 @@ def resolve_character_prompt_name(asset: dict[str, Any]) -> str:
return resolve_asset_prompt_name(asset, "角色")
+def resolve_narration_prompt_name(asset: dict[str, Any]) -> str:
+ return resolve_asset_prompt_name(asset, "旁白")
+
+
def resolve_scene_prompt_name(asset: dict[str, Any]) -> str:
return resolve_asset_prompt_name(asset, "场景")
@@ -146,7 +159,7 @@ def build_seedance_reference_catalog(
seen_image_asset_ids.add(asset_id)
catalog.images.append(SeedanceReferenceFile(asset_id=asset_id, url=image_url))
- if asset.get("type") == "character":
+ if asset.get("type") in {"character", "narration"}:
voice_audio_url = read_asset_voice_audio_url(asset.get("params"))
if voice_audio_url and asset_id not in seen_audio_asset_ids:
seen_audio_asset_ids.add(asset_id)
@@ -227,8 +240,10 @@ def build_seedance_body_text(
reference: list[dict[str, Any]] | None,
catalog: SeedanceReferenceCatalog,
) -> str:
+ # 先纠正误标为对白/旁白的空镜画面行
+ normalized = rewrite_misclassified_visual_voice_lines(content or "")
asset_by_id = {int(asset["id"]): asset for asset in (reference or [])}
- replaced = replace_duration_mentions_with_time_ranges(content or "")
+ replaced = replace_duration_mentions_with_time_ranges(normalized)
replaced = ASSET_MENTION_TOKEN_PATTERN.sub(
lambda match: replace_asset_mention_token(int(match.group(1)), asset_by_id, catalog),
replaced,
@@ -242,10 +257,12 @@ def build_seedance_prompt_text(
catalog: SeedanceReferenceCatalog | None = None,
video_style_id: str | None = None,
) -> str:
+ # 提交前统一纠正空镜误标,保证强制约束与正文一致
+ normalized = rewrite_misclassified_visual_voice_lines(content or "")
resolved_catalog = catalog or build_seedance_reference_catalog(reference)
sections = [
build_visual_style_section(video_style_id),
- build_seedance_production_section(content or ""),
+ build_seedance_production_section(normalized),
build_reference_index_section(
reference,
"character",
@@ -254,6 +271,14 @@ def build_seedance_prompt_text(
"参考音频",
resolve_character_prompt_name,
),
+ build_reference_index_section(
+ reference,
+ "narration",
+ resolved_catalog.audio_index_by_asset_id,
+ SEEDANCE_NARRATION_VOICE_SECTION_HEADER,
+ "参考音频",
+ resolve_narration_prompt_name,
+ ),
build_reference_index_section(
reference,
"character",
@@ -270,7 +295,7 @@ def build_seedance_prompt_text(
"参考图",
resolve_scene_prompt_name,
),
- build_seedance_body_text(content, reference, resolved_catalog),
+ build_seedance_body_text(normalized, reference, resolved_catalog),
]
return "\n\n".join(section for section in sections if section)
@@ -280,11 +305,30 @@ def build_seedance_content_items(
content: str | None,
reference: list[dict[str, Any]] | None,
video_style_id: str | None = None,
+ continuity_first_frame_url: str | None = None,
) -> list[dict[str, Any]]:
catalog = build_seedance_reference_catalog(reference)
prompt_text = build_seedance_prompt_text(content, reference, catalog, video_style_id)
items: list[dict[str, Any]] = []
+ continuity = (continuity_first_frame_url or "").strip()
+ has_reference_media = bool(catalog.images or catalog.audios)
+
+ if continuity and prompt_text:
+ # Seedance:first/last_frame 不能与 reference_* 混用;有角色/场景参考时改挂 reference_image
+ if has_reference_media:
+ prompt_text = (
+ "【强制约束:镜头衔接】另附上一镜尾帧作为参考图(参考图序列最后一张)。"
+ "本段开场须从该尾帧画面自然续接,保持主体、场景与光影连贯,禁止跳切到无关画面。\n\n"
+ + prompt_text
+ )
+ else:
+ prompt_text = (
+ "【强制约束:镜头衔接】本段视频必须以首帧图为开场画面自然续接,"
+ "保持主体、场景与光影连贯,禁止跳切到无关画面。\n\n"
+ + prompt_text
+ )
+
if prompt_text:
items.append({"type": "text", "text": prompt_text})
@@ -298,6 +342,25 @@ def build_seedance_content_items(
{"type": "audio_url", "audio_url": {"url": audio.url}, "role": "reference_audio"}
)
+ if continuity:
+ if has_reference_media:
+ items.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": continuity},
+ "role": "reference_image",
+ }
+ )
+ else:
+ # 无参考媒体时可用 first_frame,并在外层省略 ratio
+ items.append(
+ {
+ "type": "image_url",
+ "image_url": {"url": continuity},
+ "role": "first_frame",
+ }
+ )
+
return items
@@ -317,18 +380,27 @@ def resolve_seedance_resolution(resolution: str | None) -> str:
def build_seedance_generate_body(input_params: BuildSeedanceGenerateBodyInput) -> dict[str, Any]:
content = input_params.get("content")
fallback = int(input_params.get("duration_fallback") or 8)
+ continuity = (input_params.get("continuity_first_frame_url") or "").strip() or None
+ reference = input_params.get("reference")
+ catalog = build_seedance_reference_catalog(reference)
+ # 仅「纯首帧、无参考媒体」时省略 ratio;混用参考时必须保留 ratio、且尾帧用 reference_image
+ use_first_frame_mode = bool(continuity) and not (catalog.images or catalog.audios)
- return {
+ body: dict[str, Any] = {
"model": resolve_seedance_model_endpoint(input_params.get("model_id")),
"content": build_seedance_content_items(
content,
- input_params.get("reference"),
+ reference,
input_params.get("video_style_id"),
+ continuity_first_frame_url=continuity,
),
"duration": resolve_seedance_duration_from_content(content, fallback=fallback),
- "ratio": resolve_seedance_ratio(input_params.get("aspect_ratio")),
"resolution": resolve_seedance_resolution(input_params.get("resolution")),
"watermark": False,
- "generate_audio": False,
+ # Seedance 原生配音+烧录字幕;关闭则仅有画面、无对白/BGM/字幕
+ "generate_audio": True,
"return_last_frame": True,
}
+ if not use_first_frame_mode:
+ body["ratio"] = resolve_seedance_ratio(input_params.get("aspect_ratio"))
+ return body
diff --git a/backend/app/services/drama/character_intro_llm.py b/backend/app/services/drama/character_intro_llm.py
new file mode 100644
index 0000000..6c6326e
--- /dev/null
+++ b/backend/app/services/drama/character_intro_llm.py
@@ -0,0 +1,219 @@
+"""LLM 补齐人物介绍叠字(stub 角色 / 摘要缺小传时)。"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from app.services.drama.build_fragments import (
+ build_summary_character_lookup,
+ infer_character_intro_text,
+ _find_summary_character,
+ _is_generic_intro_text,
+ _merge_params_with_summary,
+ _shorten_intro,
+)
+from app.services.drama.llm import drama_chat_json
+
+logger = logging.getLogger(__name__)
+
+SUMMARY_TEXT_MAX = 3500
+BODY_SAMPLE_MAX = 4000
+BODY_PER_EPISODE_MAX = 1200
+
+CHARACTER_INTRO_SYSTEM = """你是影视编剧助理,为短剧/漫剧角色写「人物介绍叠字」短文案。
+
+用途:角色本剧首次出场时,画面在**该角色身旁**叠字一行「角色名|身份头衔」(非口播、非底部字幕)。
+
+要求:
+1. 每条介绍 8~24 个汉字,突出身份、地位或与主线关系的一句话
+2. 风格贴合故事类型与剧本语境,可用「/」连接两个短语(如「治水首领/夏朝始祖」)
+3. 禁止占位废话:「出场人物」「剧本分集出场人物」「配角」等
+4. 只写给定名单中的角色;不要编造名单外人物
+
+输出严格 JSON(不要 markdown):
+{"intros": {"角色名": "叠字介绍文案"}}
+"""
+
+
+def _summary_blob(summary: dict[str, Any] | None) -> str:
+ if not isinstance(summary, dict):
+ return ""
+ parts: list[str] = []
+ for key in ("storyType", "oneLineStory", "coreHook", "synopsis"):
+ val = str(summary.get(key) or "").strip()
+ if val:
+ parts.append(val)
+ for ch in summary.get("characters") or []:
+ if not isinstance(ch, dict):
+ continue
+ name = str(ch.get("name") or "").strip()
+ if not name:
+ continue
+ bits = [
+ str(ch.get("roleType") or "").strip(),
+ str(ch.get("title") or "").strip(),
+ str(ch.get("identityBackground") or "").strip(),
+ ]
+ line = " ".join(b for b in bits if b)
+ if line:
+ parts.append(f"{name}:{line}")
+ blob = "\n".join(parts)
+ return blob[:SUMMARY_TEXT_MAX]
+
+
+def _bodies_sample(episode_bodies: list[str] | None) -> str:
+ if not episode_bodies:
+ return ""
+ chunks: list[str] = []
+ used = 0
+ for body in episode_bodies:
+ text = (body or "").strip()
+ if not text:
+ continue
+ piece = text[:BODY_PER_EPISODE_MAX]
+ if used + len(piece) > BODY_SAMPLE_MAX:
+ piece = piece[: max(0, BODY_SAMPLE_MAX - used)]
+ if not piece:
+ break
+ chunks.append(piece)
+ used += len(piece)
+ return "\n---\n".join(chunks)
+
+
+def _build_intro_user_prompt(
+ names: list[str],
+ *,
+ summary: dict[str, Any] | None,
+ episode_bodies: list[str] | None,
+ story_type: str | None,
+) -> str:
+ genre = (story_type or "").strip()
+ if not genre and isinstance(summary, dict):
+ genre = str(summary.get("storyType") or "").strip()
+ lines = [
+ "请为以下角色各写一条人物介绍叠字文案:",
+ "、".join(names),
+ ]
+ if genre:
+ lines.append(f"故事类型:{genre}")
+ summary_text = _summary_blob(summary)
+ if summary_text:
+ lines.append(f"剧本摘要:\n{summary_text}")
+ body_text = _bodies_sample(episode_bodies)
+ if body_text:
+ lines.append(f"分集剧本节选:\n{body_text}")
+ return "\n\n".join(lines)
+
+
+def _parse_intro_response(raw: Any, names: list[str]) -> dict[str, str]:
+ allowed = {n.strip() for n in names if n.strip()}
+ result: dict[str, str] = {}
+ if isinstance(raw, dict):
+ intros = raw.get("intros")
+ if isinstance(intros, dict):
+ for key, val in intros.items():
+ name = str(key or "").strip()
+ intro = _shorten_intro(str(val or ""), max_len=28)
+ if name in allowed and intro and not _is_generic_intro_text(intro):
+ result[name] = intro
+ for key in ("characters", "items"):
+ items = raw.get(key)
+ if isinstance(items, list):
+ for item in items:
+ if not isinstance(item, dict):
+ continue
+ name = str(item.get("name") or "").strip()
+ intro = _shorten_intro(
+ str(item.get("intro") or item.get("title") or item.get("introText") or ""),
+ max_len=28,
+ )
+ if name in allowed and intro and not _is_generic_intro_text(intro):
+ result[name] = intro
+ return result
+
+
+async def llm_enrich_character_intros(
+ names: list[str],
+ *,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ story_type: str | None = None,
+) -> dict[str, str]:
+ """批量 LLM 生成人物介绍叠字;失败时返回空 dict。"""
+ unique: list[str] = []
+ seen: set[str] = set()
+ for name in names:
+ n = str(name or "").strip()
+ if n and n not in seen:
+ seen.add(n)
+ unique.append(n)
+ if not unique:
+ return {}
+ user = _build_intro_user_prompt(
+ unique,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ story_type=story_type,
+ )
+ try:
+ raw = await drama_chat_json(
+ CHARACTER_INTRO_SYSTEM,
+ user,
+ temperature=0.35,
+ max_tokens=1024,
+ )
+ parsed = _parse_intro_response(raw, unique)
+ logger.info("LLM 人物介绍补齐 count=%s names=%s", len(parsed), list(parsed.keys()))
+ return parsed
+ except Exception: # noqa: BLE001
+ logger.exception("LLM 人物介绍补齐失败 names=%s", unique)
+ return {}
+
+
+def collect_names_needing_intro(
+ character_assets: list[Any],
+ *,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+) -> list[str]:
+ """规则链路仍缺介绍文案的角色名(保序)。"""
+ lookup = build_summary_character_lookup(summary)
+ missing: list[str] = []
+ seen: set[str] = set()
+ for asset in character_assets:
+ name = str(getattr(asset, "name", "") or "").strip()
+ if not name or name in seen:
+ continue
+ seen.add(name)
+ params = getattr(asset, "params", None) or {}
+ if not isinstance(params, dict):
+ params = {}
+ merged = _merge_params_with_summary(params, _find_summary_character(lookup, name))
+ if infer_character_intro_text(name, merged, summary, episode_bodies):
+ continue
+ missing.append(name)
+ return missing
+
+
+async def prepare_character_intro_overrides(
+ character_assets: list[Any],
+ *,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ story_type: str | None = None,
+) -> dict[str, str]:
+ """先规则推断,缺的再一次性 LLM 补齐。"""
+ names = collect_names_needing_intro(
+ character_assets,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ )
+ if not names:
+ return {}
+ return await llm_enrich_character_intros(
+ names,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ story_type=story_type,
+ )
diff --git a/backend/app/services/drama/fragment_plan.py b/backend/app/services/drama/fragment_plan.py
new file mode 100644
index 0000000..e39b9c5
--- /dev/null
+++ b/backend/app/services/drama/fragment_plan.py
@@ -0,0 +1,494 @@
+"""单集 LLM 分镜:调用模型规划,再规范化为可落库分镜草稿。"""
+
+from __future__ import annotations
+
+import logging
+import re
+from typing import Any
+
+from app.services.drama.build_fragments import (
+ FRAGMENT_DURATION_MIN,
+ FRAGMENT_SOFT_MAX,
+ FRAGMENT_TOTAL_MAX,
+ _build_character_intro_lines,
+ _build_production_cues,
+ _clamp_duration,
+ _estimate_line_duration,
+ _find_asset_by_name,
+ _format_narrative_line,
+ _inject_character_mentions,
+ build_character_binding,
+ build_summary_character_lookup,
+)
+from app.services.drama.fragment_plan_prompt import (
+ FRAGMENT_PLAN_SYSTEM_PROMPT,
+ build_fragment_plan_user_prompt,
+)
+from app.services.drama.llm import drama_chat_json
+
+logger = logging.getLogger(__name__)
+
+
+def build_asset_catalog(assets: list[Any]) -> list[dict[str, Any]]:
+ # 压缩资产目录给 LLM(角色带身份,场景仅名)
+ catalog: list[dict[str, Any]] = []
+ for asset in assets:
+ kind = str(getattr(asset, "type", "") or "")
+ if kind not in {"character", "scene"}:
+ continue
+ params = getattr(asset, "params", None) or {}
+ if not isinstance(params, dict):
+ params = {}
+ catalog.append(
+ {
+ "id": int(asset.id),
+ "type": kind,
+ "name": str(getattr(asset, "name", "") or ""),
+ "roleType": str(params.get("roleType") or "").strip() or None,
+ "title": str(params.get("title") or "").strip() or None,
+ }
+ )
+ return catalog
+
+
+def _build_character_bindings(
+ character_names: list[str],
+ character_assets: list[Any],
+ *,
+ summary_lookup: dict[str, dict[str, Any]] | None = None,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
+) -> list[dict[str, Any]]:
+ # 按名匹配角色资产,附带介绍文案与是否重要(摘要补全 stub)
+ bindings: list[dict[str, Any]] = []
+ for character_name in character_names:
+ character_asset = _find_asset_by_name(character_assets, str(character_name))
+ if character_asset is None:
+ continue
+ bindings.append(
+ build_character_binding(
+ str(character_name),
+ character_asset,
+ summary_lookup=summary_lookup,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ intro_overrides=intro_overrides,
+ )
+ )
+ return bindings
+
+
+def _coerce_lines(raw: Any) -> list[str]:
+ # lines / content 字段统一成非空文本行
+ if isinstance(raw, list):
+ return [str(x).strip() for x in raw if str(x).strip()]
+ if isinstance(raw, str) and raw.strip():
+ return [ln.strip() for ln in raw.replace("\r\n", "\n").split("\n") if ln.strip()]
+ return []
+
+
+def _clamp_fragment_duration(seconds: int, line_count: int) -> int:
+ # 单镜时长钳制;无模型给值时按行数粗估
+ if seconds <= 0:
+ seconds = max(FRAGMENT_DURATION_MIN, min(FRAGMENT_TOTAL_MAX, line_count * 3 or 8))
+ return min(max(int(seconds), 4), FRAGMENT_TOTAL_MAX)
+
+
+def _truthy_opening_flag(
+ item: dict[str, Any],
+ index: int,
+ *,
+ allow_opening: bool = True,
+) -> bool:
+ # 首条默认开幕;或模型显式 is_opening;续拆时禁止开幕
+ if not allow_opening:
+ return False
+ if index == 0:
+ return True
+ flag = item.get("is_opening")
+ if flag is None:
+ flag = item.get("isOpening")
+ if isinstance(flag, bool):
+ return flag
+ if isinstance(flag, (int, float)):
+ return bool(flag)
+ if isinstance(flag, str):
+ return flag.strip().lower() in {"1", "true", "yes", "opening", "开幕"}
+ return False
+
+
+def _build_opening_cue_lines(
+ *,
+ episode_number: int | None,
+ episode_name: str | None,
+ project_title: str | None,
+ story_type: str | None,
+ one_line_story: str | None,
+ background_blurb: str | None,
+) -> list[str]:
+ # 开幕叠字:集号 / 集名 / 剧名 / 背景简介
+ cues: list[str] = []
+ ep_no = int(episode_number or 0)
+ title = (episode_name or "").strip()
+ series = (project_title or "").strip()
+ if ep_no > 0 and title:
+ cues.append(f"【片头·集号叠字】第{ep_no}集|{title}")
+ elif ep_no > 0:
+ cues.append(f"【片头·集号叠字】第{ep_no}集")
+ elif title:
+ cues.append(f"【片头·集名叠字】{title}")
+ if series:
+ cues.append(f"【片头·剧名叠字】{series}")
+ genre = (story_type or "").strip()
+ if genre:
+ cues.append(f"【片头·类型标注】{genre}")
+ bg = (background_blurb or one_line_story or "").strip()
+ if bg:
+ short = re.split(r"[。!?]", bg, maxsplit=1)[0].strip() or bg
+ if len(short) > 48:
+ short = short[:47] + "…"
+ cues.append(f"【背景介绍·画面叠字】{short}")
+ return cues
+
+
+def _pick_background_blurb(
+ *,
+ one_line_story: str | None,
+ synopsis: str | None,
+ core_hook: str | None,
+) -> str | None:
+ # 开幕背景文案优先级:一句话 > 钩子 > 梗概首句
+ for raw in (one_line_story, core_hook, synopsis):
+ text = (raw or "").strip()
+ if text:
+ return text
+ return None
+
+
+def _merge_bindings_for_fragment_body(
+ bindings: list[dict[str, Any]],
+ raw_lines: list[str],
+ body_text: str,
+ character_assets: list[Any],
+ *,
+ summary_lookup: dict[str, dict[str, Any]] | None,
+ summary: dict[str, Any] | None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
+) -> list[dict[str, Any]]:
+ # 补全 LLM 未列 character_names、但正文/@asset 已点名的角色
+ seen = {str(b.get("name") or "") for b in bindings}
+ extra_names: list[str] = []
+ raw_blob = "\n".join(raw_lines)
+ for asset in character_assets:
+ name = str(getattr(asset, "name", "") or "").strip()
+ if not name or name in seen:
+ continue
+ aid = int(asset.id)
+ if name in raw_blob or re.search(rf"@asset:{aid}(?!\d)", body_text):
+ extra_names.append(name)
+ seen.add(name)
+ if not extra_names:
+ return bindings
+ return [
+ *bindings,
+ *_build_character_bindings(
+ extra_names,
+ character_assets,
+ summary_lookup=summary_lookup,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ intro_overrides=intro_overrides,
+ ),
+ ]
+
+
+def normalize_llm_fragment_items(
+ items: list[Any],
+ assets: list[Any],
+ *,
+ episode_number: int | None = None,
+ episode_name: str | None = None,
+ project_title: str | None = None,
+ story_type: str | None = None,
+ one_line_story: str | None = None,
+ synopsis: str | None = None,
+ core_hook: str | None = None,
+ already_introduced: set[str] | None = None,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
+ allow_opening: bool = True,
+) -> list[dict[str, Any]]:
+ """
+ 将 LLM fragments 转为落库草稿。
+ 注入 @asset、字幕/BGM、开幕集号/背景、重要角色本剧首次出场介绍。
+ already_introduced:更早分集已介绍过的角色名。
+ summary:剧本摘要,stub 资产从此补人物介绍。
+ allow_opening:False 时续拆,不注入开幕叠字。
+ """
+ character_assets = [a for a in assets if getattr(a, "type", "") == "character"]
+ scene_assets = [a for a in assets if getattr(a, "type", "") == "scene"]
+ summary_lookup = build_summary_character_lookup(summary)
+ # introduced 本剧已介绍角色(含更早分集)
+ introduced: set[str] = set(already_introduced or ())
+ drafts: list[dict[str, Any]] = []
+ opening_cues = _build_opening_cue_lines(
+ episode_number=episode_number,
+ episode_name=episode_name,
+ project_title=project_title,
+ story_type=story_type,
+ one_line_story=one_line_story,
+ background_blurb=_pick_background_blurb(
+ one_line_story=one_line_story,
+ synopsis=synopsis,
+ core_hook=core_hook,
+ ),
+ )
+
+ for index, item in enumerate(items):
+ if not isinstance(item, dict):
+ continue
+ lines = _coerce_lines(item.get("lines") or item.get("content"))
+ if not lines:
+ continue
+ scene_name = str(item.get("scene_name") or item.get("sceneName") or "").strip() or None
+ raw_names = item.get("character_names") or item.get("characterNames") or []
+ if isinstance(raw_names, str):
+ character_names = [p.strip() for p in re.split(r"[、,,/|]", raw_names) if p.strip()]
+ elif isinstance(raw_names, list):
+ character_names = [str(n).strip() for n in raw_names if str(n).strip()]
+ else:
+ character_names = []
+
+ # 正文未点名但 catalog 有的角色:从行文再扫一次资产名
+ bindings = _build_character_bindings(
+ character_names,
+ character_assets,
+ summary_lookup=summary_lookup,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ )
+ if not bindings:
+ # 兜底:全角色资产按名扫描本镜正文
+ mentioned = []
+ blob = "\n".join(lines)
+ for asset in character_assets:
+ name = str(getattr(asset, "name", "") or "").strip()
+ if name and name in blob:
+ mentioned.append(name)
+ bindings = _build_character_bindings(
+ mentioned,
+ character_assets,
+ summary_lookup=summary_lookup,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ intro_overrides=intro_overrides,
+ )
+ character_names = [b["name"] for b in bindings]
+
+ scene_asset_id: int | None = None
+ matched_ids: list[int] = []
+ if scene_name:
+ scene_asset = _find_asset_by_name(scene_assets, scene_name)
+ if scene_asset is not None:
+ scene_asset_id = int(scene_asset.id)
+ matched_ids.append(scene_asset_id)
+ for b in bindings:
+ aid = int(b["assetId"])
+ if aid not in matched_ids:
+ matched_ids.append(aid)
+
+ body_lines: list[str] = []
+ used = 0
+ # timed_blocks 本 LLM 镜内各行 (时长, 文本行);超软/硬上限时拆成多条 Fragment
+ timed_blocks: list[tuple[int, list[str]]] = []
+ for line in lines:
+ raw = _inject_character_mentions(line, bindings)
+ formatted = _format_narrative_line(raw)
+ if scene_asset_id and scene_name and scene_name in formatted and f"@asset:{scene_asset_id}" not in formatted:
+ formatted = formatted.replace(scene_name, f"@asset:{scene_asset_id} {scene_name}", 1)
+ line_dur = _clamp_duration(_estimate_line_duration(formatted))
+ if line_dur <= 0:
+ continue
+ timed_blocks.append((line_dur, [f"@duration:{line_dur}", formatted]))
+
+ if not timed_blocks:
+ continue
+
+ chunk_index = 0
+
+ def flush_chunk(*, is_last: bool) -> None:
+ # 落盘当前块:注入介绍 / 开幕 cue,并保证 duration_sec 与 @duration 合计一致
+ nonlocal body_lines, used, bindings, matched_ids, character_names, chunk_index
+ if not body_lines:
+ return
+
+ body_text = "\n".join(body_lines)
+ bindings = _merge_bindings_for_fragment_body(
+ bindings,
+ lines,
+ body_text,
+ character_assets,
+ summary_lookup=summary_lookup,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ intro_overrides=intro_overrides,
+ )
+ for b in bindings:
+ aid = int(b["assetId"])
+ if aid not in matched_ids:
+ matched_ids.append(aid)
+
+ is_opening = (
+ _truthy_opening_flag(item, index, allow_opening=allow_opening)
+ and not drafts
+ and chunk_index == 0
+ )
+ pending = [
+ b
+ for b in bindings
+ if b.get("important")
+ and b.get("introText")
+ and str(b.get("name") or "") not in introduced
+ ]
+ to_intro: list[dict[str, Any]] = []
+ for b in pending:
+ name = str(b["name"])
+ asset_id = b.get("assetId")
+ listed = name in character_names
+ mentioned = name in body_text or (
+ asset_id is not None
+ and bool(re.search(rf"@asset:{int(asset_id)}(?!\d)", body_text))
+ )
+ if listed or mentioned:
+ to_intro.append(b)
+ introduced.add(name)
+
+ intro_lines = _build_character_intro_lines(to_intro)
+ opening_lines = opening_cues if is_opening else []
+ cues = _build_production_cues(None, body_lines[:3], [*opening_lines, *intro_lines])
+ content = "\n".join([*cues, *body_lines]).strip()
+ duration = min(FRAGMENT_TOTAL_MAX, max(used, FRAGMENT_DURATION_MIN))
+ drafts.append(
+ {
+ "content": content,
+ "duration_sec": duration,
+ "asset_ids": list(matched_ids),
+ "scene_name": scene_name,
+ "character_names": character_names,
+ "is_opening": is_opening,
+ }
+ )
+ chunk_index += 1
+ body_lines = []
+ used = 0
+
+ for block_dur, block_rows in timed_blocks:
+ if used > 0 and used >= FRAGMENT_SOFT_MAX and used + block_dur > FRAGMENT_SOFT_MAX:
+ flush_chunk(is_last=False)
+ if used > 0 and used + block_dur > FRAGMENT_TOTAL_MAX:
+ flush_chunk(is_last=False)
+
+ take_dur = block_dur
+ if take_dur > FRAGMENT_TOTAL_MAX:
+ take_dur = FRAGMENT_TOTAL_MAX
+ if used + take_dur > FRAGMENT_TOTAL_MAX:
+ take_dur = FRAGMENT_TOTAL_MAX - used
+ if take_dur <= 0:
+ flush_chunk(is_last=False)
+ take_dur = min(block_dur, FRAGMENT_TOTAL_MAX)
+
+ if take_dur != block_dur:
+ rewritten = [
+ f"@duration:{take_dur}" if ln.startswith("@duration:") else ln
+ for ln in block_rows
+ ]
+ body_lines.extend(rewritten)
+ else:
+ body_lines.extend(block_rows)
+ used += take_dur
+
+ flush_chunk(is_last=True)
+
+ return drafts
+
+
+async def plan_fragments_with_llm(
+ *,
+ episode_name: str,
+ episode_body: str,
+ assets: list[Any],
+ episode_number: int | None = None,
+ project_title: str | None = None,
+ story_type: str | None = None,
+ one_line_story: str | None = None,
+ synopsis: str | None = None,
+ core_hook: str | None = None,
+ already_introduced: set[str] | None = None,
+ summary: dict[str, Any] | None = None,
+ episode_bodies: list[str] | None = None,
+ intro_overrides: dict[str, str] | None = None,
+ locked_summaries: list[str] | None = None,
+) -> list[dict[str, Any]]:
+ """
+ 调用 LLM 规划分镜并规范化。
+ 若模型结果为空则抛错,由上层决定是否回退规则切分。
+ already_introduced:本剧更早分集已介绍角色。
+ locked_summaries:本集已拍分镜摘要;非空时续拆(不开幕)。
+ """
+ catalog = build_asset_catalog(assets)
+ locked = [str(s).strip() for s in (locked_summaries or []) if str(s).strip()]
+ user_prompt = build_fragment_plan_user_prompt(
+ episode_name=episode_name,
+ episode_body=episode_body,
+ asset_catalog=catalog,
+ episode_number=episode_number,
+ project_title=project_title,
+ story_type=story_type,
+ one_line_story=one_line_story,
+ synopsis=synopsis,
+ core_hook=core_hook,
+ locked_summaries=locked,
+ )
+ raw = await drama_chat_json(
+ FRAGMENT_PLAN_SYSTEM_PROMPT,
+ user_prompt,
+ temperature=0.4,
+ )
+ items: list[Any] = []
+ if isinstance(raw, dict):
+ items = raw.get("fragments") or raw.get("shots") or raw.get("storyboard") or []
+ elif isinstance(raw, list):
+ items = raw
+ if not isinstance(items, list) or not items:
+ raise RuntimeError("LLM 分镜结果为空")
+
+ drafts = normalize_llm_fragment_items(
+ items,
+ assets,
+ episode_number=episode_number,
+ episode_name=episode_name,
+ project_title=project_title,
+ story_type=story_type,
+ one_line_story=one_line_story,
+ synopsis=synopsis,
+ core_hook=core_hook,
+ already_introduced=already_introduced,
+ summary=summary,
+ episode_bodies=episode_bodies,
+ intro_overrides=intro_overrides,
+ allow_opening=not bool(locked),
+ )
+ if not drafts:
+ raise RuntimeError("LLM 分镜规范化后为空")
+ logger.info(
+ "LLM 分镜完成 episode=%s ep_no=%s fragments=%s introduced_before=%s locked=%s",
+ episode_name,
+ episode_number,
+ len(drafts),
+ len(already_introduced or ()),
+ len(locked),
+ )
+ return drafts
diff --git a/backend/app/services/drama/fragment_plan_prompt.py b/backend/app/services/drama/fragment_plan_prompt.py
new file mode 100644
index 0000000..19da20b
--- /dev/null
+++ b/backend/app/services/drama/fragment_plan_prompt.py
@@ -0,0 +1,180 @@
+"""单集 LLM 分镜规划:系统提示与用户提示拼装。"""
+
+from __future__ import annotations
+
+from typing import Any
+
+FRAGMENT_PLAN_SYSTEM_PROMPT = """你是短剧视频分镜导演,负责把「场记剧本」拆成适合 AI 视频模型(Seedance 2.5)逐条生成的分镜。
+
+## 输出
+只输出一个 JSON 对象(不要 markdown、不要代码围栏):
+{
+ "fragments": [
+ {
+ "duration_sec": 12,
+ "scene_name": "地点名或空字符串",
+ "character_names": ["本镜出镜角色名"],
+ "is_opening": false,
+ "lines": [
+ "空镜:环境建立描写",
+ "角色名:对白内容",
+ "旁白(VO):旁白内容"
+ ]
+ }
+ ]
+}
+
+## 开幕镜(强制,fragments[0])
+每集第一条必须是开幕镜,并设 `"is_opening": true`,用于交代「看什么剧、第几集、本集背景」:
+1. duration_sec 建议 8–15。
+2. lines 须同时包含(顺序建议如下,可用空镜画面表达;开幕尽量少对白):
+ - 集号与集名信息:明确写出「第N集」+ 本集标题(用户会提供集号与标题,必须用原样,不要改写数字)。
+ - 背景介绍:用 1–3 句交代世界观/时代/地点氛围,或本集开场前观众需知的前情(可参考用户给的一句话故事、类型、梗概,不要编造与摘要冲突的设定)。
+ - 开场画面:建立主场景气氛(风雨、宫殿、战场等),可先不出主角,或仅远景点到;写成「空镜:…」或纯画面描写。
+3. 开幕镜 character_names 通常为空或极少;不要在开幕镜写人物介绍文案(介绍叠字由系统处理)。
+4. 后续剧情镜从 fragments[1] 开始,is_opening 可省略或为 false。
+
+## 何时切新镜(满足任一即新开一条 fragment)
+1. 场景切换(地点 / 日夜 / 内外景)。
+2. 主要角色组合明显变化。
+3. 情绪段落切换(铺垫→冲突→反转→收束)。
+4. 叙事职责不同(开幕 ≠ 对白戏 ≠ 纯空镜)。
+5. 累计将超过约 20 秒(硬上限 30 秒)。
+
+## 硬性规则
+1. duration_sec 必须在 4–30 之间,优先 8–20;单镜叙事完整、可单独成片。
+2. 按剧情节奏与场面转换拆镜,不要机械按字数/行数切;一场戏可拆 1–4 镜,整集避免碎成过多碎片;勿一句一对白一镜。
+3. lines 只写画面、动作、对白、旁白;保留角色真实姓名。
+ - 纯画面 / 空镜 / 景别必须写成「空镜:…」「远景:…」「近景:…」「特写:…」「全景:…」等,**禁止**写成旁白或「角色名:台词」。
+ - 只有真正要口播的内容才写「角色名:对白」或「旁白(VO):…」。
+ - 空镜镜只有画面描写,无对白无旁白。
+4. 禁止输出:### 场标题、出场人物行、【字幕】【BGM】【人物介绍】【片头】【背景介绍】、@asset、@duration。
+ 人物介绍叠字、首次出场去重、片头集号等由**系统后处理**写入,模型不要自行编排或猜测「谁该介绍」。
+5. character_names 只列本镜真正出镜、且在 lines 里被点到的角色名(与资产目录一致);群演/兵丁/百姓等可省略。
+ 系统会按本剧更早分集 + 本集分镜顺序扫描,仅在角色**本剧第一次出现的那一镜**自动加介绍叠字。
+6. 环境建立空镜可独立成镜;对白密集处按情绪段落合并。
+7. 覆盖输入剧本的全部有效剧情,不要删减关键冲突与转折。
+8. 开幕镜之后不要再重复整集片头;集号只在开幕镜强调一次。
+9. 单镜内 lines 建议约 3–7 行(建立→动作→对白/旁白→反应),15s 左右约 3–5 个镜头变化;避免 15 秒内切镜过密,也避免整镜只有 1–2 句干瘪摘要。
+
+## 画面描写密度(强制,解决「分镜描述太少」)
+每一条**画面行**(空镜/景别/动作)必须信息完整,按公式写满,禁止一句话糊弄:
+**主体 + 动作/姿态 + 场景环境 + 景别或运镜 + 结束态(本段结束时画面可见状态)**。
+可选补:光影、天气、前后景层次、道具在手中的具体用法。
+
+### 禁止的瘦写法(不合格)
+- 「禹站在河边。」「众人惊慌。」「空镜:山崩。」
+- 只有对白、几乎没有画面行。
+- 把一整场戏压成一句摘要,不写空间关系与动作过程。
+
+### 合格示例(学习后应达到的粒度)
+- 「全景:禹立于裂石崖边,右手开山斧贴身、左手定海针斜指岩缝,身后伯益执鞭跟近,应龙半空盘旋碎石飞溅;结束态:针尖已抵入岩缝,浊水自缝中渗出。」
+- 「特写:禹眉峰紧锁,目光盯紧岩缝水纹,定海针缓缓没入;结束态:水纹由细线变为涌动,禹抬眼示意伯益。」
+- 「空镜:黄河浊浪拍击老石,远坡百姓扶老携幼撤离,近岸芦苇被风压平;结束态:高坡人影渐远,河道仍汹涌。」
+
+### 对白/旁白行
+台词本身保持口语自然;若该段同时有明显动作,可另起一行画面写动作与结束态,**不要**把动作塞进「角色名:」冒号后当台词念出。
+对白镜仍须至少 1 条建立/反应画面行,避免「纯对白白板」。
+"""
+
+
+def build_fragment_plan_user_prompt(
+ *,
+ episode_name: str,
+ episode_body: str,
+ asset_catalog: list[dict[str, Any]],
+ episode_number: int | None = None,
+ project_title: str | None = None,
+ story_type: str | None = None,
+ one_line_story: str | None = None,
+ synopsis: str | None = None,
+ core_hook: str | None = None,
+ locked_summaries: list[str] | None = None,
+) -> str:
+ # 拼装用户侧:集号/背景元信息 + 分集正文 + 资产目录
+ ep_no = int(episode_number or 0)
+ ep_label = f"第{ep_no}集" if ep_no > 0 else "本集"
+ locked = [str(s).strip() for s in (locked_summaries or []) if str(s).strip()]
+ lines = [
+ f"剧名:{(project_title or '').strip() or '未命名短剧'}",
+ f"集号:{ep_label}" + (f"(episodeNumber={ep_no})" if ep_no > 0 else ""),
+ f"分集标题:{(episode_name or '').strip() or '未命名'}",
+ "",
+ ]
+ if locked:
+ lines.extend(
+ [
+ f"【续拆|前 {len(locked)} 条分镜已生成视频,内容锁定】",
+ "- 不要输出开幕镜(is_opening 全部 false)。",
+ "- 不要重复下列已拍内容;只规划尚未覆盖的后续剧情。",
+ "- 覆盖场记正文里尚未被已拍分镜讲完的部分。",
+ "",
+ "【已锁定分镜摘要】",
+ ]
+ )
+ for i, summary in enumerate(locked, start=1):
+ short = summary if len(summary) <= 220 else summary[:219] + "…"
+ lines.append(f"{i}. {short}")
+ lines.append("")
+ if (story_type or "").strip() or (one_line_story or "").strip():
+ lines.append("【背景参考|勿再写开幕】")
+ if (story_type or "").strip():
+ lines.append(f"- 类型:{story_type.strip()}")
+ if (one_line_story or "").strip():
+ lines.append(f"- 一句话故事:{one_line_story.strip()}")
+ else:
+ lines.extend(
+ [
+ "【开幕镜必须使用的标注信息|请写入 fragments[0].lines】",
+ f"- 集号原文:{ep_label}",
+ f"- 集名原文:{(episode_name or '').strip() or ep_label}",
+ ]
+ )
+ if (project_title or "").strip():
+ lines.append(f"- 剧名原文:{project_title.strip()}")
+ if (story_type or "").strip():
+ lines.append(f"- 类型:{story_type.strip()}")
+ if (core_hook or "").strip():
+ lines.append(f"- 钩子:{core_hook.strip()}")
+ if (one_line_story or "").strip():
+ lines.append(f"- 一句话故事:{one_line_story.strip()}")
+ if (synopsis or "").strip():
+ syn = synopsis.strip()
+ if len(syn) > 420:
+ syn = syn[:419] + "…"
+ lines.append(f"- 故事梗概(背景参考):{syn}")
+
+ lines.extend(
+ [
+ "",
+ "【分集场记正文】",
+ (episode_body or "").strip() or "(空)",
+ "",
+ "【可用资产目录|拆镜时 character_names / scene_name 尽量使用下列名称】",
+ ]
+ )
+ if not asset_catalog:
+ lines.append("(暂无资产)")
+ else:
+ for item in asset_catalog:
+ kind = str(item.get("type") or "")
+ name = str(item.get("name") or "")
+ aid = item.get("id")
+ role = str(item.get("roleType") or item.get("title") or "").strip()
+ extra = f"|{role}" if role else ""
+ lines.append(f"- [{kind}] id={aid} name={name}{extra}")
+ if locked:
+ lines.extend(
+ [
+ "",
+ "请输出 JSON:{\"fragments\":[...]};全部为后续剧情镜(不要开幕镜),从已拍内容之后续拆。",
+ ]
+ )
+ else:
+ lines.extend(
+ [
+ "",
+ "请输出 JSON:{\"fragments\":[...]};第一条必须是开幕镜(is_opening=true,含集号与背景介绍)。",
+ ]
+ )
+ return "\n".join(lines)
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index a753450..ba512b7 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import logging
import time
+from pathlib import Path
from typing import Any
from sqlalchemy import select
@@ -15,16 +16,74 @@ from app.models_drama import DramaAsset, DramaEpisodeFragment, DramaFragmentAsse
from app.services.ark import get_ark
from app.services.billing import record_usage
from app.services.drama.build_seedance_generate_body import (
+ ASSET_MENTION_TOKEN_PATTERN,
build_seedance_generate_body,
build_seedance_reference_catalog,
drama_asset_to_payload,
+ read_asset_voice_audio_url,
)
from app.services.drama.generation_prompt import build_generation_prompt
from app.services.drama.seedream_options import resolve_seedream_model_endpoint, resolve_seedream_size
+from app.services.drama.visual_prompt import resolve_visual_prompt_for_asset
from app.services.drama.voice_synthesis import synthesize_voice_asset
logger = logging.getLogger(__name__)
+# 分镜视频前需要参考图的资产类型
+IMAGE_REF_ASSET_TYPES = frozenset({"character", "scene", "prop"})
+
+
+# 读取分镜已落盘的尾帧 URL
+def read_fragment_last_frame_url(fragment: DramaEpisodeFragment | None) -> str | None:
+ if not fragment:
+ return None
+ params = fragment.params if isinstance(fragment.params, dict) else {}
+ for key in ("lastFrameUrl", "last_frame_url"):
+ value = params.get(key)
+ if isinstance(value, str) and value.strip():
+ return value.strip()
+ return None
+
+
+# 写入分镜尾帧 URL(生成完成后持久化,供下一镜衔接)
+def write_fragment_last_frame_url(fragment: DramaEpisodeFragment, url: str | None) -> None:
+ params = dict(fragment.params or {}) if isinstance(fragment.params, dict) else {}
+ cleaned = (url or "").strip()
+ if cleaned:
+ params["lastFrameUrl"] = cleaned
+ else:
+ params.pop("lastFrameUrl", None)
+ params.pop("last_frame_url", None)
+ fragment.params = params
+
+
+# 项目是否开启「上一镜尾帧 → 本镜首帧」衔接(默认开启)
+def project_link_last_frame_enabled(project: DramaProject) -> bool:
+ params = project.params if isinstance(project.params, dict) else {}
+ raw = params.get("linkLastFrame")
+ if raw is None:
+ raw = params.get("link_last_frame")
+ if raw is None:
+ return True
+ return bool(raw)
+
+
+# 查找同集中 sort_order 更小的上一镜
+async def find_previous_episode_fragment(
+ db: AsyncSession,
+ fragment: DramaEpisodeFragment,
+) -> DramaEpisodeFragment | None:
+ result = await db.execute(
+ select(DramaEpisodeFragment)
+ .where(
+ DramaEpisodeFragment.episode_id == fragment.episode_id,
+ DramaEpisodeFragment.sort_order < int(fragment.sort_order or 0),
+ )
+ .order_by(DramaEpisodeFragment.sort_order.desc())
+ .limit(1)
+ )
+ return result.scalars().first()
+
def fragment_generation_status(fragment: DramaEpisodeFragment) -> dict[str, Any]:
"""读取分镜片段生成状态(done / running / failed / idle)。"""
@@ -37,6 +96,242 @@ def fragment_generation_status(fragment: DramaEpisodeFragment) -> dict[str, Any]
return {"status": "idle"}
+# 从分镜正文提取 @asset:id
+def extract_asset_ids_from_content(content: str) -> list[int]:
+ ids: list[int] = []
+ seen: set[int] = set()
+ for match in ASSET_MENTION_TOKEN_PATTERN.finditer(content or ""):
+ asset_id = int(match.group(1))
+ if asset_id in seen:
+ continue
+ seen.add(asset_id)
+ ids.append(asset_id)
+ return ids
+
+
+# 判断资产是否缺参考图
+def asset_needs_reference_image(asset: DramaAsset) -> bool:
+ kind = (asset.type or "").strip().lower()
+ if kind not in IMAGE_REF_ASSET_TYPES:
+ return False
+ cover = (asset.cover or "").strip()
+ url = (asset.url or "").strip()
+ return not cover and not url
+
+
+# 读取资产生图提示词(缺省时用名称兜底)
+def read_asset_visual_prompt(asset: DramaAsset) -> str:
+ params = asset.params if isinstance(asset.params, dict) else {}
+ stored = str(
+ params.get("visualPrompt")
+ or params.get("visualImage")
+ or ""
+ ).strip()
+ if stored:
+ return stored
+ name = (asset.name or "").strip() or f"资产{asset.id}"
+ kind = (asset.type or "character").strip()
+ return f"{kind} {name}"
+
+
+async def _set_fragment_generation(
+ db: AsyncSession,
+ fragment: DramaEpisodeFragment,
+ payload: dict[str, Any],
+) -> None:
+ # 写入分镜 generation 状态供前端轮询
+ params = dict(fragment.params or {})
+ params["generation"] = payload
+ fragment.params = params
+ await db.commit()
+
+
+async def ensure_fragment_reference_images(
+ db: AsyncSession,
+ user: User,
+ project: DramaProject,
+ fragment: DramaEpisodeFragment,
+ *,
+ ref_assets: list[DramaAsset] | None = None,
+) -> list[DramaAsset]:
+ """
+ 分镜视频生成前:收集引用资产,对缺图的角色/场景/道具动态 Seedream 生图。
+ 返回刷新后的参考资产列表(含正文 @asset 与引用表)。
+ """
+ # collected_ids 引用表 + 正文 @asset
+ collected_ids: list[int] = []
+ seen: set[int] = set()
+
+ refs = (
+ await db.execute(
+ select(DramaFragmentAssetRef)
+ .where(DramaFragmentAssetRef.fragment_id == fragment.id)
+ .order_by(DramaFragmentAssetRef.id.asc())
+ )
+ ).scalars().all()
+ for ref in refs:
+ if ref.asset_id in seen:
+ continue
+ seen.add(ref.asset_id)
+ collected_ids.append(ref.asset_id)
+
+ for asset_id in extract_asset_ids_from_content(fragment.content or ""):
+ if asset_id in seen:
+ continue
+ seen.add(asset_id)
+ collected_ids.append(asset_id)
+
+ assets_by_id: dict[int, DramaAsset] = {}
+ if ref_assets:
+ for asset in ref_assets:
+ assets_by_id[asset.id] = asset
+
+ for asset_id in collected_ids:
+ if asset_id in assets_by_id:
+ continue
+ asset = await db.get(DramaAsset, asset_id)
+ if asset and asset.project_id == project.id:
+ assets_by_id[asset_id] = asset
+
+ ordered = [assets_by_id[i] for i in collected_ids if i in assets_by_id]
+ missing = [a for a in ordered if asset_needs_reference_image(a)]
+ if not missing:
+ return ordered
+
+ logger.info(
+ "分镜缺图资产动态生成 fragment_id=%s count=%s ids=%s",
+ fragment.id,
+ len(missing),
+ [a.id for a in missing],
+ )
+ await _set_fragment_generation(
+ db,
+ fragment,
+ {
+ "status": "running",
+ "phase": "assets",
+ "message": f"正在生成参考图 0/{len(missing)}",
+ "assets_total": len(missing),
+ "assets_done": 0,
+ },
+ )
+
+ # 补齐正文提到但引用表没有的关联
+ existing_ref_ids = {ref.asset_id for ref in refs}
+ for asset in ordered:
+ if asset.id in existing_ref_ids:
+ continue
+ if (asset.type or "").lower() not in IMAGE_REF_ASSET_TYPES:
+ continue
+ db.add(DramaFragmentAssetRef(fragment_id=fragment.id, asset_id=asset.id))
+ existing_ref_ids.add(asset.id)
+ await db.flush()
+
+ for index, asset in enumerate(missing):
+ try:
+ prompt = await resolve_visual_prompt_for_asset(asset, project)
+ except Exception: # noqa: BLE001
+ prompt = read_asset_visual_prompt(asset)
+ if not (prompt or "").strip():
+ prompt = read_asset_visual_prompt(asset)
+ await _set_fragment_generation(
+ db,
+ fragment,
+ {
+ "status": "running",
+ "phase": "assets",
+ "message": f"正在生成参考图 {index + 1}/{len(missing)}:{asset.name or asset.id}",
+ "assets_total": len(missing),
+ "assets_done": index,
+ "asset_id": asset.id,
+ },
+ )
+ updated = await generate_asset_image(
+ db,
+ user,
+ project,
+ prompt,
+ asset=asset,
+ name=asset.name,
+ kind=(asset.type or "character"),
+ image_style_id=str((project.params or {}).get("image_style_id") or "") or None,
+ )
+ assets_by_id[updated.id] = updated
+ logger.info(
+ "分镜参考图已补齐 fragment_id=%s asset_id=%s url=%s",
+ fragment.id,
+ updated.id,
+ (updated.cover or updated.url or "")[:80],
+ )
+
+ await _set_fragment_generation(
+ db,
+ fragment,
+ {
+ "status": "running",
+ "phase": "video",
+ "message": "参考图已就绪,开始生成视频",
+ "assets_total": len(missing),
+ "assets_done": len(missing),
+ },
+ )
+ return [assets_by_id[i] for i in collected_ids if i in assets_by_id]
+
+
+async def ensure_reference_assets_public_urls(
+ db: AsyncSession,
+ assets: list[DramaAsset],
+) -> list[DramaAsset]:
+ """将引用资产的本地 cover/url 同步上传 OSS,供 Seedance 公网拉取。"""
+ from app.services import storage as storage_svc
+
+ changed = False
+ for asset in assets:
+ for field in ("cover", "url"):
+ raw = (getattr(asset, field) or "").strip()
+ if not raw:
+ continue
+ if raw.startswith("https://"):
+ continue
+ published = storage_svc.republish_url(raw, sync=True)
+ if published and published != raw and str(published).startswith("https://"):
+ setattr(asset, field, published)
+ changed = True
+ logger.info(
+ "资产参考图已同步 OSS asset_id=%s field=%s",
+ asset.id,
+ field,
+ )
+ # 角色音色本地音频同样需要公网
+ params = dict(asset.params or {}) if isinstance(asset.params, dict) else {}
+ voice_url = read_asset_voice_audio_url(params)
+ if voice_url and not voice_url.startswith("https://"):
+ published_voice = storage_svc.republish_url(voice_url, sync=True)
+ if (
+ published_voice
+ and published_voice != voice_url
+ and str(published_voice).startswith("https://")
+ ):
+ binding = params.get("voiceAudio")
+ if isinstance(binding, dict):
+ params["voiceAudio"] = {**binding, "url": str(published_voice)}
+ canvas = params.get("canvas")
+ if isinstance(canvas, dict):
+ voice_binding = canvas.get("voiceAudio")
+ if isinstance(voice_binding, dict):
+ params["canvas"] = {
+ **canvas,
+ "voiceAudio": {**voice_binding, "url": str(published_voice)},
+ }
+ asset.params = params
+ changed = True
+ if changed:
+ await db.commit()
+ for asset in assets:
+ await db.refresh(asset)
+ return assets
+
+
async def generate_asset_image(
db: AsyncSession,
user: User,
@@ -84,7 +379,20 @@ async def generate_asset_image(
size=size,
model=model,
)
+ # Seedance 需公网图:优先同步 OSS;失败再用 Seedream 临时 CDN
+ from app.services import storage as storage_svc
+
url = result.local_url or ""
+ if url:
+ published = storage_svc.republish_url(url, sync=True)
+ if published and str(published).startswith("https://"):
+ url = str(published)
+ elif result.remote_url and str(result.remote_url).startswith("https://"):
+ url = str(result.remote_url)
+ logger.warning(
+ "OSS 未拿到 https,回退 Seedream CDN project_id=%s",
+ project.id,
+ )
logger.info("Seedream 返回 project_id=%s url=%s", project.id, (url or "")[:100])
await record_usage(
@@ -142,6 +450,7 @@ async def generate_voice_asset_audio(
voice_prompt: str,
sample_text: str | None = None,
speaker: str | None = None,
+ character_asset: DramaAsset | None = None,
) -> DramaAsset:
"""为 voice 类型资产按提示词合成参考音频。"""
return await synthesize_voice_asset(
@@ -152,9 +461,44 @@ async def generate_voice_asset_audio(
voice_prompt=voice_prompt,
sample_text=sample_text,
speaker=speaker,
+ character_name=character_asset.name if character_asset else None,
+ character_asset=character_asset,
)
+# 组装分镜 Seedance 引用 payload(含全局旁白音色)
+def build_fragment_ref_payloads(
+ project: DramaProject,
+ ref_assets: list[DramaAsset],
+) -> list[dict[str, Any]]:
+ ref_payloads = [drama_asset_to_payload(a) for a in ref_assets]
+ narrator_voice: Any = (project.params or {}).get("narrationVoiceAudio")
+ if isinstance(narrator_voice, dict):
+ narration_url = str(
+ narrator_voice.get("url") or narrator_voice.get("previewUrl") or ""
+ ).strip()
+ if narration_url and not narration_url.startswith("https://"):
+ from app.services import storage as storage_svc
+
+ published_voice = storage_svc.republish_url(narration_url, sync=True)
+ if published_voice and str(published_voice).startswith("https://"):
+ narrator_voice = {**narrator_voice, "url": str(published_voice)}
+
+ narration_voice_audio_url = str(narrator_voice.get("url") or "").strip()
+ if narration_voice_audio_url:
+ narrator_payload = {
+ "id": -1,
+ "type": "narration",
+ "assetType": "audio",
+ "name": "旁白",
+ "cover": "",
+ "url": "",
+ "params": {"voiceAudio": narrator_voice},
+ }
+ ref_payloads = [narrator_payload, *ref_payloads]
+ return ref_payloads
+
+
async def generate_fragment_video(
db: AsyncSession,
user: User,
@@ -185,42 +529,68 @@ async def generate_fragment_video(
seen_ids.add(ref.asset_id)
ref_assets.append(asset)
- ref_payloads = [drama_asset_to_payload(a) for a in ref_assets]
+ # 缺图的引用资产先动态生图,再组 Seedance 参考
+ ref_assets = await ensure_fragment_reference_images(
+ db,
+ user,
+ project,
+ fragment,
+ ref_assets=ref_assets,
+ )
+ # 已有本地图的资产同步上 OSS,避免 Seedance 拿不到公网 URL
+ ref_assets = await ensure_reference_assets_public_urls(db, ref_assets)
+
+ ref_payloads = build_fragment_ref_payloads(project, ref_assets)
style_id = str((project.params or {}).get("image_style_id") or "").strip() or None
catalog = build_seedance_reference_catalog(ref_payloads)
+ continuity_url: str | None = None
+ if project_link_last_frame_enabled(project):
+ prev = await find_previous_episode_fragment(db, fragment)
+ continuity_url = read_fragment_last_frame_url(prev)
+ if continuity_url:
+ continuity_url = storage_svc_early_republish(continuity_url)
+
t0 = time.time()
image_url = ""
for item in catalog.images:
image_url = item.url
break
+ local_last_frame: str | None = None
if ref_payloads and (catalog.images or catalog.audios):
+ # ratio 优先项目 params,默认竖屏 9:16(与分集编辑页一致)
+ ratio = str((project.params or {}).get("aspect_ratio") or "").strip() or "9:16"
+ resolution = str((project.params or {}).get("resolution") or "").strip() or "480p"
body = build_seedance_generate_body(
{
"content": prompt,
"reference": ref_payloads,
"video_style_id": style_id,
- "aspect_ratio": "16:9",
- "resolution": "480p",
+ "aspect_ratio": ratio,
+ "resolution": resolution,
"duration_fallback": duration,
+ "continuity_first_frame_url": continuity_url,
}
)
- local_video = await ark.gen_and_wait_seedance_body(
+ local_video, local_last_frame = await ark.gen_and_wait_seedance_body(
body,
project_id=project.id,
shot_no=fragment.id,
)
elif image_url:
+ ratio = str((project.params or {}).get("aspect_ratio") or "").strip() or "9:16"
local_video = await ark.gen_and_wait_video(
image_url,
prompt,
duration,
project_id=project.id,
shot_no=fragment.id,
- ratio="16:9",
+ ratio=ratio,
+ generate_audio=True,
)
else:
+ ratio = str((project.params or {}).get("aspect_ratio") or "").strip() or "9:16"
still = await ark.gen_image(prompt[:500], project_id=project.id, shot_no=fragment.id)
image_url = still.local_url or ""
local_video = await ark.gen_and_wait_video(
@@ -229,26 +599,60 @@ async def generate_fragment_video(
duration,
project_id=project.id,
shot_no=fragment.id,
- ratio="16:9",
+ ratio=ratio,
+ generate_audio=True,
)
- fragment.video = local_video
- fragment.cover = fragment.cover or image_url
+ # Seedance 成片落盘后立即同步 OSS,避免库里长期留 /static
+ from app.services import storage as storage_svc
+
+ video_url = storage_svc.republish_url(local_video, sync=True) or local_video
+ # 封面必须来自成片帧,禁止用角色/场景参考图冒充
+ cover_url = ""
+ video_path = storage_svc.local_path_from_url(local_video)
+ if video_path is None and isinstance(local_video, str) and not local_video.startswith("http"):
+ candidate = Path(local_video)
+ if candidate.exists():
+ video_path = candidate
+ if video_path and video_path.exists():
+ from app.services.ffmpeg_compose import extract_video_poster_frame
+
+ poster_dest = storage_svc.project_dir(project.id) / f"shot_{fragment.id}_cover.jpg"
+ if extract_video_poster_frame(video_path, poster_dest):
+ cover_src = storage_svc.rel_static_url(poster_dest)
+ cover_url = storage_svc.republish_url(cover_src, sync=True) or cover_src
+ last_frame_url = None
+ if local_last_frame:
+ last_frame_url = storage_svc.republish_url(local_last_frame, sync=True) or local_last_frame
+ if not cover_url:
+ cover_url = last_frame_url
+ fragment.video = video_url
+ fragment.cover = cover_url or ""
+ write_fragment_last_frame_url(fragment, last_frame_url)
await record_usage(
db,
user_id=user.id,
project_id=None,
drama_project_id=project.id,
- billing_key="seedance",
+ billing_key="seedance2:video0",
model=settings.model_video,
estimated=True,
)
await db.commit()
await db.refresh(fragment)
logger.info(
- "fragment video done id=%s secs=%.1f url=%s",
+ "fragment video done id=%s secs=%.1f url=%s last_frame=%s continuity=%s",
fragment.id,
time.time() - t0,
- (local_video or "")[:80],
+ (video_url or "")[:80],
+ bool(last_frame_url),
+ bool(continuity_url),
)
return fragment
+
+
+# 衔接用尾帧尽量走公网 URL(本地 /static 时尝试 republish)
+def storage_svc_early_republish(url: str) -> str:
+ from app.services import storage as storage_svc
+
+ return storage_svc.republish_url(url, sync=True) or url
diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.py
index d909181..cd946cb 100644
--- a/backend/app/services/drama/jobs.py
+++ b/backend/app/services/drama/jobs.py
@@ -36,6 +36,247 @@ logger = logging.getLogger(__name__)
# in-process fallback handles
_running: dict[str, asyncio.Task] = {}
+# 分集视频取消标记(episode_id)
+_video_cancelled_episodes: set[int] = set()
+_episode_video_celery_ids: dict[int, str] = {}
+
+VIDEO_CELERY_TASKS = frozenset(
+ {
+ "drama.episode_generate",
+ "app.workers.tasks.regen_video_task",
+ }
+)
+VIDEO_QUEUES = ("video", "pipeline")
+ACTIVE_VIDEO_GEN_STATUSES = frozenset({"queued", "running", "generating"})
+
+
+def _is_episode_video_cancelled(episode_id: int) -> bool:
+ return int(episode_id) in _video_cancelled_episodes
+
+
+def _mark_episode_video_cancelled(episode_id: int) -> None:
+ _video_cancelled_episodes.add(int(episode_id))
+
+
+def _clear_episode_video_cancelled(episode_id: int) -> None:
+ _video_cancelled_episodes.discard(int(episode_id))
+
+
+def _cancel_inprocess_episode_video(episode_id: int) -> bool:
+ key = _job_key("epgen", episode_id)
+ task = _running.get(key)
+ if task is None or task.done():
+ return False
+ task.cancel()
+ return True
+
+
+def _revoke_celery_task_ids(task_ids: list[str]) -> int:
+ if not task_ids:
+ return 0
+ try:
+ from app.workers.celery_app import celery_app
+
+ for tid in task_ids:
+ celery_app.control.revoke(tid, terminate=True, signal="SIGTERM")
+ return len(task_ids)
+ except Exception: # noqa: BLE001
+ logger.exception("revoke celery video tasks failed")
+ return 0
+
+
+def _episode_id_from_video_celery_message(msg: dict[str, Any]) -> int | None:
+ headers = msg.get("headers") or {}
+ task = str(headers.get("task") or "")
+ if task != "drama.episode_generate":
+ return None
+ body = msg.get("body")
+ if not body:
+ return None
+ try:
+ import base64
+ import json
+
+ if isinstance(body, bytes):
+ body = body.decode("utf-8", errors="replace")
+ raw = base64.b64decode(body)
+ payload = json.loads(raw.decode("utf-8"))
+ args = payload[0] if isinstance(payload, (list, tuple)) and payload else None
+ if isinstance(args, (list, tuple)) and args:
+ return int(args[0])
+ except Exception: # noqa: BLE001
+ return None
+ return None
+
+
+def _purge_video_queue_messages(*, episode_id: int | None = None) -> tuple[int, list[str]]:
+ """从 video/pipeline 队列移除视频任务;返回 (removed, revoked_ids)。"""
+ try:
+ import json
+
+ import redis
+
+ r = redis.Redis.from_url(get_settings().redis_url, decode_responses=True)
+ total_removed = 0
+ revoked_ids: list[str] = []
+ for queue in VIDEO_QUEUES:
+ items = r.lrange(queue, 0, -1) or []
+ if not items:
+ continue
+ kept: list[str] = []
+ queue_removed = 0
+ for raw in items:
+ try:
+ msg = json.loads(raw)
+ except Exception: # noqa: BLE001
+ kept.append(raw)
+ continue
+ headers = msg.get("headers") or {}
+ task = str(headers.get("task") or "")
+ if task not in VIDEO_CELERY_TASKS:
+ kept.append(raw)
+ continue
+ ep_id = _episode_id_from_video_celery_message(msg)
+ if episode_id is not None and ep_id != int(episode_id):
+ kept.append(raw)
+ continue
+ tid = str(headers.get("id") or "")
+ if tid:
+ revoked_ids.append(tid)
+ queue_removed += 1
+ if queue_removed <= 0:
+ continue
+ pipe = r.pipeline()
+ pipe.delete(queue)
+ if kept:
+ pipe.rpush(queue, *kept)
+ pipe.execute()
+ total_removed += queue_removed
+ return total_removed, revoked_ids
+ except Exception: # noqa: BLE001
+ logger.exception("purge video queue failed episode_id=%s", episode_id)
+ return 0, []
+
+
+def _collect_active_video_celery_ids(*, episode_id: int | None = None) -> list[str]:
+ ids: list[str] = []
+ try:
+ from app.workers.celery_app import celery_app
+
+ inspect = celery_app.control.inspect(timeout=2.0)
+ for fetch in (inspect.active, inspect.reserved, inspect.scheduled):
+ data = fetch() or {}
+ for _worker, tasks in data.items():
+ for task in tasks or []:
+ name = str(task.get("name") or task.get("request", {}).get("name") or "")
+ if name not in VIDEO_CELERY_TASKS:
+ continue
+ args = task.get("args") or task.get("request", {}).get("args") or []
+ if name == "drama.episode_generate" and episode_id is not None:
+ if not args or int(args[0]) != int(episode_id):
+ continue
+ tid = str(task.get("id") or task.get("request", {}).get("id") or "")
+ if tid:
+ ids.append(tid)
+ except Exception: # noqa: BLE001
+ logger.exception("inspect active video tasks failed")
+ return ids
+
+
+async def _reset_fragment_video_generation(
+ db,
+ *,
+ episode_id: int | None = None,
+) -> int:
+ q = select(DramaEpisodeFragment)
+ if episode_id is not None:
+ q = q.where(DramaEpisodeFragment.episode_id == int(episode_id))
+ frags = (await db.execute(q)).scalars().all()
+ changed = 0
+ for frag in frags:
+ params = dict(frag.params or {})
+ gen = params.get("generation") if isinstance(params, dict) else None
+ status = str(gen.get("status") or "") if isinstance(gen, dict) else ""
+ if status not in ACTIVE_VIDEO_GEN_STATUSES:
+ continue
+ params["generation"] = {"status": "cancelled"}
+ frag.params = params
+ changed += 1
+ if changed:
+ await db.commit()
+ return changed
+
+
+async def cancel_episode_video_jobs(episode_id: int) -> dict[str, Any]:
+ """取消单集视频任务:revoke Celery、终止进程内任务、重置分镜状态。"""
+ _mark_episode_video_cancelled(episode_id)
+ cancelled_inprocess = _cancel_inprocess_episode_video(episode_id)
+ revoked_ids: list[str] = []
+ stored = _episode_video_celery_ids.pop(int(episode_id), None)
+ if stored:
+ revoked_ids.append(stored)
+ revoked_ids.extend(_collect_active_video_celery_ids(episode_id=episode_id))
+ purged, purged_ids = _purge_video_queue_messages(episode_id=episode_id)
+ revoked_ids.extend(purged_ids)
+ revoked = _revoke_celery_task_ids(list(dict.fromkeys(revoked_ids)))
+ async with AsyncSessionLocal() as db:
+ fragments = await _reset_fragment_video_generation(db, episode_id=episode_id)
+ logger.info(
+ "取消分集视频 episode_id=%s inprocess=%s purged=%s revoked=%s fragments=%s",
+ episode_id,
+ cancelled_inprocess,
+ purged,
+ revoked,
+ fragments,
+ )
+ return {
+ "ok": True,
+ "episode_id": episode_id,
+ "inprocess": cancelled_inprocess,
+ "purged": purged,
+ "revoked": revoked,
+ "fragments": fragments,
+ }
+
+
+async def cancel_all_episode_video_jobs() -> dict[str, Any]:
+ """取消全部漫剧分镜视频任务。"""
+ episode_ids = set(_episode_video_celery_ids.keys()) | set(_video_cancelled_episodes)
+ async with AsyncSessionLocal() as db:
+ frags = (await db.execute(select(DramaEpisodeFragment))).scalars().all()
+ for frag in frags:
+ params = frag.params or {}
+ gen = params.get("generation") if isinstance(params, dict) else None
+ status = str(gen.get("status") or "") if isinstance(gen, dict) else ""
+ if status in ACTIVE_VIDEO_GEN_STATUSES:
+ episode_ids.add(int(frag.episode_id))
+ for ep_id in list(episode_ids):
+ _mark_episode_video_cancelled(ep_id)
+ _cancel_inprocess_episode_video(ep_id)
+
+ revoked_ids = _collect_active_video_celery_ids()
+ revoked_ids.extend(_episode_video_celery_ids.values())
+ purged, purged_ids = _purge_video_queue_messages()
+ revoked_ids.extend(purged_ids)
+ revoked = _revoke_celery_task_ids(list(dict.fromkeys(revoked_ids)))
+ _episode_video_celery_ids.clear()
+
+ async with AsyncSessionLocal() as db:
+ fragments = await _reset_fragment_video_generation(db)
+ logger.info(
+ "取消全部视频任务 purged=%s revoked=%s fragments=%s episodes=%s",
+ purged,
+ revoked,
+ fragments,
+ len(episode_ids),
+ )
+ return {
+ "ok": True,
+ "purged": purged,
+ "revoked": revoked,
+ "fragments": fragments,
+ "episodes": len(episode_ids),
+ }
def _redis_ok() -> bool:
@@ -304,6 +545,209 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[
return {"ok": False, "error": str(exc)[:500]}
+# ---------- episode fragment plan (LLM) ----------
+
+
+def dispatch_episode_fragment_plan_job(episode_id: int, *, fallback_rules: bool = True) -> str:
+ # 入队单集 LLM 分镜;Celery 不可用时进程内跑
+ if _use_celery():
+ from app.workers.drama_tasks import drama_episode_fragment_plan_task
+
+ result = drama_episode_fragment_plan_task.apply_async(
+ args=[episode_id, fallback_rules],
+ queue="pipeline",
+ )
+ logger.info(
+ "dispatch 单集分镜 → Celery episode_id=%s task_id=%s",
+ episode_id,
+ result.id,
+ )
+ return str(result.id)
+
+ key = _job_key("fragplan", episode_id)
+ if key in _running and not _running[key].done():
+ logger.info("dispatch 单集分镜 → 进程内已在跑 episode_id=%s", episode_id)
+ return "in-process"
+ _running[key] = asyncio.create_task(
+ run_episode_fragment_plan_job(episode_id, fallback_rules=fallback_rules)
+ )
+ logger.info("dispatch 单集分镜 → 进程内新建 episode_id=%s", episode_id)
+ return "in-process"
+
+
+async def run_episode_fragment_plan_job(
+ episode_id: int,
+ *,
+ fallback_rules: bool = True,
+) -> dict[str, Any]:
+ # Worker:LLM 规划本集分镜并落库;失败可选回退规则切分
+ from app.services.drama.build_fragments import build_fragments_from_episode_body
+ from app.services.drama.fragment_plan import plan_fragments_with_llm
+ from app.services.drama.llm import DramaLlmUnavailableError
+ from app.services.drama.seed import (
+ _episode_bodies,
+ _fragment_is_protected,
+ replace_episode_fragments_with_drafts,
+ resolve_episode_script_body,
+ )
+
+ logger.info("开始单集 LLM 分镜 episode_id=%s", episode_id)
+ async with AsyncSessionLocal() as db:
+ episode = await db.get(
+ DramaEpisode,
+ episode_id,
+ options=[
+ selectinload(DramaEpisode.fragments).selectinload(
+ DramaEpisodeFragment.asset_references
+ ),
+ selectinload(DramaEpisode.project).selectinload(DramaProject.script),
+ ],
+ )
+ if not episode or not episode.project:
+ logger.warning("单集分镜失败:缺少分集 episode_id=%s", episode_id)
+ return {"ok": False, "error": "missing_episode"}
+
+ project = episode.project
+ script = project.script
+ body = resolve_episode_script_body(script.episode_content if script else None, episode)
+ if not (body or "").strip():
+ params = dict(episode.params or {})
+ params["fragment_plan_status"] = "failed"
+ params["fragment_plan_error"] = "本集剧本正文为空,无法分镜"
+ episode.params = params
+ await db.commit()
+ return {"ok": False, "error": "empty_body"}
+
+ assets_result = await db.execute(
+ select(DramaAsset).where(DramaAsset.project_id == project.id)
+ )
+ assets = list(assets_result.scalars().all())
+
+ # 本剧更早分集已介绍角色(跨集去重)
+ from app.services.drama.build_fragments import collect_series_introduced_names
+
+ siblings_result = await db.execute(
+ select(DramaEpisode)
+ .where(DramaEpisode.project_id == project.id)
+ .options(selectinload(DramaEpisode.fragments))
+ )
+ siblings = list(siblings_result.scalars().all())
+ ep_params = episode.params if isinstance(episode.params, dict) else {}
+ ep_no = int(ep_params.get("episodeNumber") or 0) or None
+ already_introduced = collect_series_introduced_names(
+ siblings,
+ before_episode_number=ep_no,
+ exclude_episode_id=episode.id,
+ )
+
+ # 本集已有视频/手改分镜:续拆时锁定,并把已介绍角色并入去重集
+ from app.services.drama.build_fragments import extract_introduced_names_from_content
+
+ protected_frags = sorted(
+ [f for f in (episode.fragments or []) if _fragment_is_protected(f)],
+ key=lambda f: int(f.sort_order or 0),
+ )
+ locked_summaries: list[str] = []
+ for frag in protected_frags:
+ for name in extract_introduced_names_from_content(frag.content or ""):
+ already_introduced.add(name)
+ # 摘要:去掉 cue 行后取前几行画面/对白
+ narr: list[str] = []
+ for raw in (frag.content or "").replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if not line or line.startswith("@") or line.startswith("【"):
+ continue
+ narr.append(line)
+ if len(narr) >= 3:
+ break
+ locked_summaries.append(";".join(narr) if narr else f"分镜#{frag.sort_order}")
+
+ mode_used = "llm"
+ summary = script.summary if script and isinstance(script.summary, dict) else {}
+ from app.services.drama.character_intro_llm import prepare_character_intro_overrides
+
+ all_bodies = _episode_bodies(script.episode_content if script else None)
+ if body and body not in all_bodies:
+ all_bodies.append(body)
+ character_assets = [a for a in assets if getattr(a, "type", "") == "character"]
+ intro_overrides = await prepare_character_intro_overrides(
+ character_assets,
+ summary=summary,
+ episode_bodies=all_bodies,
+ story_type=str(summary.get("storyType") or "") or None,
+ )
+ continuation = bool(locked_summaries)
+ try:
+ drafts = await plan_fragments_with_llm(
+ episode_name=episode.name or "",
+ episode_body=body,
+ assets=assets,
+ episode_number=ep_no,
+ project_title=project.title or "",
+ story_type=str(summary.get("storyType") or "") or None,
+ one_line_story=str(summary.get("oneLineStory") or "") or None,
+ synopsis=str(summary.get("synopsis") or "") or None,
+ core_hook=str(summary.get("coreHook") or "") or None,
+ already_introduced=already_introduced,
+ summary=summary,
+ episode_bodies=all_bodies,
+ intro_overrides=intro_overrides,
+ locked_summaries=locked_summaries or None,
+ )
+ except (DramaLlmUnavailableError, RuntimeError, Exception) as exc: # noqa: BLE001
+ logger.exception("LLM 分镜失败 episode_id=%s err=%s", episode_id, exc)
+ if not fallback_rules:
+ params = dict(episode.params or {})
+ params["fragment_plan_status"] = "failed"
+ params["fragment_plan_error"] = str(exc)[:500]
+ episode.params = params
+ await db.commit()
+ return {"ok": False, "error": str(exc)[:500]}
+ drafts = build_fragments_from_episode_body(
+ body,
+ assets,
+ already_introduced=already_introduced,
+ summary=summary,
+ episode_bodies=all_bodies,
+ intro_overrides=intro_overrides,
+ )
+ mode_used = "rules_fallback"
+ continuation = False
+
+ await replace_episode_fragments_with_drafts(
+ db,
+ episode,
+ body,
+ assets,
+ drafts,
+ preserve_protected=True,
+ continuation=continuation,
+ )
+ # 重新加载 params(replace 会写 fingerprint)
+ params = dict(episode.params or {})
+ params["fragment_plan_status"] = "completed"
+ params["fragment_plan_mode"] = mode_used
+ params.pop("fragment_plan_error", None)
+ params["fragment_plan_count"] = len(protected_frags) + len(drafts)
+ params["fragment_plan_preserved"] = len(protected_frags)
+ episode.params = params
+ await db.commit()
+ logger.info(
+ "单集分镜完成 episode_id=%s mode=%s new=%s preserved=%s continuation=%s",
+ episode_id,
+ mode_used,
+ len(drafts),
+ len(protected_frags),
+ continuation,
+ )
+ return {
+ "ok": True,
+ "mode": mode_used,
+ "count": len(protected_frags) + len(drafts),
+ "preserved": len(protected_frags),
+ }
+
+
# ---------- episode video ----------
@@ -312,13 +756,15 @@ def dispatch_episode_generate_job(
user_id: int,
fragment_ids: list[int],
) -> str:
+ _clear_episode_video_cancelled(episode_id)
if _use_celery():
from app.workers.drama_tasks import drama_episode_generate_task
result = drama_episode_generate_task.apply_async(
args=[episode_id, user_id, fragment_ids],
- queue="pipeline",
+ queue="video",
)
+ _episode_video_celery_ids[int(episode_id)] = str(result.id)
logger.info(
"dispatch 分集视频 → Celery episode_id=%s fragments=%s task_id=%s",
episode_id,
@@ -342,36 +788,37 @@ def dispatch_episode_generate_job(
return "in-process"
-async def run_episode_generate_job(
+# 单个分镜视频(独立 DB session,供并发池调用)
+async def _generate_one_fragment_video(
+ *,
episode_id: int,
user_id: int,
- fragment_ids: list[int],
-) -> dict[str, Any]:
- logger.info(
- "开始生成分集视频 episode_id=%s fragments=%s",
- episode_id,
- len(fragment_ids),
- )
- async with AsyncSessionLocal() as db:
- ep = await db.get(
- DramaEpisode,
- episode_id,
- options=[selectinload(DramaEpisode.project)],
- )
- if not ep:
- logger.warning("分集视频失败:分集不存在 episode_id=%s", episode_id)
- return {"ok": False, "error": "missing_episode"}
- project = ep.project
- user = await db.get(User, user_id)
- if not project or not user:
- return {"ok": False, "error": "missing_project_or_user"}
-
- ok_count = 0
- fail_count = 0
- for fid in fragment_ids:
+ fragment_id: int,
+ sem: asyncio.Semaphore,
+) -> bool:
+ async with sem:
+ async with AsyncSessionLocal() as db:
+ ep = await db.get(
+ DramaEpisode,
+ episode_id,
+ options=[
+ selectinload(DramaEpisode.project).selectinload(DramaProject.script),
+ ],
+ )
+ if not ep or not ep.project:
+ logger.warning(
+ "分镜视频跳过:分集/项目不存在 episode_id=%s fragment_id=%s",
+ episode_id,
+ fragment_id,
+ )
+ return False
+ project = ep.project
+ user = await db.get(User, user_id)
+ if not user:
+ return False
frag = await db.get(
DramaEpisodeFragment,
- fid,
+ fragment_id,
options=[
selectinload(DramaEpisodeFragment.asset_references).selectinload(
DramaFragmentAssetRef.asset
@@ -379,39 +826,123 @@ async def run_episode_generate_job(
],
)
if not frag or frag.episode_id != episode_id:
- continue
+ return False
+
+ if _is_episode_video_cancelled(episode_id):
+ params = dict(frag.params or {})
+ params["generation"] = {"status": "cancelled"}
+ frag.params = params
+ await db.commit()
+ logger.info(
+ "分镜视频已取消 fragment_id=%s episode_id=%s",
+ fragment_id,
+ episode_id,
+ )
+ return False
+
params = dict(frag.params or {})
params["generation"] = {"status": "running"}
frag.params = params
await db.commit()
try:
- logger.info("生成分镜视频 fragment_id=%s episode_id=%s", fid, episode_id)
+ logger.info(
+ "生成分镜视频 fragment_id=%s episode_id=%s",
+ fragment_id,
+ episode_id,
+ )
await generate_fragment_video(db, user, project, frag)
await db.refresh(frag)
params = dict(frag.params or {})
+ last_frame = ""
+ if isinstance(frag.params, dict):
+ raw = frag.params.get("lastFrameUrl") or frag.params.get("last_frame_url")
+ if isinstance(raw, str):
+ last_frame = raw
params["generation"] = {
"status": "done",
"video": frag.video,
"cover": frag.cover,
+ "lastFrameUrl": last_frame or None,
}
+ if last_frame:
+ params["lastFrameUrl"] = last_frame
frag.params = params
await db.commit()
- ok_count += 1
+ return True
except Exception as exc: # noqa: BLE001
- fail_count += 1
params = dict(frag.params or {})
params["generation"] = {"status": "failed", "error": str(exc)[:500]}
frag.params = params
await db.commit()
- logger.exception("分镜视频失败 fragment_id=%s", fid)
- continue
- logger.info(
- "分集视频结束 episode_id=%s ok=%s fail=%s",
+ logger.exception("分镜视频失败 fragment_id=%s", fragment_id)
+ return False
+
+
+async def run_episode_generate_job(
+ episode_id: int,
+ user_id: int,
+ fragment_ids: list[int],
+) -> dict[str, Any]:
+ # 校验分集后,按 Seedance 并发上限并行生成各分镜
+ logger.info(
+ "开始生成分集视频 episode_id=%s fragments=%s",
+ episode_id,
+ len(fragment_ids),
+ )
+ async with AsyncSessionLocal() as db:
+ ep = await db.get(
+ DramaEpisode,
episode_id,
- ok_count,
- fail_count,
+ options=[
+ selectinload(DramaEpisode.project).selectinload(DramaProject.script),
+ ],
)
- return {"ok": True, "episode_id": episode_id}
+ if not ep:
+ logger.warning("分集视频失败:分集不存在 episode_id=%s", episode_id)
+ return {"ok": False, "error": "missing_episode"}
+ project = ep.project
+ user = await db.get(User, user_id)
+ if not project or not user:
+ return {"ok": False, "error": "missing_project_or_user"}
+
+ # valid_ids 属于本集且存在的分镜
+ valid_ids: list[int] = []
+ for fid in fragment_ids:
+ frag = await db.get(DramaEpisodeFragment, fid)
+ if frag and frag.episode_id == episode_id:
+ valid_ids.append(fid)
+
+ # limit 对齐 Seedance 官方并发(默认 10)
+ limit = max(1, int(get_settings().pipeline_video_concurrency or 10))
+ sem = asyncio.Semaphore(limit)
+ logger.info(
+ "分集视频并发 episode_id=%s concurrency=%s fragments=%s",
+ episode_id,
+ limit,
+ len(valid_ids),
+ )
+ results = await asyncio.gather(
+ *[
+ _generate_one_fragment_video(
+ episode_id=episode_id,
+ user_id=user_id,
+ fragment_id=fid,
+ sem=sem,
+ )
+ for fid in valid_ids
+ ]
+ )
+ ok_count = sum(1 for ok in results if ok)
+ fail_count = len(results) - ok_count
+ _episode_video_celery_ids.pop(int(episode_id), None)
+ _clear_episode_video_cancelled(episode_id)
+ logger.info(
+ "分集视频结束 episode_id=%s ok=%s fail=%s",
+ episode_id,
+ ok_count,
+ fail_count,
+ )
+ return {"ok": True, "episode_id": episode_id}
# ---------- asset image ----------
diff --git a/backend/app/services/drama/seed.py b/backend/app/services/drama/seed.py
index ebe93a3..a6f01e0 100644
--- a/backend/app/services/drama/seed.py
+++ b/backend/app/services/drama/seed.py
@@ -23,6 +23,7 @@ from app.models_drama import (
from app.services.drama.build_fragments import (
CAST_LINE_RE,
build_fragments_from_episode_body,
+ extract_introduced_names_from_content,
is_raw_screenplay_fragment,
parse_cast_names,
split_episode_content_into_scenes,
@@ -228,7 +229,9 @@ async def seed_assets_from_script(
for name in character_names:
if not name or name in existing_names:
continue
- ch = summary_by_name.get(name) or _character_stub_from_cast(name, story_type)
+ ch = summary_by_name.get(name) or _character_stub_from_cast(
+ name, story_type, summary=summary, bodies=bodies,
+ )
asset = DramaAsset(
project_id=project.id,
type="character",
@@ -386,6 +389,7 @@ async def seed_episodes_from_script(
await db.execute(select(DramaAsset).where(DramaAsset.project_id == project.id))
).scalars().all()
)
+ summary = script.summary if isinstance(script.summary, dict) else None
existing = list(
(
@@ -414,6 +418,8 @@ async def seed_episodes_from_script(
if not existing:
created: list[DramaEpisode] = []
+ # series_introduced 本剧已介绍角色(按集号累计)
+ series_introduced: set[str] = set()
for item in bodies:
ep_no = int(item.get("episodeNumber") or len(created) + 1)
title = str(item.get("title") or f"第{ep_no}集")
@@ -425,23 +431,59 @@ async def seed_episodes_from_script(
)
db.add(episode)
await db.flush()
- await _replace_episode_fragments(db, episode, body, assets)
+ planned = await _replace_episode_fragments(
+ db,
+ episode,
+ body,
+ assets,
+ already_introduced=series_introduced,
+ summary=summary,
+ )
+ for frag in planned:
+ series_introduced.update(
+ extract_introduced_names_from_content(str(frag.get("content") or ""))
+ )
created.append(episode)
await db.commit()
return await _reload_episodes(db, project.id)
# 已有分集:按集号同步名称与分镜(已生成视频 / 用户编辑过的分镜默认保留,除非 force)
- for episode in existing:
+ # series_introduced 按集号累计本剧已介绍角色
+ series_introduced: set[str] = set()
+ ordered_existing = sorted(
+ existing,
+ key=lambda ep: (
+ int((ep.params or {}).get("episodeNumber") or 0) if isinstance(ep.params, dict) else 0,
+ int(ep.id or 0),
+ ),
+ )
+ for episode in ordered_existing:
params = episode.params if isinstance(episode.params, dict) else {}
ep_no = int(params.get("episodeNumber") or 0)
item = body_by_number.get(ep_no)
if item is None:
+ for frag in episode.fragments or []:
+ series_introduced.update(extract_introduced_names_from_content(frag.content or ""))
continue
title = str(item.get("title") or episode.name)
body = str(item.get("body") or item.get("content") or "")
episode.name = title
if force or _episode_should_replace_fragments(episode, body):
- await _replace_episode_fragments(db, episode, body, assets)
+ planned = await _replace_episode_fragments(
+ db,
+ episode,
+ body,
+ assets,
+ already_introduced=series_introduced,
+ summary=summary,
+ )
+ for frag in planned:
+ series_introduced.update(
+ extract_introduced_names_from_content(str(frag.get("content") or ""))
+ )
+ else:
+ for frag in episode.fragments or []:
+ series_introduced.update(extract_introduced_names_from_content(frag.content or ""))
# 补建剧本里有、库中没有的集
existing_numbers = {
@@ -461,8 +503,18 @@ async def seed_episodes_from_script(
)
db.add(episode)
await db.flush()
- await _replace_episode_fragments(db, episode, body, assets)
-
+ planned = await _replace_episode_fragments(
+ db,
+ episode,
+ body,
+ assets,
+ already_introduced=series_introduced,
+ summary=summary,
+ )
+ for frag in planned:
+ series_introduced.update(
+ extract_introduced_names_from_content(str(frag.get("content") or ""))
+ )
await db.commit()
return await _reload_episodes(db, project.id)
@@ -472,17 +524,52 @@ async def _replace_episode_fragments(
episode: DramaEpisode,
body: str,
assets: list[DramaAsset],
-) -> None:
- # 删除旧分镜并按场次重建(一场可拆多条)
- for old in list(episode.fragments or []):
- await db.delete(old)
+ drafts: list[dict[str, Any]] | None = None,
+ already_introduced: set[str] | None = None,
+ summary: dict[str, Any] | None = None,
+ *,
+ preserve_protected: bool = False,
+ continuation: bool = False,
+) -> list[dict[str, Any]]:
+ # 删除旧分镜并重建;preserve_protected 时保留已有视频/手改分镜
+ existing = list(episode.fragments or [])
+ protected = (
+ sorted(
+ [f for f in existing if _fragment_is_protected(f)],
+ key=lambda f: int(f.sort_order or 0),
+ )
+ if preserve_protected
+ else []
+ )
+ protected_ids = {int(f.id) for f in protected}
+ for old in existing:
+ if int(old.id) not in protected_ids:
+ await db.delete(old)
await db.flush()
- drafts = build_fragments_from_episode_body(body, assets)
- for i, frag in enumerate(drafts):
+ planned = (
+ drafts
+ if drafts is not None
+ else build_fragments_from_episode_body(
+ body,
+ assets,
+ already_introduced=already_introduced,
+ summary=summary,
+ )
+ )
+ # 全量重拆时跳过与已拍前缀等量的草稿;续拆(continuation)则草稿全是后续镜
+ if protected and not continuation:
+ skip = min(len(protected), len(planned))
+ planned = planned[skip:]
+ if protected:
+ for i, frag in enumerate(protected):
+ frag.sort_order = i
+
+ base = len(protected)
+ for i, frag in enumerate(planned):
row = DramaEpisodeFragment(
episode_id=episode.id,
- sort_order=i,
+ sort_order=base + i,
content=str(frag.get("content") or ""),
duration_sec=int(frag.get("duration_sec") or 8),
params={
@@ -500,6 +587,40 @@ async def _replace_episode_fragments(
ep_params = dict(episode.params) if isinstance(episode.params, dict) else {}
ep_params["fragment_source_fp"] = _script_body_fingerprint(body)
episode.params = ep_params
+ return planned
+
+
+def resolve_episode_script_body(episode_content: Any, episode: DramaEpisode) -> str:
+ # 按 episodeNumber 从剧本 episode_content 取本集场记正文
+ ep_no = 0
+ if isinstance(episode.params, dict):
+ ep_no = int(episode.params.get("episodeNumber") or 0)
+ for item in _normalize_episode_list(episode_content):
+ if int(item.get("episodeNumber") or 0) == ep_no:
+ return str(item.get("body") or item.get("content") or "")
+ return ""
+
+
+async def replace_episode_fragments_with_drafts(
+ db: AsyncSession,
+ episode: DramaEpisode,
+ body: str,
+ assets: list[DramaAsset],
+ drafts: list[dict[str, Any]],
+ *,
+ preserve_protected: bool = True,
+ continuation: bool = False,
+) -> None:
+ # 用外部草稿(LLM)覆盖本集分镜;默认保留已生成视频/手改
+ await _replace_episode_fragments(
+ db,
+ episode,
+ body,
+ assets,
+ drafts=drafts,
+ preserve_protected=preserve_protected,
+ continuation=continuation,
+ )
def _script_body_fingerprint(body: str) -> str:
@@ -606,10 +727,17 @@ def _extract_cast_names_from_bodies(bodies: list[str]) -> list[str]:
return names
-def _character_stub_from_cast(name: str, story_type: str = "") -> dict[str, Any]:
+def _character_stub_from_cast(
+ name: str,
+ story_type: str = "",
+ summary: dict[str, Any] | None = None,
+ bodies: list[str] | None = None,
+) -> dict[str, Any]:
"""分集出场但摘要未写小传时的角色 stub(供建资产 + 后续 AI 补提示词)。"""
+ from app.services.drama.build_fragments import infer_character_intro_text
+
genre = (story_type or "").strip() or "短剧"
- return {
+ stub_params = {
"name": name,
"title": "出场人物",
"roleType": "配角",
@@ -624,6 +752,11 @@ def _character_stub_from_cast(name: str, story_type: str = "") -> dict[str, Any]
"relationships": "",
"growthArc": "出场 -> 卷入冲突 -> 结局余韵",
}
+ intro = infer_character_intro_text(name, stub_params, summary, bodies)
+ if intro:
+ stub_params["title"] = intro
+ stub_params["identityBackground"] = intro
+ return stub_params
def _normalize_episode_list(episode_content: Any) -> list[dict[str, Any]]:
diff --git a/backend/app/services/drama/voice_design.py b/backend/app/services/drama/voice_design.py
new file mode 100644
index 0000000..bf5113e
--- /dev/null
+++ b/backend/app/services/drama/voice_design.py
@@ -0,0 +1,170 @@
+"""火山引擎音色设计 API(POST /api/v3/tts/voice_design)。"""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import httpx
+
+from app.config import Settings, get_settings
+from app.services import storage
+
+logger = logging.getLogger(__name__)
+
+VOICE_DESIGN_SUCCESS_STATUS = {2, 4}
+
+
+@dataclass
+class VoiceDesignResult:
+ """音色设计接口返回摘要。"""
+
+ speaker_id: str
+ demo_audio_url: str
+ status: int
+ log_id: str
+ available_training_times: int | None = None
+
+
+# 解析控制台购买的 S_ speaker 池(逗号分隔)
+def parse_speaker_pool(raw: str) -> list[str]:
+ return [item.strip() for item in (raw or "").split(",") if item.strip().startswith("S_")]
+
+
+# 是否已配置音色设计所需凭证与 speaker 槽位
+def voice_design_enabled(settings: Settings | None = None) -> bool:
+ cfg = settings or get_settings()
+ if not parse_speaker_pool(cfg.volc_tts_voice_design_speaker_ids):
+ return False
+ if (cfg.volc_tts_api_key or "").strip():
+ return True
+ return bool((cfg.volc_tts_app_id or "").strip() and (cfg.volc_tts_access_key or "").strip())
+
+
+# 为 voice 资产选取或复用 S_ speaker 槽位
+def resolve_speaker_slot(
+ asset_id: int,
+ params: dict[str, Any] | None,
+ pool: list[str],
+) -> str:
+ blob = params if isinstance(params, dict) else {}
+ existing = str(blob.get("designedSpeakerId") or blob.get("speaker") or "").strip()
+ if existing.startswith("S_"):
+ return existing
+ if not pool:
+ raise ValueError("未配置 VOLC_TTS_VOICE_DESIGN_SPEAKER_IDS(控制台购买的 S_ 音色槽)")
+ return pool[asset_id % len(pool)]
+
+
+# 构建 voice_design 鉴权头(新版 X-Api-Key 或旧版 AppId + AccessKey)
+def build_voice_design_headers(settings: Settings) -> dict[str, str]:
+ headers = {
+ "Content-Type": "application/json",
+ "X-Api-Request-Id": str(uuid.uuid4()),
+ }
+ api_key = (settings.volc_tts_api_key or "").strip()
+ if api_key:
+ headers["X-Api-Key"] = api_key
+ return headers
+ headers["X-Api-App-Key"] = settings.volc_tts_app_id
+ headers["X-Api-Access-Key"] = settings.volc_tts_access_key
+ return headers
+
+
+# 截断文本提示词与试听台词至接口上限
+def clamp_voice_design_prompt(text_prompt: str, sample_text: str) -> tuple[str, str]:
+ prompt = (text_prompt or "").strip()[:200]
+ text = (sample_text or "").strip()[:300]
+ if not prompt:
+ raise ValueError("音色描述 text_prompt 不能为空")
+ if not text:
+ raise ValueError("试听台词 text 不能为空")
+ return prompt, text
+
+
+# 调用音色设计 HTTP 接口
+async def design_voice(
+ *,
+ speaker_id: str,
+ text_prompt: str,
+ sample_text: str,
+ image_url: str | None = None,
+ settings: Settings | None = None,
+) -> VoiceDesignResult:
+ cfg = settings or get_settings()
+ prompt, text = clamp_voice_design_prompt(text_prompt, sample_text)
+ body: dict[str, Any] = {
+ "speaker_id": speaker_id,
+ "text": text,
+ "prompt": {"text_prompt": prompt},
+ }
+ image = (image_url or "").strip()
+ if image.startswith("http://") or image.startswith("https://"):
+ body["prompt"]["image_prompt"] = {"image_url": image}
+
+ url = (cfg.volc_tts_voice_design_url or "").strip()
+ headers = build_voice_design_headers(cfg)
+
+ async with httpx.AsyncClient(timeout=180.0) as client:
+ resp = await client.post(url, headers=headers, json=body)
+
+ log_id = resp.headers.get("X-Tt-Logid", "")
+ try:
+ payload = resp.json()
+ except Exception: # noqa: BLE001
+ payload = {}
+
+ if resp.status_code >= 400:
+ code = payload.get("code")
+ message = payload.get("message") or resp.text[:400]
+ logger.error(
+ "voice_design HTTP %s code=%s logid=%s speaker=%s msg=%s",
+ resp.status_code,
+ code,
+ log_id,
+ speaker_id,
+ message,
+ )
+ raise RuntimeError(f"音色设计失败({code}): {message}")
+
+ status = int(payload.get("status") or 0)
+ designed_speaker = str(payload.get("speaker_id") or speaker_id).strip()
+ demo_audio = str(payload.get("demo_audio") or "").strip()
+
+ logger.info(
+ "voice_design ok logid=%s speaker=%s status=%s training_left=%s",
+ log_id,
+ designed_speaker,
+ status,
+ payload.get("available_training_times"),
+ )
+
+ if status not in VOICE_DESIGN_SUCCESS_STATUS:
+ raise RuntimeError(f"音色设计未完成 status={status} logid={log_id}")
+
+ if not demo_audio:
+ raise RuntimeError(f"音色设计未返回 demo_audio logid={log_id}")
+
+ return VoiceDesignResult(
+ speaker_id=designed_speaker,
+ demo_audio_url=demo_audio,
+ status=status,
+ log_id=log_id,
+ available_training_times=payload.get("available_training_times"),
+ )
+
+
+# 下载 demo_audio 到本地并返回 /static URL
+async def persist_demo_audio(
+ demo_url: str,
+ *,
+ project_id: int,
+ asset_id: int,
+) -> str:
+ dest_dir = storage.project_dir(project_id or 0)
+ dest = dest_dir / f"voice_design_{asset_id:04d}.mp3"
+ await storage.download_to(demo_url, dest)
+ return storage.publish_local(dest, sync=True)
diff --git a/backend/app/services/drama/voice_prompt.py b/backend/app/services/drama/voice_prompt.py
index 2ecc4db..0e72900 100644
--- a/backend/app/services/drama/voice_prompt.py
+++ b/backend/app/services/drama/voice_prompt.py
@@ -8,6 +8,8 @@ from typing import Any
from app.models_drama import DramaAsset, DramaProject
from app.services.drama.llm import drama_chat_text
+from app.services.drama.voice_synthesis import build_voice_sample_text
+from app.services.voices import infer_drama_speaker_from_prompt
logger = logging.getLogger(__name__)
@@ -114,8 +116,8 @@ def fallback_voice_prompt(asset: DramaAsset, summary_char: dict[str, Any] | None
async def suggest_voice_prompt_for_character(
asset: DramaAsset,
project: DramaProject,
-) -> str:
- """根据角色资产与剧本摘要生成音色描述。"""
+) -> tuple[str, str, str]:
+ """根据角色资产与剧本摘要生成音色描述、推荐 speaker 与试听台词。"""
summary = None
if project.script and isinstance(project.script.summary, dict):
summary = project.script.summary
@@ -138,4 +140,7 @@ async def suggest_voice_prompt_for_character(
prompt = normalize_voice_prompt_text(raw)
if len(prompt) < 8:
prompt = fallback_voice_prompt(asset, summary_char)
- return prompt
+ name = asset.name or "角色"
+ speaker = infer_drama_speaker_from_prompt(prompt, character_name=name, asset_id=asset.id)
+ sample_text = build_voice_sample_text(prompt, name, short=True)
+ return prompt, speaker, sample_text
diff --git a/backend/app/services/drama/voice_reference_audio.py b/backend/app/services/drama/voice_reference_audio.py
new file mode 100644
index 0000000..2376920
--- /dev/null
+++ b/backend/app/services/drama/voice_reference_audio.py
@@ -0,0 +1,288 @@
+"""参考音色音频时长:合成源头截断 + 一次性旧数据修复。"""
+
+from __future__ import annotations
+
+import logging
+import shutil
+import subprocess
+from pathlib import Path
+from typing import Any
+
+from sqlalchemy import select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.config import get_settings
+from app.models_drama import DramaAsset, DramaProject
+from app.services import storage as storage_svc
+from app.services.drama.build_seedance_generate_body import read_asset_voice_audio_url
+from app.services.ffmpeg_compose import probe_duration
+
+logger = logging.getLogger(__name__)
+
+# Seedance r2v 单条 reference_audio 上限(API 30.2s)
+SEEDANCE_REFERENCE_AUDIO_MAX_SEC = 30.0
+# 合成完成后截断目标(2–15s 即可)
+VOICE_REFERENCE_TARGET_SEC = 15.0
+
+
+# 用 ffmpeg 将音频截断至 max_sec
+def trim_audio_to_max(path: Path, max_sec: float, dest: Path | None = None) -> Path:
+ settings = get_settings()
+ ffmpeg = shutil.which(settings.ffmpeg_path) or shutil.which("ffmpeg")
+ if not ffmpeg or not path.exists():
+ return path
+ out = dest or path.with_name(f"{path.stem}_trim{path.suffix}")
+ out.parent.mkdir(parents=True, exist_ok=True)
+ proc = subprocess.run(
+ [
+ ffmpeg,
+ "-y",
+ "-i",
+ str(path),
+ "-t",
+ f"{max_sec:.3f}",
+ "-c:a",
+ "libmp3lame",
+ "-q:a",
+ "4",
+ str(out),
+ ],
+ capture_output=True,
+ text=True,
+ check=False,
+ )
+ if proc.returncode != 0:
+ logger.warning(
+ "ffmpeg 截断参考音频失败 path=%s stderr=%s",
+ path,
+ (proc.stderr or "")[:200],
+ )
+ return path
+ if out.exists() and out.stat().st_size > 500:
+ return out
+ return path
+
+
+# 合成完成后:本地参考音若超长则截断并重新发布
+def finalize_voice_reference_url(
+ url: str,
+ *,
+ project_id: int,
+ asset_id: int,
+ max_sec: float = VOICE_REFERENCE_TARGET_SEC,
+) -> str:
+ raw = (url or "").strip()
+ if not raw:
+ return raw
+ local = storage_svc.local_path_from_url(raw)
+ if local is None or not local.exists():
+ return raw
+ duration = probe_duration(local)
+ if duration is not None and duration <= max_sec:
+ return raw
+ dest = storage_svc.project_dir(project_id) / f"voice_ref_{asset_id:04d}.mp3"
+ trimmed = trim_audio_to_max(local, max_sec, dest)
+ if trimmed.resolve() == local.resolve():
+ return raw
+ published = storage_svc.publish_local(trimmed, sync=True)
+ return published or storage_svc.rel_static_url(trimmed)
+
+
+# 更新 params 内 voiceAudio / canvas.voiceAudio 的 url
+def patch_params_voice_url(params: dict[str, Any], url: str) -> dict[str, Any]:
+ next_params = dict(params)
+ binding = next_params.get("voiceAudio")
+ if isinstance(binding, dict):
+ next_params["voiceAudio"] = {**binding, "url": url}
+ canvas = next_params.get("canvas")
+ if isinstance(canvas, dict):
+ voice_binding = canvas.get("voiceAudio")
+ if isinstance(voice_binding, dict):
+ next_params["canvas"] = {**canvas, "voiceAudio": {**voice_binding, "url": url}}
+ return next_params
+
+
+def _local_duration(url: str) -> float | None:
+ local = storage_svc.local_path_from_url(url)
+ if local and local.exists():
+ return probe_duration(local)
+ return None
+
+
+def _trim_and_publish_url(
+ url: str,
+ *,
+ project_id: int,
+ asset_id: int,
+ max_sec: float = VOICE_REFERENCE_TARGET_SEC,
+) -> tuple[str, bool]:
+ """返回 (新 URL, 是否变更)。"""
+ new_url = finalize_voice_reference_url(
+ url,
+ project_id=project_id,
+ asset_id=asset_id,
+ max_sec=max_sec,
+ )
+ return new_url, new_url != url
+
+
+# 一次性修复:voice 资产、角色绑定、旁白绑定中的超长参考音
+async def backfill_long_voice_references(
+ db: AsyncSession,
+ *,
+ dry_run: bool = False,
+ limit: int = 500,
+ max_sec: float = VOICE_REFERENCE_TARGET_SEC,
+) -> dict[str, Any]:
+ stats = {
+ "ok": True,
+ "dry_run": dry_run,
+ "voice_assets_checked": 0,
+ "voice_assets_trimmed": 0,
+ "characters_updated": 0,
+ "projects_updated": 0,
+ "skipped_remote_only": 0,
+ "errors": [],
+ }
+
+ voice_rows = (
+ await db.execute(
+ select(DramaAsset)
+ .where(DramaAsset.type == "voice")
+ .order_by(DramaAsset.id.asc())
+ .limit(limit)
+ )
+ ).scalars().all()
+
+ url_by_voice_id: dict[int, str] = {}
+
+ for asset in voice_rows:
+ stats["voice_assets_checked"] += 1
+ url = (asset.url or "").strip()
+ if not url:
+ continue
+ duration = _local_duration(url)
+ if duration is not None and duration <= max_sec:
+ url_by_voice_id[asset.id] = url
+ continue
+ if storage_svc.local_path_from_url(url) is None:
+ stats["skipped_remote_only"] += 1
+ url_by_voice_id[asset.id] = url
+ continue
+ if dry_run:
+ stats["voice_assets_trimmed"] += 1
+ url_by_voice_id[asset.id] = url
+ continue
+ try:
+ new_url, changed = _trim_and_publish_url(
+ url,
+ project_id=asset.project_id,
+ asset_id=asset.id,
+ max_sec=max_sec,
+ )
+ if changed:
+ asset.url = new_url
+ asset.cover = new_url
+ params = dict(asset.params or {}) if isinstance(asset.params, dict) else {}
+ params["referenceAudioTrimmed"] = True
+ asset.params = params
+ stats["voice_assets_trimmed"] += 1
+ url_by_voice_id[asset.id] = new_url if changed else url
+ except Exception as exc: # noqa: BLE001
+ stats["errors"].append(f"voice#{asset.id}: {exc}")
+ url_by_voice_id[asset.id] = url
+
+ char_rows = (
+ await db.execute(
+ select(DramaAsset)
+ .where(DramaAsset.type == "character")
+ .order_by(DramaAsset.id.asc())
+ .limit(limit)
+ )
+ ).scalars().all()
+
+ for asset in char_rows:
+ params = dict(asset.params or {}) if isinstance(asset.params, dict) else {}
+ binding = params.get("voiceAudio")
+ if not isinstance(binding, dict):
+ continue
+ url = read_asset_voice_audio_url(params)
+ if not url:
+ continue
+ source_id = binding.get("sourceAssetId")
+ if isinstance(source_id, int) and source_id in url_by_voice_id:
+ new_url = url_by_voice_id[source_id]
+ if new_url != url:
+ if not dry_run:
+ asset.params = patch_params_voice_url(params, new_url)
+ stats["characters_updated"] += 1
+ continue
+ duration = _local_duration(url)
+ if duration is not None and duration <= max_sec:
+ continue
+ if storage_svc.local_path_from_url(url) is None:
+ stats["skipped_remote_only"] += 1
+ continue
+ if dry_run:
+ stats["characters_updated"] += 1
+ continue
+ try:
+ new_url, changed = _trim_and_publish_url(
+ url,
+ project_id=asset.project_id,
+ asset_id=asset.id,
+ max_sec=max_sec,
+ )
+ if changed:
+ asset.params = patch_params_voice_url(params, new_url)
+ stats["characters_updated"] += 1
+ except Exception as exc: # noqa: BLE001
+ stats["errors"].append(f"character#{asset.id}: {exc}")
+
+ project_rows = (await db.execute(select(DramaProject).order_by(DramaProject.id.asc()).limit(limit))).scalars().all()
+ for project in project_rows:
+ params = dict(project.params or {}) if isinstance(project.params, dict) else {}
+ narrator = params.get("narrationVoiceAudio")
+ if not isinstance(narrator, dict):
+ continue
+ url = str(narrator.get("url") or narrator.get("previewUrl") or "").strip()
+ if not url:
+ continue
+ source_id = narrator.get("sourceAssetId")
+ if isinstance(source_id, int) and source_id in url_by_voice_id:
+ new_url = url_by_voice_id[source_id]
+ if new_url != url:
+ if not dry_run:
+ params["narrationVoiceAudio"] = {**narrator, "url": new_url}
+ project.params = params
+ stats["projects_updated"] += 1
+ continue
+ duration = _local_duration(url)
+ if duration is not None and duration <= max_sec:
+ continue
+ if storage_svc.local_path_from_url(url) is None:
+ stats["skipped_remote_only"] += 1
+ continue
+ if dry_run:
+ stats["projects_updated"] += 1
+ continue
+ try:
+ new_url, changed = _trim_and_publish_url(
+ url,
+ project_id=project.id,
+ asset_id=project.id,
+ max_sec=max_sec,
+ )
+ if changed:
+ params["narrationVoiceAudio"] = {**narrator, "url": new_url}
+ project.params = params
+ stats["projects_updated"] += 1
+ except Exception as exc: # noqa: BLE001
+ stats["errors"].append(f"project#{project.id}: {exc}")
+
+ if not dry_run:
+ await db.commit()
+
+ if stats["errors"]:
+ stats["ok"] = False
+ return stats
diff --git a/backend/app/services/drama/voice_synthesis.py b/backend/app/services/drama/voice_synthesis.py
index 1bf8bf2..52564d5 100644
--- a/backend/app/services/drama/voice_synthesis.py
+++ b/backend/app/services/drama/voice_synthesis.py
@@ -1,97 +1,482 @@
-"""漫剧音色资产:根据提示词合成参考音频(供 Seedance reference_audio 使用)。"""
+"""漫剧音色资产:音色设计或 TTS 合成参考音频(供 Seedance reference_audio 使用)。"""
+
+
from __future__ import annotations
+
+
import logging
+
+import re
+
from typing import Any
+
+
from sqlalchemy.ext.asyncio import AsyncSession
+
+
from app.config import get_settings
+
from app.models import User
+
from app.models_drama import DramaAsset, DramaProject
+
from app.services.ark import get_ark
+
from app.services.billing import record_usage
+from app.services.drama.voice_design import (
+
+ design_voice,
+
+ parse_speaker_pool,
+
+ persist_demo_audio,
+
+ resolve_speaker_slot,
+
+ voice_design_enabled,
+
+)
+
+from app.services.drama.voice_reference_audio import finalize_voice_reference_url
+from app.services.voices import infer_drama_speaker_from_prompt
+
+
+
logger = logging.getLogger(__name__)
-DEFAULT_SAMPLE_TEXT = "你好,我是这个角色。请仔细听我的音色与语气。"
-# 根据音色描述推断 TTS speaker
-def infer_speaker_from_voice_prompt(voice_prompt: str) -> str:
- prompt = voice_prompt or ""
- male_kw = ("男", "少年", "大叔", "青年男", "老年男", "公子", "王爷", "少年音")
- female_kw = ("女", "少女", "女声", "温柔", "御姐", "小姐", "娘娘", "萝莉")
- if any(k in prompt for k in male_kw):
- return "zh_male_shaonianzixin_uranus_bigtts"
- if any(k in prompt for k in female_kw):
- return "zh_female_vv_uranus_bigtts"
- return "zh_female_tianmeixiaoyuan_uranus_bigtts"
+NAME_SUFFIX_PATTERN = re.compile(r"(音色|的声音|语音)$")
+
+
+
+
+
+# 从 voice 资产名还原角色名(如「禹音色」→「禹」)
+
+def normalize_character_name(name: str | None) -> str:
+
+ raw = (name or "我").strip() or "我"
+
+ return NAME_SUFFIX_PATTERN.sub("", raw).strip() or "我"
+
+
+
+
+
+# 生成 Seedance 参考音短试听句(约 2–3 秒,对齐 ai-manju)
+def build_voice_sample_line_short(character_name: str | None = None) -> str:
+ name = normalize_character_name(character_name)
+ display = name[:8] if len(name) > 8 else name
+ return f"你好,我是{display}。"
+
+
+# 生成角色差异化试听台词
+def build_voice_sample_text(
+ voice_prompt: str,
+ character_name: str | None = None,
+ *,
+ short: bool = False,
+) -> str:
+ if short:
+ return build_voice_sample_line_short(character_name)
+
+ name = normalize_character_name(character_name)
+
+ prompt = (voice_prompt or "").strip()
+
+ blob = f"{name} {prompt}"
+
+
+
+ if any(k in blob for k in ("老", "翁", "族老", "首领", "青叔")):
+
+ line = f"{name}:诸位且听我说,此事关乎两岸百姓,不可延误。"
+
+ elif any(k in blob for k in ("禹", "治水", "领袖", "帝王", "君主")):
+
+ line = f"{name}:疏堵并举,通川达海,方能安民。"
+
+ elif any(k in blob for k in ("伯益", "谋士", "儒雅", "书生")):
+
+ line = f"{name}:依我之见,当先察水势,再定工段。"
+
+ elif any(k in blob for k in ("青壮", "少年", "青年", "小伙")):
+
+ line = f"{name}:跟我上,这点工程算不了什么!"
+
+ elif any(k in blob for k in ("百姓", "群众", "平民", "妇人")):
+
+ line = f"{name}:只求河道通畅,我们也好安心过日子。"
+
+ elif any(k in blob for k in ("女", "姑娘", "少女")):
+
+ line = f"{name}:请放心,我会把情况说明白。"
+
+ elif prompt:
+
+ snippet = prompt[:36].rstrip(",。;、 ")
+
+ line = f"{name}:{snippet}。"
+
+ else:
+
+ line = f"{name}:请听我的语气与声线。"
+
+
+
+ return line[:180]
+
+
+
+
+
+# 解析可用于 voice_design image_prompt 的公网角色图 URL
+
+def resolve_character_image_url(character: DramaAsset | None) -> str | None:
+
+ if not character:
+
+ return None
+
+ from app.services import storage as storage_svc
+
+
+
+ for field in ("cover", "url"):
+
+ raw = str(getattr(character, field) or "").strip()
+
+ if not raw:
+
+ continue
+
+ if raw.startswith("https://"):
+
+ return raw
+
+ published = storage_svc.republish_url(raw, sync=True)
+
+ if published and str(published).startswith("https://"):
+
+ return str(published)
+
+ return None
+
+
+
+
+
+async def _synthesize_via_voice_design(
+
+ *,
+
+ settings,
+
+ project: DramaProject,
+
+ asset: DramaAsset,
+
+ prompt: str,
+
+ text: str,
+
+ display_name: str,
+
+ image_url: str | None,
+
+) -> tuple[str, str]:
+
+ """调用音色设计 API,返回 (audio_url, designed_speaker_id)。"""
+
+ pool = parse_speaker_pool(settings.volc_tts_voice_design_speaker_ids)
+
+ speaker_slot = resolve_speaker_slot(
+
+ asset.id,
+
+ asset.params if isinstance(asset.params, dict) else {},
+
+ pool,
+
+ )
+
+
+
+ logger.info(
+
+ "音色设计 project_id=%s asset_id=%s speaker=%s name=%s image=%s",
+
+ project.id,
+
+ asset.id,
+
+ speaker_slot,
+
+ display_name,
+
+ bool(image_url),
+
+ )
+
+
+
+ result = await design_voice(
+
+ speaker_id=speaker_slot,
+
+ text_prompt=prompt,
+
+ sample_text=text,
+
+ image_url=image_url,
+
+ settings=settings,
+
+ )
+
+ audio_url = await persist_demo_audio(
+
+ result.demo_audio_url,
+
+ project_id=project.id,
+
+ asset_id=asset.id,
+
+ )
+
+ logger.info(
+
+ "音色设计完成 project_id=%s asset_id=%s speaker=%s logid=%s url=%s",
+
+ project.id,
+
+ asset.id,
+
+ result.speaker_id,
+
+ result.log_id,
+
+ audio_url[:80],
+
+ )
+
+ return audio_url, result.speaker_id
+
-# 生成试听文案
-def build_voice_sample_text(voice_prompt: str, character_name: str | None = None) -> str:
- name = (character_name or "我").strip() or "我"
- hint = (voice_prompt or "").strip()[:120]
- if hint:
- return f"{name}:{DEFAULT_SAMPLE_TEXT}(音色:{hint})"
- return f"{name}:{DEFAULT_SAMPLE_TEXT}"
async def synthesize_voice_asset(
+
db: AsyncSession,
+
user: User,
+
project: DramaProject,
+
asset: DramaAsset,
+
*,
+
voice_prompt: str,
+
sample_text: str | None = None,
+
speaker: str | None = None,
+
+ character_name: str | None = None,
+
+ character_asset: DramaAsset | None = None,
+
) -> DramaAsset:
+
"""按提示词合成音色参考音频并写回 voice 资产。"""
+
settings = get_settings()
+
ark = get_ark()
+
prompt = (voice_prompt or "").strip()
+
if not prompt:
+
raise ValueError("缺少音色描述 prompt")
- resolved_speaker = (speaker or "").strip() or infer_speaker_from_voice_prompt(prompt)
- text = (sample_text or "").strip() or build_voice_sample_text(prompt, asset.name)
- logger.info(
- "合成音色资产 project_id=%s asset_id=%s speaker=%s text_len=%s",
- project.id,
- asset.id,
- resolved_speaker,
- len(text),
- )
- audio_url = await ark.tts(
- text,
- resolved_speaker,
+
+ display_name = normalize_character_name(character_name or asset.name)
+
+ # Seedance reference_audio 宜 2–15s;默认短句,未配槽位时走 preset TTS + 语气 context
+ text = (sample_text or "").strip() or build_voice_sample_text(prompt, display_name, short=True)
+
+ image_url = resolve_character_image_url(character_asset)
+
+
+
+ audio_url: str | None = None
+
+ resolved_speaker = (speaker or "").strip()
+
+ voice_design_meta: dict[str, Any] = {}
+
+
+
+ if voice_design_enabled(settings) and not settings.ark_mock:
+
+ try:
+
+ audio_url, designed_speaker = await _synthesize_via_voice_design(
+
+ settings=settings,
+
+ project=project,
+
+ asset=asset,
+
+ prompt=prompt,
+
+ text=text,
+
+ display_name=display_name,
+
+ image_url=image_url,
+
+ )
+
+ resolved_speaker = designed_speaker
+
+ voice_design_meta = {"voiceDesign": True, "voiceDesignStatus": "success"}
+
+ except Exception as exc: # noqa: BLE001
+
+ logger.warning(
+
+ "音色设计失败,回退 preset TTS project_id=%s asset_id=%s err=%s",
+
+ project.id,
+
+ asset.id,
+
+ exc,
+
+ )
+
+ voice_design_meta = {
+
+ "voiceDesign": True,
+
+ "voiceDesignStatus": "fallback",
+
+ "voiceDesignError": str(exc)[:500],
+
+ }
+
+
+
+ if not audio_url:
+
+ if not resolved_speaker or not resolved_speaker.startswith("S_"):
+
+ resolved_speaker = infer_drama_speaker_from_prompt(
+
+ prompt,
+
+ character_name=display_name,
+
+ asset_id=asset.id,
+
+ )
+
+ logger.info(
+
+ "合成音色资产(TTS) project_id=%s asset_id=%s speaker=%s name=%s",
+
+ project.id,
+
+ asset.id,
+
+ resolved_speaker,
+
+ display_name,
+
+ )
+
+ audio_url = await ark.tts(
+ text,
+ resolved_speaker,
+ project_id=project.id,
+ shot_no=asset.id,
+ emotion_hint=prompt,
+ )
+
+
+
+ audio_url = finalize_voice_reference_url(
+ audio_url or "",
project_id=project.id,
- shot_no=asset.id,
+ asset_id=asset.id,
)
asset.url = audio_url
+
asset.cover = asset.cover or audio_url
+
params: dict[str, Any] = dict(asset.params or {})
+
params["voicePrompt"] = prompt
+
params["sampleText"] = text
+
params["speaker"] = resolved_speaker
+
+ if resolved_speaker.startswith("S_"):
+
+ params["designedSpeakerId"] = resolved_speaker
+
+ params["characterName"] = display_name
+
+ if character_asset:
+
+ params["sourceCharacterAssetId"] = character_asset.id
+
+ params.update(voice_design_meta)
+
gen = params.get("generation") if isinstance(params.get("generation"), dict) else {}
+
params["generation"] = {**gen, "status": "done", "url": audio_url}
+
asset.params = params
+
+
await record_usage(
+
db,
+
user_id=user.id,
+
project_id=None,
+
drama_project_id=project.id,
+
billing_key="tts",
+
model=settings.model_audio,
+
estimated=True,
+
)
+
await db.commit()
+
await db.refresh(asset)
+
return asset
+
+
diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.py
index 8e68513..498968f 100644
--- a/backend/app/services/ffmpeg_compose.py
+++ b/backend/app/services/ffmpeg_compose.py
@@ -162,6 +162,47 @@ def _which(bin_name: str) -> str:
return path
+def extract_video_poster_frame(
+ video: str | Path,
+ dest: Path,
+ *,
+ at_sec: float = 0.05,
+) -> bool:
+ """从视频抽取封面帧(默认接近首帧),成功返回 True。"""
+ src = Path(video)
+ if not src.exists():
+ logger.warning("抽封面失败:视频不存在 path=%s", src)
+ return False
+ try:
+ ffmpeg = _which("ffmpeg")
+ except RuntimeError:
+ logger.warning("抽封面失败:未找到 ffmpeg")
+ return False
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ cmd = [
+ ffmpeg,
+ "-y",
+ "-ss",
+ f"{max(0.0, float(at_sec)):.3f}",
+ "-i",
+ str(src),
+ "-frames:v",
+ "1",
+ "-q:v",
+ "2",
+ str(dest),
+ ]
+ proc = subprocess.run(cmd, capture_output=True, text=True)
+ if proc.returncode != 0 or not dest.exists() or dest.stat().st_size <= 0:
+ logger.warning(
+ "抽封面失败 path=%s stderr=%s",
+ src,
+ (proc.stderr or "")[-500:],
+ )
+ return False
+ return True
+
+
def _canvas(opts: ComposeOptions) -> tuple[int, int]:
w, h = _RATIO_SIZE.get(opts.ratio, _RATIO_SIZE["16:9"])
if opts.resolution_mode == "hd":
diff --git a/backend/app/services/oss_queue.py b/backend/app/services/oss_queue.py
index 0bef4da..65345ce 100644
--- a/backend/app/services/oss_queue.py
+++ b/backend/app/services/oss_queue.py
@@ -4,9 +4,10 @@ from __future__ import annotations
import hashlib
import logging
+from typing import Any
import redis
-from sqlalchemy import update
+from sqlalchemy import String, cast, or_, select, update
from app.config import get_settings
from app.services import oss as oss_svc
@@ -17,6 +18,9 @@ logger = logging.getLogger(__name__)
_ENQUEUE_KEY = "ai_movie:oss:enqueued:{digest}"
_ENQUEUE_TTL = 7200
+# JSON params 内可能存本地媒体 URL 的字段
+_ASSET_PARAM_URL_KEYS = ("voiceAudio", "cover", "url", "image", "video")
+
def _redis() -> redis.Redis:
return redis.Redis.from_url(
@@ -71,6 +75,43 @@ def clear_enqueue_marker(local_url: str) -> None:
pass
+# 从资产 params 递归收集本地 /static URL
+def _collect_local_urls_from_params(params: Any, out: set[str]) -> None:
+ if isinstance(params, dict):
+ for key, value in params.items():
+ if key in _ASSET_PARAM_URL_KEYS and isinstance(value, str):
+ raw = value.strip()
+ if storage.is_local_static_url(raw):
+ out.add(raw)
+ else:
+ _collect_local_urls_from_params(value, out)
+ elif isinstance(params, list):
+ for item in params:
+ _collect_local_urls_from_params(item, out)
+
+
+# 将 params 内 old→new 的本地 URL 替换;有改动返回 True
+def _rewrite_local_urls_in_params(params: Any, old: str, new: str) -> bool:
+ changed = False
+ if isinstance(params, dict):
+ for key, value in list(params.items()):
+ if isinstance(value, str) and value.strip() == old:
+ params[key] = new
+ changed = True
+ elif isinstance(value, (dict, list)):
+ if _rewrite_local_urls_in_params(value, old, new):
+ changed = True
+ elif isinstance(params, list):
+ for index, item in enumerate(params):
+ if isinstance(item, str) and item.strip() == old:
+ params[index] = new
+ changed = True
+ elif isinstance(item, (dict, list)):
+ if _rewrite_local_urls_in_params(item, old, new):
+ changed = True
+ return changed
+
+
async def backfill_media_url(old_url: str, new_url: str) -> int:
"""Replace exact local URL references with OSS URL across media tables."""
old = (old_url or "").strip()
@@ -80,12 +121,15 @@ async def backfill_media_url(old_url: str, new_url: str) -> int:
from app.database import AsyncSessionLocal
from app.models import Project, Shot, Template, Work
+ from app.models_drama import DramaAsset, DramaEpisodeFragment
targets: list[tuple[type, list[str]]] = [
(Shot, ["image_url", "video_url", "audio_url"]),
(Project, ["cover_url", "final_video_url", "ref_image_url"]),
(Template, ["preview_cover"]),
(Work, ["cover_url", "video_url"]),
+ (DramaAsset, ["cover", "url"]),
+ (DramaEpisodeFragment, ["cover", "video"]),
]
changed = 0
async with AsyncSessionLocal() as db:
@@ -96,7 +140,132 @@ async def backfill_media_url(old_url: str, new_url: str) -> int:
update(model).where(col == old).values(**{field: new})
)
changed += int(result.rowcount or 0)
+
+ # 仅当 params JSON 文本含该 URL 时回写(音色 voiceAudio 等)
+ assets = (
+ await db.execute(
+ select(DramaAsset).where(
+ DramaAsset.params.is_not(None),
+ cast(DramaAsset.params, String).like(f"%{old}%"),
+ )
+ )
+ ).scalars().all()
+ for asset in assets:
+ params = asset.params
+ if not isinstance(params, dict):
+ continue
+ rewritten = dict(params)
+ if _rewrite_local_urls_in_params(rewritten, old, new):
+ asset.params = rewritten
+ changed += 1
await db.commit()
if changed:
logger.info("oss backfill %s row(s): %s → %s", changed, old, new)
return changed
+
+
+async def collect_pending_local_media_urls(*, limit: int = 2000) -> list[str]:
+ """扫描库中仍指向本地 /static 的媒体 URL(含漫剧)。"""
+ from app.database import AsyncSessionLocal
+ from app.models import Project, Shot, Template, Work
+ from app.models_drama import DramaAsset, DramaEpisodeFragment
+
+ found: set[str] = set()
+ async with AsyncSessionLocal() as db:
+ column_targets: list[tuple[type, list[str]]] = [
+ (Shot, ["image_url", "video_url", "audio_url"]),
+ (Project, ["cover_url", "final_video_url", "ref_image_url"]),
+ (Template, ["preview_cover"]),
+ (Work, ["cover_url", "video_url"]),
+ (DramaAsset, ["cover", "url"]),
+ (DramaEpisodeFragment, ["cover", "video"]),
+ ]
+ for model, fields in column_targets:
+ clauses = []
+ for field in fields:
+ col = getattr(model, field)
+ clauses.append(col.like("/static/%"))
+ clauses.append(col.like("%/static/%"))
+ rows = (await db.execute(select(model).where(or_(*clauses)))).scalars().all()
+ for row in rows:
+ for field in fields:
+ raw = (getattr(row, field) or "").strip()
+ if storage.is_local_static_url(raw):
+ found.add(raw)
+ if len(found) >= limit:
+ return sorted(found)
+
+ assets = (
+ await db.execute(
+ select(DramaAsset).where(DramaAsset.params.is_not(None))
+ )
+ ).scalars().all()
+ for asset in assets:
+ _collect_local_urls_from_params(asset.params, found)
+ if len(found) >= limit:
+ break
+ return sorted(found)[:limit]
+
+
+def upload_local_url_sync(local_url: str) -> str | None:
+ """同步上传单个本地 URL;成功返回 OSS https,失败返回 None。"""
+ url = (local_url or "").strip()
+ if not url or not storage.is_local_static_url(url):
+ return None
+ if not oss_svc.oss_enabled():
+ return None
+ path = storage.local_path_from_url(url)
+ if not path or not path.is_file():
+ logger.warning("oss backfill skip missing file %s", url)
+ return None
+ oss_url = storage.upload_local_sync(path)
+ if storage.is_local_static_url(oss_url):
+ raise RuntimeError(f"upload returned local URL for {url}")
+ return oss_url
+
+
+async def backfill_pending_local_media(*, limit: int = 500, dry_run: bool = False) -> dict[str, Any]:
+ """把库里仍是 /static 的媒体补传到 OSS 并回写 URL。"""
+ pending = await collect_pending_local_media_urls(limit=limit)
+ # uploaded / failed / skipped / changed_rows 统计
+ uploaded = 0
+ failed = 0
+ skipped = 0
+ changed_rows = 0
+ errors: list[str] = []
+
+ if dry_run:
+ return {
+ "ok": True,
+ "dry_run": True,
+ "pending": len(pending),
+ "urls": pending[:50],
+ }
+
+ if not oss_svc.oss_enabled():
+ return {"ok": False, "error": "OSS disabled", "pending": len(pending)}
+
+ for local_url in pending:
+ try:
+ oss_url = upload_local_url_sync(local_url)
+ if not oss_url:
+ skipped += 1
+ continue
+ changed_rows += await backfill_media_url(local_url, oss_url)
+ clear_enqueue_marker(local_url)
+ uploaded += 1
+ logger.info("oss pending backfill ok %s → %s", local_url, oss_url)
+ except Exception as exc: # noqa: BLE001
+ failed += 1
+ errors.append(f"{local_url}: {exc}"[:240])
+ logger.exception("oss pending backfill failed %s", local_url)
+
+ return {
+ "ok": failed == 0,
+ "pending": len(pending),
+ "uploaded": uploaded,
+ "skipped": skipped,
+ "failed": failed,
+ "changed_rows": changed_rows,
+ "errors": errors[:20],
+ }
diff --git a/backend/app/services/seedance_segments.py b/backend/app/services/seedance_segments.py
index 91bccd2..a4d5ce1 100644
--- a/backend/app/services/seedance_segments.py
+++ b/backend/app/services/seedance_segments.py
@@ -17,10 +17,164 @@ SHOT_DURATION_MAX = 30
DURATION_TOKEN_RE = re.compile(r"@duration:(\d+)")
NARRATION_PREFIX = "【旁白·慢速清晰·同步字幕】"
+DIALOGUE_PREFIX = "【对白·慢速清晰·同步字幕】"
+VISUAL_PREFIX = "【画面·无配音仅环境音】"
+EMPTY_SHOT_PREFIX = "【空镜·可仅环境音与 BGM】"
SUBTITLE_CUE = "【字幕:全程简体中文字幕,旁白逐句同步烧录】"
+DRAMA_SUBTITLE_CUE = "【字幕:底部居中·简体中文·逐句轮换·与口播同步】"
+# 历史 cue,提交前统一替换为现行文案
+LEGACY_DRAMA_SUBTITLE_CUES = (
+ "【字幕:底部居中·简体中文·仅标记段落同步】",
+ "【字幕:底部居中·简体中文】",
+)
DEFAULT_BGM_MOOD = "贴合内容的轻量配乐,情绪平稳,不抢旁白"
SEEDANCE_PRODUCTION_SECTION_HEADER = "【强制约束:音频、字幕与配乐】"
+# 空镜/景别冒号标签:正文若以此开头则不得配音、不得烧字幕
+VISUAL_SHOT_LABEL_RE = re.compile(
+ r"^(?:"
+ r"空镜|画面|远景|近景|中景|全景|特写|大特写|"
+ r"跟拍|俯拍|仰拍|航拍|推镜|拉镜|摇镜|环境|镜头|动作|转场|闪回|"
+ r"建立镜头|气氛镜头"
+ r")\s*[::]"
+)
+VOICE_CUE_PREFIX_RE = re.compile(
+ r"^【(?:对白|旁白|内心独白)[^】]*】\s*"
+)
+
+PRODUCTION_META_PREFIXES = (
+ "【字幕",
+ "【BGM",
+ "【人物介绍",
+ "【片头",
+ "【背景介绍",
+ "【强制约束",
+)
+
+
+def is_production_meta_line(line: str) -> bool:
+ stripped = (line or "").strip()
+ return any(stripped.startswith(prefix) for prefix in PRODUCTION_META_PREFIXES)
+
+
+def _strip_voice_cue_prefix(line: str) -> str:
+ # 去掉对白/旁白/内心独白前缀
+ return VOICE_CUE_PREFIX_RE.sub("", (line or "").strip()).strip()
+
+
+def is_visual_description_body(text: str) -> bool:
+ # 判断正文是否为纯画面/空镜描写(不含配音意图)
+ body = _strip_voice_cue_prefix(text or "").strip()
+ body = re.sub(r"^【(?:画面|空镜)[^】]*】\s*", "", body).strip()
+ if not body:
+ return False
+ if VISUAL_SHOT_LABEL_RE.match(body):
+ return True
+ if body.startswith("空镜") or body.startswith("△") or body.startswith("Δ"):
+ return True
+ return False
+
+
+def normalize_drama_subtitle_cue(content: str) -> str:
+ """将历史字幕 cue 统一为现行「逐句轮换」文案。"""
+ text = content or ""
+ for old in LEGACY_DRAMA_SUBTITLE_CUES:
+ if old in text:
+ text = text.replace(old, DRAMA_SUBTITLE_CUE)
+ return text
+
+
+def normalize_character_intro_cue(content: str) -> str:
+ """将历史人物介绍 cue 统一为「角色身旁」定位。"""
+ # 负向前瞻:已是「·角色身旁」的不二次替换
+ return re.sub(
+ r"【人物介绍·画面叠字】(?!·角色身旁)",
+ "【人物介绍·画面叠字·角色身旁】",
+ content or "",
+ )
+
+
+def rewrite_misclassified_visual_voice_lines(content: str) -> str:
+ """
+ 纠正「空镜:…」等被误打成对白/旁白前缀的行。
+ 供 Seedance 提交前兜底,使旧分镜也能按画面-only 约束生成。
+ """
+ text = normalize_character_intro_cue(normalize_drama_subtitle_cue(content))
+ out: list[str] = []
+ for raw in text.replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if not line:
+ out.append(raw)
+ continue
+ if line.startswith("@duration:") or is_production_meta_line(line):
+ out.append(raw)
+ continue
+ if VOICE_CUE_PREFIX_RE.match(line) and is_visual_description_body(line):
+ body = _strip_voice_cue_prefix(line)
+ out.append(f"{VISUAL_PREFIX}{body}")
+ continue
+ out.append(raw)
+ return "\n".join(out)
+
+
+def script_has_narration_cue(content: str) -> bool:
+ """检测脚本是否含旁白 cue(忽略字幕/BGM 等元数据行)。"""
+ for raw in (content or "").replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if not line or line.startswith("@duration:") or is_production_meta_line(line):
+ continue
+ if is_visual_description_body(line):
+ continue
+ if NARRATION_PREFIX in line or line.startswith("【旁白"):
+ return True
+ return False
+
+
+def script_has_dialogue_cue(content: str) -> bool:
+ """检测脚本是否含对白 cue。"""
+ for raw in (content or "").replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if not line or line.startswith("@duration:") or is_production_meta_line(line):
+ continue
+ if is_visual_description_body(line):
+ continue
+ if DIALOGUE_PREFIX in line or line.startswith("【对白"):
+ return True
+ return False
+
+
+def script_is_drama_mixed(segment_script: str) -> bool:
+ """漫剧混排:画面描述 + 对白/旁白分段,而非整镜旁白。"""
+ content = segment_script or ""
+ if script_has_visual_only_cue(content):
+ return True
+ if script_has_dialogue_cue(content):
+ return True
+ if DRAMA_SUBTITLE_CUE in content:
+ return True
+ if "仅标记段落同步" in content:
+ return True
+ if "逐句轮换" in content:
+ return True
+ if "对白旁白同步" in content:
+ return True
+ return False
+
+
+def script_has_visual_only_cue(content: str) -> bool:
+ """检测脚本是否含画面描述 cue(漫剧混排)。"""
+ for raw in (content or "").replace("\r\n", "\n").split("\n"):
+ line = raw.strip()
+ if (
+ line.startswith(VISUAL_PREFIX)
+ or line.startswith("【画面·")
+ or line.startswith("【空镜")
+ or EMPTY_SHOT_PREFIX in line
+ or is_visual_description_body(line)
+ ):
+ return True
+ return False
+
BGM_MOOD_KEYWORDS: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"紧张|危机|压迫|悬疑"), "低沉紧张、鼓点渐强,烘托压迫感,音量低于人声"),
(re.compile(r"温暖|人文|故事|情感"), "温暖人文、钢琴弦乐铺底,音量低于人声"),
@@ -85,23 +239,11 @@ def build_production_cues(bgm_mood: str) -> list[str]:
return [SUBTITLE_CUE, f"【BGM:{mood}】"]
-def script_has_narration_cue(content: str) -> bool:
- """检测脚本是否含旁白 cue / 旁白前缀。"""
- for raw in (content or "").replace("\r\n", "\n").split("\n"):
- line = raw.strip()
- if not line or line.startswith("@duration:"):
- continue
- if NARRATION_PREFIX in line or line.startswith("【旁白"):
- return True
- if "旁白" in line[:24]:
- return True
- return False
-
-
def build_seedance_production_section(segment_script: str) -> str:
- """组装科普版 Seedance 音频/字幕/BGM 强制约束(对齐漫剧子集,无人物介绍/@asset)。"""
- # has_vo 脚本是否含旁白
+ """组装 Seedance 音频/字幕/BGM 强制约束(科普旁白 / 漫剧画面+对白混排)。"""
has_vo = script_has_narration_cue(segment_script)
+ has_dialogue = script_has_dialogue_cue(segment_script)
+ drama_mixed = script_is_drama_mixed(segment_script)
# bgm_mood 从脚本 BGM cue 或正文推断
bgm_mood = DEFAULT_BGM_MOOD
for raw in (segment_script or "").replace("\r\n", "\n").split("\n"):
@@ -117,7 +259,47 @@ def build_seedance_production_section(segment_script: str) -> str:
if "音量低于人声" not in bgm_mood:
bgm_mood = f"{bgm_mood},音量低于人声"
- # lines 约束条目
+ if drama_mixed:
+ lines = [
+ "1. 配音范围:仅【旁白·…】【对白·…】标记的段落需要口播;"
+ "【画面·…】标记或未带配音前缀的段落为画面/动作描述,只呈现视觉与环境音,"
+ "禁止为其生成配音、禁止烧字幕、禁止把画面描述念出来。",
+ "2. 语速:旁白/对白语速自然偏慢,吐字清晰,留有呼吸与停顿;严禁加速赶词。",
+ "3. 字幕:仅【旁白·…】【对白·…】口播内容烧录简体中文字幕,底部居中;"
+ "同一时刻只显示一行(一句),随口播进度逐句轮换,禁止把整段对白一次性叠满屏幕;"
+ "禁止重复字、叠字、口吃式重复;字幕必须与当前正在说的那一句逐字一致;"
+ "画面描述段不出现字幕。",
+ ]
+ if has_vo:
+ lines.append(
+ "4. 旁白:【旁白·…】段落以第三人称旁白慢速清晰配音;"
+ "字幕逐句轮换,与当前口播句同步。"
+ )
+ elif has_dialogue:
+ lines.append(
+ "4. 对白:【对白·…】段落按角色对白配音;"
+ "字幕逐句轮换,与当前口播句同步;无对白标记时保持环境音即可。"
+ )
+ else:
+ lines.append(
+ "4. 人声:本镜若无旁白/对白标记,则全程无口播,仅环境音与 BGM。"
+ )
+ lines.append(
+ f"5. 背景音乐:{bgm_mood};BGM 音量低于人声约 30%。"
+ )
+ lines.append(
+ "6. 音效:环境音与动作音效与画面同步,层次低于人声。"
+ )
+ if "【人物介绍" in (segment_script or ""):
+ lines.append(
+ "7. 人物介绍叠字:【人物介绍·画面叠字·角色身旁】须贴在对应角色身旁"
+ "(肩侧/身旁小字),随该角色首次入画短暂出现;"
+ "禁止居中大标题、禁止底部与口播字幕抢位;"
+ "禁止口播念出介绍全文。"
+ )
+ return f"{SEEDANCE_PRODUCTION_SECTION_HEADER}\n" + "\n".join(lines)
+
+ # 科普旁白模式:整镜以旁白段为主
lines = [
"1. 语速:旁白语速自然偏慢,吐字清晰,留有呼吸与停顿;严禁加速赶词、压缩台词或提高播放倍速。",
"2. 字幕:全程烧录简体中文字幕,位置底部居中,字号清晰可读;旁白须逐句同步显示,字幕与口播一致。",
diff --git a/backend/app/services/voices.py b/backend/app/services/voices.py
index 9af404e..1342d0b 100644
--- a/backend/app/services/voices.py
+++ b/backend/app/services/voices.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import hashlib
from typing import Any
# id used in API / project.voice_id; speaker is openspeech speaker id
@@ -30,14 +31,101 @@ VOICE_PRESETS: list[dict[str, Any]] = [
"gender": "female",
"speaker": "zh_female_vv_uranus_bigtts",
},
+ {
+ "id": "zh_female_xiaohe_uranus_bigtts",
+ "label": "小何 · 通用女声",
+ "gender": "female",
+ "speaker": "zh_female_xiaohe_uranus_bigtts",
+ },
{
"id": "zh_male_shaonianzixin_uranus_bigtts",
"label": "少年梓辛 · 男声",
"gender": "male",
"speaker": "zh_male_shaonianzixin_uranus_bigtts",
},
+ {
+ "id": "zh_male_m191_uranus_bigtts",
+ "label": "云舟 · 稳重男声",
+ "gender": "male",
+ "speaker": "zh_male_m191_uranus_bigtts",
+ },
+ {
+ "id": "zh_male_taocheng_uranus_bigtts",
+ "label": "小天 · 年轻男声",
+ "gender": "male",
+ "speaker": "zh_male_taocheng_uranus_bigtts",
+ },
+ {
+ "id": "zh_male_ruyayichen_uranus_bigtts",
+ "label": "儒雅逸辰 · 男声",
+ "gender": "male",
+ "speaker": "zh_male_ruyayichen_uranus_bigtts",
+ },
+ {
+ "id": "zh_male_baqiqingshu_uranus_bigtts",
+ "label": "霸气青叔 · 男声",
+ "gender": "male",
+ "speaker": "zh_male_baqiqingshu_uranus_bigtts",
+ },
+]
+
+# 漫剧角色音色:按关键词为不同角色匹配不同 speaker(避免全员同一声线)
+DRAMA_SPEAKER_RULES: list[dict[str, Any]] = [
+ {
+ "speaker": "zh_male_baqiqingshu_uranus_bigtts",
+ "gender": "male",
+ "keywords": ("老", "翁", "族老", "长者", "首领", "青叔", "大叔", "沉稳", "威严", "苍", "应龙"),
+ },
+ {
+ "speaker": "zh_male_m191_uranus_bigtts",
+ "gender": "male",
+ "keywords": ("领袖", "帝王", "君主", "大王", "治水", "禹", "庄重", "浑厚", "史诗", "统帅"),
+ },
+ {
+ "speaker": "zh_male_ruyayichen_uranus_bigtts",
+ "gender": "male",
+ "keywords": ("儒雅", "书生", "谋士", "伯益", "文士", "智", "温和", "清朗", "参谋"),
+ },
+ {
+ "speaker": "zh_male_shaonianzixin_uranus_bigtts",
+ "gender": "male",
+ "keywords": ("少年", "青年", "青壮", "小伙", "活力", "清亮", "少年音", "梓辛"),
+ },
+ {
+ "speaker": "zh_male_taocheng_uranus_bigtts",
+ "gender": "male",
+ "keywords": ("年轻", "小哥", "明快", "阳光", "清爽"),
+ },
+ {
+ "speaker": "zh_female_vv_uranus_bigtts",
+ "gender": "female",
+ "keywords": ("国风", "古风", "神话", "御姐", "女王", "仙", "神女"),
+ },
+ {
+ "speaker": "zh_female_shuangkuaisisi_uranus_bigtts",
+ "gender": "female",
+ "keywords": ("爽快", "利落", "都市", "干练", "清脆"),
+ },
+ {
+ "speaker": "zh_female_tianmeixiaoyuan_uranus_bigtts",
+ "gender": "female",
+ "keywords": ("温柔", "甜美", "柔和", "亲和", "少女", "姑娘"),
+ },
+ {
+ "speaker": "zh_female_xiaohe_uranus_bigtts",
+ "gender": "female",
+ "keywords": ("通用", "百姓", "群众", "平民", "村妇", "妇人"),
+ },
+ {
+ "speaker": "zh_female_cancan_uranus_bigtts",
+ "gender": "female",
+ "keywords": ("旁白", "解说", "叙述", "播报"),
+ },
]
+MALE_HINTS = ("男", "少年", "青年男", "老年男", "公子", "王爷", "少年音", "大叔", "青壮", "将", "伯", "公")
+FEMALE_HINTS = ("女", "少女", "女声", "御姐", "小姐", "娘娘", "萝莉", "姑娘", "妇人", "村妇")
+
# Template audio_config.voice_preset aliases → speaker
VOICE_ALIASES: dict[str, str] = {
"narrator_calm": "zh_female_cancan_uranus_bigtts",
@@ -67,6 +155,51 @@ def resolve_speaker(voice_id: str | None, *, template_preset: str | None = None)
return raw
+# 推断漫剧角色应使用的 TTS speaker(多声线 + 稳定哈希打散同分候选)
+def infer_drama_speaker_from_prompt(
+ voice_prompt: str,
+ *,
+ character_name: str = "",
+ asset_id: int = 0,
+) -> str:
+ prompt = f"{character_name} {voice_prompt or ''}"
+ male_score = sum(1 for k in MALE_HINTS if k in prompt)
+ female_score = sum(1 for k in FEMALE_HINTS if k in prompt)
+ if male_score > female_score:
+ gender = "male"
+ elif female_score > male_score:
+ gender = "female"
+ else:
+ gender = "male" if asset_id % 2 else "female"
+
+ scored: list[tuple[int, str]] = []
+ for rule in DRAMA_SPEAKER_RULES:
+ if rule["gender"] != gender:
+ continue
+ score = sum(1 for kw in rule["keywords"] if kw in prompt)
+ if score > 0:
+ scored.append((score, str(rule["speaker"])))
+
+ if not scored:
+ pool = [str(r["speaker"]) for r in DRAMA_SPEAKER_RULES if r["gender"] == gender]
+ if not pool:
+ return "zh_female_cancan_uranus_bigtts"
+ digest = hashlib.md5(f"{asset_id}:{character_name}:{voice_prompt}".encode()).hexdigest()
+ return pool[int(digest[:8], 16) % len(pool)]
+
+ max_score = max(s for s, _ in scored)
+ top = [speaker for s, speaker in scored if s == max_score]
+ if len(top) == 1:
+ return top[0]
+ digest = hashlib.md5(f"{asset_id}:{character_name}".encode()).hexdigest()
+ return top[int(digest[:8], 16) % len(top)]
+
+
+# 兼容旧调用
+def infer_speaker_from_voice_prompt(voice_prompt: str, *, character_name: str = "", asset_id: int = 0) -> str:
+ return infer_drama_speaker_from_prompt(voice_prompt, character_name=character_name, asset_id=asset_id)
+
+
PREVIEW_TEXT = "大家好,这是当前音色的试听效果,适合科普短视频旁白讲解。"
diff --git a/backend/app/workers/autoscale.py b/backend/app/workers/autoscale.py
index 45ddc5f..ac8b5ba 100644
--- a/backend/app/workers/autoscale.py
+++ b/backend/app/workers/autoscale.py
@@ -53,10 +53,11 @@ class CeleryAutoscaler:
self.poll_sec = max(2.0, float(self.settings.celery_autoscale_poll_sec))
self.scale_down_sec = max(5.0, float(self.settings.celery_autoscale_idle_sec))
self.queue = (self.settings.celery_autoscale_queue or QUEUE_NAME).strip() or QUEUE_NAME
- # Always also consume OSS upload queue so async media publish is processed.
+ # Always also consume OSS + 漫剧视频队列,避免被资产生图堵住
queues = [q.strip() for q in self.queue.split(",") if q.strip()]
- if "oss" not in queues:
- queues.append("oss")
+ for extra in ("oss", "video"):
+ if extra not in queues:
+ queues.append(extra)
self.worker_queues = ",".join(queues)
self.host = socket.gethostname().split(".")[0]
self.workers: dict[int, WorkerProc] = {}
@@ -85,10 +86,11 @@ class CeleryAutoscaler:
def queue_load(self) -> tuple[int, int, int]:
"""Return (pending, unacked, load)."""
pending = int(self._redis.llen(self.queue) or 0)
- try:
- pending += int(self._redis.llen("oss") or 0)
- except Exception: # noqa: BLE001
- pass
+ for extra_q in ("oss", "video"):
+ try:
+ pending += int(self._redis.llen(extra_q) or 0)
+ except Exception: # noqa: BLE001
+ pass
try:
unacked = int(self._redis.hlen("unacked") or 0)
except Exception: # noqa: BLE001
diff --git a/backend/app/workers/celery_app.py b/backend/app/workers/celery_app.py
index 003a872..5306176 100644
--- a/backend/app/workers/celery_app.py
+++ b/backend/app/workers/celery_app.py
@@ -36,7 +36,8 @@ celery_app.conf.update(
"app.workers.tasks.upload_media_task": {"queue": "oss"},
"drama.script_summary": {"queue": "pipeline"},
"drama.episode_scripts": {"queue": "pipeline"},
- "drama.episode_generate": {"queue": "pipeline"},
+ # 分镜视频独立队列,避免被资产生图堵在 pipeline 后面
+ "drama.episode_generate": {"queue": "video"},
"drama.asset_image": {"queue": "pipeline"},
},
)
diff --git a/backend/app/workers/drama_tasks.py b/backend/app/workers/drama_tasks.py
index 10ce693..5268241 100644
--- a/backend/app/workers/drama_tasks.py
+++ b/backend/app/workers/drama_tasks.py
@@ -41,6 +41,26 @@ def drama_episode_scripts_task(self, project_id: int, force: bool = False) -> di
return result
+@celery_app.task(name="drama.episode_fragment_plan", bind=True, max_retries=1)
+def drama_episode_fragment_plan_task(
+ self,
+ episode_id: int,
+ fallback_rules: bool = True,
+) -> dict:
+ # Celery:单集 LLM 分镜
+ from app.services.drama.jobs import run_episode_fragment_plan_job
+
+ logger.info(
+ "[Celery] 领取单集分镜任务 episode_id=%s fallback=%s task_id=%s",
+ episode_id,
+ fallback_rules,
+ self.request.id,
+ )
+ result = _run(run_episode_fragment_plan_job(episode_id, fallback_rules=fallback_rules))
+ logger.info("[Celery] 单集分镜任务结束 episode_id=%s result=%s", episode_id, result)
+ return result
+
+
@celery_app.task(name="drama.episode_generate", bind=True, max_retries=1)
def drama_episode_generate_task(
self,
diff --git a/backend/scripts/backfill_oss_media.py b/backend/scripts/backfill_oss_media.py
new file mode 100644
index 0000000..d022815
--- /dev/null
+++ b/backend/scripts/backfill_oss_media.py
@@ -0,0 +1,41 @@
+"""把库中仍为 /static 的媒体补传到 OSS 并回写 URL。
+
+用法(在 backend 目录):
+ .\\.venv\\Scripts\\python -m scripts.backfill_oss_media
+ .\\.venv\\Scripts\\python -m scripts.backfill_oss_media --dry-run
+ .\\.venv\\Scripts\\python -m scripts.backfill_oss_media --limit 100
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import sys
+from pathlib import Path
+
+BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(BACKEND_ROOT))
+
+
+# 解析 CLI 并执行补传
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Backfill local /static media to OSS")
+ parser.add_argument("--limit", type=int, default=500, help="最多处理多少条本地 URL")
+ parser.add_argument("--dry-run", action="store_true", help="只列出待补传,不上传")
+ args = parser.parse_args()
+
+ from app.logging_setup import configure_logging
+ from app.services.oss_queue import backfill_pending_local_media
+
+ configure_logging(level="INFO", sql_echo=False)
+ result = asyncio.run(
+ backfill_pending_local_media(limit=max(1, args.limit), dry_run=bool(args.dry_run))
+ )
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0 if result.get("ok") else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/backend/scripts/backfill_voice_reference_audio.py b/backend/scripts/backfill_voice_reference_audio.py
new file mode 100644
index 0000000..1939efd
--- /dev/null
+++ b/backend/scripts/backfill_voice_reference_audio.py
@@ -0,0 +1,46 @@
+"""一次性修复超长 reference_audio(截断至 15s 并回写绑定)。
+
+用法(在 backend 目录):
+ .\\.venv\\Scripts\\python -m scripts.backfill_voice_reference_audio
+ .\\.venv\\Scripts\\python -m scripts.backfill_voice_reference_audio --dry-run
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import sys
+from pathlib import Path
+
+BACKEND_ROOT = Path(__file__).resolve().parents[1]
+if str(BACKEND_ROOT) not in sys.path:
+ sys.path.insert(0, str(BACKEND_ROOT))
+
+
+async def _run(*, dry_run: bool, limit: int) -> dict:
+ from app import models # noqa: F401
+ from app import models_drama # noqa: F401
+ from app.database import AsyncSessionLocal
+ from app.services.drama.voice_reference_audio import backfill_long_voice_references
+
+ async with AsyncSessionLocal() as db:
+ return await backfill_long_voice_references(db, dry_run=dry_run, limit=limit)
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description="Backfill long voice reference audio")
+ parser.add_argument("--limit", type=int, default=2000, help="每类资产最多处理条数")
+ parser.add_argument("--dry-run", action="store_true", help="只统计,不写库")
+ args = parser.parse_args()
+
+ from app.logging_setup import configure_logging
+
+ configure_logging(level="INFO", sql_echo=False)
+ result = asyncio.run(_run(dry_run=bool(args.dry_run), limit=max(1, args.limit)))
+ print(json.dumps(result, ensure_ascii=False, indent=2))
+ return 0 if result.get("ok") else 1
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/backend/scripts/resplit_episode_overlong_fragments.py b/backend/scripts/resplit_episode_overlong_fragments.py
new file mode 100644
index 0000000..e13cdae
--- /dev/null
+++ b/backend/scripts/resplit_episode_overlong_fragments.py
@@ -0,0 +1,188 @@
+"""将指定分集中 @duration 合计 >30s 的分镜按软/硬上限拆开并写回库。"""
+from __future__ import annotations
+
+import json
+import re
+import sqlite3
+from pathlib import Path
+
+from app.services.drama.build_fragments import (
+ FRAGMENT_TOTAL_MAX,
+ split_overlong_fragment_content,
+)
+
+DB = Path(__file__).resolve().parents[1] / "ai_movie.db"
+ASSET_RE = re.compile(r"@asset:(\d+)")
+DURATION_RE = re.compile(r"@duration:(\d+)")
+
+
+def sum_duration(content: str) -> int:
+ return sum(int(m) for m in DURATION_RE.findall(content or ""))
+
+
+def extract_asset_ids(content: str) -> list[int]:
+ seen: set[int] = set()
+ out: list[int] = []
+ for m in ASSET_RE.finditer(content or ""):
+ aid = int(m.group(1))
+ if aid and aid not in seen:
+ seen.add(aid)
+ out.append(aid)
+ return out
+
+
+def find_episode_id(conn: sqlite3.Connection, episode_number: int = 2) -> int:
+ rows = conn.execute(
+ "SELECT id, name, params FROM drama_episodes ORDER BY id"
+ ).fetchall()
+ for row in rows:
+ try:
+ params = json.loads(row["params"] or "{}")
+ except Exception:
+ params = {}
+ if int(params.get("episodeNumber") or params.get("episode_number") or 0) == episode_number:
+ return int(row["id"])
+ raise SystemExit(f"未找到第 {episode_number} 集")
+
+
+def main() -> None:
+ conn = sqlite3.connect(DB)
+ conn.row_factory = sqlite3.Row
+ episode_id = find_episode_id(conn, 2)
+ frags = conn.execute(
+ """
+ SELECT id, sort_order, duration_sec, content, cover, video, params
+ FROM drama_episode_fragments
+ WHERE episode_id=?
+ ORDER BY sort_order, id
+ """,
+ (episode_id,),
+ ).fetchall()
+
+ # old_id -> asset_ids
+ ref_map: dict[int, list[int]] = {}
+ for f in frags:
+ rows = conn.execute(
+ "SELECT asset_id FROM drama_fragment_asset_refs WHERE fragment_id=? ORDER BY id",
+ (f["id"],),
+ ).fetchall()
+ ref_map[int(f["id"])] = [int(r["asset_id"]) for r in rows]
+
+ rebuilt: list[dict] = []
+ split_count = 0
+ for f in frags:
+ content = f["content"] or ""
+ total = sum_duration(content)
+ params = {}
+ try:
+ params = json.loads(f["params"] or "{}") if f["params"] else {}
+ except Exception:
+ params = {}
+ if not isinstance(params, dict):
+ params = {}
+
+ if total <= FRAGMENT_TOTAL_MAX:
+ rebuilt.append(
+ {
+ "content": content,
+ "cover": f["cover"] or "",
+ "video": f["video"] or "",
+ "duration_sec": int(f["duration_sec"] or total or 8),
+ "params": params,
+ "asset_ids": ref_map.get(int(f["id"])) or extract_asset_ids(content),
+ }
+ )
+ continue
+
+ chunks = split_overlong_fragment_content(content)
+ if len(chunks) <= 1:
+ rebuilt.append(
+ {
+ "content": content,
+ "cover": f["cover"] or "",
+ "video": f["video"] or "",
+ "duration_sec": min(FRAGMENT_TOTAL_MAX, total),
+ "params": params,
+ "asset_ids": ref_map.get(int(f["id"])) or extract_asset_ids(content),
+ }
+ )
+ continue
+
+ split_count += 1
+ print(
+ f"split frag sort={f['sort_order']} id={f['id']} {total}s -> "
+ f"{[d for _, d in chunks]}"
+ )
+ for idx, (chunk_content, chunk_dur) in enumerate(chunks):
+ chunk_params = {
+ **params,
+ "user_edited": True,
+ "resplit_from": int(f["id"]),
+ "resplit_index": idx,
+ }
+ # 拆开后旧成片不再对应,清空 video;封面仅保留首块
+ chunk_cover = (f["cover"] or "") if idx == 0 else ""
+ asset_ids = extract_asset_ids(chunk_content)
+ if not asset_ids:
+ asset_ids = list(ref_map.get(int(f["id"])) or [])
+ rebuilt.append(
+ {
+ "content": chunk_content,
+ "cover": chunk_cover,
+ "video": "",
+ "duration_sec": chunk_dur,
+ "params": chunk_params,
+ "asset_ids": asset_ids,
+ }
+ )
+
+ if split_count == 0:
+ print("没有需要拆分的超长分镜")
+ return
+
+ # 事务:删旧分镜(级联删 refs)再插入
+ cur = conn.cursor()
+ cur.execute("BEGIN")
+ try:
+ cur.execute(
+ "DELETE FROM drama_episode_fragments WHERE episode_id=?",
+ (episode_id,),
+ )
+ for order, item in enumerate(rebuilt):
+ cur.execute(
+ """
+ INSERT INTO drama_episode_fragments
+ (episode_id, sort_order, content, cover, video, duration_sec, params)
+ VALUES (?, ?, ?, ?, ?, ?, ?)
+ """,
+ (
+ episode_id,
+ order,
+ item["content"],
+ item["cover"],
+ item["video"],
+ item["duration_sec"],
+ json.dumps(item["params"], ensure_ascii=False),
+ ),
+ )
+ frag_id = cur.lastrowid
+ for aid in item["asset_ids"]:
+ cur.execute(
+ """
+ INSERT OR IGNORE INTO drama_fragment_asset_refs (fragment_id, asset_id)
+ VALUES (?, ?)
+ """,
+ (frag_id, aid),
+ )
+ conn.commit()
+ except Exception:
+ conn.rollback()
+ raise
+
+ print(f"done episode_id={episode_id} fragments={len(rebuilt)} split_sources={split_count}")
+ for order, item in enumerate(rebuilt):
+ print(f" #{order} duration={item['duration_sec']}s assets={item['asset_ids']}")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/backend/tests/test_build_fragments.py b/backend/tests/test_build_fragments.py
index ca84789..f8c35cc 100644
--- a/backend/tests/test_build_fragments.py
+++ b/backend/tests/test_build_fragments.py
@@ -1,8 +1,13 @@
-"""分镜切分:场内按时长二次拆条。"""
+"""分镜切分:场内按时长二次拆条;人物介绍按首次出场注入。"""
+
+from types import SimpleNamespace
from app.services.drama.build_fragments import (
FRAGMENT_SOFT_MAX,
FRAGMENT_TOTAL_MAX,
+ _is_important_character,
+ _resolve_character_intro_text,
+ build_character_binding,
build_fragments_from_episode_body,
plan_fragments_from_scene,
)
@@ -19,7 +24,9 @@ def test_long_scene_splits_into_multiple_fragments():
body,
{"sceneName": "羽山刑场", "characterNames": ["禹"]},
scene_asset_id=1,
- character_bindings=[{"name": "禹", "assetId": 2, "introText": "治水"}],
+ character_bindings=[
+ {"name": "禹", "assetId": 2, "introText": "治水英雄", "important": True},
+ ],
)
assert len(chunks) >= 2
@@ -27,17 +34,196 @@ def test_long_scene_splits_into_multiple_fragments():
assert duration <= FRAGMENT_TOTAL_MAX
assert "@duration:" in content
assert "【字幕" in content
- # 首条应含人物介绍;后续可不含
- assert "【人物介绍" in chunks[0][0]
+ # 首条应含人物介绍;后续跨镜不再重复
+ intro_hits = [c for c, _ in chunks if "【人物介绍·画面叠字·角色身旁】禹|治水英雄" in c]
+ assert len(intro_hits) == 1
assert all(d <= FRAGMENT_SOFT_MAX or True for _, d in chunks)
def test_build_fragments_one_scene_header_can_yield_many():
narrative = "\n".join(
- [f"旁白(VO):第{i}段旁白内容用来累计时长超过三十秒的阈值。" for i in range(15)]
+ [f"旁白(VO):第{i}段旁白内容用来累计时长超过三十秒的填充。" for i in range(15)]
)
content = f"### 场1-1\n日外 大河\n出场人物:无\n{narrative}"
drafts = build_fragments_from_episode_body(content, [])
assert len(drafts) >= 2
total = sum(int(d["duration_sec"]) for d in drafts)
assert total > FRAGMENT_TOTAL_MAX
+
+
+def test_intro_only_on_first_appearance_across_scenes():
+ # 跨场同一重要角色只介绍一次;次要群体角色不介绍
+ assets = [
+ SimpleNamespace(
+ id=1,
+ type="character",
+ name="鲧",
+ params={"title": "治水先驱", "roleType": "主角"},
+ ),
+ SimpleNamespace(
+ id=2,
+ type="character",
+ name="禹",
+ params={"title": "治水英雄", "roleType": "主角"},
+ ),
+ SimpleNamespace(
+ id=3,
+ type="character",
+ name="行刑兵",
+ params={"title": "出场人物", "roleType": "配角"},
+ ),
+ SimpleNamespace(
+ id=4,
+ type="character",
+ name="部落百姓",
+ params={"title": "出场人物", "roleType": "群演"},
+ ),
+ ]
+ content = "\n".join(
+ [
+ "### 场1-1",
+ "日外 羽山刑场",
+ "出场人物:鲧、行刑兵、部落百姓",
+ "△ 刑场全景,洪水拍打山崖。",
+ "鲧被绑在杉木柱上,白发湿透。",
+ "### 场1-2",
+ "日外 羽山刑场",
+ "出场人物:鲧、禹",
+ "禹冲上刑场高喊父亲。",
+ "鲧抬头望向禹。",
+ ]
+ )
+ drafts = build_fragments_from_episode_body(content, assets)
+ joined = "\n---\n".join(d["content"] for d in drafts)
+
+ assert "【人物介绍·画面叠字·角色身旁】鲧|治水先驱" in joined
+ assert "【人物介绍·画面叠字·角色身旁】禹|治水英雄" in joined
+ assert joined.count("【人物介绍·画面叠字·角色身旁】鲧|") == 1
+ assert joined.count("【人物介绍·画面叠字·角色身旁】禹|") == 1
+ assert "行刑兵" not in joined or "【人物介绍·画面叠字·角色身旁】行刑兵" not in joined
+ assert "【人物介绍·画面叠字·角色身旁】部落百姓" not in joined
+
+ # 鲧应出现在首次提及他所在的分镜,而非机械堆在开场空镜
+ first_with_gun = next(d for d in drafts if "【人物介绍·画面叠字·角色身旁】鲧|" in d["content"])
+ assert "鲧" in first_with_gun["content"] or "@asset:1" in first_with_gun["content"]
+
+
+def test_important_and_intro_helpers():
+ assert _is_important_character("鲧", role_type="主角", title="治水先驱")
+ assert _is_important_character("四岳首领", role_type="重要配角", title="部落长老")
+ assert not _is_important_character("行刑兵", role_type="配角", title="出场人物")
+ assert not _is_important_character("部落百姓", role_type="群演", title="出场人物")
+ assert _resolve_character_intro_text({"title": "出场人物", "roleType": "主角"}) == "主角"
+ assert _resolve_character_intro_text({"title": "治水先驱"}) == "治水先驱"
+
+
+def test_stub_asset_uses_summary_for_intro():
+ # 资产仍为 stub,但摘要有小传 → 应可介绍
+ asset = SimpleNamespace(
+ id=132,
+ type="character",
+ name="禹",
+ params={"title": "出场人物", "roleType": "配角", "coreTags": "出场人物"},
+ )
+ summary = {
+ "characters": [
+ {
+ "name": "禹(大禹)",
+ "roleType": "主角",
+ "title": "治水英雄",
+ "identityBackground": "鲧之子,承父遗志治理洪水",
+ },
+ ]
+ }
+ binding = build_character_binding("禹", asset, summary=summary)
+ assert binding["important"] is True
+ assert binding["introText"] == "治水英雄"
+
+
+def test_narrative_summary_fallback_for_gun():
+ asset = SimpleNamespace(
+ id=131,
+ type="character",
+ name="鲧",
+ params={"title": "出场人物", "roleType": "配角"},
+ )
+ summary = {
+ "characters": [],
+ "synopsis": "罪臣之子大禹因父亲鲧盗息壤堵水失败被处死,在部落的唾骂中临危受命。",
+ }
+ binding = build_character_binding("鲧", asset, summary=summary)
+ assert binding["important"] is True
+ assert binding["introText"]
+ assert "鲧" in binding["introText"] or "堵水" in binding["introText"]
+
+
+def test_stub_identity_background_not_used_as_intro():
+ from app.services.drama.build_fragments import infer_character_intro_text
+
+ assert infer_character_intro_text(
+ "鲧",
+ {"title": "出场人物", "identityBackground": "剧本分集出场人物「鲧」"},
+ ) is None
+
+ asset = SimpleNamespace(
+ id=3,
+ type="character",
+ name="舜",
+ params={"title": "出场人物", "roleType": "配角", "identityBackground": "剧本分集出场人物「舜」"},
+ )
+ bodies = ["四岳首领推举禹治水,舜帝端坐大殿目光深沉。"]
+ binding = build_character_binding("舜", asset, summary={"characters": []}, episode_bodies=bodies)
+ assert binding["introText"]
+ assert "剧本分集出场人物" not in binding["introText"]
+ assert "舜" in binding["introText"]
+
+
+def test_scene_description_marked_visual_not_voiceover():
+ from app.services.drama.build_fragments import _format_narrative_line
+ from app.services.seedance_segments import (
+ DRAMA_SUBTITLE_CUE,
+ build_seedance_production_section,
+ rewrite_misclassified_visual_voice_lines,
+ script_has_dialogue_cue,
+ script_has_narration_cue,
+ )
+
+ scene = "月亮被乌云遮得严严实实,只有零星的火把亮着,禹跪在新堆的坟前。"
+ formatted = _format_narrative_line(scene)
+ assert formatted.startswith("【画面·无配音仅环境音】")
+ assert scene in formatted
+
+ dialogue = "伯益:大洪水来了,快撤!"
+ assert _format_narrative_line(dialogue).startswith("【对白·慢速清晰·同步字幕】")
+
+ # 「空镜:…」是画面描述,绝不能打成对白/旁白
+ empty_shot = "空镜:浑浊的黄河浪扣打着门口老石,溅起数丈高的浊浪。"
+ empty_formatted = _format_narrative_line(empty_shot)
+ assert empty_formatted.startswith("【画面·无配音仅环境音】")
+ assert "对白" not in empty_formatted
+ assert "旁白" not in empty_formatted
+
+ # 已误标为对白的旧数据:格式化与提交前纠正均可修复
+ mistagged = "【对白·慢速清晰·同步字幕】" + empty_shot
+ assert _format_narrative_line(mistagged).startswith("【画面·无配音仅环境音】")
+ fixed_script = rewrite_misclassified_visual_voice_lines(
+ "\n".join([DRAMA_SUBTITLE_CUE, "@duration:6", mistagged])
+ )
+ assert "【对白" not in fixed_script
+ assert "【画面·无配音仅环境音】空镜:" in fixed_script
+ assert script_has_dialogue_cue(fixed_script) is False
+
+ script = "\n".join(
+ [
+ DRAMA_SUBTITLE_CUE,
+ "【BGM:流动感环境音乐;音量低于人声】",
+ "@duration:6",
+ empty_formatted,
+ "@duration:6",
+ _format_narrative_line(dialogue),
+ ]
+ )
+ assert script_has_narration_cue(script) is False
+ section = build_seedance_production_section(script)
+ assert "禁止为其生成配音" in section
+ assert "画面描述段不出现字幕" in section
diff --git a/backend/tests/test_character_intro_llm.py b/backend/tests/test_character_intro_llm.py
new file mode 100644
index 0000000..7e5d315
--- /dev/null
+++ b/backend/tests/test_character_intro_llm.py
@@ -0,0 +1,63 @@
+"""人物介绍 LLM 补齐。"""
+
+import asyncio
+from unittest.mock import AsyncMock, patch
+
+from types import SimpleNamespace
+
+from app.services.drama.build_fragments import build_character_binding
+from app.services.drama.character_intro_llm import (
+ _parse_intro_response,
+ collect_names_needing_intro,
+ prepare_character_intro_overrides,
+)
+
+
+def test_parse_intro_response():
+ raw = {"intros": {"鲧": "治水先驱/因盗息壤被诛", "舜": "尧帝禅让之君"}}
+ parsed = _parse_intro_response(raw, ["鲧", "舜", "禹"])
+ assert parsed["鲧"] == "治水先驱/因盗息壤被诛"
+ assert parsed["舜"] == "尧帝禅让之君"
+ assert "禹" not in parsed
+
+
+def test_collect_names_needing_intro_skips_stub_identity():
+ asset = SimpleNamespace(
+ id=1,
+ type="character",
+ name="鲧",
+ params={"title": "出场人物", "identityBackground": "剧本分集出场人物「鲧」"},
+ )
+ missing = collect_names_needing_intro([asset], summary={"characters": []})
+ assert missing == ["鲧"]
+
+
+def test_prepare_character_intro_overrides_uses_llm():
+ asset = SimpleNamespace(
+ id=1,
+ type="character",
+ name="鲧",
+ params={"title": "出场人物", "identityBackground": "剧本分集出场人物「鲧」"},
+ )
+ mock_llm = AsyncMock(
+ return_value={"intros": {"鲧": "治水先驱/盗息壤被诛"}},
+ )
+ with patch(
+ "app.services.drama.character_intro_llm.drama_chat_json",
+ mock_llm,
+ ):
+ overrides = asyncio.run(
+ prepare_character_intro_overrides(
+ [asset],
+ summary={"storyType": "古风神话", "synopsis": "禹承父志治水。"},
+ episode_bodies=[],
+ )
+ )
+ assert overrides.get("鲧") == "治水先驱/盗息壤被诛"
+ binding = build_character_binding(
+ "鲧",
+ asset,
+ summary={"characters": []},
+ intro_overrides=overrides,
+ )
+ assert binding["introText"] == "治水先驱/盗息壤被诛"
diff --git a/backend/tests/test_ensure_fragment_assets.py b/backend/tests/test_ensure_fragment_assets.py
new file mode 100644
index 0000000..1944c41
--- /dev/null
+++ b/backend/tests/test_ensure_fragment_assets.py
@@ -0,0 +1,33 @@
+"""分镜视频前动态补齐缺图资产。"""
+
+from types import SimpleNamespace
+
+from app.services.drama.generation import (
+ asset_needs_reference_image,
+ extract_asset_ids_from_content,
+ read_asset_visual_prompt,
+)
+
+
+def test_extract_asset_ids_from_content_dedupes():
+ text = "开场 @asset:9 中段 @asset:9 结尾 @asset:3"
+ assert extract_asset_ids_from_content(text) == [9, 3]
+
+
+def test_asset_needs_reference_image():
+ empty = SimpleNamespace(type="character", cover="", url=None)
+ ready = SimpleNamespace(type="character", cover="/x.png", url="")
+ voice = SimpleNamespace(type="voice", cover="", url="")
+ assert asset_needs_reference_image(empty) is True
+ assert asset_needs_reference_image(ready) is False
+ assert asset_needs_reference_image(voice) is False
+
+
+def test_read_asset_visual_prompt_fallback():
+ asset = SimpleNamespace(
+ id=7,
+ type="scene",
+ name="龙门",
+ params={"visualPrompt": " 峡谷裂口,云雾,史诗感 "},
+ )
+ assert "峡谷裂口" in read_asset_visual_prompt(asset)
diff --git a/backend/tests/test_fragment_plan.py b/backend/tests/test_fragment_plan.py
new file mode 100644
index 0000000..3c18cfa
--- /dev/null
+++ b/backend/tests/test_fragment_plan.py
@@ -0,0 +1,113 @@
+"""LLM 分镜草稿规范化。"""
+
+from types import SimpleNamespace
+
+from app.services.drama.fragment_plan import normalize_llm_fragment_items
+from app.services.drama.fragment_plan_prompt import FRAGMENT_PLAN_SYSTEM_PROMPT
+
+
+def test_fragment_plan_system_prompt_requires_visual_density():
+ # 用户反馈「分镜描述太少」:系统提示必须强制画面公式与结束态,不能只靠 docs
+ prompt = FRAGMENT_PLAN_SYSTEM_PROMPT
+ assert "画面描写密度" in prompt
+ assert "结束态" in prompt
+ assert "主体 + 动作" in prompt or "主体 + 动作/姿态" in prompt
+ assert "禁止的瘦写法" in prompt
+ assert "3–7 行" in prompt or "3-7 行" in prompt
+
+
+def test_normalize_llm_injects_intro_once_for_important_cast():
+ assets = [
+ SimpleNamespace(
+ id=1,
+ type="character",
+ name="鲧",
+ params={"title": "治水先驱", "roleType": "主角"},
+ ),
+ SimpleNamespace(
+ id=2,
+ type="character",
+ name="禹",
+ params={"title": "治水英雄", "roleType": "主角"},
+ ),
+ SimpleNamespace(
+ id=3,
+ type="character",
+ name="行刑兵",
+ params={"title": "出场人物", "roleType": "配角"},
+ ),
+ SimpleNamespace(id=10, type="scene", name="羽山刑场", params={}),
+ ]
+ items = [
+ {
+ "duration_sec": 10,
+ "scene_name": "羽山刑场",
+ "character_names": [],
+ "is_opening": True,
+ "lines": [
+ "羽山刑场全景,洪水拍崖。",
+ "旁白(VO):上古洪荒,治水未成。",
+ ],
+ },
+ {
+ "duration_sec": 12,
+ "scene_name": "羽山刑场",
+ "character_names": ["鲧", "禹"],
+ "lines": [
+ "鲧被绑在杉木柱上。",
+ "禹冲上刑场高喊父亲。",
+ ],
+ },
+ ]
+ drafts = normalize_llm_fragment_items(
+ items,
+ assets,
+ episode_number=1,
+ episode_name="羽山刑场",
+ project_title="大禹治水",
+ story_type="古风神话",
+ one_line_story="鲧禹父子在洪荒中对抗天命。",
+ )
+ assert len(drafts) == 2
+ opening = drafts[0]["content"]
+ assert "【片头·集号叠字】第1集|羽山刑场" in opening
+ assert "【片头·剧名叠字】大禹治水" in opening
+ assert "【背景介绍·画面叠字】" in opening
+ assert "【人物介绍·画面叠字·角色身旁】鲧" not in opening
+
+ joined = "\n---\n".join(d["content"] for d in drafts)
+ assert "【人物介绍·画面叠字·角色身旁】鲧|治水先驱" in joined
+ assert "【人物介绍·画面叠字·角色身旁】禹|治水英雄" in joined
+ assert joined.count("【人物介绍·画面叠字·角色身旁】鲧|") == 1
+ assert "【人物介绍·画面叠字·角色身旁】行刑兵" not in joined
+
+
+def test_normalize_llm_splits_when_durations_exceed_hard_max():
+ # LLM 把过多对白塞进一镜时,规范化须按 30s 硬上限拆成多条
+ import re
+
+ long = "这是一句足够长的对白用来推高单行估算时长到上限附近,确保多行合计必然超过三十秒硬上限。"
+ assets = [
+ SimpleNamespace(id=1, type="character", name="禹", params={"title": "治水", "roleType": "主角"}),
+ SimpleNamespace(id=10, type="scene", name="工地", params={}),
+ ]
+ items = [
+ {
+ "duration_sec": 30,
+ "scene_name": "工地",
+ "character_names": ["禹"],
+ "lines": [
+ f"禹:{long}",
+ f"禹:{long}",
+ f"禹:{long}",
+ f"禹:{long}",
+ f"禹:{long}",
+ ],
+ },
+ ]
+ drafts = normalize_llm_fragment_items(items, assets)
+ assert len(drafts) >= 2
+ for draft in drafts:
+ total = sum(int(m) for m in re.findall(r"@duration:(\d+)", draft["content"]))
+ assert total <= 30
+ assert draft["duration_sec"] == total
diff --git a/backend/tests/test_oss_queue_backfill.py b/backend/tests/test_oss_queue_backfill.py
new file mode 100644
index 0000000..f285985
--- /dev/null
+++ b/backend/tests/test_oss_queue_backfill.py
@@ -0,0 +1,35 @@
+"""OSS 队列回填:漫剧表 + 旧 /static 补传。"""
+
+from __future__ import annotations
+
+from app.services.oss_queue import (
+ _collect_local_urls_from_params,
+ _rewrite_local_urls_in_params,
+)
+
+
+def test_rewrite_local_urls_in_params_nested():
+ params = {
+ "voiceAudio": "/static/generated/p1/voice.mp3",
+ "canvas": {"voiceAudio": "/static/generated/p1/voice.mp3", "other": 1},
+ }
+ assert _rewrite_local_urls_in_params(
+ params,
+ "/static/generated/p1/voice.mp3",
+ "https://cdn.example/voice.mp3",
+ )
+ assert params["voiceAudio"] == "https://cdn.example/voice.mp3"
+ assert params["canvas"]["voiceAudio"] == "https://cdn.example/voice.mp3"
+
+
+def test_collect_local_urls_from_params():
+ found: set[str] = set()
+ _collect_local_urls_from_params(
+ {
+ "voiceAudio": "/static/a.mp3",
+ "canvas": {"voiceAudio": "https://cdn.example/b.mp3"},
+ "note": "/static/not-a-media-key.txt",
+ },
+ found,
+ )
+ assert found == {"/static/a.mp3"}
diff --git a/backend/tests/test_seedance_continuity.py b/backend/tests/test_seedance_continuity.py
new file mode 100644
index 0000000..8ccc54d
--- /dev/null
+++ b/backend/tests/test_seedance_continuity.py
@@ -0,0 +1,75 @@
+"""Seedance 请求体:尾帧衔接不可与 reference 媒体混用 first_frame。"""
+
+from app.services.drama.build_seedance_generate_body import build_seedance_generate_body
+
+
+def test_build_body_without_continuity_keeps_ratio():
+ body = build_seedance_generate_body(
+ {
+ "content": "@duration:4\n空镜:江面起雾",
+ "aspect_ratio": "9:16",
+ "resolution": "480p",
+ "duration_fallback": 8,
+ }
+ )
+ assert body["ratio"] == "9:16"
+ assert body["return_last_frame"] is True
+ assert not any(
+ item.get("role") == "first_frame" for item in body["content"] if isinstance(item, dict)
+ )
+
+
+def test_build_body_continuity_alone_uses_first_frame_and_omits_ratio():
+ body = build_seedance_generate_body(
+ {
+ "content": "@duration:6\n近景:禹抬头望天",
+ "aspect_ratio": "9:16",
+ "resolution": "720p",
+ "duration_fallback": 8,
+ "continuity_first_frame_url": "https://cdn.example.com/prev_last.jpg",
+ }
+ )
+ assert "ratio" not in body
+ assert body["return_last_frame"] is True
+ first = next(
+ item
+ for item in body["content"]
+ if isinstance(item, dict) and item.get("role") == "first_frame"
+ )
+ assert first["image_url"]["url"] == "https://cdn.example.com/prev_last.jpg"
+ text = next(item for item in body["content"] if item.get("type") == "text")
+ assert "镜头衔接" in text["text"]
+
+
+def test_build_body_continuity_with_reference_uses_reference_image_keeps_ratio():
+ body = build_seedance_generate_body(
+ {
+ "content": "@duration:6\n禹:水患未平。",
+ "aspect_ratio": "9:16",
+ "resolution": "480p",
+ "duration_fallback": 8,
+ "continuity_first_frame_url": "https://cdn.example.com/prev_last.jpg",
+ "reference": [
+ {
+ "id": 1,
+ "type": "character",
+ "name": "禹",
+ "cover": "https://cdn.example.com/yu.jpg",
+ "url": "https://cdn.example.com/yu.jpg",
+ "params": {},
+ }
+ ],
+ }
+ )
+ assert body["ratio"] == "9:16"
+ roles = [item.get("role") for item in body["content"] if isinstance(item, dict)]
+ assert "first_frame" not in roles
+ assert roles.count("reference_image") >= 2
+ last_image = [
+ item
+ for item in body["content"]
+ if isinstance(item, dict) and item.get("role") == "reference_image"
+ ][-1]
+ assert last_image["image_url"]["url"] == "https://cdn.example.com/prev_last.jpg"
+ text = next(item for item in body["content"] if item.get("type") == "text")
+ assert "参考图序列最后一张" in text["text"]
diff --git a/backend/tests/test_seedance_segments.py b/backend/tests/test_seedance_segments.py
index 8b6f75d..96fb4de 100644
--- a/backend/tests/test_seedance_segments.py
+++ b/backend/tests/test_seedance_segments.py
@@ -100,3 +100,55 @@ def test_apply_segment_script_edit_fills_cues():
assert "【字幕:" in out["segment_script"]
assert "【BGM:" in out["segment_script"]
assert out["narration"]
+
+
+def test_empty_shot_misclassified_as_dialogue_is_rewritten():
+ from app.services.seedance_segments import (
+ DRAMA_SUBTITLE_CUE,
+ rewrite_misclassified_visual_voice_lines,
+ script_has_dialogue_cue,
+ script_has_visual_only_cue,
+ )
+
+ mistagged = "\n".join(
+ [
+ DRAMA_SUBTITLE_CUE,
+ "【BGM:流动感环境音乐;音量低于人声】",
+ "@duration:6",
+ "【对白·慢速清晰·同步字幕】空镜:浑浊的黄河浪扣打着门口老石。",
+ ]
+ )
+ fixed = rewrite_misclassified_visual_voice_lines(mistagged)
+ assert "【对白" not in fixed
+ assert "【画面·无配音仅环境音】空镜:" in fixed
+ assert script_has_dialogue_cue(fixed) is False
+ assert script_has_visual_only_cue(fixed) is True
+ section = build_seedance_production_section(fixed)
+ assert "禁止为其生成配音" in section
+ assert "画面描述段不出现字幕" in section
+ assert "逐句轮换" in section
+
+
+def test_legacy_drama_subtitle_cue_normalized_on_rewrite():
+ from app.services.seedance_segments import (
+ DRAMA_SUBTITLE_CUE,
+ rewrite_misclassified_visual_voice_lines,
+ )
+
+ legacy = "【字幕:底部居中·简体中文·仅标记段落同步】\n@duration:4\n空镜:黄河浪。"
+ fixed = rewrite_misclassified_visual_voice_lines(legacy)
+ assert DRAMA_SUBTITLE_CUE in fixed
+ assert "仅标记段落同步" not in fixed
+ assert "逐句轮换" in build_seedance_production_section(fixed)
+
+
+def test_character_intro_cue_normalized_beside_character():
+ from app.services.seedance_segments import rewrite_misclassified_visual_voice_lines
+
+ legacy = "【人物介绍·画面叠字】禹|治水英雄\n@duration:4\n【对白·慢速清晰·同步字幕】禹:水患未平。"
+ fixed = rewrite_misclassified_visual_voice_lines(legacy)
+ assert "【人物介绍·画面叠字·角色身旁】禹|治水英雄" in fixed
+ assert "【人物介绍·画面叠字】禹" not in fixed.replace("【人物介绍·画面叠字·角色身旁】", "")
+ section = build_seedance_production_section(fixed)
+ assert "角色身旁" in section
+ assert "禁止居中大标题" in section
diff --git a/backend/tests/test_series_introduced.py b/backend/tests/test_series_introduced.py
new file mode 100644
index 0000000..bb2c5a5
--- /dev/null
+++ b/backend/tests/test_series_introduced.py
@@ -0,0 +1,82 @@
+"""本剧跨集人物介绍去重。"""
+
+from types import SimpleNamespace
+
+from app.services.drama.build_fragments import (
+ collect_series_introduced_names,
+ extract_introduced_names_from_content,
+)
+from app.services.drama.fragment_plan import normalize_llm_fragment_items
+
+
+def test_extract_introduced_names_from_content():
+ content = "\n".join(
+ [
+ "【字幕:底部居中】",
+ "【人物介绍·画面叠字·角色身旁】鲧|治水先驱",
+ "【人物介绍·画面叠字·角色身旁】禹|治水英雄",
+ "@duration:3",
+ ]
+ )
+ assert extract_introduced_names_from_content(content) == ["鲧", "禹"]
+
+
+def test_collect_series_introduced_names_skips_later_episodes():
+ ep1 = SimpleNamespace(
+ id=1,
+ params={"episodeNumber": 1},
+ fragments=[
+ SimpleNamespace(content="【人物介绍·画面叠字·角色身旁】鲧|治水先驱\n画面"),
+ ],
+ )
+ ep2 = SimpleNamespace(
+ id=2,
+ params={"episodeNumber": 2},
+ fragments=[
+ SimpleNamespace(content="【人物介绍·画面叠字·角色身旁】禹|治水英雄\n画面"),
+ ],
+ )
+ before_ep2 = collect_series_introduced_names([ep1, ep2], before_episode_number=2)
+ assert before_ep2 == {"鲧"}
+ before_ep3 = collect_series_introduced_names([ep1, ep2], before_episode_number=3)
+ assert before_ep3 == {"鲧", "禹"}
+
+
+def test_normalize_skips_series_already_introduced():
+ assets = [
+ SimpleNamespace(
+ id=1,
+ type="character",
+ name="鲧",
+ params={"title": "治水先驱", "roleType": "主角"},
+ ),
+ SimpleNamespace(
+ id=2,
+ type="character",
+ name="禹",
+ params={"title": "治水英雄", "roleType": "主角"},
+ ),
+ ]
+ items = [
+ {
+ "duration_sec": 8,
+ "is_opening": True,
+ "character_names": [],
+ "lines": ["空镜开场。"],
+ },
+ {
+ "duration_sec": 10,
+ "character_names": ["鲧", "禹"],
+ "lines": ["鲧看着禹。", "禹:父亲。"],
+ },
+ ]
+ drafts = normalize_llm_fragment_items(
+ items,
+ assets,
+ episode_number=2,
+ episode_name="父子重逢",
+ already_introduced={"鲧"},
+ )
+ joined = "\n".join(d["content"] for d in drafts)
+ assert "【人物介绍·画面叠字·角色身旁】鲧" not in joined
+ assert "【人物介绍·画面叠字·角色身旁】禹|治水英雄" in joined
diff --git a/backend/tests/test_split_overlong_fragment.py b/backend/tests/test_split_overlong_fragment.py
new file mode 100644
index 0000000..3ab86d2
--- /dev/null
+++ b/backend/tests/test_split_overlong_fragment.py
@@ -0,0 +1,26 @@
+"""超长分镜按 @duration 拆分。"""
+
+from app.services.drama.build_fragments import split_overlong_fragment_content
+
+
+def test_split_overlong_keeps_header_and_caps_chunks():
+ content = "\n".join(
+ [
+ "【字幕:底部居中·简体中文·仅标记段落同步】",
+ "【BGM:庄重史诗】",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第一段足够长的对白内容用来占满时长。",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第二段继续讲治水方案与人心。",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第三段再补一句把合计推过三十秒。",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第四段必须落到下一镜。",
+ ]
+ )
+ chunks = split_overlong_fragment_content(content)
+ assert len(chunks) >= 2
+ for text, dur in chunks:
+ assert "【字幕:" in text
+ assert dur <= 30
+ assert text.count("@duration:") >= 1
diff --git a/backend/tests/test_voice_design.py b/backend/tests/test_voice_design.py
new file mode 100644
index 0000000..5eb9d01
--- /dev/null
+++ b/backend/tests/test_voice_design.py
@@ -0,0 +1,40 @@
+"""音色设计工具函数测试。"""
+
+from app.services.drama.voice_design import (
+ clamp_voice_design_prompt,
+ parse_speaker_pool,
+ resolve_speaker_slot,
+ voice_design_enabled,
+)
+
+
+def test_parse_speaker_pool() -> None:
+ assert parse_speaker_pool("S_a, S_b ,zh_x") == ["S_a", "S_b"]
+
+
+def test_resolve_speaker_slot_reuses_designed() -> None:
+ assert resolve_speaker_slot(3, {"designedSpeakerId": "S_keep"}, ["S_a", "S_b"]) == "S_keep"
+
+
+def test_resolve_speaker_slot_picks_from_pool() -> None:
+ slot = resolve_speaker_slot(1, {}, ["S_a", "S_b", "S_c"])
+ assert slot in {"S_a", "S_b", "S_c"}
+
+
+def test_clamp_voice_design_prompt() -> None:
+ prompt, text = clamp_voice_design_prompt("a" * 250, "b" * 400)
+ assert len(prompt) == 200
+ assert len(text) == 300
+
+
+def test_voice_design_enabled_requires_pool_and_auth(monkeypatch) -> None:
+ from app.config import Settings
+
+ cfg = Settings(
+ volc_tts_voice_design_speaker_ids="S_test",
+ volc_tts_api_key="key",
+ )
+ assert voice_design_enabled(cfg) is True
+
+ cfg2 = Settings(volc_tts_voice_design_speaker_ids="S_test")
+ assert voice_design_enabled(cfg2) is False
diff --git a/backend/tests/test_voice_reference_audio.py b/backend/tests/test_voice_reference_audio.py
new file mode 100644
index 0000000..2ea3a2f
--- /dev/null
+++ b/backend/tests/test_voice_reference_audio.py
@@ -0,0 +1,22 @@
+"""参考音色时长:合成源头截断。"""
+
+from app.services.drama.voice_reference_audio import (
+ SEEDANCE_REFERENCE_AUDIO_MAX_SEC,
+ VOICE_REFERENCE_TARGET_SEC,
+ patch_params_voice_url,
+)
+
+
+def test_voice_reference_target_under_api_limit():
+ assert VOICE_REFERENCE_TARGET_SEC < SEEDANCE_REFERENCE_AUDIO_MAX_SEC
+ assert SEEDANCE_REFERENCE_AUDIO_MAX_SEC <= 30.2
+
+
+def test_patch_params_voice_url():
+ params = {
+ "voiceAudio": {"sourceAssetId": 1, "url": "/static/old.mp3", "label": "禹音色"},
+ "canvas": {"voiceAudio": {"sourceAssetId": 1, "url": "/static/old.mp3"}},
+ }
+ next_params = patch_params_voice_url(params, "/static/new.mp3")
+ assert next_params["voiceAudio"]["url"] == "/static/new.mp3"
+ assert next_params["canvas"]["voiceAudio"]["url"] == "/static/new.mp3"
diff --git a/backend/tests/test_voice_synthesis.py b/backend/tests/test_voice_synthesis.py
new file mode 100644
index 0000000..747e85a
--- /dev/null
+++ b/backend/tests/test_voice_synthesis.py
@@ -0,0 +1,66 @@
+"""漫剧音色 speaker 推断与试听文案测试。"""
+
+from app.services.drama.voice_synthesis import (
+ build_voice_sample_line_short,
+ build_voice_sample_text,
+ normalize_character_name,
+)
+from app.services.ark import ArkGateway
+from app.services.voices import infer_drama_speaker_from_prompt
+
+
+def test_normalize_character_name_strips_suffix() -> None:
+ assert normalize_character_name("禹音色") == "禹"
+ assert normalize_character_name("伯益") == "伯益"
+
+
+def test_build_voice_sample_line_short() -> None:
+ assert build_voice_sample_line_short("禹") == "你好,我是禹。"
+ assert build_voice_sample_line_short("很长的角色名称测试") == "你好,我是很长的角色名称测。"
+
+
+def test_build_voice_sample_text_short_mode() -> None:
+ assert build_voice_sample_text("任意描述", "伯益", short=True) == "你好,我是伯益。"
+
+
+def test_infer_drama_speaker_differs_by_role() -> None:
+ yu = infer_drama_speaker_from_prompt(
+ "中年男性,治水领袖,声线浑厚庄重",
+ character_name="禹",
+ asset_id=1,
+ )
+ boyi = infer_drama_speaker_from_prompt(
+ "青年男性,儒雅谋士,声线清朗温和",
+ character_name="伯益",
+ asset_id=2,
+ )
+ elder = infer_drama_speaker_from_prompt(
+ "老年男性,部落族老,声线沙哑沉稳",
+ character_name="部落族老",
+ asset_id=3,
+ )
+ assert yu != boyi or yu != elder
+ assert all(s.startswith("zh_") for s in (yu, boyi, elder))
+
+
+def test_build_voice_sample_text_uses_role_lines() -> None:
+ yu = build_voice_sample_text("治水领袖,浑厚男声", "禹", short=False)
+ crowd = build_voice_sample_text("百姓群像,朴实女声", "两岸百姓", short=False)
+ assert "禹" in yu
+ assert "两岸百姓" in crowd
+ assert yu != crowd
+
+
+def test_build_tts_additions_includes_context_texts() -> None:
+ raw = ArkGateway._build_tts_additions("zh_female_vv_uranus_bigtts", "清亮少女音")
+ assert raw is not None
+ assert "context_texts" in raw
+ assert "清亮少女音" in raw
+
+
+def test_build_tts_additions_speaker_clone() -> None:
+ raw = ArkGateway._build_tts_additions("S_abc123", "低沉男声")
+ assert raw is not None
+ assert "model_type" in raw
+ assert "context_texts" in raw
+
diff --git a/deploy/scripts/import_drama_sqlite_to_postgres.py b/deploy/scripts/import_drama_sqlite_to_postgres.py
new file mode 100644
index 0000000..3be1499
--- /dev/null
+++ b/deploy/scripts/import_drama_sqlite_to_postgres.py
@@ -0,0 +1,416 @@
+#!/usr/bin/env python3
+"""
+从 sqlite(本地开发的 backend/ai_movie.db)导入漫剧模块数据到线上 Postgres。
+
+导入范围:drama_projects / drama_scripts / drama_assets / drama_episodes /
+drama_episode_fragments / drama_fragment_asset_refs / drama_asset_episodes
+
+用户映射策略:
+- 依据源 sqlite 中 drama_projects.owner 对应 users.email
+- 在目标 Postgres 的 users 表里按 email 查找 user_id
+- 若目标不存在该 email:跳过该项目(不会创建用户,以避免密钥/密码缺失)
+"""
+
+from __future__ import annotations
+
+import argparse
+import asyncio
+import json
+import sqlite3
+from datetime import datetime
+from typing import Any, Optional
+
+from sqlalchemy import select
+
+from app.database import AsyncSessionLocal
+from app.models import User
+from app.models_drama import (
+ DramaAsset,
+ DramaAssetEpisode,
+ DramaEpisode,
+ DramaEpisodeFragment,
+ DramaFragmentAssetRef,
+ DramaProject,
+ DramaScript,
+)
+
+
+def _parse_dt(raw: Any) -> Optional[datetime]:
+ if raw is None:
+ return None
+ if isinstance(raw, datetime):
+ return raw
+ if isinstance(raw, (int, float)):
+ # sqlite timestamp fallback
+ return datetime.fromtimestamp(raw)
+ s = str(raw)
+ s = s.strip()
+ if not s:
+ return None
+ # 默认匹配 sqlite 常见:YYYY-MM-DD HH:MM:SS
+ try:
+ return datetime.fromisoformat(s)
+ except ValueError:
+ pass
+ try:
+ return datetime.strptime(s, "%Y-%m-%d %H:%M:%S")
+ except ValueError:
+ return None
+
+
+def _jload(raw: Any) -> Any:
+ if raw is None:
+ return None
+ if isinstance(raw, (dict, list)):
+ return raw
+ if isinstance(raw, str):
+ s = raw.strip()
+ if not s:
+ return None
+ try:
+ return json.loads(s)
+ except json.JSONDecodeError:
+ return None
+ return None
+
+
+async def import_one(
+ source_sqlite: str,
+ dry_run: bool,
+ project_ids: list[int] | None,
+ import_missing_users: bool,
+) -> None:
+ con = sqlite3.connect(source_sqlite)
+ con.row_factory = sqlite3.Row
+ cur = con.cursor()
+
+ # 1) 取源 users email 映射
+ cur.execute("select id as user_id, email from users")
+ src_users = cur.fetchall()
+ user_email_by_id = {int(r["user_id"]): r["email"] for r in src_users if r["email"]}
+
+ # 2) 取源 drama_projects
+ cur.execute(
+ "select id, user_id, title, description, content, params, created_at, updated_at "
+ "from drama_projects order by id"
+ )
+ src_projects_all = cur.fetchall()
+ src_projects = src_projects_all
+ if project_ids:
+ project_id_set = set(project_ids)
+ src_projects = [r for r in src_projects_all if int(r["id"]) in project_id_set]
+ if not src_projects:
+ print("No drama_projects found in source sqlite.")
+ return
+
+ # 3) 依据源项目 owner email 查目标 users
+ src_owner_emails = sorted({user_email_by_id.get(int(r["user_id"])) for r in src_projects})
+ src_owner_emails = [e for e in src_owner_emails if e]
+
+ async with AsyncSessionLocal() as session:
+ dest_users = await session.execute(
+ select(User).where(User.email.in_(src_owner_emails)) if src_owner_emails else select(User).where(False)
+ )
+ dest_users_list = dest_users.scalars().all()
+ dest_user_id_by_email = {u.email: u.id for u in dest_users_list}
+
+ print(f"[users] source owners: {src_owner_emails}")
+ print(f"[users] destination found: {len(dest_user_id_by_email)}")
+
+ missing_emails = [e for e in src_owner_emails if e not in dest_user_id_by_email]
+ if missing_emails:
+ print(f"[users] missing in destination: {missing_emails}")
+ if import_missing_users and not dry_run:
+ # 直接拷贝源 users(包含 hashed_password),确保后续项目归属可见
+ cur.execute(
+ "select id, email, nickname, hashed_password, quota_left, balance_fen, frozen_fen, plan, billing_unlimited, role, created_at "
+ "from users"
+ )
+ src_users_full = cur.fetchall()
+ src_user_rows_by_email = {r["email"]: r for r in src_users_full if r["email"]}
+
+ for email in missing_emails:
+ row = src_user_rows_by_email.get(email)
+ if not row:
+ continue
+ u = User(
+ email=email,
+ nickname=row["nickname"] or "创作者",
+ hashed_password=row["hashed_password"] or "",
+ quota_left=int(row["quota_left"] or 0),
+ balance_fen=int(row["balance_fen"] or 0),
+ frozen_fen=int(row["frozen_fen"] or 0),
+ plan=row["plan"] or "free",
+ billing_unlimited=bool(row["billing_unlimited"] or False),
+ role=row["role"] or "user",
+ created_at=_parse_dt(row["created_at"]),
+ )
+ session.add(u)
+ await session.flush()
+ dest_user_id_by_email[email] = int(u.id)
+ print(f"[users] inserted missing users: {len(missing_emails)}")
+ else:
+ print("[users] import-missing-users disabled or dry-run; projects for these owners will be skipped.")
+
+ # 映射表
+ project_id_map: dict[int, int] = {}
+ asset_id_map: dict[int, int] = {}
+ episode_id_map: dict[int, int] = {}
+ fragment_id_map: dict[int, int] = {}
+
+ # 用事务包住插入,便于回滚
+ try:
+ # 4) projects
+ inserted_projects = 0
+ skipped_projects = 0
+ for r in src_projects:
+ old_pid = int(r["id"])
+ old_uid = int(r["user_id"])
+ email = user_email_by_id.get(old_uid)
+ new_uid = dest_user_id_by_email.get(email or "")
+ if new_uid is None:
+ skipped_projects += 1
+ print(f"[skip] project old_id={old_pid} owner_email={email!r} not found in destination users")
+ continue
+
+ if dry_run:
+ project_id_map[old_pid] = -1
+ inserted_projects += 1
+ continue
+
+ proj = DramaProject(
+ user_id=new_uid,
+ title=r["title"] or "未命名漫剧",
+ description=r["description"],
+ content=_jload(r["content"]),
+ params=_jload(r["params"]),
+ created_at=_parse_dt(r["created_at"]),
+ updated_at=_parse_dt(r["updated_at"]),
+ )
+ session.add(proj)
+ await session.flush()
+ project_id_map[old_pid] = int(proj.id)
+ inserted_projects += 1
+
+ print(f"[projects] inserted={inserted_projects} skipped={skipped_projects}")
+
+ # 5) scripts(按项目注入)
+ cur.execute(
+ "select id, project_id, episode_id, name, source, summary, episode_content, params, created_at, updated_at "
+ "from drama_scripts order by id"
+ )
+ src_scripts = cur.fetchall()
+ inserted_scripts = 0
+ for r in src_scripts:
+ old_pid = int(r["project_id"])
+ new_pid = project_id_map.get(old_pid)
+ if new_pid is None:
+ continue
+ if dry_run:
+ inserted_scripts += 1
+ continue
+
+ scr = DramaScript(
+ project_id=new_pid,
+ episode_id=int(r["episode_id"]) if r["episode_id"] is not None else None,
+ name=r["name"] or "剧本",
+ source=r["source"],
+ summary=_jload(r["summary"]),
+ episode_content=_jload(r["episode_content"]),
+ params=_jload(r["params"]),
+ created_at=_parse_dt(r["created_at"]),
+ updated_at=_parse_dt(r["updated_at"]),
+ )
+ session.add(scr)
+ await session.flush()
+ inserted_scripts += 1
+ print(f"[scripts] inserted={inserted_scripts}")
+
+ # 6) episodes
+ cur.execute(
+ "select id, project_id, name, params, created_at, updated_at "
+ "from drama_episodes order by id"
+ )
+ src_episodes = cur.fetchall()
+ for r in src_episodes:
+ old_eid = int(r["id"])
+ old_pid = int(r["project_id"])
+ new_pid = project_id_map.get(old_pid)
+ if new_pid is None:
+ continue
+
+ if dry_run:
+ episode_id_map[old_eid] = -1
+ continue
+
+ ep = DramaEpisode(
+ project_id=new_pid,
+ name=r["name"] or "",
+ params=_jload(r["params"]),
+ created_at=_parse_dt(r["created_at"]),
+ updated_at=_parse_dt(r["updated_at"]),
+ )
+ session.add(ep)
+ await session.flush()
+ episode_id_map[old_eid] = int(ep.id)
+
+ print(f"[episodes] mapped={len(episode_id_map)}")
+
+ # 7) assets
+ cur.execute(
+ "select id, project_id, type, asset_type, name, cover, url, params, derive_id, created_at, updated_at "
+ "from drama_assets order by id"
+ )
+ src_assets = cur.fetchall()
+ for r in src_assets:
+ old_aid = int(r["id"])
+ old_pid = int(r["project_id"])
+ new_pid = project_id_map.get(old_pid)
+ if new_pid is None:
+ continue
+
+ if dry_run:
+ asset_id_map[old_aid] = -1
+ continue
+
+ asset = DramaAsset(
+ project_id=new_pid,
+ type=r["type"] or "none",
+ asset_type=r["asset_type"] or "image",
+ name=r["name"],
+ cover=r["cover"],
+ url=r["url"],
+ params=_jload(r["params"]),
+ derive_id=r["derive_id"],
+ created_at=_parse_dt(r["created_at"]),
+ updated_at=_parse_dt(r["updated_at"]),
+ )
+ session.add(asset)
+ await session.flush()
+ asset_id_map[old_aid] = int(asset.id)
+
+ print(f"[assets] mapped={len(asset_id_map)}")
+
+ # 8) fragments
+ cur.execute(
+ "select id, episode_id, sort_order, content, cover, video, duration_sec, params, created_at, updated_at "
+ "from drama_episode_fragments order by id"
+ )
+ src_fragments = cur.fetchall()
+ for r in src_fragments:
+ old_fid = int(r["id"])
+ old_eid = int(r["episode_id"])
+ new_eid = episode_id_map.get(old_eid)
+ if new_eid is None:
+ continue
+
+ if dry_run:
+ fragment_id_map[old_fid] = -1
+ continue
+
+ frag = DramaEpisodeFragment(
+ episode_id=new_eid,
+ sort_order=int(r["sort_order"] or 0),
+ content=r["content"] or "",
+ cover=r["cover"] or "",
+ video=r["video"] or "",
+ duration_sec=r["duration_sec"],
+ params=_jload(r["params"]),
+ created_at=_parse_dt(r["created_at"]),
+ updated_at=_parse_dt(r["updated_at"]),
+ )
+ session.add(frag)
+ await session.flush()
+ fragment_id_map[old_fid] = int(frag.id)
+
+ print(f"[fragments] mapped={len(fragment_id_map)}")
+
+ # 9) join tables
+ # drama_asset_episodes
+ cur.execute("select id, asset_id, episode_id, created_at from drama_asset_episodes order by id")
+ src_asset_episodes = cur.fetchall()
+ inserted_asset_episodes = 0
+ for r in src_asset_episodes:
+ old_aid = int(r["asset_id"])
+ old_eid = int(r["episode_id"])
+ new_aid = asset_id_map.get(old_aid)
+ new_eid = episode_id_map.get(old_eid)
+ if new_aid is None or new_eid is None:
+ continue
+ if dry_run:
+ inserted_asset_episodes += 1
+ continue
+ session.add(
+ DramaAssetEpisode(
+ asset_id=new_aid,
+ episode_id=new_eid,
+ created_at=_parse_dt(r["created_at"]),
+ )
+ )
+ inserted_asset_episodes += 1
+ print(f"[drama_asset_episodes] inserted={inserted_asset_episodes}")
+
+ # drama_fragment_asset_refs
+ cur.execute("select id, fragment_id, asset_id from drama_fragment_asset_refs order by id")
+ src_frag_refs = cur.fetchall()
+ inserted_frag_refs = 0
+ for r in src_frag_refs:
+ old_fid = int(r["fragment_id"])
+ old_aid = int(r["asset_id"])
+ new_fid = fragment_id_map.get(old_fid)
+ new_aid = asset_id_map.get(old_aid)
+ if new_fid is None or new_aid is None:
+ continue
+ if dry_run:
+ inserted_frag_refs += 1
+ continue
+ session.add(DramaFragmentAssetRef(fragment_id=new_fid, asset_id=new_aid))
+ inserted_frag_refs += 1
+ print(f"[drama_fragment_asset_refs] inserted={inserted_frag_refs}")
+
+ print("Import done.")
+ if not dry_run:
+ await session.commit()
+ except Exception:
+ if not dry_run:
+ await session.rollback()
+ raise
+
+ con.close()
+
+
+def _parse_args() -> argparse.Namespace:
+ p = argparse.ArgumentParser()
+ p.add_argument("--source-sqlite", required=True, help="Path to source sqlite file (drama data).")
+ p.add_argument("--dry-run", action="store_true", help="Only calculate mapping, do not insert.")
+ p.add_argument(
+ "--project-ids",
+ default="",
+ help="仅导入指定 drama_projects 的 id(逗号分隔),例如:--project-ids 7,8",
+ )
+ p.add_argument(
+ "--import-missing-users",
+ action="store_true",
+ help="目标库 users 表中缺失的 owner email:从源 sqlite 插入(会同步 hashed_password)",
+ )
+ return p.parse_args()
+
+
+def main() -> None:
+ args = _parse_args()
+ project_ids = None
+ if args.project_ids:
+ project_ids = [int(x.strip()) for x in args.project_ids.split(",") if x.strip()]
+ asyncio.run(
+ import_one(
+ source_sqlite=args.source_sqlite,
+ dry_run=bool(args.dry_run),
+ project_ids=project_ids,
+ import_missing_users=bool(args.import_missing_users),
+ )
+ )
+
+
+if __name__ == "__main__":
+ main()
+
diff --git a/docs/EPISODE_RULES.md b/docs/EPISODE_RULES.md
new file mode 100644
index 0000000..e2b7e29
--- /dev/null
+++ b/docs/EPISODE_RULES.md
@@ -0,0 +1,378 @@
+# 漫剧分集规则(产品主规范)
+
+> **地位**:PRINTFILM 漫剧「分集 → 分镜 → Seedance 生成」的**单一真相源**。
+> 后续改 `fragment_plan` / `build_fragments` / 前端编辑器 / 规则弹窗,均以本文为准。
+>
+> 细则附录:[SEEDANCE_2_5.md](./SEEDANCE_2_5.md)(模型参数)· [SHOT_SPLITTING.md](./SHOT_SPLITTING.md)(拆镜操作细节)
+> 资料来源:火山方舟 / Seed 官方、社区 Prompt Skill(MapleShaw / dexhunter)、本仓库现实现。
+> 版本:v1.0 · 2026-08-13
+
+---
+
+## 0. 一句话原则
+
+**一集 = 开幕交代 + 若干可独立重跑的分镜;一分镜 = 一次 Seedance 任务(≤30s);镜内用画面/对白/旁白分段,空镜绝不口播。**
+
+---
+
+## 1. 层级模型
+
+```
+项目 Project
+ └─ 分集 Episode(本集场记正文 + 顶栏生成参数)
+ └─ 分镜 Fragment(一次 Seedance 调用)
+ └─ 段 Beat(@duration + 画面|对白|旁白)
+```
+
+| 层级 | 产品对象 | 时长 | 一次动作 |
+|------|----------|------|----------|
+| 分集 | `DramaEpisode` | 多镜串联,常见 1–3 分钟量级成片 | AI 重新分镜 / 全部生成 |
+| 分镜 | `DramaFragment` | **优先 8–20s,硬上限 30s** | 单镜「生成」 |
+| 段 | 脚本内 `@duration` | **3–12s** | 镜内节奏,非独立任务 |
+
+常量(代码必须对齐):
+
+| 常量 | 值 | 位置 |
+|------|-----|------|
+| 单段 min/max | 3 / 12 | `seedance_segments` / `segmentDuration.ts` |
+| 单镜软/硬上限 | 20 / 30 | `build_fragments` |
+| Seedance duration | 4–30 | `fragment_content_duration` / Ark |
+| 参考音频目标/上限 | 15s / ~30s | `voice_reference_audio` |
+
+---
+
+## 2. 分集结构规则
+
+### 2.1 开幕镜(强制,`fragments[0]`)
+
+| 要求 | 说明 |
+|------|------|
+| `is_opening: true` | 仅首条 |
+| 时长 | 建议 8–15s |
+| 必须交代 | 「第 N 集」原文 + 本集标题;1–3 句背景/前情;开场气氛画面 |
+| 角色 | `character_names` 通常空或极少;**禁止**写人物介绍文案 |
+| 片头 | 集号只在开幕强调一次;后续镜禁止重复整集片头 |
+
+系统后处理写入:`【片头·集号叠字】`、`【背景介绍·画面叠字】` 等(模型不要输出这些 cue)。
+
+### 2.2 正戏镜(`fragments[1…]`)
+
+- 按**场面 / 情绪段落**拆,一场戏通常 1–4 镜
+- 覆盖场记全部有效冲突与转折,禁止无故删戏
+- 整集避免碎成「一句一对白一镜」
+
+### 2.3 何时必须切新镜
+
+满足任一即切:
+
+1. 场景切换(地点 / 日夜 / 内外)
+2. 主要角色组合明显变化
+3. 情绪段落切换(铺垫→冲突→反转→收束)
+4. 叙事职责不同(开幕 ≠ 对白戏 ≠ 纯空镜)
+5. 累计将超过软上限 ~20s(硬上限 30s)
+
+### 2.4 分集顶栏参数(作用于本集各镜)
+
+| UI | 提交字段 | 规则 |
+|----|----------|------|
+| 视频风格 | 提示词风格块 | 全片强制画风 |
+| 模型 | `model` | 默认 Seedance 2.5 |
+| 画幅 | `ratio` | 竖屏短剧常用 `9:16` |
+| 清晰度 | `resolution` | 草稿 `480p`,成片可 `720p` |
+
+同集生成应保持画幅/风格一致;单镜可改脚本,不改顶栏默认。
+
+---
+
+## 3. 分镜脚本规则(Fragment content)
+
+### 3.1 脚本组装顺序(系统写入)
+
+```
+【字幕 cue】
+【BGM cue】
+【片头/背景叠字】(仅开幕)
+【人物介绍·画面叠字·角色身旁】(仅本剧首次出场,贴角色身旁)
+@duration:N
+【画面|对白|旁白】正文…
+(可多段 @duration)
+```
+
+漫剧字幕 cue:`【字幕:底部居中·简体中文·逐句轮换·与口播同步】`
+(同一时刻只显示一行/一句,随口播逐句轮换;勿用「全程旁白烧录」类科普 cue,避免整镜被念。)
+
+### 3.2 三类正文(铁律)
+
+| 类型 | 用户/LLM 写法 | 系统前缀 | 配音 | 字幕 |
+|------|---------------|----------|------|------|
+| 画面 / 空镜 | `空镜:…` `远景:…` 或纯环境动作描写 | `【画面·无配音仅环境音】` | 否 | 否 |
+| 对白 | `角色名:台词` | `【对白·慢速清晰·同步字幕】` | 是 | 是 |
+| 旁白 | `旁白(VO):…` | `【旁白·慢速清晰·同步字幕】` | 是 | 是 |
+
+**禁止**:
+
+- 把 `空镜:黄河浪…` 写成对白/旁白(会口播并烧字幕)
+- 在画面段要求「对口型 / 贴词同步」
+- 无口播意图却使用「同步字幕」对白前缀
+
+提交 Seedance 前须纠正误标行(已实现 `rewrite_misclassified_visual_voice_lines`)。
+
+### 3.3 镜内节奏模板(推荐)
+
+**建立空镜 →(动作)→ 对白/旁白 →(反应空镜)**
+
+```
+【字幕:底部居中·简体中文·逐句轮换·与口播同步】
+【BGM:史诗弦乐铺底,音量低于人声】
+@duration:4
+【画面·无配音仅环境音】空镜:浑浊黄河拍击老石,远坡百姓扶老携幼……
+@duration:6
+【对白·慢速清晰·同步字幕】禹:水患未平,岂能退!
+@duration:4
+【画面·无配音仅环境音】特写:禹攥紧简册,目光望向下游。
+```
+
+单镜内镜头变化建议:**约 3–7 段**;15s 内过密易闪。
+
+### 3.4 时长估算
+
+| 类型 | 经验 |
+|------|------|
+| 空镜 / 画面 | 2–6s |
+| 旁白 | ~3 字/秒,再钳 3–12s |
+| 对白 | 略短于旁白,留呼吸停顿 |
+
+口播:**慢速清晰,禁止赶词**(写入 Seedance 强制约束)。
+
+### 3.5 `@asset` 与 `@duration`
+
+| Token | 含义 | 提交时 |
+|-------|------|--------|
+| `@asset:ID` | 引用角色/场景/道具 | →「名称(参考图 N)」 |
+| `@duration:N` | 本段秒数 | → `00:00-00:04` 时间区间;合计 → API `duration` |
+
+LLM 分镜**禁止**直接输出 `@asset` / `@duration` / `【字幕】【BGM】【人物介绍】`(系统后处理注入)。
+
+---
+
+## 4. 资产与参考规则
+
+### 4.1 本镜引用范围
+
+- 只引用**本镜真正用到的**角色图 / 场景图 / 音色
+- 稳定优先:主体参考图约 **1–8**,勿一镜塞满 30 张
+- `character_names`:仅正文点到的出镜角色;群演可省略
+
+### 4.2 音色
+
+| 规则 | 说明 |
+|------|------|
+| 要对白的角色 | 必须绑定试听(`reference_audio`) |
+| 旁白 | 可用项目级旁白音色 |
+| 时长 | 合成后截到 **≤15s**(API 单条/合计上限约 30s) |
+
+### 4.3 人物介绍叠字
+
+- 仅**本剧第一次出现**的重要角色
+- 格式:`【人物介绍·画面叠字·角色身旁】姓名|短简介`
+- 位置:贴在对应角色**身旁**(肩侧小字),随首次入画短暂出现;禁止居中大标题、禁止与底部口播字幕抢位
+- 非口播;不要让模型念介绍全文
+
+### 4.4 Seedance 2.5 素材上限(生成侧)
+
+| 类型 | 上限 | 备注 |
+|------|------|------|
+| 参考图 | ≤30 | 产品侧按本镜精简 |
+| 参考视频 | ≤10,合计 ≤~30s | 当前主路径少用 |
+| 参考音频 | ≤10,合计 ≤~30s | 角色+旁白 |
+
+详见 [SEEDANCE_2_5.md](./SEEDANCE_2_5.md)。
+
+---
+
+## 5. 运镜与提示词写法(分集内可用)
+
+社区与官方共识,写入镜内画面描写时遵守:
+
+1. **公式**:主体 + 动作/姿态 + 场景环境 +(景别/运镜)+ **结束态** +(光影可选)
+2. **每段运动轴 ≤ 2**(推+摇可以;推+摇+升同时易失控)
+3. **近景大旋转易崩脸** → 环绕留给中景以上
+4. **参考必须写清用途**:形象 / 场景 / 运镜 / 音色(本仓库用「参考图 N / 参考音频 N」约束块)
+5. **信息完整、忌干瘪**:禁止「禹站在河边」式一句摘要;须写清空间关系、道具用法与本段结束可见状态。同时避免堆砌无关形容词噪声
+6. **勿写编辑/延长措辞**于普通生成(避免任务被重分类)
+
+景别标签可直接用于画面行:`空镜:` `远景:` `近景:` `特写:` `全景:` 等。
+
+AI 重新分镜(`fragment_plan`)须按上述公式输出画面行;单镜建议 **3–7 行**(建立→动作→口播→反应),对白镜至少保留 1 条画面行。
+
+### 5.1 编辑器词库(`@` → 小工具 → 景别/运镜)
+
+代码源:`frontend/src/lib/dramaCameraLexicon.ts`
+
+| 组 | 可插入前缀 |
+|----|------------|
+| 景别 | `空镜:` `远景:` `全景:` `中景:` `近景:` `特写:` `大特写:` `建立镜头:` `气氛镜头:` |
+| 运镜 | `推镜:` `拉镜:` `摇镜:` `移镜:` `跟拍:` `俯拍:` `仰拍:` `航拍:` |
+
+插入后继续补写主体与动作;这些行一律按**画面**处理,禁止再包一层对白/旁白 cue。
+
+### 5.2 分镜板多宫格导入(路径 D)
+
+顶栏「导入分镜板」:
+
+| 模式 | 条件 | 行为 |
+|------|------|------|
+| D-1 | ≤4 格 | 改写第 1 镜为多段 `@duration` + 各格素材参考 |
+| D-2 | ≥5 格 | 每格一镜,替换本集分镜列表 |
+
+同时可选六式剪辑节奏写入时长;正文注入「不复刻网格边框/编号/分隔线」。
+
+---
+
+## 6. Seedance 提交契约(每镜)
+
+| 字段 | 来源 |
+|------|------|
+| `model` | 顶栏模型 |
+| `content[]` | text 提示词 + reference_image + reference_audio |
+| `duration` | `@duration` 合计(4–30) |
+| `ratio` / `resolution` | 顶栏 |
+| `generate_audio` | `true`(短剧口播) |
+| `watermark` | `false` |
+| `return_last_frame` | `true`(落盘 `params.lastFrameUrl`;顶栏可开关跨镜衔接) |
+
+提示词块顺序:
+
+1. 画面风格强制约束
+2. 音频/字幕/BGM 强制约束(区分画面-only vs 对白/旁白)
+3. 角色/旁白音色 → 参考音频序号
+4. 角色形象 / 场景 → 参考图序号
+5. 正文(已替换 asset / duration)
+
+---
+
+## 7. AI 重新分镜(`fragment_plan`)契约
+
+### 7.1 模型只输出
+
+```json
+{
+ "fragments": [
+ {
+ "duration_sec": 12,
+ "scene_name": "地点",
+ "character_names": ["角色"],
+ "is_opening": true,
+ "lines": ["空镜:…", "禹:…", "旁白(VO):…"]
+ }
+ ]
+}
+```
+
+### 7.2 模型禁止输出
+
+`### 场`、出场人物行、一切 `【字幕】【BGM】【人物介绍】【片头】`、`@asset`、`@duration`。
+
+### 7.2.1 画面描写密度(与 §5 对齐)
+
+- 每条画面行:主体 + 动作 + 场景 + 景别/运镜 + 结束态
+- 单镜约 3–7 行;对白镜至少 1 条画面行
+- 禁止干瘪一句摘要;禁止把动作塞进对白冒号后当台词
+
+### 7.3 系统后处理
+
+1. 行分类打前缀(空镜 → 画面)
+2. 注入 cue / `@duration` / 开幕叠字 / 首次介绍
+3. 超软上限拆 Fragment
+
+---
+
+## 8. 生成与预览行为
+
+| 规则 | 说明 |
+|------|------|
+| 单镜生成 | 仅锁当前镜按钮;其它镜可编辑、可预览 |
+| 全部生成 | 有进行中任务时禁止重复全部入队 |
+| 并行 | video 队列最多约 10 路 |
+| 预览 | 轮询刷新 fragments **不得打断**正在播放的视频 |
+| AI 重新分镜 | 与视频生成互斥 |
+
+---
+
+## 9. 分集质量门禁(发布前 / 生成前)
+
+### 9.1 结构
+
+- [ ] 存在开幕镜且含集号+背景+气氛
+- [ ] 正戏覆盖关键冲突,无无故删戏
+- [ ] 无「一句一镜」碎片化
+
+### 9.2 脚本
+
+- [ ] 每镜合计 ≤30s,单段 3–12s
+- [ ] 空镜/景别均为画面前缀
+- [ ] 对白/旁白前缀仅用于真实口播
+- [ ] BGM 声明音量低于人声
+
+### 9.3 资产
+
+- [ ] 出镜角色有图;说话角色有音色
+- [ ] 本镜引用未明显超量
+- [ ] 音色试听 ≤15s
+
+### 9.4 提交
+
+- [ ] 顶栏画幅/模型/风格已确认
+- [ ] 普通生成未含「编辑/延长」歧义措辞
+
+---
+
+## 10. 后续完善清单(按本文推进)
+
+改代码时对照本节勾选;完成一项在 PR / 发布记录里引用本文章节号。
+
+| 优先级 | 项 | 对应章节 | 状态 |
+|--------|-----|----------|------|
+| P0 | 空镜/景别永不进对白前缀;提交前纠正 | §3.2 | 已做 |
+| P0 | 开幕镜强制字段与系统叠字 | §2.1 | 已有,持续校验 |
+| P1 | `fragment_plan_prompt` 与本文 §3/§5/§7 全文对齐(含画面密度/结束态) | §5、§7 | 已对齐(2026-08-13 加密度硬约束) |
+| P1 | 前端脚本校验:空镜行禁止对白 cue、时长合计告警 | §3、§9 | 已做(`dramaEpisodeScriptValidate` + 编辑区提示 + 生成阻断) |
+| P1 | SeedanceRulesModal 文案与本文同步 | §3–§6 | 已同步(漫剧字幕 cue / 空镜铁律) |
+| P2 | 运镜词库(景别/推拉摇移)写入编辑器 @ 菜单或帮助 | §5 | 已做(`dramaCameraLexicon` + @ 小工具) |
+| P2 | 生成前资产门禁(缺图/缺音色阻断或明确警告) | §4、§9.3 | 已做(警告级,确认框可继续) |
+| P2 | 尾帧衔接 / 延长路径产品化(可选) | §6 `return_last_frame` | 已做:落盘尾帧;有参考媒体时以 `reference_image` 衔接(禁混 `first_frame`);延长路径未做 |
+| P3 | 分镜板多宫格导入(路径 D) | 社区 Skill | 已做(顶栏「导入分镜板」D-1/D-2 + 节奏公式) |
+| P3 | 剪辑节奏公式用于整集导出 | 社区 Skill | 已做(导入时写入时长;`dramaEditRhythm` 可供导出规划) |
+
+---
+
+## 11. 相关代码索引
+
+| 模块 | 路径 |
+|------|------|
+| AI 分镜提示 | `backend/app/services/drama/fragment_plan_prompt.py` |
+| AI 分镜规范化 | `backend/app/services/drama/fragment_plan.py` |
+| 场记切镜 / 行分类 | `backend/app/services/drama/build_fragments.py` |
+| 生产约束 / 空镜纠正 | `backend/app/services/seedance_segments.py` |
+| 组装请求体 | `backend/app/services/drama/build_seedance_generate_body.py` |
+| 生成任务 | `backend/app/services/drama/generation.py` / `jobs.py` |
+| 前端时长 | `frontend/src/lib/segmentDuration.ts` |
+| 前端脚本/资产门禁 | `frontend/src/lib/dramaEpisodeScriptValidate.ts` |
+| 运镜/景别词库 | `frontend/src/lib/dramaCameraLexicon.ts` |
+| 分镜板宫格导入 | `frontend/src/lib/dramaStoryboardGrid.ts` / `StoryboardGridImportModal` |
+| 剪辑节奏公式 | `frontend/src/lib/dramaEditRhythm.ts` |
+| 分集编辑页 | `frontend/src/pages/drama/EpisodeEditPage.tsx` |
+| 规则弹窗 | `frontend/src/components/drama/SeedanceRulesModal.tsx` |
+
+---
+
+## 12. 文档关系
+
+| 文档 | 职责 |
+|------|------|
+| **本文 EPISODE_RULES.md** | 分集产品规则主规范(改需求先改这里) |
+| [SEEDANCE_2_5.md](./SEEDANCE_2_5.md) | 模型/API 参数百科 |
+| [SHOT_SPLITTING.md](./SHOT_SPLITTING.md) | 拆镜操作手册与示例 |
+| [STANDARDS.md](./STANDARDS.md) | 工程规范 |
+
+上游 Seedance 官方变更时:先更新 `SEEDANCE_2_5.md`,再修订本文 §4.4 / §6,最后改代码常量。
diff --git a/docs/SEEDANCE_2_5.md b/docs/SEEDANCE_2_5.md
new file mode 100644
index 0000000..353441c
--- /dev/null
+++ b/docs/SEEDANCE_2_5.md
@@ -0,0 +1,207 @@
+# Seedance 2.5 参数与使用规则
+
+> 汇总自字节跳动 Seed 官方发布说明、即梦 / fal / reAPI / Segmind / Atlas 等公开 API 文档(检索日:2026-08-13)。
+> 第三方网关字段名可能略有差异;**本仓库实际提交以火山方舟 `content` 多模态格式为准**(见文末「本仓库映射」)。
+
+相关链接:
+
+- 官方发布:[一镜成片,随心参考|Seedance 2.5](https://seed.bytedance.com/zh/blog/one-take-creation-flexible-referencing-introducing-seedance-2-5)
+- 项目页:[seedance2_5](https://seed.bytedance.com/seedance2_5)
+- 使用指南(即梦/BytePlus 系公开稿):[How To Use Seedance 2.5](https://fal.ai/learn/devs/how-to-use-seedance-2-5)
+- 参数参考示例:[reAPI Seedance 2.5](https://reapi.ai/docs/seedance-2-5)、[fal reference-to-video](https://fal.ai/models/bytedance/seedance-2.5/reference-to-video/api)
+
+拆镜与分集产品规则见:[EPISODE_RULES.md](./EPISODE_RULES.md)、[SHOT_SPLITTING.md](./SHOT_SPLITTING.md)。
+
+---
+
+## 1. 模型定位(相对 2.0)
+
+| 能力 | Seedance 2.0(常见公开口径) | Seedance 2.5 |
+|------|------------------------------|--------------|
+| 单次生成时长 | 约 4–15s(部分渠道到 15s) | **4–30s**(可 `-1` / auto) |
+| 参考图 | 最多约 9 | **最多 30** |
+| 参考视频 | 最多约 3 | **最多 10**(合计时长 ≤ ~30s) |
+| 参考音频 | 最多约 3 | **最多 10**(合计时长 ≤ ~30s) |
+| 仅音频参考 | 通常需配图/视频 | **支持 audio-only**(2.5) |
+| 原生分辨率 | 视渠道;部分 2.0 有 1080p | 公开 API 多为 **480p / 720p**(无原生 1080p/4K) |
+| 长叙事 | 偏短片段 | 单次可组织多镜头;支持多轮延长 |
+| 编辑 | 有 | 强化时间戳编辑、绿幕/视角/参考编辑 |
+
+---
+
+## 2. 生成模式(由输入推断,无需单独 mode 字段)
+
+多数网关按「塞了哪些媒体」隐式分流:
+
+| 模式 | 典型触发 | 说明 |
+|------|----------|------|
+| Text-to-video | 仅文本 | `prompt` 必填 |
+| Image-to-video / 首尾帧 | `first_frame` / `last_frame`(或 `image_with_roles`) | 画幅常锁定为首帧;首尾帧比例宜一致 |
+| Reference-to-video | 参考图 / 视频 / 音频 + 描述性 prompt | 多模态参考生视频;引用写法见 §4 |
+| Video edit | 参考视频 + prompt 含「编辑/替换/改…」意图 | **时长通常只能 auto/`-1`**,画幅跟随源片 |
+| Video extend | 参考视频 + prompt 含「延长/续写」意图 | 画幅跟随源片;时长可设 |
+
+注意:edit / extend 常由 **prompt 措辞异步判定**。若出现「duration/ratio 参数错误」,先去掉编辑/延长类措辞,或按上表改参数。
+
+---
+
+## 3. 核心 API 参数一览
+
+下列为公开文档中的常见字段(英文网关命名)。火山方舟侧等价项见 §7。
+
+| 参数 | 类型 | 常见默认 | 规则 |
+|------|------|----------|------|
+| `model` | string | — | 如 `doubao-seedance-2.5-*` / 渠道别名 |
+| `prompt` / text | string | — | 纯文生必填;有参考时可省略。部分渠道上限约 2 万字 |
+| `duration` | int | `5` | **4–30**;`-1` / `auto` 由模型择优。编辑任务多用 `-1` |
+| `resolution` | string | `720p` | **`480p` / `720p`**(2.5 公开原生档) |
+| `ratio` / `aspect_ratio` / `size` | string | `adaptive` | `16:9` `9:16` `1:1` `4:3` `3:4` `21:9` `adaptive` |
+| `generate_audio` | bool | `true` | 原生配音 + 音效 + BGM;关闭则通常无对白/配乐 |
+| `watermark` | bool | 视渠道 | 是否水印 |
+| `return_last_frame` | bool | `false` | 返回尾帧,便于镜头衔接 / 延长 |
+| `seed` | int | 随机 | 近似可复现 |
+| 参考图 | URL[] | — | 最多 **30**;单张常见上限约 30MB / ≤4K |
+| 参考视频 | URL[] | — | 最多 **10**;单段约 **2–30s**,合计 ≤ **~30s**;单文件约 ≤200MB |
+| 参考音频 | URL[] | — | 最多 **10**;单段约 **2–30s**,合计 ≤ **~30s**;单文件约 ≤15MB(wav/mp3) |
+
+### 3.1 参考素材硬限制(务必遵守)
+
+| 素材 | 数量上限 | 时长 | 其它 |
+|------|----------|------|------|
+| 图 | ≤ 30 | — | jpeg/png/webp 等;公网 URL |
+| 视频 | ≤ 10 | 单段 ~2–30.2s,**合计 ≤ ~30.2s** | mp4/mov;边长约 300–6000px;比例约 0.4–2.5;帧率约 24–60 |
+| 音频 | ≤ 10 | 单段 ~2–30.2s,**合计 ≤ ~30.2s** | wav/mp3 |
+
+稳定性建议(非硬上限,来自公开使用指南):
+
+- 主体参考图:优先 **1–8** 个不同主体
+- 主体参考视频:优先 **1–5** 主体,每主体约 5–10s
+- 音频:只留与任务直接相关的声线 / 对白 / 环境 / 音乐
+- 多视角同一主体:拆成多张独立图,避免一张拼贴
+
+### 3.2 任务类型与参数锁定
+
+| 任务 | 画幅 | 时长 |
+|------|------|------|
+| 视频编辑 | 锁定源视频;不可另设 | 约等于源时长(误差约 ±0.3–0.4s);常用 `-1` |
+| 首帧 / 首尾帧 | 锁定首帧比例 | 可设 |
+| 视频延长 | 锁定源视频 | 可设 4–30 |
+
+首尾帧:两张图比例不一致时,尾帧可能被拉伸。
+
+---
+
+## 4. Prompt 与引用写法
+
+### 4.1 基础公式(公开指南)
+
+```
+主体 + 动作/事件 +(场景)+(画风)+(景别/运镜/切镜)+(音频)
+```
+
+示例要素:谁在做什么 → 环境光影 → 中景推近再切正面 → 保留环境音。
+
+### 4.2 参考素材必须在文案里「指名」
+
+不要只靠图上的文字标签。推荐:
+
+```
+@Image 1 / 参考图1 定义角色外貌与服装(不要用图中背景)
+@Video 1 / 参考视频1 定义运镜节奏(不要用片中人物身份)
+@Audio 1 / 参考音频1 定义声线与指定对白
+```
+
+多主体时逐个绑定,禁止「图 1–4 分别是四个角色」这种含糊写法。
+
+### 4.3 音字特殊语法(即梦公开稿)
+
+| 内容 | 语法 | 例 |
+|------|------|----|
+| 音乐 | `()` | `(轻柔钢琴铺底)` |
+| 音效 | `<>` | `<雷声滚过>` |
+| 对白 | `{}` | `{你好,欢迎回来。}` |
+| 字幕 | `【】` | `【第一章:启程】` |
+
+非中文对白:先声明语种,再写 `{台词}`。
+
+### 4.4 长视频(≤30s)叙事
+
+- 用 **阶段 + 结束态**:每阶段只做一次主要状态变化,并写清镜头末可见状态
+- 需要卡点时用 **时间戳**(`0-5秒` / `5-10秒`),区间应连续、少重叠
+- 时间戳是节奏预算,不是精确剪辑点;不要要求「1 秒内做完三个动作」
+- 多镜头可用 `Shot 1:` / `Shot 2:` 或中文「镜 1 / 镜 2」
+
+### 4.5 编辑 / 延长措辞示例
+
+- 编辑:明确「编辑 @视频1,保持…不变,仅改…」
+- 延长:明确「延长 @视频1,衔接画面与主体继续生成…」
+
+误用编辑/延长措辞会导致任务被重分类并触发参数校验失败。
+
+---
+
+## 5. 输出与异步
+
+- 提交多为异步:`task_id` → 轮询至成功
+- 输出常见为 mp4;部分渠道支持 mov(后期友好、兼容性较差)
+- `return_last_frame=true` 时返回尾帧 URL,便于下一镜衔接
+- 结果 URL 可能过期,应落自有 OSS
+
+---
+
+## 6. 实践红线(跨文档共识)
+
+1. **单条 reference_audio / reference_video 勿超过 ~30s**;多条合计也不要超过 ~30s。
+2. **2.5 原生分辨率按 480p/720p 规划**;更高清多为渠道后处理,不是模型原生档。
+3. 参考图与「仅首尾帧」在部分网关 **互斥**;混用前查渠道说明。
+4. 参考 URL 需 **公网可访问**(本仓库会走 OSS 公开链)。
+5. 空镜 / 纯画面描写不要写成对白口播;否则易被烧字幕(本仓库会纠正「空镜:」误标)。
+6. `generate_audio=false` 时通常无口播与配乐——短剧口播场景保持 `true`。
+
+---
+
+## 7. 本仓库(PRINTFILM / drama)映射
+
+代码入口:`backend/app/services/drama/build_seedance_generate_body.py`、`seedance_segments.py`、`ark.py`。
+
+| 产品侧 | 提交字段 / 行为 |
+|--------|-----------------|
+| 顶栏模型 | `model` |
+| 画幅 / 清晰度 | `ratio`、`resolution`(默认常为 `9:16` + `480p`) |
+| 脚本 `@duration` 合计 | `duration`(钳制约 4–30) |
+| 分镜正文 + 强制约束块 | `content[]` 中 `type=text` |
+| 角色/场景封面 | `image_url` + `role=reference_image` |
+| 角色/旁白试听 | `audio_url` + `role=reference_audio`(源头截到约 15s) |
+| 原生配音 | `generate_audio: true` |
+| 水印 | `watermark: false` |
+| 尾帧 | `return_last_frame: true` |
+
+提示词组装顺序(摘要):
+
+1. 【强制约束:视频画面风格】
+2. 【强制约束:音频、字幕与配乐】
+3. 角色/旁白音色 → 参考音频序号
+4. 角色形象 / 场景 → 参考图序号
+5. 正文:`@asset` →「名称(参考图 N)」;`@duration:N` → `00:00-00:04` 时间区间
+
+分镜 cue:
+
+- 画面 / 空镜 → `【画面·无配音仅环境音】`(禁止配音与字幕)
+- 旁白 → `【旁白·慢速清晰·同步字幕】`
+- 对白 → `【对白·慢速清晰·同步字幕】`
+- 漫剧字幕 cue → `【字幕:底部居中·简体中文·逐句轮换·与口播同步】`
+
+单镜脚本内建议:`@duration` 单段 3–12s,镜合计 ≤ 30s(与 Seedance 单次上限对齐)。
+
+---
+
+## 8. 资料来源与维护
+
+| 来源 | 用途 |
+|------|------|
+| ByteDance Seed 博客(2026-07-31) | 2.5 能力口径:30s、30/10/10 参考、编辑与延长 |
+| fal / BytePlus「How To Use Seedance 2.5」 | Prompt 公式、时间戳、编辑参数锁定、素材建议量 |
+| reAPI / fal / Segmind / Atlas API 页 | duration / resolution / ratio / 参考时长等硬限制 |
+| 本仓库代码 | 方舟 `content` 形态与 drama 生产 cue |
+
+上游若调整上限,以火山方舟 / 即梦最新文档为准,并同步改本页与 `voice_reference_audio.py` 等常量。
diff --git a/docs/SHOT_SPLITTING.md b/docs/SHOT_SPLITTING.md
new file mode 100644
index 0000000..7e7ea25
--- /dev/null
+++ b/docs/SHOT_SPLITTING.md
@@ -0,0 +1,208 @@
+# 拆分镜头指南(短剧 / Seedance)
+
+> 面向 PRINTFILM 漫剧分镜操作细节。
+> **产品主规范请先读 [EPISODE_RULES.md](./EPISODE_RULES.md)**;参数硬限制见 [SEEDANCE_2_5.md](./SEEDANCE_2_5.md)。
+> 资料综合:影视分镜常识、Seedance 公开 Prompt 指南、本仓库 `fragment_plan` / `build_fragments` / `seedance_segments`。
+
+检索与整理日:2026-08-13。
+
+---
+
+## 1. 为什么要拆镜
+
+Seedance 2.5 **单次最长约 30 秒**,可在一段里做多镜头叙事,但:
+
+- 单次塞太多事件 → 漏戏、跳切混乱、主体漂移
+- 单次太碎(1–2 秒一切)→ 油腻感、口播赶词、字幕糊
+- 本产品按「分镜 = 一次 Seedance 任务」计费与排队,拆镜直接决定成本与可控性
+
+目标:**每一镜叙事完整、可单独成片**,镜内再用 `@duration` 切小节段。
+
+---
+
+## 2. 两层结构(本仓库约定)
+
+```
+场记剧本
+ └─ 分镜 Fragment(一次 Seedance 调用,4–30s)
+ └─ 段 Beat(@duration:N,建议 3–12s)
+ ├─ 画面 / 空镜(无配音、无字幕)
+ ├─ 旁白(口播 + 字幕)
+ └─ 对白(口播 + 字幕)
+```
+
+| 层级 | 时长建议 | 职责 |
+|------|----------|------|
+| Fragment(镜) | 优先 **8–20s**,硬上限 **30s** | 一场戏的一个情绪/场面单元 |
+| Beat(段) | **3–12s** | 镜内节奏:建立 → 动作 → 口播 |
+
+常量对齐:`SEGMENT_DURATION_MIN/MAX = 3/12`,`SHOT_DURATION_MAX / FRAGMENT_TOTAL_MAX = 30`。
+
+---
+
+## 3. 何时「切新镜」(Fragment)
+
+满足任一条,优先开新镜:
+
+1. **场景切换**(地点 / 日夜 / 内外景明显变化)
+2. **主要角色组合变化**(新主角进场、群像切双人对峙)
+3. **情绪段落切换**(铺垫 → 冲突 → 反转 → 收束)
+4. **叙事职责不同**(开幕介绍 ≠ 正戏对白 ≠ 空镜收尾)
+5. **累计时长将超过 20–30s**(软上限约 20s 可先切,硬上限 30s)
+
+不要:
+
+- 机械按字数 / 行数切
+- 「一句对白一镜」
+- 开幕后再重复整集片头
+
+### 3.1 开幕镜(强制)
+
+每集 `fragments[0]`:
+
+- 集号 + 集名
+- 1–3 句世界观 / 前情
+- 建立主场景气氛(可先不出主角)
+- 人物介绍叠字由系统注入,模型不要编介绍文案
+
+---
+
+## 4. 镜内怎么切段(Beat)
+
+### 4.1 推荐节奏模板
+
+**建立空镜 → 动作 → 对白/旁白 →(可选)反应空镜**
+
+```
+【字幕:底部居中·简体中文·逐句轮换·与口播同步】
+【BGM:……;音量低于人声】
+@duration:4
+【画面·无配音仅环境音】空镜:黄河浊浪拍击老石,远处百姓扶老携幼……
+@duration:6
+【对白·慢速清晰·同步字幕】禹:水患未平,岂能退!
+@duration:4
+【画面·无配音仅环境音】特写:禹攥紧治水简册,目光望向河道。
+```
+
+### 4.2 画面 vs 口播(易错)
+
+| 写法 | 正确前缀 | 是否配音/字幕 |
+|------|----------|----------------|
+| `空镜:…` / `远景:…` / 纯环境描写 | `【画面·无配音仅环境音】` | **否** |
+| `角色名:台词` | `【对白·慢速清晰·同步字幕】` | 是 |
+| `旁白(VO):…` | `【旁白·慢速清晰·同步字幕】` | 是 |
+| 人物介绍 | `【人物介绍·画面叠字·角色身旁】姓名|简介` | 贴角色身旁叠字,非口播念介绍全文 |
+
+**禁止**:把 `空镜:黄河浪…` 打成对白——模型会念「空镜」并烧字幕。
+提交前仓库会对误标行做纠正,但脚本里仍应写对。
+
+### 4.3 时长估算
+
+| 类型 | 估时经验 |
+|------|----------|
+| 空镜 / 纯画面 | 约 2–6s(看信息量) |
+| 旁白 | 约 **3 字/秒** 慢速清晰,再钳到 3–12s |
+| 对白 | 略短于旁白估时,留呼吸 |
+
+口播忌「赶词」:Seedance 强制约束里要求语速偏慢、吐字清晰。
+
+---
+
+## 5. Seedance 友好的多镜头写法
+
+公开指南建议:
+
+1. **阶段 + 结束态**:每阶段一个主事件,写清结束时可见状态
+2. **时间戳**(可选):`0-5秒` / `5-10秒` 分配节奏预算
+3. **单次 15s 左右**:约 **3–5 个镜头变化**较稳(产品侧单镜 3–7 行);再密易闪
+4. **参考素材按场景选用**,不要一镜塞进全部 30 张图
+5. **画面行密度**:`主体 + 动作 + 场景 + 景别/运镜 + 结束态`;禁止「众人惊慌」「山崩」式干瘪摘要
+
+示例(时间戳):
+
+```
+0-4秒:空镜建立河道,仅环境音与 BGM。结束态:浊浪拍岸,无人近景。
+4-10秒:禹入画中景,对白「……」。结束态:禹立于石上,面向下游。
+10-15秒:远景百姓撤离。结束态:高坡人影渐远,河道仍汹涌。
+```
+
+本仓库会把 `@duration:N` 展开为 `00:00-00:04` 这类区间再交给模型。
+`fragment_plan_prompt` 已把「画面描写密度」写成系统硬约束;文档学到的粒度必须落到 LLM 输出,不能只停在 docs。
+
+---
+
+## 6. 资产与参考(拆镜时就要想好)
+
+拆镜时同步决定「这镜谁出场」:
+
+| 资产 | Seedance 用途 |
+|------|----------------|
+| 角色图 | `reference_image` + 形象约束 |
+| 场景图 | `reference_image` + 场景约束 |
+| 角色/旁白音色 | `reference_audio`(单条建议 ≤15s,API 上限约 30s) |
+| `@asset:ID` | 正文替换为「名称(参考图 N)」 |
+
+规则:
+
+- `character_names` 只列真正出镜且正文点到的角色
+- 群演 / 兵丁 / 百姓可省略
+- 人物介绍仅在本剧**首次出场**那一镜由系统叠字
+
+---
+
+## 7. AI 分镜(`fragment_plan`)输出约定
+
+模型只输出 JSON `fragments[]`,每项含:
+
+- `duration_sec`(4–30)
+- `scene_name` / `character_names`
+- `is_opening`(首条 true)
+- `lines`:纯画面 / 对白 / 旁白文本
+
+禁止模型输出:`### 场`、出场人物行、`【字幕】【BGM】【人物介绍】`、`@asset`、`@duration`(由系统后处理写入)。
+
+系统后处理会:
+
+1. `_format_narrative_line` 打上画面/对白/旁白前缀
+2. 注入 `@duration`、字幕/BGM cue、开幕叠字、首次出场介绍
+3. 超软上限拆成多条 Fragment
+
+---
+
+## 8. 质量自检清单
+
+生成前快速过一遍:
+
+- [ ] 单镜合计时长 ≤ 30s,单段 3–12s
+- [ ] 空镜 / 景别描写已是「画面」前缀,不会被念
+- [ ] 有口播则有对应旁白/对白 cue;无口播则不要写「同步字幕」对白前缀
+- [ ] 出镜角色有参考图;要说话的角色已绑音色
+- [ ] 顶栏画幅 / 清晰度 / 风格与本集一致
+- [ ] 未在普通生成 prompt 里误写「编辑/延长」类措辞(避免任务被重分类)
+
+---
+
+## 9. 与官方能力的关系
+
+Seedance 2.5 宣传「一镜成片、多轮延长、30s 多镜头」——**不等于**不需要拆镜:
+
+| 策略 | 适用 |
+|------|------|
+| 单次长镜(15–30s)内多切 | 同一空间、连续动作、少换装 |
+| 产品拆 Fragment 多次生成 | 换场、换人、强情绪转折、要单独重跑一镜 |
+| 延长(extend) | 已有成片尾帧衔接;本产品当前主路径仍是「按 Fragment 新建」 |
+
+优先:**可重跑、可替换的分镜粒度**,再用镜内 `@duration` 做叙事节奏。
+
+---
+
+## 10. 相关代码
+
+| 文件 | 作用 |
+|------|------|
+| `backend/app/services/drama/fragment_plan_prompt.py` | LLM 拆镜系统提示 |
+| `backend/app/services/drama/fragment_plan.py` | LLM 结果规范化 |
+| `backend/app/services/drama/build_fragments.py` | 场记切镜、行分类、时长打包 |
+| `backend/app/services/seedance_segments.py` | 生产约束、空镜纠正、时长展开 |
+| `frontend/src/lib/segmentDuration.ts` | 前端时长校验常量 |
+| `frontend/src/components/drama/SeedanceRulesModal.tsx` | 产品内规则弹窗 |
diff --git a/docs/releases/2026-08-12.md b/docs/releases/2026-08-12.md
new file mode 100644
index 0000000..9fe9a76
--- /dev/null
+++ b/docs/releases/2026-08-12.md
@@ -0,0 +1,45 @@
+# 发布记录 · 2026-08-12
+
+## 2026-08-12 16:13 · 漫剧分镜/分集全量发布
+
+- **操作者**:Agent(按用户要求)
+- **方式**:`deploy_kepu.py` 全量(首次因 frontend TS 类型错误中断,修复后重跑成功)
+- **范围**:frontend / admin / api / worker / nginx / env
+- **变更摘要**:
+ - 人物介绍:规则推断 + LLM 批量补齐 stub 角色小传(鲧/舜等)
+ - Seedance 漫剧模式:画面行不配音,仅对白/旁白段配音+字幕;修正字幕 cue 误读旁白
+ - 分镜生成互斥:仅拦截同一分镜重复提交,其他镜可编辑与单独生成
+ - 取消视频任务 API + 队列面板停止按钮
+ - 分集列表 UI 重做(海报卡片、进度、状态)
+ - 分镜故事板画布(episodeCanvas)、分集视频时间轴播放器
+ - LLM 分镜规划(fragment_plan)与单集重新分镜
+- **验证**:
+ - [x] `https://kepu.printfilm.com/api/health` ok
+ - [x] 前台首页 HTTPS 200
+ - [x] `https://admin.kepu.printfilm.com/api/health` ok
+ - [x] admin 首页 HTTPS 200
+ - [ ] 业务冒烟:重新分镜人物介绍、画面不念旁白、分镜并行生成、分集列表 UI
+- **备注 / 回滚**:
+ - 全量脚本覆盖远端 `backend/.env`;EPAY/CORS/OSS 与脚本模板一致
+ - Celery worker 已重启,监听 `pipeline,oss`
+
+## 2026-08-12 16:29 · UI 打磨 + 全局弹窗 + 本地同步线上
+
+- **操作者**:Agent(按用户要求)
+- **方式**:`deploy_kepu.py` 全量
+- **范围**:frontend / admin / api / worker / nginx
+- **变更摘要**:
+ - 漫剧 Agent 首页 UI 重做(hero、项目列表行卡片、字数计数)
+ - 剧情大纲 / 资产库 / 分集视频三步工作流页头统一
+ - 全局 `DialogHost` 升级(Lucide 图标、lime 主题)
+ - 全部生成确认改用 `dialog.confirm`(移除 `window.confirm`)
+ - 分镜单镜/全量生成、批量生图、重新生成分集剧本等确认弹窗
+- **验证**:
+ - [x] `https://kepu.printfilm.com/api/health` ok
+ - [x] 前台首页 HTTPS 200(`index-BxUOEMu1.js` / `index-DuEAXr5P.css`)
+ - [x] admin 首页 HTTPS 200
+ - [x] api / worker active
+ - [ ] 业务冒烟:生成确认弹窗、Agent 首页、三步工作流 UI
+- **备注 / 回滚**:
+ - 线上 `/opt/ai_movie` 已与本地源码包同步;数据库未清库
+ - worker 已重启
diff --git a/docs/releases/README.md b/docs/releases/README.md
index f2ae110..29e0beb 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -33,4 +33,6 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-08-12 | UI 打磨 + 全局弹窗 + 本地同步线上 | [2026-08-12.md](./2026-08-12.md) |
+| 2026-08-12 | 漫剧分镜/分集全量:人物介绍 LLM、画面不配音、分镜非互斥、分集 UI | [2026-08-12.md](./2026-08-12.md) |
| 2026-08-11 | 全量上线 + admin 域名 + 易支付/定价热修 | [2026-08-11.md](./2026-08-11.md) |
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index c0c6592..5097c95 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -16,6 +16,7 @@ import AssetLibraryPage from './pages/drama/AssetLibraryPage'
import ProjectWorkspacePage from './pages/drama/ProjectWorkspacePage'
import EpisodeEditPage from './pages/drama/EpisodeEditPage'
import CanvasPage from './pages/drama/canvas/CanvasPage'
+import EpisodeStoryboardPage from './pages/drama/episodeCanvas/EpisodeStoryboardPage'
import './styles/printfilm.css'
import './App.css'
@@ -39,6 +40,10 @@ export default function App() {
<Route path="/drama/assets" element={<AssetLibraryPage />} />
<Route path="/drama/projects/:projectId" element={<ProjectWorkspacePage />} />
<Route path="/drama/projects/:projectId/episodes/:episodeId" element={<EpisodeEditPage />} />
+ <Route
+ path="/drama/projects/:projectId/episodes/:episodeId/canvas"
+ element={<EpisodeStoryboardPage />}
+ />
<Route path="/drama/projects/:projectId/canvas" element={<CanvasPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.ts
index 7f4e244..d98c513 100644
--- a/frontend/src/api/drama.ts
+++ b/frontend/src/api/drama.ts
@@ -168,6 +168,8 @@ export type DramaImageGenerateResult = {
export type DramaVoicePromptResult = {
ok: boolean
voice_prompt: string
+ speaker?: string
+ sample_text?: string
asset_id: number
}
@@ -187,7 +189,7 @@ export const dramaApi = {
}) =>
request<DramaProject>('/api/drama/projects', { method: 'POST', body: JSON.stringify(body) }),
getProject: (id: number) => request<DramaProject>(`/api/drama/projects/${id}`),
- updateProject: (id: number, body: { title?: string; description?: string }) =>
+ updateProject: (id: number, body: { title?: string; description?: string; params?: Record<string, unknown> | null }) =>
request<DramaProject>(`/api/drama/projects/${id}`, { method: 'PATCH', body: JSON.stringify(body) }),
deleteProject: (id: number) =>
request<{ ok: boolean }>(`/api/drama/projects/${id}`, { method: 'DELETE' }),
@@ -287,6 +289,18 @@ export const dramaApi = {
`/api/drama/episodes/seed_from_script?project_id=${projectId}${force ? '&force=true' : ''}`,
{ method: 'POST' },
),
+ /** 单集 AI(LLM)重新分镜;轮询 episode.params.fragment_plan_status */
+ planEpisodeFragments: (
+ episodeId: number,
+ body?: { force?: boolean; fallback_rules?: boolean },
+ ) =>
+ request<DramaEpisode>(`/api/drama/episodes/${episodeId}/plan_fragments`, {
+ method: 'POST',
+ body: JSON.stringify({
+ force: body?.force ?? true,
+ fallback_rules: body?.fallback_rules ?? true,
+ }),
+ }),
saveFragments: (
episodeId: number,
fragments: Array<{
@@ -318,6 +332,18 @@ export const dramaApi = {
fragments: Array<{ fragment_id: number; status: string; video?: string; cover?: string }>
}>(`/api/drama/episodes/${episodeId}/generate_status`),
+ cancelEpisodeGenerate: (episodeId: number) =>
+ request<{ ok: boolean; episode_id: number; fragments: number }>(
+ `/api/drama/episodes/${episodeId}/cancel_generate`,
+ { method: 'POST' },
+ ),
+
+ cancelAllVideoJobs: () =>
+ request<{ ok: boolean; purged: number; revoked: number; fragments: number }>(
+ '/api/drama/cancel_video_jobs',
+ { method: 'POST' },
+ ),
+
generateImage: (body: {
project_id: number
asset_id?: number
@@ -341,6 +367,7 @@ export const dramaApi = {
voice_prompt: string
sample_text?: string
speaker?: string
+ character_asset_id?: number
}) =>
request<DramaVoiceGenerateResult>('/api/drama/generation/voice', {
method: 'POST',
diff --git a/frontend/src/components/drama/CharacterVoicePreviewButton.tsx b/frontend/src/components/drama/CharacterVoicePreviewButton.tsx
new file mode 100644
index 0000000..c5ff3c4
--- /dev/null
+++ b/frontend/src/components/drama/CharacterVoicePreviewButton.tsx
@@ -0,0 +1,69 @@
+/** 角色音色试听按钮(卡片内联播放,不弹窗) */
+import { useRef } from 'react'
+import { Volume2 } from 'lucide-react'
+import { resolveDramaMediaUrl } from '../../api/drama'
+
+type Props = {
+ url: string
+ label?: string
+ className?: string
+ size?: 'sm' | 'md'
+ variant?: 'button' | 'chip' | 'inline'
+ onError?: (message: string) => void
+}
+
+// 点击播放已绑定音色的试听音频
+export function CharacterVoicePreviewButton({
+ url,
+ label,
+ className = '',
+ size = 'sm',
+ variant = 'button',
+ onError,
+}: Props) {
+ const audioRef = useRef<HTMLAudioElement | null>(null)
+ const src = resolveDramaMediaUrl(url)
+
+ function handlePreview() {
+ if (!src) {
+ onError?.('试听地址无效')
+ return
+ }
+ if (!audioRef.current) {
+ audioRef.current = new Audio(src)
+ } else {
+ audioRef.current.src = src
+ }
+ void audioRef.current.play().catch(() => {
+ onError?.('播放失败')
+ })
+ }
+
+ if (!src) return null
+
+ let btnClass = 'drama-voice-preview-btn'
+ if (variant === 'button') {
+ const sizeClass = size === 'md' ? 'pf-btn' : 'pf-btn pf-btn-sm'
+ btnClass = `${sizeClass} drama-voice-preview-btn`
+ } else if (variant === 'chip') {
+ btnClass = 'fc-toolbar-chip'
+ }
+ if (className) {
+ btnClass = `${btnClass} ${className}`
+ }
+
+ return (
+ <button
+ type="button"
+ className={btnClass}
+ onClick={(e) => {
+ e.stopPropagation()
+ handlePreview()
+ }}
+ title={label ? `试听:${label}` : '试听音色'}
+ >
+ <Volume2 size={14} strokeWidth={1.8} aria-hidden />
+ 试听
+ </button>
+ )
+}
diff --git a/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsx b/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsx
new file mode 100644
index 0000000..077724b
--- /dev/null
+++ b/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsx
@@ -0,0 +1,471 @@
+/** 分集编辑:带分镜分段进度条的视频播放器(客户端顺序连播) */
+import { Download, MonitorPlay, Pause, Play, Volume2, VolumeX } from 'lucide-react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { resolveDramaMediaUrl, type DramaFragment } from '../../api/drama'
+import {
+ buildEpisodeVideoTimelineSegments,
+ formatVideoTimelineClock,
+ resolveEpisodeTimelineSegmentFillRatio,
+ resolveEpisodeVideoTimelineTotalDuration,
+ resolveFragmentPlaybackFromGlobalTime,
+ resolveGlobalTimeFromFragmentPlayback,
+ resolveNextPlayableFragmentId,
+ resolveVideoTimelineSeekTime,
+ type DramaEpisodeVideoTimelineSegment,
+} from '../../lib/dramaEpisodeVideoTimeline'
+
+type Props = {
+ fragments: DramaFragment[]
+ playingFragmentId: number | null
+ onPlayingFragmentChange: (fragmentId: number) => void
+ aspectRatio: string
+}
+
+// 渲染带分镜分段进度条的视频播放器
+export function DramaFragmentSegmentedVideoPlayer({
+ fragments,
+ playingFragmentId,
+ onPlayingFragmentChange,
+ aspectRatio,
+}: Props) {
+ // videoRef 视频元素引用
+ const videoRef = useRef<HTMLVideoElement | null>(null)
+ // trackRef 分段进度条容器引用
+ const trackRef = useRef<HTMLDivElement | null>(null)
+ // isSeeking 是否正在拖动进度条
+ const isSeekingRef = useRef(false)
+ // autoLinkNextRef 是否自动衔接下一片段
+ const autoLinkNextRef = useRef(true)
+ // playingFragmentIdRef 当前播放分镜 ID
+ const playingFragmentIdRef = useRef(playingFragmentId)
+ // timelineSegmentsRef 时间轴分段缓存
+ const timelineSegmentsRef = useRef(buildEpisodeVideoTimelineSegments(fragments))
+ // shouldResumePlayRef 切换分镜后是否继续播放
+ const shouldResumePlayRef = useRef(false)
+ // pendingSeekTimeRef 切换分镜后待跳转的本地时间
+ const pendingSeekTimeRef = useRef<number | null>(null)
+ // autoPlayAttemptedRef 当前视频是否已尝试自动播放
+ const autoPlayAttemptedRef = useRef(false)
+ // playingSegmentRef 当前播放区间(供事件回调读取,避免轮询刷新 fragments 重绑事件)
+ const playingSegmentRef = useRef<DramaEpisodeVideoTimelineSegment | null>(null)
+ // prevPlayingFragmentIdRef 上次已处理的分镜切换
+ const prevPlayingFragmentIdRef = useRef<number | null>(playingFragmentId)
+ // isPlaying 是否正在播放
+ const [isPlaying, setIsPlaying] = useState(false)
+ // globalCurrentTime 全局时间轴当前位置(秒)
+ const [globalCurrentTime, setGlobalCurrentTime] = useState(0)
+ // autoLinkNext 当前片段播完后自动播放下一片段
+ const [autoLinkNext, setAutoLinkNext] = useState(true)
+ // muted 是否静音
+ const [muted, setMuted] = useState(false)
+
+ playingFragmentIdRef.current = playingFragmentId
+ autoLinkNextRef.current = autoLinkNext
+
+ // timelineSegments 分集全部分镜时间轴分段
+ const timelineSegments = useMemo(
+ () => buildEpisodeVideoTimelineSegments(fragments),
+ [fragments],
+ )
+
+ timelineSegmentsRef.current = timelineSegments
+
+ // totalDuration 分集时间轴总时长
+ const totalDuration = useMemo(
+ () => resolveEpisodeVideoTimelineTotalDuration(timelineSegments),
+ [timelineSegments],
+ )
+
+ // playingFragment 当前播放分镜
+ const playingFragment = useMemo(
+ () => fragments.find((fragment) => fragment.id === playingFragmentId) ?? null,
+ [fragments, playingFragmentId],
+ )
+
+ // playingSegment 当前播放分镜在时间轴上的区间
+ const playingSegment = useMemo(
+ () => timelineSegments.find((segment) => segment.fragmentId === playingFragmentId) ?? null,
+ [playingFragmentId, timelineSegments],
+ )
+
+ playingSegmentRef.current = playingSegment
+
+ // videoUrl 当前分镜视频地址
+ const videoUrl = playingFragment?.video ? resolveDramaMediaUrl(playingFragment.video) : null
+ // posterUrl 当前分镜封面地址
+ const posterUrl = playingFragment?.cover ? resolveDramaMediaUrl(playingFragment.cover) : null
+ // hasCurrentVideo 当前分镜是否可播放
+ const hasCurrentVideo = Boolean(videoUrl)
+ // hasAnyVideo 是否存在任一分镜视频
+ const hasAnyVideo = timelineSegments.some((segment) => segment.hasVideo)
+
+ // ratioClass 画幅 CSS 类名
+ const ratioClass = `ratio-${aspectRatio.replace(':', 'x')}`
+
+ // 切换播放或暂停
+ const handleTogglePlay = useCallback(() => {
+ const video = videoRef.current
+
+ if (!video || !hasCurrentVideo) {
+ return
+ }
+
+ if (video.paused) {
+ void video.play().catch(() => undefined)
+ return
+ }
+
+ video.pause()
+ }, [hasCurrentVideo])
+
+ // 跳转到全局时间轴位置
+ const seekToGlobalTime = useCallback(
+ (globalTimeSec: number) => {
+ const playback = resolveFragmentPlaybackFromGlobalTime(timelineSegments, globalTimeSec)
+
+ if (!playback) {
+ return
+ }
+
+ setGlobalCurrentTime(
+ resolveGlobalTimeFromFragmentPlayback(
+ playback.segment,
+ playback.localTimeSec,
+ playback.segment.durationSec,
+ ),
+ )
+
+ if (playback.segment.fragmentId !== playingFragmentIdRef.current) {
+ pendingSeekTimeRef.current = playback.localTimeSec
+ shouldResumePlayRef.current = isPlaying
+ onPlayingFragmentChange(playback.segment.fragmentId)
+ return
+ }
+
+ const video = videoRef.current
+
+ if (video && hasCurrentVideo) {
+ video.currentTime = playback.localTimeSec
+ }
+ },
+ [hasCurrentVideo, isPlaying, onPlayingFragmentChange, timelineSegments],
+ )
+
+ // 根据点击位置跳转播放进度
+ const seekByClientX = useCallback(
+ (clientX: number) => {
+ const track = trackRef.current
+
+ if (!track || totalDuration <= 0) {
+ return
+ }
+
+ const rect = track.getBoundingClientRect()
+ const ratio = (clientX - rect.left) / rect.width
+ const nextGlobalTime = resolveVideoTimelineSeekTime(ratio, totalDuration)
+
+ seekToGlobalTime(nextGlobalTime)
+ },
+ [seekToGlobalTime, totalDuration],
+ )
+
+ // 绑定视频事件(仅在当前视频地址变化时重置)
+ useEffect(() => {
+ const video = videoRef.current
+
+ if (!video || !videoUrl) {
+ return
+ }
+
+ autoPlayAttemptedRef.current = false
+
+ const tryAutoPlay = () => {
+ if (autoPlayAttemptedRef.current) {
+ return
+ }
+
+ autoPlayAttemptedRef.current = true
+
+ if (shouldResumePlayRef.current) {
+ void video.play().catch(() => undefined)
+ shouldResumePlayRef.current = false
+ }
+ }
+
+ const handleLoadedMetadata = () => {
+ if (pendingSeekTimeRef.current !== null) {
+ video.currentTime = pendingSeekTimeRef.current
+ pendingSeekTimeRef.current = null
+ }
+ }
+
+ const handleDurationChange = () => {
+ if (pendingSeekTimeRef.current !== null) {
+ video.currentTime = pendingSeekTimeRef.current
+ pendingSeekTimeRef.current = null
+ }
+ }
+
+ const handleCanPlay = () => {
+ if (pendingSeekTimeRef.current !== null) {
+ video.currentTime = pendingSeekTimeRef.current
+ pendingSeekTimeRef.current = null
+ }
+
+ tryAutoPlay()
+ }
+
+ const handleTimeUpdate = () => {
+ const segment = playingSegmentRef.current
+
+ if (isSeekingRef.current || !segment) {
+ return
+ }
+
+ const nextGlobalTime = resolveGlobalTimeFromFragmentPlayback(
+ segment,
+ video.currentTime,
+ Number.isFinite(video.duration) ? video.duration : segment.durationSec,
+ )
+
+ setGlobalCurrentTime(nextGlobalTime)
+ }
+
+ const handlePlay = () => {
+ setIsPlaying(true)
+ }
+
+ const handlePause = () => {
+ setIsPlaying(false)
+ }
+
+ const handleEnded = () => {
+ if (!autoLinkNextRef.current) {
+ setIsPlaying(false)
+ return
+ }
+
+ const nextFragmentId = resolveNextPlayableFragmentId(
+ timelineSegmentsRef.current,
+ playingFragmentIdRef.current ?? 0,
+ )
+
+ if (!nextFragmentId) {
+ setIsPlaying(false)
+ return
+ }
+
+ shouldResumePlayRef.current = true
+ onPlayingFragmentChange(nextFragmentId)
+ }
+
+ video.addEventListener('timeupdate', handleTimeUpdate)
+ video.addEventListener('loadedmetadata', handleLoadedMetadata)
+ video.addEventListener('durationchange', handleDurationChange)
+ video.addEventListener('canplay', handleCanPlay)
+ video.addEventListener('play', handlePlay)
+ video.addEventListener('pause', handlePause)
+ video.addEventListener('ended', handleEnded)
+
+ if (video.readyState >= HTMLMediaElement.HAVE_FUTURE_DATA) {
+ tryAutoPlay()
+ }
+
+ return () => {
+ video.removeEventListener('timeupdate', handleTimeUpdate)
+ video.removeEventListener('loadedmetadata', handleLoadedMetadata)
+ video.removeEventListener('durationchange', handleDurationChange)
+ video.removeEventListener('canplay', handleCanPlay)
+ video.removeEventListener('play', handlePlay)
+ video.removeEventListener('pause', handlePause)
+ video.removeEventListener('ended', handleEnded)
+ }
+ }, [onPlayingFragmentChange, videoUrl])
+
+ // 仅在用户切换分镜时重置到该分镜起点(生成轮询刷新 fragments 不应打断播放)
+ useEffect(() => {
+ if (playingFragmentId === prevPlayingFragmentIdRef.current) {
+ return
+ }
+
+ prevPlayingFragmentIdRef.current = playingFragmentId
+
+ if (!playingSegment) {
+ setGlobalCurrentTime(0)
+ return
+ }
+
+ if (shouldResumePlayRef.current || pendingSeekTimeRef.current !== null) {
+ return
+ }
+
+ setGlobalCurrentTime(playingSegment.startSec)
+
+ const video = videoRef.current
+
+ if (video && videoUrl) {
+ video.pause()
+ video.currentTime = 0
+ setIsPlaying(false)
+ }
+ }, [playingFragmentId, playingSegment, videoUrl])
+
+ useEffect(() => {
+ const video = videoRef.current
+
+ if (!video) {
+ return
+ }
+
+ video.muted = muted
+ }, [muted])
+
+ // 下载当前分镜视频
+ const handleDownloadVideo = useCallback(() => {
+ if (!videoUrl) {
+ return
+ }
+
+ const link = document.createElement('a')
+
+ link.href = videoUrl
+ link.download = ''
+ link.rel = 'noopener noreferrer'
+ link.target = '_blank'
+ link.click()
+ }, [videoUrl])
+
+ // playheadLeft 播放指针横向位置百分比
+ const playheadLeft = totalDuration > 0 ? (globalCurrentTime / totalDuration) * 100 : 0
+
+ return (
+ <div className="drama-ep-segmented-player">
+ <div
+ className={`drama-ep-player drama-ep-segmented-screen ${ratioClass}${
+ !hasCurrentVideo ? ' is-empty' : ''
+ }`}
+ >
+ {hasCurrentVideo ? (
+ <>
+ <video
+ ref={videoRef}
+ src={videoUrl ?? undefined}
+ poster={posterUrl ?? undefined}
+ playsInline
+ preload="auto"
+ />
+ <button
+ type="button"
+ aria-label="下载视频"
+ className="drama-ep-video-download"
+ onClick={handleDownloadVideo}
+ >
+ <Download size={16} strokeWidth={1.8} />
+ </button>
+ </>
+ ) : posterUrl ? (
+ <img src={posterUrl} alt="分镜预览" />
+ ) : (
+ <div className="drama-ep-player-placeholder">
+ <span>视频待生成</span>
+ </div>
+ )}
+ </div>
+
+ <div className="drama-ep-video-controls">
+ <p className="drama-ep-video-clock">
+ {formatVideoTimelineClock(globalCurrentTime)} / {formatVideoTimelineClock(totalDuration)}
+ </p>
+
+ <div className="drama-ep-video-toolbar">
+ <button
+ type="button"
+ aria-label={isPlaying ? '暂停' : '播放'}
+ disabled={!hasCurrentVideo}
+ className="drama-ep-video-icon-btn"
+ onClick={handleTogglePlay}
+ >
+ {isPlaying ? (
+ <Pause size={16} strokeWidth={2} />
+ ) : (
+ <Play size={16} strokeWidth={2} />
+ )}
+ </button>
+
+ <div
+ ref={trackRef}
+ className={`drama-ep-video-track${totalDuration <= 0 ? ' is-disabled' : ''}`}
+ onPointerDown={(event) => {
+ if (totalDuration <= 0) {
+ return
+ }
+
+ isSeekingRef.current = true
+ seekByClientX(event.clientX)
+ }}
+ onPointerMove={(event) => {
+ if (totalDuration <= 0 || !isSeekingRef.current) {
+ return
+ }
+
+ seekByClientX(event.clientX)
+ }}
+ onPointerUp={() => {
+ isSeekingRef.current = false
+ }}
+ onPointerLeave={() => {
+ isSeekingRef.current = false
+ }}
+ >
+ {timelineSegments.map((segment, index) => (
+ <div
+ key={segment.fragmentId}
+ className={`drama-ep-video-track-seg${
+ index < timelineSegments.length - 1 ? ' has-divider' : ''
+ }`}
+ style={{ flex: segment.durationSec }}
+ >
+ <div
+ className="drama-ep-video-track-fill"
+ style={{
+ width: `${resolveEpisodeTimelineSegmentFillRatio(segment, globalCurrentTime) * 100}%`,
+ }}
+ />
+ </div>
+ ))}
+
+ <div className="drama-ep-video-playhead" style={{ left: `${playheadLeft}%` }} />
+ </div>
+
+ <button
+ type="button"
+ aria-label={autoLinkNext ? '关闭自动衔接下一片段' : '开启自动衔接下一片段'}
+ title={
+ autoLinkNext ? '关闭自动衔接下一片段' : '当前片段播放完后自动播放下一片段'
+ }
+ disabled={!hasAnyVideo}
+ className={`drama-ep-video-autolink${autoLinkNext ? ' is-on' : ''}`}
+ onClick={() => setAutoLinkNext((value) => !value)}
+ >
+ <MonitorPlay size={16} strokeWidth={1.8} />
+ <span className="drama-ep-video-autolink-bar" />
+ </button>
+
+ <button
+ type="button"
+ aria-label={muted ? '取消静音' : '静音'}
+ disabled={!hasCurrentVideo}
+ className="drama-ep-video-icon-btn is-muted"
+ onClick={() => setMuted((value) => !value)}
+ >
+ {muted ? (
+ <VolumeX size={16} strokeWidth={1.8} />
+ ) : (
+ <Volume2 size={16} strokeWidth={1.8} />
+ )}
+ </button>
+ </div>
+ </div>
+ </div>
+ )
+}
diff --git a/frontend/src/components/drama/DramaGenQueuePanel.tsx b/frontend/src/components/drama/DramaGenQueuePanel.tsx
index 0e74074..f97c4f5 100644
--- a/frontend/src/components/drama/DramaGenQueuePanel.tsx
+++ b/frontend/src/components/drama/DramaGenQueuePanel.tsx
@@ -1,8 +1,15 @@
-/** 漫剧生图全局队列:右下角圆钮,点击展开约半屏高弹层 */
+/** 漫剧全局生成队列:右下角圆钮,展示图片 / 视频等任务 */
import { useCallback, useEffect, useMemo, useState } from 'react'
-import { ImageIcon, Trash2, X } from 'lucide-react'
-import { useDramaImageGenQueue } from '../../hooks/useDramaImageGenQueue'
-import { clearFinishedDramaImageGenJobs } from '../../lib/dramaImageGenQueue'
+import { Clapperboard, ImageIcon, Layers, Octagon, Trash2, X } from 'lucide-react'
+import { dramaApi } from '../../api/drama'
+import {
+ clearFinishedDramaGenJobs,
+ markVideoJobsCancelled,
+ subscribeDramaGenQueueOpen,
+ useDramaGenQueue,
+ type DramaGenJob,
+} from '../../lib/dramaGenQueue'
+import { DRAMA_IMAGE_GEN_MAX_CONCURRENT } from '../../lib/dramaImageGenQueue'
import '../../pages/drama/drama.css'
const OPEN_STORAGE_KEY = 'drama-gen-queue-fab-open'
@@ -14,14 +21,14 @@ const STATUS_LABEL: Record<string, string> = {
failed: '失败',
}
-const TYPE_LABEL: Record<string, string> = {
- character: '角色',
- scene: '场景',
- prop: '道具',
- material: '素材',
+const IMAGE_SUBTYPE_LABEL: Record<string, string> = {
+ character: '角色图',
+ scene: '场景图',
+ prop: '道具图',
+ material: '素材图',
}
-// 读取上次展开偏好(默认折叠为圆钮)
+// 读取折叠偏好
function readOpenPreference(): boolean {
try {
return localStorage.getItem(OPEN_STORAGE_KEY) === '1'
@@ -30,9 +37,21 @@ function readOpenPreference(): boolean {
}
}
-// 渲染右下角生图队列 FAB + 半高弹层
+// 任务类型展示
+function jobTypeLabel(job: DramaGenJob): string {
+ if (job.kind === 'video') return job.subtype || '分镜视频'
+ return IMAGE_SUBTYPE_LABEL[job.subtype] || job.subtype || '图片'
+}
+
+// 任务图标
+function JobKindIcon({ kind }: { kind: DramaGenJob['kind'] }) {
+ if (kind === 'video') return <Clapperboard size={16} strokeWidth={1.75} aria-hidden />
+ return <ImageIcon size={16} strokeWidth={1.75} aria-hidden />
+}
+
+// 渲染右下角统一生成队列
export function DramaGenQueuePanel() {
- const queue = useDramaImageGenQueue()
+ const queue = useDramaGenQueue()
const [open, setOpen] = useState(readOpenPreference)
const active = useMemo(
@@ -43,6 +62,7 @@ export function DramaGenQueuePanel() {
() => queue.filter((j) => j.status === 'done' || j.status === 'failed'),
[queue],
)
+ const failed = useMemo(() => queue.filter((j) => j.status === 'failed'), [queue])
useEffect(() => {
try {
@@ -52,6 +72,13 @@ export function DramaGenQueuePanel() {
}
}, [open])
+ // 入队后自动展开面板
+ useEffect(() => {
+ return subscribeDramaGenQueueOpen(() => {
+ setOpen(true)
+ })
+ }, [])
+
const toggleOpen = useCallback(() => {
setOpen((prev) => !prev)
}, [])
@@ -60,37 +87,59 @@ export function DramaGenQueuePanel() {
setOpen(false)
}, [])
+ const cancelAllVideo = useCallback(async () => {
+ try {
+ await dramaApi.cancelAllVideoJobs()
+ markVideoJobsCancelled()
+ } catch {
+ /* ignore */
+ }
+ }, [])
+
if (queue.length === 0) return null
const queuedOnly = queue.filter((j) => j.status === 'queued' || j.status === 'running')
- const badgeCount = active.length > 0 ? active.length : finished.length
+ const badgeCount = active.length > 0 ? active.length : failed.length > 0 ? failed.length : finished.length
return (
<div className="drama-gen-fab-root" aria-live="polite">
{open ? (
- <div className="drama-gen-fab-panel" role="dialog" aria-label="生图队列">
+ <div className="drama-gen-fab-panel" role="dialog" aria-label="生成队列">
<header className="drama-gen-fab-head">
<div className="drama-gen-fab-title">
- <ImageIcon size={18} strokeWidth={1.75} aria-hidden />
+ <Layers size={18} strokeWidth={1.75} aria-hidden />
<div>
- <strong>生图队列</strong>
+ <strong>生成队列</strong>
<span>
{active.length > 0
? `${active.length} 项进行中`
- : finished.length > 0
- ? '全部完成'
- : ''}
+ : failed.length > 0
+ ? `${failed.length} 项失败`
+ : finished.length > 0
+ ? '全部完成'
+ : ''}
</span>
</div>
</div>
<div className="drama-gen-fab-actions">
- {finished.length > 0 && active.length === 0 ? (
+ {active.some((j) => j.kind === 'video') ? (
+ <button
+ type="button"
+ className="drama-gen-fab-icon-btn"
+ onClick={cancelAllVideo}
+ title="取消全部视频任务"
+ aria-label="取消全部视频任务"
+ >
+ <Octagon size={16} />
+ </button>
+ ) : null}
+ {finished.length > 0 ? (
<button
type="button"
className="drama-gen-fab-icon-btn"
- onClick={clearFinishedDramaImageGenJobs}
- title="清空已完成"
- aria-label="清空已完成"
+ onClick={clearFinishedDramaGenJobs}
+ title="清空已结束"
+ aria-label="清空已结束"
>
<Trash2 size={16} />
</button>
@@ -110,17 +159,25 @@ export function DramaGenQueuePanel() {
<ul className="drama-gen-fab-list">
{queue.map((job) => {
const queueIndex = queuedOnly.findIndex((j) => j.id === job.id)
- const typeLabel = TYPE_LABEL[job.assetType] || job.assetType
return (
<li key={job.id} className={`drama-gen-fab-item is-${job.status}`}>
<div className="drama-gen-fab-item-head">
<div className="drama-gen-fab-item-main">
- <span className="drama-gen-fab-name">{job.assetName}</span>
- <span className="drama-gen-fab-type">{typeLabel}</span>
+ <span className="drama-gen-fab-kind">
+ <JobKindIcon kind={job.kind} />
+ <em>{job.kind === 'video' ? '视频' : '图片'}</em>
+ </span>
+ <span className="drama-gen-fab-name">{job.title}</span>
+ <span className="drama-gen-fab-type">{jobTypeLabel(job)}</span>
+ {job.message && (job.status === 'queued' || job.status === 'running') ? (
+ <span className="drama-gen-fab-msg">{job.message}</span>
+ ) : null}
</div>
<span className="drama-gen-fab-status">
{job.status === 'queued' && queueIndex >= 0
- ? `排队 #${queueIndex + 1}`
+ ? queuedOnly.length <= 1 || queueIndex === 0
+ ? '等待 Worker'
+ : `排队 #${queueIndex + 1}`
: STATUS_LABEL[job.status]}
</span>
</div>
@@ -138,7 +195,9 @@ export function DramaGenQueuePanel() {
{active.length > 0 ? (
<footer className="drama-gen-fab-foot">
<span className="drama-gen-fab-foot-dot" aria-hidden />
- 串行生图,完成后自动处理下一项
+ 图片走 pipeline 队列;分镜视频走独立 video 队列(Seedance 最多 10
+ 路并行)。刷新后会按进行中状态恢复(图最多轮询{' '}
+ {DRAMA_IMAGE_GEN_MAX_CONCURRENT} 路)
</footer>
) : null}
</div>
@@ -146,13 +205,13 @@ export function DramaGenQueuePanel() {
<button
type="button"
- className={`drama-gen-fab-btn${active.length > 0 ? ' is-busy' : ''}`}
+ className={`drama-gen-fab-btn${active.length > 0 ? ' is-busy' : ''}${failed.length > 0 && active.length === 0 ? ' is-failed' : ''}`}
onClick={toggleOpen}
- title={open ? '收起生图队列' : '展开生图队列'}
+ title={open ? '收起生成队列' : '展开生成队列'}
aria-expanded={open}
- aria-label="生图队列"
+ aria-label="生成队列"
>
- <ImageIcon size={22} strokeWidth={1.75} aria-hidden />
+ <Layers size={22} strokeWidth={1.75} aria-hidden />
{badgeCount > 0 ? <span className="drama-gen-fab-badge">{badgeCount}</span> : null}
</button>
</div>
diff --git a/frontend/src/components/drama/SeedanceRulesModal.tsx b/frontend/src/components/drama/SeedanceRulesModal.tsx
new file mode 100644
index 0000000..2b3fff2
--- /dev/null
+++ b/frontend/src/components/drama/SeedanceRulesModal.tsx
@@ -0,0 +1,246 @@
+/** Seedance 传值与脚本规则说明弹窗(分集编辑页,对齐 docs/EPISODE_RULES.md) */
+import { useState } from 'react'
+import Modal from '../ui/Modal'
+import {
+ SEGMENT_DURATION_MAX,
+ SEGMENT_DURATION_MIN,
+ SHOT_DURATION_MAX,
+} from '../../lib/segmentDuration'
+import {
+ DIALOGUE_PREFIX,
+ DRAMA_NARRATION_PREFIX,
+ DRAMA_SUBTITLE_CUE,
+ VISUAL_PREFIX,
+} from '../../lib/dramaEpisodeScriptValidate'
+
+type Tab = 'payload' | 'script' | 'usage'
+
+type Props = {
+ open: boolean
+ onClose: () => void
+}
+
+// 渲染 Seedance 规则说明弹窗
+export function SeedanceRulesModal({ open, onClose }: Props) {
+ const [tab, setTab] = useState<Tab>('payload')
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ title="Seedance 传值与使用规则"
+ size="lg"
+ className="pf-help-modal seedance-rules-modal"
+ footer={
+ <button type="button" className="pf-btn pf-btn-lime pf-btn-sm" onClick={onClose}>
+ 知道了
+ </button>
+ }
+ >
+ <div className="pf-help">
+ <p className="pf-help-lede">
+ 分镜视频由 Seedance 多模态接口生成。下方说明系统如何把脚本、资产与顶栏参数组装成请求,以及漫剧分集脚本写法(详见{' '}
+ <code>docs/EPISODE_RULES.md</code>)。
+ </p>
+
+ <div className="pf-help-tabs" role="tablist" aria-label="Seedance 规则分类">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === 'payload'}
+ className={tab === 'payload' ? 'active' : undefined}
+ onClick={() => setTab('payload')}
+ >
+ 传值规则
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === 'script'}
+ className={tab === 'script' ? 'active' : undefined}
+ onClick={() => setTab('script')}
+ >
+ 脚本写法
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === 'usage'}
+ className={tab === 'usage' ? 'active' : undefined}
+ onClick={() => setTab('usage')}
+ >
+ 使用建议
+ </button>
+ </div>
+
+ {tab === 'payload' ? (
+ <div className="seedance-rules-section">
+ <h4>顶栏参数 → API 字段</h4>
+ <ul className="seedance-rules-list">
+ <li>
+ <strong>模型</strong> → <code>model</code>(Seedance 2.5 / 1.5)
+ </li>
+ <li>
+ <strong>画幅 · 清晰度</strong> → <code>ratio</code>、<code>resolution</code>
+ </li>
+ <li>
+ <strong>时长</strong> → <code>duration</code>:脚本内{' '}
+ <code>@duration</code> 合计(建议 4–{SHOT_DURATION_MAX} 秒);无标签时用本镜「时长」字段
+ </li>
+ <li>
+ <strong>视频风格</strong> → 写入提示词「画面风格」强制约束块
+ </li>
+ </ul>
+
+ <h4>content 多模态数组(按顺序提交)</h4>
+ <ol className="seedance-rules-list">
+ <li>
+ <strong>text</strong>:自动组装的完整提示词(见下方各约束块 + 正文)
+ </li>
+ <li>
+ <strong>reference_image</strong>:本镜引用角色 / 场景 / 道具的封面或主图
+ </li>
+ <li>
+ <strong>reference_audio</strong>:已绑定音色的角色与旁白试听音频
+ </li>
+ </ol>
+ <p className="seedance-rules-note">
+ 系统默认开启 <code>generate_audio</code>:有口播意图时 Seedance 原生配音并烧录字幕;纯画面镜仅环境音、不烧字幕。
+ </p>
+
+ <h4>提示词自动组装顺序</h4>
+ <ol className="seedance-rules-list">
+ <li>【强制约束:视频画面风格】— 项目所选画风描述</li>
+ <li>【强制约束:音频、字幕与配乐】— 根据脚本旁白 / 对白 / 画面 cue 推断</li>
+ <li>【强制约束:角色音色】— 角色名 → 参考音频序号</li>
+ <li>【强制约束:旁白音色】— 旁白 → 参考音频序号</li>
+ <li>【强制约束:角色形象】— 角色名 → 参考图序号</li>
+ <li>【强制约束:场景】— 场景名 → 参考图序号</li>
+ <li>
+ 正文:将 <code>@asset:ID</code> 替换为「名称(参考图 N)」;将{' '}
+ <code>@duration:N</code> 替换为时间区间(如 00:00-00:04)
+ </li>
+ </ol>
+ </div>
+ ) : null}
+
+ {tab === 'script' ? (
+ <div className="seedance-rules-section">
+ <h4>时长标签</h4>
+ <ul className="seedance-rules-list">
+ <li>
+ <code>@duration:N</code>:标记一段内容的时长(秒),单段建议{' '}
+ {SEGMENT_DURATION_MIN}–{SEGMENT_DURATION_MAX} 秒
+ </li>
+ <li>
+ 一镜内所有 <code>@duration</code> 合计不超过 {SHOT_DURATION_MAX} 秒
+ </li>
+ <li>键入 <code>@</code> 可插入时长 chip 或引用资产</li>
+ </ul>
+
+ <h4>资产引用</h4>
+ <ul className="seedance-rules-list">
+ <li>
+ <code>@asset:123</code>:在正文中引用 ID 为 123 的角色 / 场景 / 道具
+ </li>
+ <li>左侧资产面板点击资产,或本镜「参与资产」条,也会自动写入引用</li>
+ <li>被引用的角色需有参考图;需口播的角色需绑定音色(参考音频)</li>
+ </ul>
+
+ <h4>漫剧常用 cue(勿用科普版「全程旁白烧录」字幕句)</h4>
+ <div className="seedance-rules-examples">
+ <code>{DRAMA_SUBTITLE_CUE}</code>
+ <code>【BGM:低沉史诗,音量低于人声】</code>
+ <code>@duration:4</code>
+ <code>{VISUAL_PREFIX}空镜:浑浊黄河拍击老石……</code>
+ <code>@duration:6</code>
+ <code>{DIALOGUE_PREFIX}禹:水患未平,岂能退!</code>
+ <code>{DRAMA_NARRATION_PREFIX}千年后,人们仍记得这一战。</code>
+ </div>
+ <ul className="seedance-rules-list">
+ <li>
+ <strong>空镜 / 景别</strong>:写成「空镜:…」「远景:…」「特写:…」或{' '}
+ <code>{VISUAL_PREFIX}</code>;<strong>禁止</strong>标成对白/旁白(会口播并烧字幕)
+ </li>
+ <li>
+ <strong>对白</strong>:<code>角色名:台词</code> 或 {DIALOGUE_PREFIX}
+ </li>
+ <li>
+ <strong>旁白</strong>:{DRAMA_NARRATION_PREFIX};字幕逐句轮换、与当前口播句同步,禁止整段叠满屏幕
+ </li>
+ <li>
+ <strong>人物介绍</strong>:本剧首次出场重要角色叠字贴在<strong>该角色身旁</strong>(非底部字幕、非居中大标题)
+ </li>
+ <li>
+ <strong>BGM</strong>:音量低于人声,不抢戏
+ </li>
+ </ul>
+
+ <h4>景别 / 运镜(@ → 小工具)</h4>
+ <ul className="seedance-rules-list">
+ <li>
+ 编辑器键入 <code>@</code> →「小工具」→「景别 / 运镜」,可一键插入「空镜:」「特写:」「推镜:」等前缀
+ </li>
+ <li>公式:主体 + 动作 + 场景 +(景别/运镜)+(光影);每段运动轴建议 ≤ 2</li>
+ <li>近景大旋转易崩脸,环绕留给中景以上</li>
+ </ul>
+ </div>
+ ) : null}
+
+ {tab === 'usage' ? (
+ <div className="seedance-rules-section">
+ <h4>生成前检查</h4>
+ <ul className="seedance-rules-list">
+ <li>脚本校验:时长合法;空镜未被标成对白/旁白(编辑区会即时提示,有错误不可生成)</li>
+ <li>本镜「参与资产」中的角色已有参考图;需说话的角色已「生成音色」或绑定试听(缺项会警告)</li>
+ <li>顶栏确认视频风格、模型、画幅与清晰度后再点「生成」</li>
+ </ul>
+
+ <h4>队列与并行</h4>
+ <ul className="seedance-rules-list">
+ <li>分镜视频走独立 video 队列,Seedance 最多 10 路并行</li>
+ <li>某一镜生成中时,仍可编辑其他镜脚本、预览已完成的视频</li>
+ <li>「全部生成」会为本集各镜依次入队;单镜「生成」仅提交当前镜</li>
+ </ul>
+
+ <h4>镜间尾帧衔接</h4>
+ <ul className="seedance-rules-list">
+ <li>
+ 生成时默认 <code>return_last_frame=true</code>,成功后把尾帧写入分镜{' '}
+ <code>params.lastFrameUrl</code>
+ </li>
+ <li>
+ 顶栏「画幅 · 清晰度」→「用上一镜尾帧作本镜首帧」开启时:若本镜有角色/场景参考图或音色,
+ 尾帧以 <code>reference_image</code> 附在末尾(Seedance 禁止与 <code>first_frame</code> 混用);
+ 无参考媒体时才用 <code>first_frame</code>
+ </li>
+ <li>
+ 普通生成请勿在脚本里写「编辑 / 延长」类措辞,以免任务被重分类;真正的「延长路径」仍未产品化
+ </li>
+ </ul>
+
+ <h4>音色与参考音频</h4>
+ <ul className="seedance-rules-list">
+ <li>角色 / 旁白音色试听会作为 reference_audio 提交,保证口播声线一致</li>
+ <li>参考音频合成后自动截到 15 秒内(API 单条上限约 30 秒)</li>
+ <li>缺少参考图时,系统会尝试自动补图后再提交 Seedance</li>
+ </ul>
+
+ <h4>AI 重新分镜</h4>
+ <p className="seedance-rules-note">
+ 会按剧本与资产重新规划各镜脚本与 @duration 结构;进行中的视频生成需等待完成后再操作,以免状态冲突。空镜须用「空镜:…」等画面写法,勿写成对白。
+ </p>
+
+ <h4>分镜板多宫格(路径 D)</h4>
+ <ul className="seedance-rules-list">
+ <li>顶栏「导入分镜板」:上传 N 宫格图并指定行列</li>
+ <li>≤4 格 → D-1 单镜多段时间戳;≥5 格 → D-2 每格一镜</li>
+ <li>可同时选择六式剪辑节奏(呼吸/心跳/海浪等)写入各段或各镜时长</li>
+ <li>正文自动注入「不复刻网格边框/编号/分隔线」约束</li>
+ </ul>
+ </div>
+ ) : null}
+ </div>
+ </Modal>
+ )
+}
diff --git a/frontend/src/components/drama/StoryboardGridImportModal.tsx b/frontend/src/components/drama/StoryboardGridImportModal.tsx
new file mode 100644
index 0000000..b0a6d35
--- /dev/null
+++ b/frontend/src/components/drama/StoryboardGridImportModal.tsx
@@ -0,0 +1,262 @@
+/** 分镜板多宫格导入:裁格 → 上传素材 → D-1 单镜多段 / D-2 每格一镜 */
+import { useMemo, useState } from 'react'
+import Modal from '../../components/ui/Modal'
+import { dramaApi, type DramaAsset, type DramaFragment } from '../../api/drama'
+import {
+ DRAMA_EDIT_RHYTHM_PRESETS,
+ suggestEpisodeFragmentDurations,
+ suggestRhythmDurations,
+ type DramaEditRhythmId,
+} from '../../lib/dramaEditRhythm'
+import {
+ buildStoryboardD1Content,
+ buildStoryboardD2CellContent,
+ resolveStoryboardImportMode,
+ splitStoryboardGridImage,
+} from '../../lib/dramaStoryboardGrid'
+
+type Props = {
+ open: boolean
+ onClose: () => void
+ projectId: number
+ episodeId: number
+ fragments: DramaFragment[]
+ onImported: (next: DramaFragment[], assets: DramaAsset[]) => void
+}
+
+// 分镜板导入弹窗
+export function StoryboardGridImportModal({
+ open,
+ onClose,
+ projectId,
+ episodeId,
+ fragments,
+ onImported,
+}: Props) {
+ /*
+ * file 宫格图
+ * rows / cols 行列
+ * rhythmId 节奏公式
+ * busy / error / previewMode 状态
+ */
+ const [file, setFile] = useState<File | null>(null)
+ const [rows, setRows] = useState(2)
+ const [cols, setCols] = useState(2)
+ const [rhythmId, setRhythmId] = useState<DramaEditRhythmId>('breath')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+
+ const cellCount = rows * cols
+ const mode = useMemo(() => resolveStoryboardImportMode(cellCount), [cellCount])
+ const previewDurations = useMemo(
+ () =>
+ mode === 'd1'
+ ? suggestRhythmDurations(cellCount, rhythmId, Math.min(15, 4 * cellCount))
+ : suggestEpisodeFragmentDurations(cellCount, rhythmId, 10),
+ [cellCount, mode, rhythmId],
+ )
+
+ // 执行导入
+ async function handleImport() {
+ if (!file) {
+ setError('请先选择分镜板图片')
+ return
+ }
+ setBusy(true)
+ setError('')
+ try {
+ const cells = await splitStoryboardGridImage(file, rows, cols)
+ const uploaded: DramaAsset[] = []
+ for (const cell of cells) {
+ const stub = await dramaApi.createAsset({
+ project_id: projectId,
+ type: 'material',
+ asset_type: 'material',
+ name: `分镜板 ${cell.row + 1}-${cell.col + 1}`,
+ params: {
+ storyboardCell: true,
+ cellIndex: cell.index,
+ source: 'storyboard_grid_import',
+ },
+ })
+ const media = new File([cell.blob], cell.fileName, { type: 'image/jpeg' })
+ const done = await dramaApi.uploadAssetMedia(stub.id, media)
+ uploaded.push(done)
+ }
+
+ const durations = previewDurations
+ let nextFragments: DramaFragment[]
+
+ if (mode === 'd1') {
+ const cover = uploaded[0]?.cover || uploaded[0]?.url || ''
+ const assetIds = uploaded.map((a) => a.id)
+ const content = buildStoryboardD1Content(cells.length, durations)
+ const base = fragments[0]
+ nextFragments = [
+ {
+ id: base?.id || 0,
+ episode_id: episodeId,
+ sort_order: 0,
+ content,
+ cover,
+ video: '',
+ duration_sec: durations.reduce((a, b) => a + b, 0),
+ asset_ids: assetIds,
+ params: {
+ ...(base?.params && typeof base.params === 'object' ? base.params : {}),
+ storyboardImport: 'd1',
+ rhythmId,
+ user_edited: true,
+ },
+ },
+ ...fragments.slice(1).map((f, i) => ({ ...f, sort_order: i + 1 })),
+ ]
+ } else {
+ nextFragments = uploaded.map((asset, index) => {
+ const sec = durations[index] ?? 8
+ return {
+ id: 0,
+ episode_id: episodeId,
+ sort_order: index,
+ content: buildStoryboardD2CellContent(index, sec),
+ cover: asset.cover || asset.url || '',
+ video: '',
+ duration_sec: sec,
+ asset_ids: [asset.id],
+ params: {
+ storyboardImport: 'd2',
+ rhythmId,
+ cellIndex: index,
+ user_edited: true,
+ },
+ }
+ })
+ }
+
+ const saved = await dramaApi.saveFragments(
+ episodeId,
+ nextFragments.map((f, i) => ({
+ sort_order: i,
+ content: f.content,
+ cover: f.cover,
+ video: f.video || '',
+ duration_sec: f.duration_sec ?? 8,
+ params: f.params || {},
+ asset_ids: f.asset_ids || [],
+ })),
+ )
+ onImported(saved.fragments || [], uploaded)
+ onClose()
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '导入失败')
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+ <Modal
+ open={open}
+ onClose={busy ? () => undefined : onClose}
+ title="导入分镜板(多宫格)"
+ size="lg"
+ className="pf-help-modal"
+ footer={
+ <>
+ <button type="button" className="pf-btn pf-btn-ghost pf-btn-sm" disabled={busy} onClick={onClose}>
+ 取消
+ </button>
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime pf-btn-sm"
+ disabled={busy || !file}
+ onClick={() => void handleImport()}
+ >
+ {busy ? '导入中…' : mode === 'd1' ? '导入为单镜多段' : '导入为多镜'}
+ </button>
+ </>
+ }
+ >
+ <div className="drama-storyboard-import">
+ <p className="drama-storyboard-import-lede">
+ 上传 N 宫格分镜板。≤4 格走 D-1(单镜时间戳);≥5 格走 D-2(每格一镜)。生成时会注入「不复刻网格」约束。
+ </p>
+
+ <label className="drama-storyboard-import-file">
+ <span>分镜板图片</span>
+ <input
+ type="file"
+ accept="image/*"
+ disabled={busy}
+ onChange={(e) => {
+ setFile(e.target.files?.[0] || null)
+ setError('')
+ }}
+ />
+ </label>
+
+ <div className="drama-storyboard-import-row">
+ <label>
+ 行
+ <input
+ type="number"
+ min={1}
+ max={6}
+ value={rows}
+ disabled={busy}
+ onChange={(e) => setRows(Number(e.target.value) || 1)}
+ />
+ </label>
+ <label>
+ 列
+ <input
+ type="number"
+ min={1}
+ max={6}
+ value={cols}
+ disabled={busy}
+ onChange={(e) => setCols(Number(e.target.value) || 1)}
+ />
+ </label>
+ <em>
+ {cellCount} 格 · {mode === 'd1' ? 'D-1 单镜多段' : 'D-2 每格一镜'}
+ </em>
+ </div>
+
+ <div className="drama-storyboard-import-rhythm">
+ <strong>剪辑节奏</strong>
+ <div className="drama-storyboard-import-rhythm-chips">
+ {DRAMA_EDIT_RHYTHM_PRESETS.map((preset) => (
+ <button
+ key={preset.id}
+ type="button"
+ className={rhythmId === preset.id ? 'is-active' : undefined}
+ disabled={busy}
+ title={preset.hint}
+ onClick={() => setRhythmId(preset.id)}
+ >
+ {preset.label}
+ </button>
+ ))}
+ </div>
+ <p>
+ 建议时长:{previewDurations.map((s) => `${s}s`).join(' · ')}
+ {mode === 'd2' ? '(将写入各镜)' : '(写入本镜各段)'}
+ </p>
+ </div>
+
+ {mode === 'd2' ? (
+ <p className="drama-storyboard-import-warn">
+ D-2 会用新分镜替换本集现有分镜列表(原视频会被清空,请确认后导入)。
+ </p>
+ ) : (
+ <p className="drama-storyboard-import-note">
+ D-1 会改写第 1 镜脚本与封面,并挂上各格素材参考;其余分镜保留。
+ </p>
+ )}
+
+ {error ? <p className="drama-storyboard-import-error">{error}</p> : null}
+ </div>
+ </Modal>
+ )
+}
diff --git a/frontend/src/components/ui/DialogHost.tsx b/frontend/src/components/ui/DialogHost.tsx
index be4d087..6f7e47d 100644
--- a/frontend/src/components/ui/DialogHost.tsx
+++ b/frontend/src/components/ui/DialogHost.tsx
@@ -1,4 +1,12 @@
import { useEffect, useId, useRef, useState, useSyncExternalStore, type FormEvent } from 'react'
+import {
+ AlertTriangle,
+ CheckCircle2,
+ CircleHelp,
+ PencilLine,
+ Sparkles,
+ type LucideIcon,
+} from 'lucide-react'
import {
closeDialog,
getDialogRequest,
@@ -7,20 +15,21 @@ import {
type DialogTone,
} from '../../lib/dialog'
+// 按弹窗类型与语气返回图标
+function dialogIcon(kind: DialogRequest['kind'], tone: DialogTone | undefined): LucideIcon {
+ if (tone === 'danger') return AlertTriangle
+ if (tone === 'success') return CheckCircle2
+ if (kind === 'prompt') return PencilLine
+ if (kind === 'confirm') return Sparkles
+ return CircleHelp
+}
+
function toneClass(tone: DialogTone | undefined) {
if (tone === 'danger') return 'pf-dialog--danger'
if (tone === 'success') return 'pf-dialog--success'
return 'pf-dialog--default'
}
-function iconFor(kind: DialogRequest['kind'], tone: DialogTone | undefined) {
- if (tone === 'danger') return '!'
- if (tone === 'success') return '✓'
- if (kind === 'prompt') return '✎'
- if (kind === 'confirm') return '?'
- return 'i'
-}
-
function dismissRequest(active: DialogRequest) {
if (active.kind === 'confirm') active.resolve(false)
else if (active.kind === 'prompt') active.resolve(null)
@@ -70,6 +79,7 @@ export default function DialogHost() {
const active: DialogRequest = req
const tone = active.options.tone || 'default'
+ const Icon = dialogIcon(active.kind, tone)
const title =
active.options.title ||
(active.kind === 'confirm' ? '请确认' : active.kind === 'prompt' ? '请输入' : '提示')
@@ -98,28 +108,30 @@ export default function DialogHost() {
onSubmit={onSubmit}
>
<div className="pf-dialog-glow" aria-hidden />
- <div className="pf-dialog-mark" aria-hidden>
- <span>{iconFor(active.kind, tone)}</span>
- </div>
- <div className="pf-dialog-body">
- <h2 id={titleId} className="pf-dialog-title">
- {title}
- </h2>
- {message ? (
- <p id={descId} className="pf-dialog-message">
- {message}
- </p>
- ) : null}
- {active.kind === 'prompt' ? (
- <input
- ref={inputRef}
- className="pf-dialog-input"
- value={promptValue}
- placeholder={active.options.placeholder || ''}
- onChange={(e) => setPromptValue(e.target.value)}
- />
- ) : null}
+ <div className="pf-dialog-header">
+ <div className="pf-dialog-mark" aria-hidden>
+ <Icon size={22} strokeWidth={1.75} />
+ </div>
+ <div className="pf-dialog-body">
+ <h2 id={titleId} className="pf-dialog-title">
+ {title}
+ </h2>
+ {message ? (
+ <p id={descId} className="pf-dialog-message">
+ {message}
+ </p>
+ ) : null}
+ </div>
</div>
+ {active.kind === 'prompt' ? (
+ <input
+ ref={inputRef}
+ className="pf-dialog-input"
+ value={promptValue}
+ placeholder={active.options.placeholder || ''}
+ onChange={(e) => setPromptValue(e.target.value)}
+ />
+ ) : null}
<div className="pf-dialog-actions">
{cancelText ? (
<button
diff --git a/frontend/src/lib/characterVoiceGenerate.ts b/frontend/src/lib/characterVoiceGenerate.ts
new file mode 100644
index 0000000..a824d49
--- /dev/null
+++ b/frontend/src/lib/characterVoiceGenerate.ts
@@ -0,0 +1,41 @@
+/** 按角色设定 AI 生成音色并绑定到 voiceAudio(无弹窗,供卡片一键生成) */
+import { dramaApi, type DramaAsset } from '../api/drama'
+import { buildBoundParams } from '../pages/drama/CharacterVoiceBindModal'
+
+export type CharacterVoiceGenerateResult = {
+ character: DramaAsset
+ voice: DramaAsset
+}
+
+// 根据角色资产生成音色描述、合成试听并写回绑定
+export async function generateAndBindCharacterVoice(
+ projectId: number,
+ asset: DramaAsset,
+): Promise<CharacterVoiceGenerateResult> {
+ const promptResult = await dramaApi.suggestVoicePrompt({
+ project_id: projectId,
+ asset_id: asset.id,
+ })
+ const voicePrompt = (promptResult.voice_prompt || '').trim()
+ if (!voicePrompt) {
+ throw new Error('音色描述为空')
+ }
+
+ const voiceResult = await dramaApi.generateVoice({
+ project_id: projectId,
+ name: `${asset.name || '角色'}音色`,
+ voice_prompt: voicePrompt,
+ speaker: promptResult.speaker || undefined,
+ sample_text: promptResult.sample_text || undefined,
+ character_asset_id: asset.id,
+ })
+ const voice = voiceResult.asset
+ if (!voice?.url) {
+ throw new Error('音色合成失败')
+ }
+
+ const character = await dramaApi.updateAsset(asset.id, {
+ params: buildBoundParams(asset, voice),
+ })
+ return { character, voice }
+}
diff --git a/frontend/src/lib/dramaCameraLexicon.ts b/frontend/src/lib/dramaCameraLexicon.ts
new file mode 100644
index 0000000..a3c8edc
--- /dev/null
+++ b/frontend/src/lib/dramaCameraLexicon.ts
@@ -0,0 +1,71 @@
+/**
+ * 漫剧运镜 / 景别词库(对齐 docs/EPISODE_RULES.md §5)
+ * 供分集编辑 @ 菜单插入画面行前缀或运镜短语
+ */
+
+export type DramaCameraLexiconGroup = 'shot' | 'move'
+
+export type DramaCameraLexiconItem = {
+ id: string
+ group: DramaCameraLexiconGroup
+ /** 列表展示名 */
+ label: string
+ /** 插入到脚本的文本(用户可继续补描写) */
+ insert: string
+ /** 一行说明 */
+ hint: string
+}
+
+/** 景别标签:写入画面行,勿标成对白 */
+export const DRAMA_SHOT_SIZE_LEXICON: DramaCameraLexiconItem[] = [
+ { id: 'empty', group: 'shot', label: '空镜', insert: '空镜:', hint: '环境建立,无对白无旁白' },
+ { id: 'wide', group: 'shot', label: '远景', insert: '远景:', hint: '交代空间关系' },
+ { id: 'full', group: 'shot', label: '全景', insert: '全景:', hint: '全身与环境同框' },
+ { id: 'medium', group: 'shot', label: '中景', insert: '中景:', hint: '腰部以上,对白常用' },
+ { id: 'close', group: 'shot', label: '近景', insert: '近景:', hint: '胸部以上,情绪贴近' },
+ { id: 'closeup', group: 'shot', label: '特写', insert: '特写:', hint: '脸或关键道具' },
+ { id: 'ecu', group: 'shot', label: '大特写', insert: '大特写:', hint: '眼、手、细节' },
+ { id: 'establish', group: 'shot', label: '建立镜头', insert: '建立镜头:', hint: '开场定场景气氛' },
+ { id: 'atmosphere', group: 'shot', label: '气氛镜头', insert: '气氛镜头:', hint: '光影/天气/物件烘托' },
+]
+
+/** 运镜短语:单段运动轴建议 ≤ 2 */
+export const DRAMA_CAMERA_MOVE_LEXICON: DramaCameraLexiconItem[] = [
+ { id: 'push', group: 'move', label: '推镜', insert: '推镜:', hint: '镜头前推靠近主体' },
+ { id: 'pull', group: 'move', label: '拉镜', insert: '拉镜:', hint: '镜头后拉展开空间' },
+ { id: 'pan', group: 'move', label: '摇镜', insert: '摇镜:', hint: '机位不动,水平/垂直扫视' },
+ { id: 'truck', group: 'move', label: '移镜', insert: '移镜:', hint: '机位平移跟随' },
+ { id: 'follow', group: 'move', label: '跟拍', insert: '跟拍:', hint: '跟随人物移动' },
+ { id: 'high', group: 'move', label: '俯拍', insert: '俯拍:', hint: '高角度向下' },
+ { id: 'low', group: 'move', label: '仰拍', insert: '仰拍:', hint: '低角度向上' },
+ { id: 'aerial', group: 'move', label: '航拍', insert: '航拍:', hint: '大全景俯视' },
+]
+
+/** 合并词库(插入列表用) */
+export const DRAMA_CAMERA_LEXICON: DramaCameraLexiconItem[] = [
+ ...DRAMA_SHOT_SIZE_LEXICON,
+ ...DRAMA_CAMERA_MOVE_LEXICON,
+]
+
+/** 运镜使用提示(只展示,不插入) */
+export const DRAMA_CAMERA_USAGE_TIPS = [
+ '公式:主体 + 动作 + 场景 +(景别/运镜)+(光影)',
+ '每段运动轴 ≤ 2(推+摇可以;推+摇+升易失控)',
+ '近景大旋转易崩脸,环绕留给中景以上',
+ '空镜/景别必须用画面写法,禁止标成对白或旁白',
+] as const
+
+// 按关键字过滤词库(匹配 label / insert / hint)
+export function filterDramaCameraLexicon(
+ items: DramaCameraLexiconItem[],
+ query: string,
+): DramaCameraLexiconItem[] {
+ const q = (query || '').trim().toLowerCase()
+ if (!q) return items
+ return items.filter(
+ (item) =>
+ item.label.toLowerCase().includes(q) ||
+ item.insert.toLowerCase().includes(q) ||
+ item.hint.toLowerCase().includes(q),
+ )
+}
diff --git a/frontend/src/lib/dramaEditRhythm.ts b/frontend/src/lib/dramaEditRhythm.ts
new file mode 100644
index 0000000..4ef61e0
--- /dev/null
+++ b/frontend/src/lib/dramaEditRhythm.ts
@@ -0,0 +1,115 @@
+/**
+ * 短剧剪辑节奏公式(社区 Skill 六式,用于分镜时长建议 / 整集导出规划)
+ * 对齐 docs/EPISODE_RULES.md §10 P3
+ */
+
+export type DramaEditRhythmId =
+ | 'breath'
+ | 'heartbeat'
+ | 'wave'
+ | 'elastic'
+ | 'pulse'
+ | 'silence_hammer'
+
+export type DramaEditRhythmPreset = {
+ id: DramaEditRhythmId
+ label: string
+ hint: string
+ /** 相对节拍权重,会归一化到目标总秒数 */
+ weights: number[]
+}
+
+export const DRAMA_EDIT_RHYTHM_PRESETS: DramaEditRhythmPreset[] = [
+ {
+ id: 'breath',
+ label: '呼吸式',
+ hint: '缓入—展开—回落,适合建立与抒情',
+ weights: [3, 5, 4, 3],
+ },
+ {
+ id: 'heartbeat',
+ label: '心跳式',
+ hint: '短促加速,适合冲突与对峙',
+ weights: [2, 2, 3, 2, 4],
+ },
+ {
+ id: 'wave',
+ label: '海浪式',
+ hint: '层层推高再泄力,适合高潮戏',
+ weights: [3, 4, 5, 6, 3],
+ },
+ {
+ id: 'elastic',
+ label: '弹性时间',
+ hint: '关键动作拉长,其余压缩',
+ weights: [2, 6, 2, 3],
+ },
+ {
+ id: 'pulse',
+ label: '脉冲式',
+ hint: '规律跳动,适合卡点与群像',
+ weights: [3, 3, 3, 3],
+ },
+ {
+ id: 'silence_hammer',
+ label: '静默锤击',
+ hint: '蓄势静场后猛切,适合反转',
+ weights: [5, 2, 6],
+ },
+]
+
+const SEGMENT_MIN = 3
+const SEGMENT_MAX = 12
+
+// 按节奏公式为 N 段分配秒数(钳制 3–12,合计贴近 targetTotal)
+export function suggestRhythmDurations(
+ segmentCount: number,
+ rhythmId: DramaEditRhythmId,
+ targetTotal = 15,
+): number[] {
+ const count = Math.max(1, Math.floor(segmentCount))
+ const preset =
+ DRAMA_EDIT_RHYTHM_PRESETS.find((p) => p.id === rhythmId) || DRAMA_EDIT_RHYTHM_PRESETS[0]
+ const weights: number[] = []
+ for (let i = 0; i < count; i++) {
+ weights.push(preset.weights[i % preset.weights.length] || 3)
+ }
+ const sumW = weights.reduce((a, b) => a + b, 0) || 1
+ const raw = weights.map((w) => (w / sumW) * Math.max(SEGMENT_MIN * count, targetTotal))
+ const clamped = raw.map((v) => Math.max(SEGMENT_MIN, Math.min(SEGMENT_MAX, Math.round(v))))
+ // 微调合计:过短则从最大段加,过长则从最大段减
+ let total = clamped.reduce((a, b) => a + b, 0)
+ const goal = Math.max(SEGMENT_MIN * count, Math.min(30, Math.round(targetTotal)))
+ let guard = 0
+ while (total < goal && guard < 40) {
+ const idx = clamped.indexOf(Math.max(...clamped))
+ if (clamped[idx] < SEGMENT_MAX) {
+ clamped[idx] += 1
+ total += 1
+ } else break
+ guard += 1
+ }
+ while (total > goal && guard < 80) {
+ const idx = clamped.indexOf(Math.max(...clamped))
+ if (clamped[idx] > SEGMENT_MIN) {
+ clamped[idx] -= 1
+ total -= 1
+ } else break
+ guard += 1
+ }
+ return clamped
+}
+
+// 整集导出规划:为每镜建议时长(D-2 / 已有分镜条数)
+export function suggestEpisodeFragmentDurations(
+ fragmentCount: number,
+ rhythmId: DramaEditRhythmId,
+ /** 单镜目标时长均值 */
+ perFragmentTarget = 10,
+): number[] {
+ const count = Math.max(1, Math.floor(fragmentCount))
+ const total = Math.min(30 * count, Math.max(4 * count, perFragmentTarget * count))
+ return suggestRhythmDurations(count, rhythmId, total).map((sec) =>
+ Math.max(4, Math.min(30, sec)),
+ )
+}
diff --git a/frontend/src/lib/dramaEpisodePromptEditor.ts b/frontend/src/lib/dramaEpisodePromptEditor.ts
index ca26ff0..5844dea 100644
--- a/frontend/src/lib/dramaEpisodePromptEditor.ts
+++ b/frontend/src/lib/dramaEpisodePromptEditor.ts
@@ -114,6 +114,20 @@ export function insertDurationChipAtRange(range: Range, seconds: number) {
selection.addRange(caretRange)
}
+// 在 Range 处插入纯文本(运镜/景别前缀等)
+export function insertPlainTextAtRange(range: Range, text: string) {
+ const selection = window.getSelection()
+ range.deleteContents()
+ const node = document.createTextNode(text)
+ range.insertNode(node)
+ if (!selection) return
+ const caretRange = document.createRange()
+ caretRange.setStartAfter(node)
+ caretRange.collapse(true)
+ selection.removeAllRanges()
+ selection.addRange(caretRange)
+}
+
// 在 Range 处插入资产标签
export function insertMentionChipAtRange(range: Range, chip: DramaMentionChipData) {
const selection = window.getSelection()
diff --git a/frontend/src/lib/dramaEpisodeScriptValidate.ts b/frontend/src/lib/dramaEpisodeScriptValidate.ts
new file mode 100644
index 0000000..31f7358
--- /dev/null
+++ b/frontend/src/lib/dramaEpisodeScriptValidate.ts
@@ -0,0 +1,239 @@
+/**
+ * 漫剧分镜脚本校验(对齐 docs/EPISODE_RULES.md §3 / §9)
+ * 用于生成前告警:时长、空镜误标对白、资产缺图/缺音色
+ */
+import type { DramaAsset, DramaFragment } from '../api/drama'
+import {
+ SEGMENT_DURATION_MAX,
+ SEGMENT_DURATION_MIN,
+ SHOT_DURATION_MAX,
+ extractDurations,
+ isValidSegmentDuration,
+ sumDuration,
+} from './segmentDuration'
+
+/** 漫剧字幕 cue(与后端 DRAMA_SUBTITLE_CUE 一致) */
+export const DRAMA_SUBTITLE_CUE = '【字幕:底部居中·简体中文·逐句轮换·与口播同步】'
+
+/** 画面无配音前缀 */
+export const VISUAL_PREFIX = '【画面·无配音仅环境音】'
+
+/** 对白前缀 */
+export const DIALOGUE_PREFIX = '【对白·慢速清晰·同步字幕】'
+
+/** 旁白前缀 */
+export const DRAMA_NARRATION_PREFIX = '【旁白·慢速清晰·同步字幕】'
+
+// 空镜 / 景别冒号标签(与后端 VISUAL_SHOT_LABEL_RE 对齐)
+const VISUAL_SHOT_LABEL_RE =
+ /^(?:空镜|画面|远景|近景|中景|全景|特写|大特写|跟拍|俯拍|仰拍|航拍|推镜|拉镜|摇镜|环境|镜头|动作|转场|闪回|建立镜头|气氛镜头)\s*[::]/
+
+const VOICE_CUE_PREFIX_RE = /^【(?:对白|旁白|内心独白)[^】]*】\s*/
+
+export type DramaScriptIssue = {
+ level: 'error' | 'warn'
+ message: string
+}
+
+// 去掉对白/旁白生产前缀
+function stripVoiceCuePrefix(line: string): string {
+ return (line || '').replace(VOICE_CUE_PREFIX_RE, '').trim()
+}
+
+// 角色是否已绑定可提交的参考音频
+function assetHasVoiceBinding(asset: DramaAsset): boolean {
+ const params = (asset.params || {}) as Record<string, unknown>
+ const raw = params.voiceAudio
+ if (raw && typeof raw === 'object') {
+ const data = raw as Record<string, unknown>
+ const url =
+ typeof data.url === 'string'
+ ? data.url
+ : typeof data.previewUrl === 'string'
+ ? data.previewUrl
+ : ''
+ if (url.trim()) return true
+ }
+ const canvas = params.canvas
+ if (canvas && typeof canvas === 'object') {
+ const voiceAudio = (canvas as Record<string, unknown>).voiceAudio
+ if (voiceAudio && typeof voiceAudio === 'object') {
+ const url = (voiceAudio as Record<string, unknown>).url
+ if (typeof url === 'string' && url.trim()) return true
+ }
+ }
+ return false
+}
+
+// 合并正文 @asset 与 asset_ids
+function listFragmentAssetIds(frag: DramaFragment): number[] {
+ const seen = new Set<number>()
+ const out: number[] = []
+ const re = /@asset:(\d+)/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(frag.content || ''))) {
+ const id = Number(m[1])
+ if (!id || seen.has(id)) continue
+ seen.add(id)
+ out.push(id)
+ }
+ for (const id of frag.asset_ids || []) {
+ if (!id || seen.has(id)) continue
+ seen.add(id)
+ out.push(id)
+ }
+ return out
+}
+
+// 判断正文是否为纯画面 / 空镜描写
+export function isVisualDescriptionBody(text: string): boolean {
+ let body = stripVoiceCuePrefix((text || '').trim())
+ body = body.replace(/^【(?:画面|空镜)[^】]*】\s*/, '').trim()
+ if (!body) return false
+ if (VISUAL_SHOT_LABEL_RE.test(body)) return true
+ if (body.startsWith('空镜') || body.startsWith('△') || body.startsWith('Δ')) return true
+ return false
+}
+
+// 脚本是否含真实口播意图(排除空镜冒号)
+function scriptLikelyNeedsVoice(content: string): boolean {
+ for (const raw of (content || '').replace(/\r\n/g, '\n').split('\n')) {
+ const line = raw.trim()
+ if (!line || line.startsWith('@duration:')) continue
+ if (
+ line.startsWith('【字幕') ||
+ line.startsWith('【BGM') ||
+ line.startsWith('【人物介绍') ||
+ line.startsWith('【片头') ||
+ line.startsWith('【背景介绍')
+ ) {
+ continue
+ }
+ if (line.startsWith('【对白') || line.startsWith('【旁白') || line.startsWith('【内心独白')) {
+ if (!isVisualDescriptionBody(line)) return true
+ continue
+ }
+ if (isVisualDescriptionBody(line)) continue
+ if (/^[^::\n]{1,16}[::]/.test(line) && !VISUAL_SHOT_LABEL_RE.test(line)) {
+ return true
+ }
+ }
+ return false
+}
+
+// 校验单镜脚本:时长 + 空镜误标
+export function validateDramaFragmentScript(content: string): DramaScriptIssue[] {
+ const issues: DramaScriptIssue[] = []
+ const durations = extractDurations(content || '')
+ const total = sumDuration(content || '')
+
+ if (durations.some((value) => !isValidSegmentDuration(value))) {
+ issues.push({
+ level: 'error',
+ message: `单个 @duration 需在 ${SEGMENT_DURATION_MIN}–${SEGMENT_DURATION_MAX} 秒之间`,
+ })
+ }
+
+ if (total > SHOT_DURATION_MAX) {
+ issues.push({
+ level: 'error',
+ message: `本镜 @duration 合计 ${total}s,超过上限 ${SHOT_DURATION_MAX}s`,
+ })
+ }
+
+ for (const raw of (content || '').replace(/\r\n/g, '\n').split('\n')) {
+ const line = raw.trim()
+ if (!line || line.startsWith('@duration:')) continue
+ if (line.startsWith('【字幕') || line.startsWith('【BGM') || line.startsWith('【人物介绍')) {
+ continue
+ }
+ if (VOICE_CUE_PREFIX_RE.test(line) && isVisualDescriptionBody(line)) {
+ issues.push({
+ level: 'error',
+ message:
+ '检测到「空镜/景别」被标成对白或旁白(会口播并烧字幕)。请改为「【画面·无配音仅环境音】」或「空镜:…」纯画面行',
+ })
+ break
+ }
+ }
+
+ return issues
+}
+
+// 校验本镜关联资产:缺图 / 说话角色缺音色(警告级,可继续生成)
+export function validateDramaFragmentAssets(
+ frag: DramaFragment | null | undefined,
+ assets: DramaAsset[],
+): DramaScriptIssue[] {
+ const issues: DramaScriptIssue[] = []
+ if (!frag) return issues
+
+ const byId = new Map(assets.map((a) => [a.id, a]))
+ const ids = listFragmentAssetIds(frag)
+ const needsVoice = scriptLikelyNeedsVoice(frag.content || '')
+
+ const missingImage: string[] = []
+ const missingVoice: string[] = []
+
+ for (const id of ids) {
+ const asset = byId.get(id)
+ if (!asset) {
+ missingImage.push(`#${id}`)
+ continue
+ }
+ const kind = (asset.type || '').toLowerCase()
+ const hasImage = Boolean((asset.cover || asset.url || '').trim())
+ if ((kind === 'character' || kind === 'scene' || kind === 'prop') && !hasImage) {
+ missingImage.push(asset.name || `#${id}`)
+ }
+ if (kind === 'character' && needsVoice && !assetHasVoiceBinding(asset)) {
+ missingVoice.push(asset.name || `#${id}`)
+ }
+ }
+
+ if (missingImage.length > 0) {
+ issues.push({
+ level: 'warn',
+ message: `以下资产缺少参考图,生成时可能自动补图或效果不稳定:${missingImage.slice(0, 5).join('、')}${missingImage.length > 5 ? '…' : ''}`,
+ })
+ }
+
+ if (missingVoice.length > 0) {
+ issues.push({
+ level: 'warn',
+ message: `脚本含对白,但以下角色尚未绑定音色:${missingVoice.slice(0, 5).join('、')}${missingVoice.length > 5 ? '…' : ''}`,
+ })
+ }
+
+ return issues
+}
+
+// 合并脚本与资产问题;有 error 则不可直接生成
+export function collectDramaGenerateGateIssues(
+ frag: DramaFragment | null | undefined,
+ assets: DramaAsset[],
+): { blocking: DramaScriptIssue[]; warnings: DramaScriptIssue[] } {
+ const scriptIssues = validateDramaFragmentScript(frag?.content || '')
+ const assetIssues = validateDramaFragmentAssets(frag, assets)
+ const all = [...scriptIssues, ...assetIssues]
+ return {
+ blocking: all.filter((i) => i.level === 'error'),
+ warnings: all.filter((i) => i.level === 'warn'),
+ }
+}
+
+// 把问题列表拼成确认框文案
+export function formatDramaGateMessage(
+ blocking: DramaScriptIssue[],
+ warnings: DramaScriptIssue[],
+ baseMessage: string,
+): string {
+ const parts = [baseMessage]
+ if (blocking.length > 0) {
+ parts.push('', '【须先修复】', ...blocking.map((i) => `· ${i.message}`))
+ }
+ if (warnings.length > 0) {
+ parts.push('', '【建议处理,仍可继续】', ...warnings.map((i) => `· ${i.message}`))
+ }
+ return parts.join('\n')
+}
diff --git a/frontend/src/lib/dramaEpisodeVideoTimeline.ts b/frontend/src/lib/dramaEpisodeVideoTimeline.ts
new file mode 100644
index 0000000..334bbd8
--- /dev/null
+++ b/frontend/src/lib/dramaEpisodeVideoTimeline.ts
@@ -0,0 +1,206 @@
+/** 分集视频预览:跨分镜全局时间轴工具 */
+import type { DramaFragment } from '../api/drama'
+
+// DramaEpisodeVideoTimelineSegment 分集时间轴上的分镜区间
+export type DramaEpisodeVideoTimelineSegment = {
+ fragmentId: number
+ index: number
+ durationSec: number
+ startSec: number
+ endSec: number
+ hasVideo: boolean
+}
+
+// 从分镜正文合计 @duration 秒数
+function sumFragmentContentDuration(content: string): number {
+ const re = /@duration:(\d+)/g
+ let total = 0
+ let m: RegExpExecArray | null
+ while ((m = re.exec(content || ''))) {
+ const sec = Number(m[1])
+ if (sec > 0) total += sec
+ }
+ return total
+}
+
+// 解析分镜在时间轴上的时长(秒)
+function resolveEpisodeFragmentTimelineDuration(fragment: DramaFragment): number {
+ const fromTags = sumFragmentContentDuration(fragment.content)
+ if (fromTags > 0) return Math.min(30, Math.max(4, fromTags))
+ const fallback = fragment.duration_sec && fragment.duration_sec > 0 ? fragment.duration_sec : 8
+ return Math.min(30, Math.max(4, fallback))
+}
+
+// 根据分集全部分镜构建时间轴分段
+export function buildEpisodeVideoTimelineSegments(
+ fragments: DramaFragment[],
+): DramaEpisodeVideoTimelineSegment[] {
+ let cursor = 0
+
+ return fragments.flatMap((fragment, index) => {
+ const durationSec = resolveEpisodeFragmentTimelineDuration(fragment)
+
+ if (durationSec <= 0) {
+ return []
+ }
+
+ const startSec = cursor
+ const endSec = cursor + durationSec
+
+ cursor = endSec
+
+ return [
+ {
+ fragmentId: fragment.id,
+ index,
+ durationSec,
+ startSec,
+ endSec,
+ hasVideo: Boolean(fragment.video),
+ },
+ ]
+ })
+}
+
+// 计算分集时间轴总时长
+export function resolveEpisodeVideoTimelineTotalDuration(
+ segments: DramaEpisodeVideoTimelineSegment[],
+): number {
+ if (segments.length === 0) {
+ return 0
+ }
+
+ return segments[segments.length - 1]?.endSec ?? 0
+}
+
+// 将分镜内播放时间映射为全局时间轴位置
+export function resolveGlobalTimeFromFragmentPlayback(
+ segment: DramaEpisodeVideoTimelineSegment,
+ localTimeSec: number,
+ localDurationSec: number,
+): number {
+ if (localDurationSec <= 0) {
+ return segment.startSec
+ }
+
+ const ratio = Math.min(1, Math.max(0, localTimeSec / localDurationSec))
+
+ return segment.startSec + ratio * segment.durationSec
+}
+
+// 将全局时间轴位置映射为分镜内播放时间
+export function resolveFragmentPlaybackFromGlobalTime(
+ segments: DramaEpisodeVideoTimelineSegment[],
+ globalTimeSec: number,
+): {
+ segment: DramaEpisodeVideoTimelineSegment
+ localTimeSec: number
+} | null {
+ if (segments.length === 0) {
+ return null
+ }
+
+ const clampedGlobalTime = Math.min(
+ Math.max(0, globalTimeSec),
+ resolveEpisodeVideoTimelineTotalDuration(segments),
+ )
+
+ const segment =
+ segments.find(
+ (item) => clampedGlobalTime >= item.startSec && clampedGlobalTime < item.endSec,
+ ) ?? segments[segments.length - 1]
+
+ if (!segment) {
+ return null
+ }
+
+ const localTimeSec = Math.min(
+ segment.durationSec,
+ Math.max(0, clampedGlobalTime - segment.startSec),
+ )
+
+ return {
+ segment,
+ localTimeSec,
+ }
+}
+
+// 解析当前全局时间所在的分镜索引
+export function resolveEpisodeVideoTimelineSegmentIndex(
+ segments: DramaEpisodeVideoTimelineSegment[],
+ globalTimeSec: number,
+): number {
+ if (segments.length === 0) {
+ return 0
+ }
+
+ const matched = segments.find(
+ (segment) => globalTimeSec >= segment.startSec && globalTimeSec < segment.endSec,
+ )
+
+ return matched?.index ?? segments[segments.length - 1]?.index ?? 0
+}
+
+// 计算单个分镜区间内的已播放比例(0–1)
+export function resolveEpisodeTimelineSegmentFillRatio(
+ segment: DramaEpisodeVideoTimelineSegment,
+ globalTimeSec: number,
+): number {
+ if (globalTimeSec >= segment.endSec) {
+ return 1
+ }
+
+ if (globalTimeSec <= segment.startSec) {
+ return 0
+ }
+
+ const span = segment.endSec - segment.startSec
+
+ if (span <= 0) {
+ return 0
+ }
+
+ return (globalTimeSec - segment.startSec) / span
+}
+
+// 将秒数格式化为 mm:ss
+export function formatVideoTimelineClock(seconds: number): string {
+ const safeSeconds = Math.max(0, Math.floor(seconds))
+ const minutes = Math.floor(safeSeconds / 60)
+ const remainSeconds = safeSeconds % 60
+
+ return `${String(minutes).padStart(2, '0')}:${String(remainSeconds).padStart(2, '0')}`
+}
+
+// 将进度条点击比例映射为全局播放时间
+export function resolveVideoTimelineSeekTime(ratio: number, totalDurationSec: number): number {
+ if (totalDurationSec <= 0) {
+ return 0
+ }
+
+ const clampedRatio = Math.min(1, Math.max(0, ratio))
+
+ return clampedRatio * totalDurationSec
+}
+
+// 查找下一个可播放视频的分镜 ID
+export function resolveNextPlayableFragmentId(
+ segments: DramaEpisodeVideoTimelineSegment[],
+ currentFragmentId: number,
+): number | null {
+ const currentIndex = segments.findIndex((segment) => segment.fragmentId === currentFragmentId)
+
+ if (currentIndex < 0) {
+ return null
+ }
+
+ for (let index = currentIndex + 1; index < segments.length; index += 1) {
+ const segment = segments[index]
+
+ if (segment?.hasVideo) {
+ return segment.fragmentId
+ }
+ }
+
+ return null
+}
diff --git a/frontend/src/lib/dramaGenQueue.ts b/frontend/src/lib/dramaGenQueue.ts
new file mode 100644
index 0000000..4fdeea6
--- /dev/null
+++ b/frontend/src/lib/dramaGenQueue.ts
@@ -0,0 +1,296 @@
+/** 漫剧全局生成队列:图片 / 视频等任务统一展示与恢复 */
+import { useSyncExternalStore } from 'react'
+
+export type DramaGenJobKind = 'image' | 'video'
+
+export type DramaGenJobStatus = 'queued' | 'running' | 'done' | 'failed'
+
+export type DramaGenJob = {
+ id: string
+ kind: DramaGenJobKind
+ projectId: number
+ /** 资产 id 或分镜 id */
+ targetId: number
+ episodeId?: number
+ title: string
+ /** 子类型文案:角色 / 场景 / 分镜视频 等 */
+ subtype: string
+ status: DramaGenJobStatus
+ message?: string
+ error?: string
+ createdAt: number
+ finishedAt?: number
+}
+
+type Listener = () => void
+
+const DONE_RETENTION_MS = 10 * 60 * 1000
+const EMPTY: DramaGenJob[] = []
+
+/*
+ * jobs 统一任务列表
+ * cachedSnapshot 对外快照
+ * listeners 订阅
+ */
+let jobs: DramaGenJob[] = []
+let cachedSnapshot: DramaGenJob[] = EMPTY
+const listeners = new Set<Listener>()
+
+// 快照是否等价
+function snapshotsEqual(a: DramaGenJob[], b: DramaGenJob[]): boolean {
+ if (a === b) return true
+ if (a.length !== b.length) return false
+ for (let i = 0; i < a.length; i += 1) {
+ const x = a[i]
+ const y = b[i]
+ if (
+ x.id !== y.id ||
+ x.status !== y.status ||
+ x.message !== y.message ||
+ x.error !== y.error ||
+ x.finishedAt !== y.finishedAt ||
+ x.title !== y.title
+ ) {
+ return false
+ }
+ }
+ return true
+}
+
+// 清理过期完成/失败项(进行中永不清)
+function pruneFinished() {
+ const now = Date.now()
+ jobs = jobs.filter((job) => {
+ if (job.status === 'queued' || job.status === 'running') return true
+ if (!job.finishedAt) return true
+ return now - job.finishedAt < DONE_RETENTION_MS
+ })
+}
+
+// 刷新快照并通知
+function emit() {
+ pruneFinished()
+ const next = jobs.length === 0 ? EMPTY : [...jobs]
+ if (!snapshotsEqual(cachedSnapshot, next)) {
+ cachedSnapshot = next
+ }
+ listeners.forEach((fn) => fn())
+}
+
+// 读取快照
+export function getDramaGenQueue(): DramaGenJob[] {
+ pruneFinished()
+ if (jobs.length === 0) {
+ cachedSnapshot = EMPTY
+ return EMPTY
+ }
+ if (!snapshotsEqual(cachedSnapshot, jobs)) {
+ cachedSnapshot = [...jobs]
+ }
+ return cachedSnapshot
+}
+
+// 订阅
+export function subscribeDramaGenQueue(listener: Listener): () => void {
+ listeners.add(listener)
+ return () => listeners.delete(listener)
+}
+
+// Hook
+export function useDramaGenQueue(): DramaGenJob[] {
+ return useSyncExternalStore(subscribeDramaGenQueue, getDramaGenQueue, getDramaGenQueue)
+}
+
+// 活跃任务数(角标)
+export function getDramaGenActiveCount(): number {
+ return jobs.filter((j) => j.status === 'queued' || j.status === 'running').length
+}
+
+// 写入或更新一条任务
+export function upsertDramaGenJob(patch: Omit<DramaGenJob, 'createdAt' | 'finishedAt'> & {
+ createdAt?: number
+ finishedAt?: number
+}): void {
+ const idx = jobs.findIndex((j) => j.id === patch.id)
+ const prev = idx >= 0 ? jobs[idx] : null
+ const status = patch.status
+ const finishedAt =
+ status === 'done' || status === 'failed'
+ ? patch.finishedAt ?? prev?.finishedAt ?? Date.now()
+ : undefined
+ const next: DramaGenJob = {
+ id: patch.id,
+ kind: patch.kind,
+ projectId: patch.projectId,
+ targetId: patch.targetId,
+ episodeId: patch.episodeId,
+ title: patch.title,
+ subtype: patch.subtype,
+ status,
+ message: patch.message,
+ error: patch.error,
+ createdAt: patch.createdAt ?? prev?.createdAt ?? Date.now(),
+ finishedAt,
+ }
+ if (idx >= 0) {
+ jobs = jobs.map((j, i) => (i === idx ? next : j))
+ } else {
+ jobs = [...jobs, next]
+ }
+ emit()
+}
+
+// 图片任务 id
+export function imageJobId(assetId: number): string {
+ return `image:${assetId}`
+}
+
+// 视频分镜任务 id
+export function videoJobId(fragmentId: number): string {
+ return `video:${fragmentId}`
+}
+
+// 同步资产生图任务到统一队列(由 dramaImageGenQueue 回调)
+export function syncImageJobToUnified(input: {
+ assetId: number
+ projectId: number
+ assetName: string
+ assetType: string
+ status: DramaGenJobStatus
+ error?: string
+}): void {
+ upsertDramaGenJob({
+ id: imageJobId(input.assetId),
+ kind: 'image',
+ projectId: input.projectId,
+ targetId: input.assetId,
+ title: input.assetName || `资产 ${input.assetId}`,
+ subtype: input.assetType || 'image',
+ status: input.status,
+ error: input.error,
+ message:
+ input.status === 'running'
+ ? '生图中'
+ : input.status === 'queued'
+ ? '排队中'
+ : undefined,
+ })
+}
+
+type FragmentStatusItem = {
+ fragment_id: number
+ status: string
+ message?: string
+ phase?: string
+ error?: string
+ video?: string
+ cover?: string
+}
+
+// 从分集 generate_status 同步视频任务
+export function syncEpisodeVideoJobs(input: {
+ projectId: number
+ episodeId: number
+ episodeName?: string
+ fragments: Array<{ id: number; sort_order?: number; content?: string }>
+ statusItems: FragmentStatusItem[]
+}): void {
+ const fragLabel = (fragId: number) => {
+ const frag = input.fragments.find((f) => f.id === fragId)
+ const idx = frag?.sort_order ?? input.fragments.findIndex((f) => f.id === fragId)
+ const n = String((typeof idx === 'number' && idx >= 0 ? idx : 0) + 1).padStart(2, '0')
+ return `片段 ${n}`
+ }
+
+ for (const item of input.statusItems) {
+ const raw = String(item.status || 'idle')
+ if (raw === 'idle') continue
+ let status: DramaGenJobStatus = 'running'
+ if (raw === 'done') status = 'done'
+ else if (raw === 'failed') status = 'failed'
+ else if (raw === 'queued') status = 'queued'
+ else status = 'running'
+
+ const title = `${input.episodeName ? `${input.episodeName} · ` : ''}${fragLabel(item.fragment_id)}`
+ upsertDramaGenJob({
+ id: videoJobId(item.fragment_id),
+ kind: 'video',
+ projectId: input.projectId,
+ targetId: item.fragment_id,
+ episodeId: input.episodeId,
+ title,
+ subtype: '分镜视频',
+ status,
+ message: item.message || (item.phase === 'assets' ? '生成参考图…' : undefined),
+ error: item.error,
+ })
+ }
+ emit()
+}
+
+// 入队时立刻写入队列(乐观展示,不依赖首轮轮询)
+export function enqueueEpisodeVideoJobs(input: {
+ projectId: number
+ episodeId: number
+ episodeName?: string
+ fragments: Array<{ id: number; sort_order?: number }>
+ fragmentIds: number[]
+}): void {
+ const idSet = new Set(input.fragmentIds)
+ const items = input.fragments
+ .filter((f) => idSet.has(f.id))
+ .map((f) => ({
+ fragment_id: f.id,
+ status: 'queued',
+ message: '已入队',
+ }))
+ syncEpisodeVideoJobs({
+ projectId: input.projectId,
+ episodeId: input.episodeId,
+ episodeName: input.episodeName,
+ fragments: input.fragments,
+ statusItems: items,
+ })
+ requestOpenDramaGenQueue()
+}
+
+// 请求打开右下角队列面板
+let openRequestSeq = 0
+const openListeners = new Set<() => void>()
+
+export function requestOpenDramaGenQueue(): void {
+ openRequestSeq += 1
+ openListeners.forEach((fn) => fn())
+}
+
+export function subscribeDramaGenQueueOpen(listener: () => void): () => void {
+ openListeners.add(listener)
+ return () => openListeners.delete(listener)
+}
+
+export function getDramaGenQueueOpenRequestSeq(): number {
+ return openRequestSeq
+}
+
+// 清空已结束(完成+失败)
+export function clearFinishedDramaGenJobs(): void {
+ jobs = jobs.filter((j) => j.status === 'queued' || j.status === 'running')
+ emit()
+}
+
+// 将进行中/排队中的视频任务标记为已取消(本地队列同步)
+export function markVideoJobsCancelled(fragmentIds?: number[]): void {
+ const idSet = fragmentIds ? new Set(fragmentIds.map((id) => videoJobId(id))) : null
+ jobs = jobs.map((job) => {
+ if (job.kind !== 'video') return job
+ if (idSet && !idSet.has(job.id)) return job
+ if (job.status !== 'queued' && job.status !== 'running') return job
+ return {
+ ...job,
+ status: 'failed' as const,
+ error: '已取消',
+ finishedAt: Date.now(),
+ }
+ })
+ emit()
+}
diff --git a/frontend/src/lib/dramaImageGenQueue.ts b/frontend/src/lib/dramaImageGenQueue.ts
index 0860e2b..2188ff5 100644
--- a/frontend/src/lib/dramaImageGenQueue.ts
+++ b/frontend/src/lib/dramaImageGenQueue.ts
@@ -1,6 +1,7 @@
-/** 漫剧资产生图全局队列:串行入队,避免多次点击互相顶掉 */
+/** 漫剧资产生图队列:入队即提交后端 Worker,刷新后可从资产状态恢复 */
import { dramaApi, type DramaAsset } from '../api/drama'
import type { ImageGenerationOptions } from './dramaGenerationOptions'
+import { syncImageJobToUnified } from './dramaGenQueue'
export type DramaImageGenStatus = 'queued' | 'running' | 'done' | 'failed'
@@ -25,32 +26,37 @@ type EnqueueInput = {
assetType?: string
prompt: string
options?: Partial<ImageGenerationOptions>
+ /** 仅恢复轮询(后端已在 generating,不再重复 POST) */
+ resumeOnly?: boolean
}
type InternalJob = DramaImageGenJob & {
+ resumeOnly: boolean
resolve: (asset: DramaAsset) => void
reject: (err: Error) => void
}
-/* 同时跑几路生图;1 = 严格队列,避免互相顶掉与限流 */
-const MAX_CONCURRENT = 1
-/* 完成后在面板保留多久 */
+/* 前端同时轮询几路;真正执行在 Celery Worker */
+const MAX_POLL_CONCURRENT = 6
const DONE_RETENTION_MS = 45_000
const POLL_INTERVAL_MS = 2000
const POLL_TIMEOUT_MS = 10 * 60 * 1000
+/** 对外暴露(文案用) */
+export const DRAMA_IMAGE_GEN_MAX_CONCURRENT = MAX_POLL_CONCURRENT
+
/*
- * jobs 内部队列
- * cachedSnapshot useSyncExternalStore 稳定快照(必须复用引用)
- * listeners 订阅回调
- * activeCount 正在请求/轮询的任务数
- * pumping 是否已调度 pump
+ * jobs 本地队列(UI + 轮询)
+ * cachedSnapshot useSyncExternalStore 快照
+ * listeners 订阅
+ * pollingCount 正在 waitForAssetImage 的数量
+ * pumping 是否已调度 poll pump
*/
let jobs: InternalJob[] = []
const EMPTY_SNAPSHOT: DramaImageGenJob[] = []
let cachedSnapshot: DramaImageGenJob[] = EMPTY_SNAPSHOT
const listeners = new Set<() => void>()
-let activeCount = 0
+let pollingCount = 0
let pumping = false
// 将内部 job 转为对外结构
@@ -89,44 +95,50 @@ function snapshotsEqual(a: DramaImageGenJob[], b: DramaImageGenJob[]): boolean {
return true
}
-// 重建并缓存对外快照(仅在内容变化时换新引用)
+// 清理过期完成项
+function pruneFinished() {
+ const now = Date.now()
+ jobs = jobs.filter((job) => {
+ if (job.status === 'queued' || job.status === 'running') return true
+ if (!job.finishedAt) return true
+ return now - job.finishedAt < DONE_RETENTION_MS
+ })
+}
+
+// 重建并缓存对外快照
function refreshSnapshot() {
pruneFinished()
- const next =
- jobs.length === 0 ? EMPTY_SNAPSHOT : jobs.map((job) => toPublicJob(job))
+ const next = jobs.length === 0 ? EMPTY_SNAPSHOT : jobs.map((job) => toPublicJob(job))
if (!snapshotsEqual(cachedSnapshot, next)) {
cachedSnapshot = next
}
}
-// 通知所有订阅方刷新
+// 通知订阅者,并同步到统一生成队列
function emit() {
refreshSnapshot()
- listeners.forEach((fn) => {
- try {
- fn()
- } catch {
- /* ignore listener errors */
+ listeners.forEach((listener) => listener())
+ for (const job of jobs) {
+ if (job.status === 'queued' || job.status === 'running' || job.finishedAt) {
+ syncImageJobToUnified({
+ assetId: job.assetId,
+ projectId: job.projectId,
+ assetName: job.assetName,
+ assetType: job.assetType,
+ status: job.status,
+ error: job.error,
+ })
}
- })
-}
-
-// 清理过期的完成/失败项
-function pruneFinished() {
- const now = Date.now()
- jobs = jobs.filter((job) => {
- if (job.status === 'queued' || job.status === 'running') return true
- if (!job.finishedAt) return false
- return now - job.finishedAt < DONE_RETENTION_MS
- })
+ }
}
-// 对外只读快照(稳定引用,供 useSyncExternalStore)
+// 读取队列快照
export function getDramaImageGenQueue(): DramaImageGenJob[] {
+ refreshSnapshot()
return cachedSnapshot
}
-// 资产是否仍在队列中(排队或生成中)
+// 某资产是否忙
export function isDramaAssetImageBusy(assetId: number): boolean {
return jobs.some(
(job) =>
@@ -152,21 +164,25 @@ function makeJobId() {
return `img-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`
}
-// 轮询直到资产生图结束,返回最新资产
+// 读取资产 generation 状态
+function readGenerationStatus(asset: DramaAsset): string {
+ const gen = (asset.params || {}).generation as { status?: string } | undefined
+ return String(gen?.status || '')
+}
+
+// 轮询直到资产生图结束
async function waitForAssetImage(projectId: number, assetId: number): Promise<DramaAsset> {
const started = Date.now()
while (Date.now() - started < POLL_TIMEOUT_MS) {
const list = await dramaApi.listAssets(projectId)
const latest = list.find((a) => a.id === assetId)
if (!latest) throw new Error('资产不存在')
- const gen = (latest.params || {}).generation as
- | { status?: string; error?: string }
- | undefined
- const status = String(gen?.status || '')
+ const status = readGenerationStatus(latest)
if ((latest.url || latest.cover) && status !== 'generating') {
return latest
}
if (status === 'failed') {
+ const gen = (latest.params || {}).generation as { error?: string } | undefined
throw new Error(String(gen?.error || '生图失败'))
}
if (status === 'done' && (latest.url || latest.cover)) {
@@ -177,22 +193,15 @@ async function waitForAssetImage(projectId: number, assetId: number): Promise<Dr
throw new Error('生图超时,请刷新后重试')
}
-// 执行单个任务:调 API + 轮询
-async function runJob(job: InternalJob) {
- job.status = 'running'
- emit()
+/*
+ * waitingPoll 已提交、等待轮询槽位的任务
+ */
+const waitingPoll: InternalJob[] = []
+
+// 有限并发轮询后端结果
+async function pollJob(job: InternalJob) {
+ pollingCount += 1
try {
- await dramaApi.generateImage({
- project_id: job.projectId,
- asset_id: job.assetId,
- prompt: job.prompt,
- name: job.assetName || undefined,
- asset_type_kind: job.assetType,
- image_style_id: job.options.image_style_id,
- model_id: job.options.model_id,
- aspect_ratio: job.options.aspect_ratio,
- resolution: job.options.resolution,
- })
const asset = await waitForAssetImage(job.projectId, job.assetId)
job.status = 'done'
job.finishedAt = Date.now()
@@ -205,32 +214,64 @@ async function runJob(job: InternalJob) {
job.finishedAt = Date.now()
emit()
job.reject(err instanceof Error ? err : new Error(message))
+ } finally {
+ pollingCount -= 1
+ pump()
+ emit()
}
}
-// 拉取排队任务并控制并发
+// 调度轮询槽位
function pump() {
if (pumping) return
pumping = true
queueMicrotask(() => {
pumping = false
- while (activeCount < MAX_CONCURRENT) {
- const next = jobs.find((job) => job.status === 'queued')
+ while (pollingCount < MAX_POLL_CONCURRENT && waitingPoll.length > 0) {
+ const next = waitingPoll.shift()
if (!next) break
- activeCount += 1
- void runJob(next).finally(() => {
- activeCount -= 1
- pump()
- emit()
- })
+ if (next.status === 'failed' || next.status === 'done') continue
+ void pollJob(next)
}
emit()
})
}
+// 提交后端(Worker 入队)后进入轮询队列
+function startJob(job: InternalJob) {
+ void (async () => {
+ try {
+ if (!job.resumeOnly) {
+ await dramaApi.generateImage({
+ project_id: job.projectId,
+ asset_id: job.assetId,
+ prompt: job.prompt,
+ name: job.assetName || undefined,
+ asset_type_kind: job.assetType,
+ image_style_id: job.options.image_style_id,
+ model_id: job.options.model_id,
+ aspect_ratio: job.options.aspect_ratio,
+ resolution: job.options.resolution,
+ })
+ }
+ job.status = 'running'
+ emit()
+ waitingPoll.push(job)
+ pump()
+ } catch (err) {
+ const message = err instanceof Error ? err.message : '生图失败'
+ job.status = 'failed'
+ job.error = message
+ job.finishedAt = Date.now()
+ emit()
+ job.reject(err instanceof Error ? err : new Error(message))
+ }
+ })()
+}
+
/**
- * 将资产生图加入全局队列;同资产已在排队/生成中时复用同一 Promise。
- * @returns 完成后的最新资产
+ * 将资产生图加入队列:立刻 POST 到后端 Worker,再本地轮询结果。
+ * 同资产已在排队/生成中时复用同一 Promise。
*/
export function enqueueDramaImageGen(input: EnqueueInput): Promise<DramaAsset> {
const existing = jobs.find(
@@ -264,16 +305,43 @@ export function enqueueDramaImageGen(input: EnqueueInput): Promise<DramaAsset> {
options: input.options || {},
status: 'queued',
createdAt: Date.now(),
+ resumeOnly: Boolean(input.resumeOnly),
resolve,
reject,
}
jobs = [...jobs, job]
emit()
- pump()
+ startJob(job)
})
}
-// 清空已结束项(手动关闭面板时)
+/**
+ * 从资产列表恢复「后端仍在 generating」的任务(刷新页面后调用)。
+ * 不再重复 POST,只接上轮询与队列 UI。
+ */
+export function resumeDramaImageGensFromAssets(
+ projectId: number,
+ assets: DramaAsset[],
+): void {
+ for (const asset of assets) {
+ if (asset.project_id !== projectId) continue
+ const status = readGenerationStatus(asset)
+ if (status !== 'generating') continue
+ if (isDramaAssetImageBusy(asset.id)) continue
+ void enqueueDramaImageGen({
+ projectId,
+ assetId: asset.id,
+ assetName: asset.name || undefined,
+ assetType: asset.type,
+ prompt: '',
+ resumeOnly: true,
+ }).catch(() => {
+ /* 面板会显示失败;页面层可再 toast */
+ })
+ }
+}
+
+// 清空已结束项
export function clearFinishedDramaImageGenJobs() {
jobs = jobs.filter((job) => job.status === 'queued' || job.status === 'running')
emit()
diff --git a/frontend/src/lib/dramaStoryboardGrid.ts b/frontend/src/lib/dramaStoryboardGrid.ts
new file mode 100644
index 0000000..90d7078
--- /dev/null
+++ b/frontend/src/lib/dramaStoryboardGrid.ts
@@ -0,0 +1,108 @@
+/**
+ * 分镜板多宫格拆分与路径 D 脚本组装(对齐 EPISODE_RULES / MapleShaw 路径 D)
+ * D-1:≤4 格 → 单镜多段 @duration;D-2:≥5 格 → 每格一镜
+ */
+
+/** 禁止模型复刻网格 UI 的画面约束 */
+export const STORYBOARD_NO_GRID_CUE =
+ '【画面约束】不复刻分镜板的网格边框、格子编号与分隔线,仅演绎各格画面内容'
+
+export type StoryboardGridCell = {
+ index: number
+ row: number
+ col: number
+ blob: Blob
+ fileName: string
+}
+
+export type StoryboardImportMode = 'd1' | 'd2'
+
+// 按格数选择 D-1 / D-2
+export function resolveStoryboardImportMode(cellCount: number): StoryboardImportMode {
+ return cellCount <= 4 ? 'd1' : 'd2'
+}
+
+// 将宫格图按 rows×cols 裁成独立单元格 Blob
+export async function splitStoryboardGridImage(
+ file: File,
+ rows: number,
+ cols: number,
+): Promise<StoryboardGridCell[]> {
+ const safeRows = Math.max(1, Math.min(6, Math.floor(rows)))
+ const safeCols = Math.max(1, Math.min(6, Math.floor(cols)))
+ const bitmap = await createImageBitmap(file)
+ try {
+ const cellW = Math.floor(bitmap.width / safeCols)
+ const cellH = Math.floor(bitmap.height / safeRows)
+ if (cellW < 8 || cellH < 8) {
+ throw new Error('宫格过小,请换更高清分镜板或减少行列数')
+ }
+ const cells: StoryboardGridCell[] = []
+ for (let row = 0; row < safeRows; row++) {
+ for (let col = 0; col < safeCols; col++) {
+ const canvas = document.createElement('canvas')
+ canvas.width = cellW
+ canvas.height = cellH
+ const ctx = canvas.getContext('2d')
+ if (!ctx) throw new Error('无法裁剪分镜板')
+ ctx.drawImage(
+ bitmap,
+ col * cellW,
+ row * cellH,
+ cellW,
+ cellH,
+ 0,
+ 0,
+ cellW,
+ cellH,
+ )
+ const blob = await new Promise<Blob>((resolve, reject) => {
+ canvas.toBlob(
+ (b) => (b ? resolve(b) : reject(new Error('单元格导出失败'))),
+ 'image/jpeg',
+ 0.92,
+ )
+ })
+ const index = cells.length
+ cells.push({
+ index,
+ row,
+ col,
+ blob,
+ fileName: `storyboard_r${row + 1}c${col + 1}.jpg`,
+ })
+ }
+ }
+ return cells
+ } finally {
+ bitmap.close()
+ }
+}
+
+// D-1:单镜多段时间戳脚本(格图作参考,正文不写网格)
+export function buildStoryboardD1Content(
+ cellCount: number,
+ durations: number[],
+): string {
+ const lines = [STORYBOARD_NO_GRID_CUE]
+ for (let i = 0; i < cellCount; i++) {
+ const sec = durations[i] ?? 4
+ lines.push(`@duration:${sec}`)
+ lines.push(
+ `【画面·无配音仅环境音】按分镜板第 ${i + 1} 格画面演绎(从左到右、从上到下),主体动作连贯。`,
+ )
+ }
+ return lines.join('\n')
+}
+
+// D-2:单格一镜的默认画面正文
+export function buildStoryboardD2CellContent(
+ cellIndex: number,
+ durationSec: number,
+): string {
+ return [
+ STORYBOARD_NO_GRID_CUE,
+ `@duration:${durationSec}`,
+ `【画面·无配音仅环境音】按分镜板第 ${cellIndex + 1} 格画面演绎,不复刻网格。`,
+ ].join('\n')
+}
diff --git a/frontend/src/pages/drama/AssetsStep.tsx b/frontend/src/pages/drama/AssetsStep.tsx
index a4af377..0ba8b81 100644
--- a/frontend/src/pages/drama/AssetsStep.tsx
+++ b/frontend/src/pages/drama/AssetsStep.tsx
@@ -1,9 +1,10 @@
/** 资产库步骤:进入时 seed,分类 Tab + 生图队列 + 角色音色绑定 */
import { useEffect, useRef, useState } from 'react'
import { Link } from 'react-router-dom'
-import { dramaApi, resolveDramaMediaUrl, type DramaAsset } from '../../api/drama'
+import { Boxes, Sparkles } from 'lucide-react'
+import { dramaApi, resolveDramaMediaUrl, type DramaAsset, type DramaProject } from '../../api/drama'
import { useDramaImageGenQueue } from '../../hooks/useDramaImageGenQueue'
-import { enqueueDramaImageGen } from '../../lib/dramaImageGenQueue'
+import { enqueueDramaImageGen, resumeDramaImageGensFromAssets } from '../../lib/dramaImageGenQueue'
import {
defaultOptionsForAssetKind,
type ImageGenerationOptions,
@@ -15,6 +16,9 @@ import {
readAssetVoiceBinding,
readVoicePrompt,
} from './CharacterVoiceBindModal'
+import { CharacterVoicePreviewButton } from '../../components/drama/CharacterVoicePreviewButton'
+import { generateAndBindCharacterVoice } from '../../lib/characterVoiceGenerate'
+import { NarratorVoiceBindModal } from './NarratorVoiceBindModal'
import { DramaAssetDetailModal } from './DramaAssetDetailModal'
import { DramaImageLightbox } from './DramaImageLightbox'
import { GlobalAssetPickerModal, importGlobalAssetToProject } from './GlobalAssetPickerModal'
@@ -41,6 +45,13 @@ function normalizeAssetList(value: unknown): DramaAsset[] {
return Array.isArray(value) ? (value as DramaAsset[]) : []
}
+// 判断资产是否尚未出图(无有效封面/主图)
+function needsImageGeneration(asset: DramaAsset): boolean {
+ const cover = (asset.cover || '').trim()
+ const url = (asset.url || '').trim()
+ return !cover && !url
+}
+
// 渲染资产库步骤
export function AssetsStep({ projectId, onError }: AssetsStepProps) {
/*
@@ -68,6 +79,11 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
const [voicePromptDrafts, setVoicePromptDrafts] = useState<Record<number, string>>({})
const [pickerOpen, setPickerOpen] = useState(false)
const [reseedBusy, setReseedBusy] = useState(false)
+ const [project, setProject] = useState<DramaProject | null>(null)
+ const [selectedCharacterIds, setSelectedCharacterIds] = useState<number[]>([])
+ const [characterVoiceBusyIds, setCharacterVoiceBusyIds] = useState<Set<number>>(() => new Set())
+ const [batchVoiceBusy, setBatchVoiceBusy] = useState(false)
+ const [narratorVoiceOpen, setNarratorVoiceOpen] = useState(false)
const genQueue = useDramaImageGenQueue()
const seeded = useRef(false)
@@ -79,8 +95,9 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
async function enter() {
setLoading(true)
try {
- const project = await dramaApi.getProject(projectId).catch(() => null)
- const styleId = project ? getImageStyleId(project.script, project) : ''
+ const p = await dramaApi.getProject(projectId).catch(() => null)
+ setProject(p)
+ const styleId = p ? getImageStyleId(p.script, p) : ''
setGenOptions((prev) => ({
...defaultOptionsForAssetKind(tab),
image_style_id: styleId || prev.image_style_id,
@@ -90,14 +107,20 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
if (!seeded.current) {
seeded.current = true
const seededResult = await dramaApi.seedAssets(projectId)
- setAssets(normalizeAssetList(seededResult?.assets))
+ const list = normalizeAssetList(seededResult?.assets)
+ setAssets(list)
+ resumeDramaImageGensFromAssets(projectId, list)
} else {
- setAssets(normalizeAssetList(await dramaApi.listAssets(projectId)))
+ const list = normalizeAssetList(await dramaApi.listAssets(projectId))
+ setAssets(list)
+ resumeDramaImageGensFromAssets(projectId, list)
}
} catch (err) {
onError(err instanceof Error ? err.message : '资产加载失败')
try {
- setAssets(normalizeAssetList(await dramaApi.listAssets(projectId)))
+ const list = normalizeAssetList(await dramaApi.listAssets(projectId))
+ setAssets(list)
+ resumeDramaImageGensFromAssets(projectId, list)
} catch {
/* ignore */
}
@@ -117,6 +140,12 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
}))
}, [tab])
+ useEffect(() => {
+ if (tab !== 'character') {
+ setSelectedCharacterIds([])
+ }
+ }, [tab])
+
// 队列完成时把最新封面写回卡片
useEffect(() => {
const projectJobs = genQueue.filter((j) => j.projectId === projectId)
@@ -142,13 +171,22 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
}, [genQueue, projectId])
const assetList = assets ?? []
+ const narrationVoiceLabel =
+ project?.params && typeof project.params === 'object'
+ ? String(
+ ((project.params as Record<string, unknown>).narrationVoiceAudio as Record<string, unknown> | undefined)?.label ||
+ '未设置',
+ )
+ : '未设置'
const filtered = assetList.filter((a) => {
const t = (a.type || '').toLowerCase()
if (tab === 'voice') return t === 'voice'
if (tab === 'material') return t === 'material' || t === 'none' || !t
return t === tab
})
- const pending = filtered.filter((a) => !(a.url || a.cover))
+ const selectedCharacterAssets = assetList.filter(
+ (a) => (a.type || '').toLowerCase() === 'character' && selectedCharacterIds.includes(a.id),
+ )
const busyAssetIds = new Set(
genQueue
.filter(
@@ -157,6 +195,8 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
)
.map((j) => j.assetId),
)
+ // 未出图:无有效 cover/url,且当前未在队列中
+ const pending = filtered.filter((a) => needsImageGeneration(a) && !busyAssetIds.has(a.id))
const queueBusy = busyAssetIds.size > 0
// 持久化项目画面风格
@@ -187,10 +227,23 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
})
}
- // 一键将无封面资产全部入队
- function batchGenerate() {
+ // 一键只入队「当前分类下尚未出图」的资产(已有图 / 排队中跳过)
+ async function batchGenerate() {
+ const targets = filtered.filter(
+ (a) => needsImageGeneration(a) && !busyAssetIds.has(a.id),
+ )
+ if (targets.length === 0) {
+ onError('当前分类没有未生成的资产')
+ return
+ }
+ const ok = await dialog.confirm({
+ title: '批量生成形象',
+ message: `将为当前「${ASSET_TABS.find((t) => t.key === tab)?.label || '分类'}」下 ${targets.length} 个未出图资产排队生图(最多 3 路并行)。是否继续?`,
+ confirmText: '开始生成',
+ })
+ if (!ok) return
setBatchBusy(true)
- const tasks = pending.map((asset) =>
+ const tasks = targets.map((asset) =>
enqueueDramaImageGen({
projectId,
assetId: asset.id,
@@ -223,6 +276,67 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
setAssets((prev) => (prev ?? []).map((a) => (a.id === updated.id ? updated : a)))
}
+ function handleVoiceCreated(voice: DramaAsset) {
+ setAssets((prev) => {
+ const list = prev ?? []
+ if (list.some((a) => a.id === voice.id)) return list
+ return [...list, voice]
+ })
+ }
+
+ // 一键 AI 生成音色并绑定(各角色独立 busy,互不阻塞)
+ async function handleGenerateCharacterVoice(asset: DramaAsset) {
+ if (characterVoiceBusyIds.has(asset.id) || batchVoiceBusy) return
+ setCharacterVoiceBusyIds((prev) => new Set(prev).add(asset.id))
+ try {
+ const { character, voice } = await generateAndBindCharacterVoice(projectId, asset)
+ handleVoiceBound(character)
+ handleVoiceCreated(voice)
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '音色生成失败')
+ } finally {
+ setCharacterVoiceBusyIds((prev) => {
+ const next = new Set(prev)
+ next.delete(asset.id)
+ return next
+ })
+ }
+ }
+
+ // 批量按角色设定生成音色
+ async function batchGenerateCharacterVoices() {
+ if (batchVoiceBusy || selectedCharacterAssets.length === 0) return
+ const ok = await dialog.confirm({
+ title: '批量生成音色',
+ message: `将为选中的 ${selectedCharacterAssets.length} 个角色分别 AI 生成音色并绑定,是否继续?`,
+ confirmText: '开始生成',
+ })
+ if (!ok) return
+ setBatchVoiceBusy(true)
+ let failCount = 0
+ for (const asset of selectedCharacterAssets) {
+ setCharacterVoiceBusyIds((prev) => new Set(prev).add(asset.id))
+ try {
+ const { character, voice } = await generateAndBindCharacterVoice(projectId, asset)
+ handleVoiceBound(character)
+ handleVoiceCreated(voice)
+ } catch {
+ failCount += 1
+ } finally {
+ setCharacterVoiceBusyIds((prev) => {
+ const next = new Set(prev)
+ next.delete(asset.id)
+ return next
+ })
+ }
+ }
+ setBatchVoiceBusy(false)
+ setSelectedCharacterIds([])
+ if (failCount > 0) {
+ onError(`${failCount} 个角色音色生成失败`)
+ }
+ }
+
// 从全局资产库导入到当前项目
async function handleImportFromLibrary(source: DramaAsset) {
const dup = assetList.some(
@@ -424,6 +538,26 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
return (
<div className="drama-assets-step">
+ <header className="drama-assets-hero">
+ <div className="drama-step-hero-main">
+ <div className="drama-step-hero-icon" aria-hidden>
+ <Boxes size={22} strokeWidth={1.75} />
+ </div>
+ <div>
+ <h2>资产库</h2>
+ <p className="drama-step-hero-sub">
+ 共 <strong>{assetList.length}</strong> 项资产 · 待生图{' '}
+ <strong>{pending.length}</strong>
+ </p>
+ </div>
+ </div>
+ </header>
+
+ <div className="drama-assets-tips" role="note">
+ <Sparkles size={15} strokeWidth={1.75} aria-hidden />
+ <span>先完成角色/场景出图,再进入分集视频步骤生成镜头。</span>
+ </div>
+
<div className="drama-assets-toolbar">
<div className="drama-asset-tabs">
{ASSET_TABS.map((t) => (
@@ -448,6 +582,17 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
新增音色
</button>
) : null}
+ {tab !== 'voice' ? (
+ <button
+ type="button"
+ className="pf-btn"
+ onClick={() => setNarratorVoiceOpen(true)}
+ title="全局旁白音色(用于所有镜头旁白 reference_audio 一致性)"
+ disabled={!project}
+ >
+ 旁白音色:{narrationVoiceLabel}
+ </button>
+ ) : null}
<button type="button" className="pf-btn" onClick={() => setPickerOpen(true)}>
从资产库选择
</button>
@@ -469,9 +614,32 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
type="button"
className="drama-btn-primary"
disabled={batchBusy || pending.length === 0}
- onClick={batchGenerate}
+ onClick={() => void batchGenerate()}
+ title={
+ pending.length > 0
+ ? `仅生成当前分类下尚未出图的 ${pending.length} 项(最多同时 3 路)`
+ : '当前分类没有未出图资产'
+ }
>
- {batchBusy || queueBusy ? `队列 ${busyAssetIds.size || '…'}` : '一键生成'}
+ {batchBusy || queueBusy
+ ? `生成中 ${busyAssetIds.size}`
+ : pending.length > 0
+ ? `一键生成未出图 (${pending.length})`
+ : '一键生成未出图'}
+ </button>
+ ) : null}
+
+ {tab === 'character' ? (
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime"
+ disabled={batchBusy || batchVoiceBusy || selectedCharacterIds.length === 0}
+ onClick={() => void batchGenerateCharacterVoices()}
+ title="按各角色人物设定分别生成音色并绑定"
+ >
+ {batchVoiceBusy
+ ? '批量生成中…'
+ : `批量生成音色(${selectedCharacterIds.length})`}
</button>
) : null}
<Link className="pf-btn" to={`/drama/projects/${projectId}/canvas`}>
@@ -596,6 +764,26 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
onClick={(e) => e.stopPropagation()}
onKeyDown={(e) => e.stopPropagation()}
>
+ {tab === 'character' && isCharacter ? (
+ <label
+ className="drama-voice-multi-select"
+ style={{ display: 'inline-flex', gap: 8, alignItems: 'center', marginRight: 8, cursor: 'pointer' }}
+ onClick={(e) => e.stopPropagation()}
+ onKeyDown={(e) => e.stopPropagation()}
+ >
+ <input
+ type="checkbox"
+ checked={selectedCharacterIds.includes(asset.id)}
+ onChange={(e) => {
+ e.stopPropagation()
+ setSelectedCharacterIds((prev) =>
+ prev.includes(asset.id) ? prev.filter((id) => id !== asset.id) : [...prev, asset.id],
+ )
+ }}
+ />
+ <span className="drama-muted">选中</span>
+ </label>
+ ) : null}
<button
type="button"
className="pf-btn pf-btn-sm"
@@ -606,18 +794,30 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
</button>
{isCharacter ? (
<>
- <button
- type="button"
- className="pf-btn pf-btn-sm"
- disabled={batchBusy}
- onClick={() => setVoiceAsset(asset)}
- >
- {voice ? '更换音色' : '绑定音色'}
- </button>
+ {voice ? (
+ <CharacterVoicePreviewButton
+ url={voice.url}
+ label={voice.label}
+ onError={onError}
+ />
+ ) : (
+ <button
+ type="button"
+ className="pf-btn pf-btn-sm pf-btn-lime"
+ disabled={
+ batchBusy ||
+ batchVoiceBusy ||
+ characterVoiceBusyIds.has(asset.id)
+ }
+ onClick={() => void handleGenerateCharacterVoice(asset)}
+ >
+ {characterVoiceBusyIds.has(asset.id) ? '生成中…' : '生成音色'}
+ </button>
+ )}
<button
type="button"
className="pf-btn pf-btn-sm drama-btn-danger-text"
- disabled={busy || batchBusy}
+ disabled={busy || batchBusy || batchVoiceBusy}
onClick={() => void handleDeleteCharacter(asset)}
>
删除
@@ -666,7 +866,20 @@ export function AssetsStep({ projectId, onError }: AssetsStepProps) {
projectId={projectId}
open
onClose={() => setVoiceAsset(null)}
- onBound={handleVoiceBound}
+ onBound={(updated) => {
+ handleVoiceBound(updated)
+ setDetailAsset((prev) => (prev?.id === updated.id ? updated : prev))
+ }}
+ onError={onError}
+ />
+ ) : null}
+
+ {project ? (
+ <NarratorVoiceBindModal
+ project={project}
+ open={narratorVoiceOpen}
+ onClose={() => setNarratorVoiceOpen(false)}
+ onUpdated={(p) => setProject(p)}
onError={onError}
/>
) : null}
diff --git a/frontend/src/pages/drama/CharacterVoiceBindModal.tsx b/frontend/src/pages/drama/CharacterVoiceBindModal.tsx
index 301e55c..a8b8930 100644
--- a/frontend/src/pages/drama/CharacterVoiceBindModal.tsx
+++ b/frontend/src/pages/drama/CharacterVoiceBindModal.tsx
@@ -19,6 +19,12 @@ type Props = {
onError: (message: string) => void
}
+// 读取 voice 资产已保存的 speaker
+function readVoiceSpeaker(asset: DramaAsset): string {
+ const params = (asset.params || {}) as Record<string, unknown>
+ return typeof params.speaker === 'string' ? params.speaker.trim() : ''
+}
+
// 读取 voice 资产的音色描述
export function readVoicePrompt(asset: DramaAsset): string {
const params = (asset.params || {}) as Record<string, unknown>
@@ -68,7 +74,7 @@ export function readAssetVoiceBinding(asset: DramaAsset): VoiceBinding | null {
}
// 构建绑定后的 params(同时写 voiceAudio 与 canvas.voiceAudio)
-function buildBoundParams(asset: DramaAsset, voice: DramaAsset): Record<string, unknown> {
+export function buildBoundParams(asset: DramaAsset, voice: DramaAsset): Record<string, unknown> {
const url = voice.url || ''
const binding: VoiceBinding = {
sourceAssetId: voice.id,
@@ -116,6 +122,7 @@ export function CharacterVoiceBindModal({
const [busy, setBusy] = useState(false)
const [synthBusy, setSynthBusy] = useState(false)
const [promptBusy, setPromptBusy] = useState(false)
+ const [suggestedSpeaker, setSuggestedSpeaker] = useState('')
const [mode, setMode] = useState<'pick' | 'create'>('pick')
const promptRequestedRef = useRef(false)
@@ -135,6 +142,7 @@ export function CharacterVoiceBindModal({
asset_id: asset.id,
})
setNewPrompt(result.voice_prompt || '')
+ setSuggestedSpeaker(result.speaker || '')
} catch (err) {
onError(err instanceof Error ? err.message : 'AI 生成音色描述失败')
} finally {
@@ -151,6 +159,7 @@ export function CharacterVoiceBindModal({
}
setSelectedId(bound?.sourceAssetId ?? null)
setNewPrompt('')
+ setSuggestedSpeaker('')
setNewName(`${asset.name || '角色'}音色`)
setMode('pick')
promptRequestedRef.current = false
@@ -189,6 +198,8 @@ export function CharacterVoiceBindModal({
project_id: projectId,
name: newName.trim() || undefined,
voice_prompt: prompt,
+ speaker: suggestedSpeaker || undefined,
+ character_asset_id: asset.id,
})
const created = result.asset
if (!created) throw new Error('合成失败')
@@ -212,6 +223,8 @@ export function CharacterVoiceBindModal({
project_id: projectId,
asset_id: voice.id,
voice_prompt: prompt,
+ speaker: readVoiceSpeaker(voice) || suggestedSpeaker || undefined,
+ character_asset_id: asset.id,
})
if (result.asset) {
setVoiceAssets((prev) => prev.map((v) => (v.id === voice.id ? result.asset! : v)))
@@ -389,6 +402,11 @@ export function CharacterVoiceBindModal({
placeholder="将根据角色身份、性格、外形等自动生成,也可手动编辑"
/>
</label>
+ {suggestedSpeaker ? (
+ <p className="drama-muted" style={{ margin: 0, fontSize: 12 }}>
+ 推荐声线:<code>{suggestedSpeaker}</code>(不同角色会自动匹配不同 TTS 发音人)
+ </p>
+ ) : null}
<button
type="button"
className="pf-btn pf-btn-lime"
diff --git a/frontend/src/pages/drama/DramaListPage.tsx b/frontend/src/pages/drama/DramaListPage.tsx
index 52a25f6..ae61c79 100644
--- a/frontend/src/pages/drama/DramaListPage.tsx
+++ b/frontend/src/pages/drama/DramaListPage.tsx
@@ -1,7 +1,17 @@
/** 漫剧 Agent 首页:AI 生剧本 / 自由画布 + 我的项目(多选删除) */
import { useCallback, useEffect, useState } from 'react'
import { Link, useNavigate } from 'react-router-dom'
-import { Clapperboard, MoreHorizontal, Trash2 } from 'lucide-react'
+import {
+ Clapperboard,
+ FolderOpen,
+ LayoutGrid,
+ Library,
+ MoreHorizontal,
+ PenLine,
+ Sparkles,
+ Trash2,
+ Wand2,
+} from 'lucide-react'
import AppShell from '../../components/layout/AppShell'
import { dramaApi, type DramaProjectListItem } from '../../api/drama'
import { dialog } from '../../lib/dialog'
@@ -26,6 +36,13 @@ function formatUpdatedAt(raw?: string) {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
}
+// 封面竖排标题(无预览图时)
+function verticalTitleLabel(name: string, max = 12): string {
+ const clean = (name || '').replace(/\s+/g, '')
+ if (clean.length <= max) return clean
+ return `${clean.slice(0, max - 1)}…`
+}
+
export default function DramaListPage() {
return (
<RequireAuth>
@@ -43,6 +60,7 @@ function DramaListInner() {
* episodeCount 目标集数
* imageStyleId 画面风格
* items 我的项目列表
+ * loading 列表加载中
* busy 创建中
* canvasBusy 画布创建中
* error 错误文案
@@ -54,6 +72,7 @@ function DramaListInner() {
const [episodeCount, setEpisodeCount] = useState(12)
const [imageStyleId, setImageStyleId] = useState<ImageStyleId | ''>('')
const [items, setItems] = useState<DramaProjectListItem[]>([])
+ const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState(false)
const [canvasBusy, setCanvasBusy] = useState(false)
const [error, setError] = useState('')
@@ -71,7 +90,10 @@ function DramaListInner() {
}
useEffect(() => {
- loadProjects().catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ setLoading(true)
+ loadProjects()
+ .catch((err) => setError(err instanceof Error ? err.message : '加载失败'))
+ .finally(() => setLoading(false))
}, [])
// AI 立即生成:创建项目并进入大纲步骤
@@ -127,6 +149,9 @@ function DramaListInner() {
}
const selectionMode = selected.size > 0
+ const storyLen = storyText.trim().length
+ const canGenerate = storyLen >= CREATIVE_MIN_LENGTH && !busy
+ const withScript = items.filter((i) => i.has_script).length
// 切换选中
const toggleSelect = useCallback((id: number) => {
@@ -209,52 +234,84 @@ function DramaListInner() {
}
}
- const canGenerate = storyText.trim().length >= CREATIVE_MIN_LENGTH && !busy
-
return (
<AppShell active="drama">
<div className="drama-page drama-agent-page">
<header className="drama-agent-hero">
- <div className="drama-agent-hero-row">
- <h1>漫剧 Agent</h1>
- <Link className="pf-btn" to="/drama/assets">
+ <div className="drama-agent-hero-main">
+ <div className="drama-agent-hero-icon" aria-hidden>
+ <Wand2 size={22} strokeWidth={1.75} />
+ </div>
+ <div>
+ <h1>漫剧 Agent</h1>
+ <p className="drama-agent-hero-sub">
+ 输入创意一键生成分集剧本,或从{' '}
+ <strong>自由画布</strong> 搭故事与资产
+ </p>
+ </div>
+ </div>
+ <div className="drama-agent-hero-actions">
+ <Link className="drama-btn-ghost drama-agent-assets-link" to="/drama/assets">
+ <Library size={16} strokeWidth={1.75} aria-hidden />
外部资产库
</Link>
</div>
</header>
- <section className="drama-agent-panel">
- <div className="drama-agent-tabs" role="tablist">
- <button
- type="button"
- role="tab"
- aria-selected={tab === 'ai'}
- className={tab === 'ai' ? 'active' : ''}
- onClick={() => handleTabClick('ai')}
- >
- AI 生剧本
- </button>
- <button
- type="button"
- role="tab"
- aria-selected={false}
- className=""
- disabled={canvasBusy}
- onClick={() => handleTabClick('canvas')}
- >
- {canvasBusy ? '创建中…' : '自由画布'}
- </button>
+ <div className="drama-agent-tips" role="note">
+ <Sparkles size={15} strokeWidth={1.75} aria-hidden />
+ <span>
+ 建议写明 <strong>故事设定</strong>、<strong>人物特征</strong>、<strong>剧情脉络</strong> 与结局走向,生成更稳。
+ </span>
+ </div>
+
+ <section className="drama-agent-panel" aria-label="创作入口">
+ <div className="drama-agent-panel-head">
+ <div className="drama-agent-tabs" role="tablist">
+ <button
+ type="button"
+ role="tab"
+ aria-selected={tab === 'ai'}
+ className={tab === 'ai' ? 'active' : ''}
+ onClick={() => handleTabClick('ai')}
+ >
+ <PenLine size={15} strokeWidth={1.75} aria-hidden />
+ AI 生剧本
+ </button>
+ <button
+ type="button"
+ role="tab"
+ aria-selected={false}
+ disabled={canvasBusy}
+ onClick={() => handleTabClick('canvas')}
+ >
+ <LayoutGrid size={15} strokeWidth={1.75} aria-hidden />
+ {canvasBusy ? '创建中…' : '自由画布'}
+ </button>
+ </div>
</div>
{tab === 'ai' ? (
<div className="drama-agent-ai">
- <textarea
- value={storyText}
- onChange={(e) => setStoryText(e.target.value)}
- disabled={busy}
- placeholder="在此输入你构想的故事内容。可以尝试输入这些要素:故事设定、主角特征、剧情脉络、最终结局等等"
- rows={6}
- />
+ <label className="drama-agent-ai-label" htmlFor="drama-agent-story">
+ 故事创意
+ </label>
+ <div className="drama-agent-ai-field">
+ <textarea
+ id="drama-agent-story"
+ value={storyText}
+ onChange={(e) => setStoryText(e.target.value)}
+ disabled={busy}
+ placeholder="在此输入你构想的故事内容。可以尝试输入这些要素:故事设定、主角特征、剧情脉络、最终结局等等"
+ rows={6}
+ />
+ <span
+ className={`drama-agent-char-count${storyLen >= CREATIVE_MIN_LENGTH ? ' is-ok' : ''}`}
+ aria-live="polite"
+ >
+ {storyLen}/{CREATIVE_MIN_LENGTH}
+ </span>
+ </div>
<div className="drama-agent-ai-footer">
<div className="drama-agent-ai-options">
<DramaImageStyleModal
@@ -271,10 +328,11 @@ function DramaListInner() {
</div>
<button
type="button"
- className="drama-btn-primary"
+ className="drama-btn-primary drama-agent-generate-btn"
disabled={!canGenerate}
onClick={() => void handleGenerate()}
>
+ <Sparkles size={16} strokeWidth={1.75} aria-hidden />
{busy ? '创建中…' : '立即生成'}
</button>
</div>
@@ -285,26 +343,62 @@ function DramaListInner() {
{error ? <p className="drama-error drama-agent-error">{error}</p> : null}
<section className="drama-project-section">
- <h2>我的项目</h2>
- {items.length === 0 ? (
- <p className="drama-muted drama-project-empty">暂无项目,先用上方面板生成一部吧</p>
+ <header className="drama-project-section-head">
+ <div className="drama-project-section-title">
+ <FolderOpen size={18} strokeWidth={1.75} aria-hidden />
+ <h2>我的项目</h2>
+ {!loading && items.length > 0 ? (
+ <span className="drama-project-section-count">{items.length}</span>
+ ) : null}
+ </div>
+ {!loading && items.length > 0 ? (
+ <p className="drama-project-section-sub">
+ 共 <strong>{items.length}</strong> 部 · 已写剧本{' '}
+ <strong>{withScript}</strong>
+ </p>
+ ) : null}
+ </header>
+
+ {loading ? (
+ <div className="drama-project-list" aria-busy="true" aria-label="加载项目">
+ {Array.from({ length: 4 }).map((_, i) => (
+ <div key={i} className="drama-project-row drama-project-row-skeleton" />
+ ))}
+ </div>
+ ) : items.length === 0 ? (
+ <div className="drama-project-empty">
+ <Clapperboard size={40} strokeWidth={1.25} aria-hidden />
+ <p>暂无项目,先用上方面板生成一部吧</p>
+ <button
+ type="button"
+ className="drama-btn-ghost"
+ onClick={() => document.getElementById('drama-agent-story')?.focus()}
+ >
+ 去写故事创意
+ </button>
+ </div>
) : (
- <div className="drama-project-grid">
+ <div className="drama-project-list">
{items.map((item) => {
const isSelected = selected.has(item.id)
return (
<article
key={item.id}
- className={`drama-project-card${isSelected ? ' is-selected' : ''}`}
+ className={`drama-project-row${isSelected ? ' is-selected' : ''}`}
>
<button
type="button"
- className="drama-project-card-cover"
+ className="drama-project-row-poster"
onClick={() => openProject(item)}
+ aria-label={`打开 ${item.title}`}
>
- <Clapperboard className="drama-project-card-clapper" size={40} strokeWidth={1.5} />
+ <div className="drama-project-row-poster-fallback">
+ <span className="drama-project-row-poster-vertical">
+ {verticalTitleLabel(item.title)}
+ </span>
+ </div>
<label
- className={`drama-project-card-check${isSelected || selectionMode ? ' is-visible' : ''}`}
+ className={`drama-project-row-check${isSelected || selectionMode ? ' is-visible' : ''}`}
onClick={(e) => e.stopPropagation()}
>
<input
@@ -313,35 +407,50 @@ function DramaListInner() {
onChange={() => toggleSelect(item.id)}
/>
</label>
- <span className="drama-project-card-eps">{item.episode_count || 0} 集</span>
+ <span className="drama-project-row-ep-badge">
+ {item.episode_count || 0} 集
+ </span>
</button>
- <div className="drama-project-card-body">
- <button
- type="button"
- className="drama-project-card-meta"
- onClick={() => openProject(item)}
- >
- <strong>{item.title}</strong>
- <span>{formatUpdatedAt(item.updated_at || item.created_at)}</span>
- </button>
- <details className="drama-project-card-more" onClick={(e) => e.stopPropagation()}>
- <summary aria-label="更多操作">
- <MoreHorizontal size={16} strokeWidth={1.8} />
- </summary>
- <div className="drama-project-card-menu">
- <button type="button" onClick={() => void handleRename(item)}>
- 重命名
- </button>
- <button
- type="button"
- className="is-danger"
- onClick={() => void handleDeleteOne(item)}
- >
- 删除
- </button>
- </div>
- </details>
- </div>
+
+ <button
+ type="button"
+ className="drama-project-row-body"
+ onClick={() => openProject(item)}
+ >
+ <strong className="drama-project-row-title">{item.title}</strong>
+ <div className="drama-project-row-meta">
+ <span>
+ <Clapperboard size={14} strokeWidth={1.75} aria-hidden />
+ {item.asset_count || 0} 资产
+ </span>
+ {item.has_script ? (
+ <span className="drama-project-row-tag is-script">已有剧本</span>
+ ) : (
+ <span className="drama-project-row-tag">待写剧本</span>
+ )}
+ <span className="drama-project-row-time">
+ {formatUpdatedAt(item.updated_at || item.created_at)}
+ </span>
+ </div>
+ </button>
+
+ <details className="drama-project-row-more" onClick={(e) => e.stopPropagation()}>
+ <summary aria-label="更多操作">
+ <MoreHorizontal size={16} strokeWidth={1.8} />
+ </summary>
+ <div className="drama-project-row-menu">
+ <button type="button" onClick={() => void handleRename(item)}>
+ 重命名
+ </button>
+ <button
+ type="button"
+ className="is-danger"
+ onClick={() => void handleDeleteOne(item)}
+ >
+ 删除
+ </button>
+ </div>
+ </details>
</article>
)
})}
diff --git a/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx b/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx
index 6e84ba3..5e93cfa 100644
--- a/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx
+++ b/frontend/src/pages/drama/EpisodeEditAssetPanel.tsx
@@ -1,5 +1,7 @@
/** 分集编辑:左侧资产栏(本集/全集 + 分类卡片) */
import { resolveDramaMediaUrl, type DramaAsset } from '../../api/drama'
+import { CharacterVoicePreviewButton } from '../../components/drama/CharacterVoicePreviewButton'
+import { readAssetVoiceBinding } from './CharacterVoiceBindModal'
import {
ASSET_TABS,
normalizeAssetTab,
@@ -16,6 +18,9 @@ type Props = {
onTabChange: (tab: AssetTab | null) => void
onOpenCanvas: () => void
onMention: (asset: DramaAsset) => void
+ onGenerateVoice?: (asset: DramaAsset) => void
+ voiceBusyIds?: ReadonlySet<number>
+ onVoiceError?: (message: string) => void
}
// 渲染分集编辑左侧资产栏
@@ -28,6 +33,9 @@ export function EpisodeEditAssetPanel({
onTabChange,
onOpenCanvas,
onMention,
+ onGenerateVoice,
+ voiceBusyIds,
+ onVoiceError,
}: Props) {
return (
<aside className="drama-ep-assets">
@@ -51,7 +59,7 @@ export function EpisodeEditAssetPanel({
<button
type="button"
className="drama-ep-icon-btn solid"
- aria-label="去画布添加素材"
+ aria-label="打开分镜故事板画布"
onClick={onOpenCanvas}
>
+
@@ -74,27 +82,59 @@ export function EpisodeEditAssetPanel({
<p className="drama-ep-empty">
{scope === 'episode'
? '本集暂无引用素材,可切换「全集」或点击资产插入脚本'
- : '暂无素材,点击右上角前往画布添加'}
+ : '暂无素材,可打开分镜画布或前往资产画布添加'}
</p>
) : (
assets.map((asset) => {
const cover = resolveDramaMediaUrl(asset.cover || asset.url)
const isScene = normalizeAssetTab(asset.type) === 'scene'
+ const isCharacter = normalizeAssetTab(asset.type) === 'character'
+ const voice = isCharacter ? readAssetVoiceBinding(asset) : null
const isActive = activeIds?.has(asset.id)
+ const voiceGenerating = voiceBusyIds?.has(asset.id) ?? false
return (
- <button
- key={asset.id}
- type="button"
- className={`drama-ep-asset-card ${isScene ? 'scene' : ''}${isActive ? ' is-linked' : ''}`}
- onClick={() => onMention(asset)}
- title={isActive ? '本镜已关联 · 点击再次插入' : '点击插入到当前分镜'}
- >
- <div className="drama-ep-asset-thumb">
- {cover ? <img src={cover} alt="" /> : <span>{(asset.name || '?')[0]}</span>}
- </div>
- <span className="drama-ep-asset-name">{asset.name || `资产 ${asset.id}`}</span>
- {isActive ? <span className="drama-ep-asset-linked">已关联</span> : null}
- </button>
+ <div key={asset.id} className="drama-ep-asset-card-wrap">
+ <button
+ type="button"
+ className={`drama-ep-asset-card ${isScene ? 'scene' : ''}${isActive ? ' is-linked' : ''}`}
+ onClick={() => onMention(asset)}
+ title={isActive ? '本镜已关联 · 点击再次插入' : '点击插入到当前分镜'}
+ >
+ <div className="drama-ep-asset-thumb">
+ {cover ? (
+ <img src={cover} alt="" loading="lazy" decoding="async" />
+ ) : (
+ <span>{(asset.name || '?')[0]}</span>
+ )}
+ </div>
+ <span className="drama-ep-asset-name">{asset.name || `资产 ${asset.id}`}</span>
+ {isActive ? <span className="drama-ep-asset-linked">已关联</span> : null}
+ {voice ? <span className="drama-ep-asset-voice">音色</span> : null}
+ </button>
+ {isCharacter && onGenerateVoice ? (
+ voice ? (
+ <CharacterVoicePreviewButton
+ url={voice.url}
+ label={voice.label}
+ variant="inline"
+ className="drama-ep-asset-voice-btn is-bound"
+ onError={onVoiceError}
+ />
+ ) : (
+ <button
+ type="button"
+ className="drama-ep-asset-voice-btn"
+ disabled={voiceGenerating}
+ onClick={(e) => {
+ e.stopPropagation()
+ onGenerateVoice(asset)
+ }}
+ >
+ {voiceGenerating ? '生成中…' : '生成音色'}
+ </button>
+ )
+ ) : null}
+ </div>
)
})
)}
diff --git a/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx b/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx
index e4fd076..5178819 100644
--- a/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx
+++ b/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx
@@ -1,6 +1,7 @@
/** 分集编辑顶栏:视频风格 / 模型 / 画幅(pill 按钮 + 下拉面板) */
import { useEffect, useRef, useState, type MouseEvent } from 'react'
-import { BarChart3, ChevronDown, RectangleVertical, Smile } from 'lucide-react'
+import { BarChart3, ChevronDown, CircleHelp, RectangleVertical, Smile } from 'lucide-react'
+import { SeedanceRulesModal } from '../../components/drama/SeedanceRulesModal'
import {
getImageStyleLabel,
IMAGE_STYLE_OPTIONS,
@@ -14,10 +15,12 @@ type Props = {
modelId: string
aspectRatio: (typeof RATIO_OPTIONS)[number]
resolution: (typeof RES_OPTIONS)[number]
+ linkLastFrame: boolean
onStyleChange: (id: ImageStyleId | '') => void
onModelChange: (id: string) => void
onAspectRatioChange: (r: (typeof RATIO_OPTIONS)[number]) => void
onResolutionChange: (r: (typeof RES_OPTIONS)[number]) => void
+ onLinkLastFrameChange: (enabled: boolean) => void
disabled?: boolean
}
@@ -37,14 +40,17 @@ export function EpisodeEditHeaderControls({
modelId,
aspectRatio,
resolution,
+ linkLastFrame,
onStyleChange,
onModelChange,
onAspectRatioChange,
onResolutionChange,
+ onLinkLastFrameChange,
disabled = false,
}: Props) {
const rootRef = useRef<HTMLDivElement>(null)
const [open, setOpen] = useState<OpenPanel>(null)
+ const [rulesOpen, setRulesOpen] = useState(false)
useEffect(() => {
if (!open) return
@@ -107,8 +113,21 @@ export function EpisodeEditHeaderControls({
<span className="fc-gen-opt-label">{outputLabel}</span>
<ChevronDown size={12} strokeWidth={2} />
</button>
+
+ <button
+ type="button"
+ className="fc-gen-opt-btn drama-seedance-help-btn"
+ disabled={disabled}
+ title="Seedance 传值与使用规则"
+ aria-label="Seedance 传值与使用规则"
+ onClick={() => setRulesOpen(true)}
+ >
+ <CircleHelp size={14} strokeWidth={1.8} />
+ </button>
</div>
+ <SeedanceRulesModal open={rulesOpen} onClose={() => setRulesOpen(false)} />
+
{open === 'style' ? (
<div className="fc-gen-opt-panel fc-gen-style-panel drama-ep-opt-panel" role="dialog" aria-label="视频风格">
<div className="fc-gen-opt-panel-title">视频风格</div>
@@ -185,6 +204,21 @@ export function EpisodeEditHeaderControls({
</button>
))}
</div>
+ <div className="fc-gen-opt-panel-title" style={{ marginTop: 12 }}>
+ 镜间衔接
+ </div>
+ <label className="drama-ep-link-last-frame">
+ <input
+ type="checkbox"
+ checked={linkLastFrame}
+ disabled={disabled}
+ onChange={(e) => onLinkLastFrameChange(e.target.checked)}
+ />
+ <span>
+ 用上一镜尾帧衔接
+ <em>有角色/场景参考时以参考图附带尾帧(不可与 first_frame 混用)</em>
+ </span>
+ </label>
</div>
) : null}
</div>
diff --git a/frontend/src/pages/drama/EpisodeEditMentionPopover.tsx b/frontend/src/pages/drama/EpisodeEditMentionPopover.tsx
index 639c8e6..6556de6 100644
--- a/frontend/src/pages/drama/EpisodeEditMentionPopover.tsx
+++ b/frontend/src/pages/drama/EpisodeEditMentionPopover.tsx
@@ -1,8 +1,14 @@
-/** 分集编辑:输入 @ 时弹出的资产 / 时长选择层 */
+/** 分集编辑:输入 @ 时弹出的资产 / 时长 / 运镜选择层 */
import { useEffect, useMemo, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
-import { Clapperboard, LayoutGrid, Timer, User } from 'lucide-react'
+import { Aperture, Clapperboard, LayoutGrid, Timer, User } from 'lucide-react'
import { resolveDramaMediaUrl, type DramaAsset } from '../../api/drama'
+import {
+ DRAMA_CAMERA_LEXICON,
+ DRAMA_CAMERA_USAGE_TIPS,
+ filterDramaCameraLexicon,
+ type DramaCameraLexiconItem,
+} from '../../lib/dramaCameraLexicon'
import {
DURATION_PRESET_OPTIONS,
FRAGMENT_CONTENT_DURATION_MAX,
@@ -24,11 +30,12 @@ type Props = {
onItemsCountChange: (count: number) => void
onSelectAsset: (asset: DramaAsset) => void
onSelectDuration: (seconds: number) => void
+ onSelectCameraPhrase: (insert: string) => void
onClose: () => void
}
type TabKey = 'assets' | 'tools'
-type ToolsView = 'list' | 'duration'
+type ToolsView = 'list' | 'duration' | 'camera'
const TYPE_LABEL: Record<string, string> = {
character: '角色',
@@ -52,6 +59,7 @@ export function EpisodeEditMentionPopover({
onItemsCountChange,
onSelectAsset,
onSelectDuration,
+ onSelectCameraPhrase,
onClose,
}: Props) {
const panelRef = useRef<HTMLDivElement>(null)
@@ -71,6 +79,20 @@ export function EpisodeEditMentionPopover({
return list.filter((a) => (a.name || '').toLowerCase().includes(q) || String(a.id).includes(q))
}, [assets, query, referencedIds, scope])
+ const filteredCamera = useMemo(
+ () => filterDramaCameraLexicon(DRAMA_CAMERA_LEXICON, toolsView === 'camera' ? query : ''),
+ [query, toolsView],
+ )
+
+ const shotItems = useMemo(
+ () => filteredCamera.filter((i) => i.group === 'shot'),
+ [filteredCamera],
+ )
+ const moveItems = useMemo(
+ () => filteredCamera.filter((i) => i.group === 'move'),
+ [filteredCamera],
+ )
+
useEffect(() => {
onItemsCountChange(tab === 'assets' ? filteredAssets.length : 0)
}, [filteredAssets.length, onItemsCountChange, tab])
@@ -97,11 +119,35 @@ export function EpisodeEditMentionPopover({
if (!open || !anchorRect) return null
- const top = Math.min(anchorRect.bottom + 8, window.innerHeight - 360)
- const left = Math.min(Math.max(12, anchorRect.left), window.innerWidth - 340)
+ const top = Math.min(anchorRect.bottom + 8, window.innerHeight - 420)
+ const left = Math.min(Math.max(12, anchorRect.left), window.innerWidth - 360)
const remaining = Math.max(0, FRAGMENT_CONTENT_DURATION_MAX - contentDurationTotal)
+ // 渲染一组运镜/景别按钮
+ function renderCameraGroup(title: string, items: DramaCameraLexiconItem[]) {
+ if (items.length === 0) return null
+ return (
+ <div className="drama-ep-mention-pop-camera-group">
+ <p className="drama-ep-mention-pop-camera-heading">{title}</p>
+ <div className="drama-ep-mention-pop-camera-grid">
+ {items.map((item) => (
+ <button
+ key={item.id}
+ type="button"
+ title={item.hint}
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => onSelectCameraPhrase(item.insert)}
+ >
+ <strong>{item.label}</strong>
+ <em>{item.hint}</em>
+ </button>
+ ))}
+ </div>
+ </div>
+ )
+ }
+
return createPortal(
<div
ref={panelRef}
@@ -200,9 +246,28 @@ export function EpisodeEditMentionPopover({
<em>剩余可用 {remaining}s</em>
</span>
</button>
+ <button
+ type="button"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setToolsView('camera')}
+ >
+ <Aperture size={16} />
+ <span>
+ <strong>景别 / 运镜</strong>
+ <em>插入空镜、特写、推拉摇移等前缀</em>
+ </span>
+ </button>
</div>
- ) : (
+ ) : toolsView === 'duration' ? (
<div className="drama-ep-mention-pop-duration">
+ <button
+ type="button"
+ className="drama-ep-mention-pop-back"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setToolsView('list')}
+ >
+ ← 返回
+ </button>
<div className="drama-ep-mention-pop-duration-presets">
{DURATION_PRESET_OPTIONS.map((sec) => {
const disabled = sec > remaining
@@ -242,6 +307,30 @@ export function EpisodeEditMentionPopover({
</button>
</div>
</div>
+ ) : (
+ <div className="drama-ep-mention-pop-camera">
+ <button
+ type="button"
+ className="drama-ep-mention-pop-back"
+ onMouseDown={(e) => e.preventDefault()}
+ onClick={() => setToolsView('list')}
+ >
+ ← 返回
+ </button>
+ {filteredCamera.length === 0 ? (
+ <p className="drama-ep-mention-pop-empty">无匹配词条</p>
+ ) : (
+ <>
+ {renderCameraGroup('景别', shotItems)}
+ {renderCameraGroup('运镜', moveItems)}
+ </>
+ )}
+ <ul className="drama-ep-mention-pop-camera-tips">
+ {DRAMA_CAMERA_USAGE_TIPS.map((tip) => (
+ <li key={tip}>{tip}</li>
+ ))}
+ </ul>
+ </div>
)}
</div>,
document.body,
diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsx
index 87cda8b..abe52f4 100644
--- a/frontend/src/pages/drama/EpisodeEditPage.tsx
+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx
@@ -23,11 +23,21 @@ import {
type AssetScope,
type AssetTab,
} from './dramaEpisodeEditUtils'
+import { enqueueEpisodeVideoJobs, syncEpisodeVideoJobs } from '../../lib/dramaGenQueue'
+import {
+ collectDramaGenerateGateIssues,
+ formatDramaGateMessage,
+} from '../../lib/dramaEpisodeScriptValidate'
+import { dialog } from '../../lib/dialog'
+import { StoryboardGridImportModal } from '../../components/drama/StoryboardGridImportModal'
import { getImageStyleId } from './dramaWorkspaceUtils'
import { EpisodeEditAssetPanel } from './EpisodeEditAssetPanel'
import { EpisodeEditHeaderControls } from './EpisodeEditHeaderControls'
import { EpisodeEditPromptEditor } from './EpisodeEditPromptEditor'
import { EpisodeEditReferenceStrip } from './EpisodeEditReferenceStrip'
+import { EpisodeEditSidePane } from './EpisodeEditSidePane'
+import { readAssetVoiceBinding } from './CharacterVoiceBindModal'
+import { generateAndBindCharacterVoice } from '../../lib/characterVoiceGenerate'
import RequireAuth from './RequireAuth'
import './drama.css'
@@ -39,6 +49,12 @@ export default function EpisodeEditPage() {
)
}
+function readFragmentPlanStatus(ep: DramaEpisode | null): string {
+ // 读取 episode.params 上的 AI 分镜状态
+ const st = ep?.params?.fragment_plan_status
+ return typeof st === 'string' ? st : ''
+}
+
// 分集编辑页主体
function EpisodeEditInner() {
const { projectId, episodeId } = useParams()
@@ -66,23 +82,82 @@ function EpisodeEditInner() {
const [modelId, setModelId] = useState('seedance-2.5')
const [aspectRatio, setAspectRatio] = useState<(typeof RATIO_OPTIONS)[number]>('9:16')
const [resolution, setResolution] = useState<(typeof RES_OPTIONS)[number]>('480p')
+ // linkLastFrame 是否用上一镜尾帧作本镜首帧(写入 project.params)
+ const [linkLastFrame, setLinkLastFrame] = useState(true)
+ // projectParams 项目 params 缓存,切换衔接开关时合并写回
+ const [projectParams, setProjectParams] = useState<Record<string, unknown>>({})
+ // storyboardImportOpen 分镜板多宫格导入弹窗
+ const [storyboardImportOpen, setStoryboardImportOpen] = useState(false)
const [busy, setBusy] = useState(false)
const [status, setStatus] = useState('')
const [error, setError] = useState('')
- const [genProgress, setGenProgress] = useState<Record<number, string>>({})
+ const [characterVoiceBusyIds, setCharacterVoiceBusyIds] = useState<Set<number>>(() => new Set())
const pollRef = useRef<number | null>(null)
- const videoRef = useRef<HTMLVideoElement | null>(null)
const selected = fragments[selectedIndex] || null
const selectedDuration = selected?.duration_sec ?? 8
+ // generatingIds 当前排队/生成中的分镜 id
+ const generatingIds = useMemo(() => {
+ const ids = new Set<number>()
+ for (const frag of fragments) {
+ if (!frag.id) continue
+ const status = readFragmentGenerationStatus(frag).status
+ if (status === 'queued' || status === 'running') ids.add(frag.id)
+ }
+ return ids
+ }, [fragments])
+ // anyFragmentGenerating 本集是否有分镜在排队/生成(不锁编辑,仅锁批量生成)
+ const anyFragmentGenerating = generatingIds.size > 0
+ // selectedIsGenerating 当前选中镜是否正在生成
+ const selectedIsGenerating = Boolean(selected?.id && generatingIds.has(selected.id))
+ // selectedGenerateLocked 仅锁当前镜的「生成」按钮
+ const selectedGenerateLocked = busy || selectedIsGenerating
+ // generateAllLocked 全部生成:有任务进行中时禁止
+ const generateAllLocked = busy || anyFragmentGenerating
+ // planFragmentsLocked AI 重新分镜与视频生成互斥
+ const planFragmentsLocked = busy || anyFragmentGenerating
const selectedRefIds = useMemo(
() => new Set(collectFragmentAssetIds(selected)),
[selected],
)
const selectedRefItems = useMemo(
- () => buildFragmentRefStripItems(selected, assets, resolveDramaMediaUrl),
+ () =>
+ buildFragmentRefStripItems(selected, assets, resolveDramaMediaUrl, (asset) => {
+ const voice = readAssetVoiceBinding(asset)
+ return voice ? { label: voice.label, url: voice.url } : null
+ }),
[selected, assets],
)
+ // selectedGateIssues 当前镜脚本/资产门禁(编辑区即时提示)
+ const selectedGateIssues = useMemo(() => {
+ const { blocking, warnings } = collectDramaGenerateGateIssues(selected, assets)
+ return [...blocking, ...warnings]
+ }, [selected, assets])
+
+ // prevLastFrameUrl 上一镜已落盘尾帧(衔接触发条件)
+ const prevLastFrameUrl = useMemo(() => {
+ if (selectedIndex <= 0) return ''
+ const prev = fragments[selectedIndex - 1]
+ const params = prev?.params
+ if (!params || typeof params !== 'object') return ''
+ const raw = (params as Record<string, unknown>).lastFrameUrl
+ return typeof raw === 'string' ? raw.trim() : ''
+ }, [fragments, selectedIndex])
+
+ // 持久化镜间衔接开关到项目 params
+ async function handleLinkLastFrameChange(enabled: boolean) {
+ setLinkLastFrame(enabled)
+ const nextParams = { ...projectParams, linkLastFrame: enabled }
+ setProjectParams(nextParams)
+ try {
+ const updated = await dramaApi.updateProject(pid, { params: nextParams })
+ if (updated.params && typeof updated.params === 'object') {
+ setProjectParams(updated.params as Record<string, unknown>)
+ }
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '保存衔接设置失败')
+ }
+ }
const referencedIds = useMemo(() => {
const set = new Set<number>()
@@ -106,53 +181,128 @@ function EpisodeEditInner() {
}
}
- // 应用后端生成进度并同步分镜状态
+ // 应用后端生成进度并同步分镜状态 + 全局队列
function applyGenerateStatus(st: Awaited<ReturnType<typeof dramaApi.generateStatus>>) {
setStatus(`完成 ${st.done}/${st.total} · 进行中 ${st.running} · 失败 ${st.failed}`)
const byId = new Map(st.fragments.map((f) => [f.fragment_id, f.status]))
- setGenProgress(Object.fromEntries(byId))
- setFragments((prev) =>
- prev.map((f) => {
+ setFragments((prev) => {
+ const next = prev.map((f) => {
if (!f.id) return f
const genStatus = byId.get(f.id)
if (!genStatus) return f
- const item = st.fragments.find((x) => x.fragment_id === f.id)
+ const item = st.fragments.find((x) => x.fragment_id === f.id) as
+ | {
+ fragment_id: number
+ status: string
+ video?: string
+ cover?: string
+ message?: string
+ phase?: string
+ error?: string
+ }
+ | undefined
return {
...f,
video: item?.video || f.video,
cover: item?.cover || f.cover,
params: {
...(f.params || {}),
- generation: { status: genStatus, video: item?.video, cover: item?.cover },
+ generation: {
+ status: genStatus,
+ video: item?.video,
+ cover: item?.cover,
+ message: item?.message,
+ phase: item?.phase,
+ error: item?.error,
+ },
},
}
- }),
- )
+ })
+ syncEpisodeVideoJobs({
+ projectId: pid,
+ episodeId: eid,
+ episodeName: episode?.name,
+ fragments: next.map((f) => ({
+ id: f.id,
+ sort_order: f.sort_order,
+ content: f.content,
+ })),
+ statusItems: st.fragments.map((f) => {
+ const row = f as {
+ fragment_id: number
+ status: string
+ message?: string
+ phase?: string
+ error?: string
+ video?: string
+ cover?: string
+ }
+ return {
+ fragment_id: row.fragment_id,
+ status: row.status,
+ message: row.message,
+ phase: row.phase,
+ error: row.error,
+ video: row.video,
+ cover: row.cover,
+ }
+ }),
+ })
+ return next
+ })
return st
}
- // 启动生成进度轮询(刷新页面后也会恢复)
+ // 启动生成进度轮询(立刻拉一次,再每 3s)
function startGeneratePolling() {
stopGeneratePolling()
- setBusy(true)
- pollRef.current = window.setInterval(async () => {
+ const tick = async () => {
try {
const st = applyGenerateStatus(await dramaApi.generateStatus(eid))
- if (st.running === 0 && st.done + st.failed >= st.total) {
+ // 仅按「进行中/排队」判断;单条生成时 total 仍是全集数量
+ if (st.running === 0) {
stopGeneratePolling()
await reload()
- setBusy(false)
}
} catch {
stopGeneratePolling()
- setBusy(false)
}
+ }
+ void tick()
+ pollRef.current = window.setInterval(() => {
+ void tick()
}, 3000)
}
- // 进页检查是否有进行中的生成任务
+ // 进页检查是否有进行中的生成任务或 AI 分镜
async function resumeGenerateIfNeeded() {
try {
+ const ep = await dramaApi.getEpisode(eid)
+ if (readFragmentPlanStatus(ep) === 'generating') {
+ setBusy(true)
+ setStatus('AI 分镜规划中…')
+ const started = Date.now()
+ while (Date.now() - started < 10 * 60 * 1000) {
+ await new Promise((r) => setTimeout(r, 2500))
+ const cur = await dramaApi.getEpisode(eid)
+ const st = readFragmentPlanStatus(cur)
+ if (st === 'completed') {
+ setEpisode(cur)
+ setFragments(cur.fragments || [])
+ setSelectedIndex(0)
+ setStatus(`AI 分镜完成 · ${(cur.fragments || []).length} 条`)
+ setBusy(false)
+ return
+ }
+ if (st === 'failed') {
+ setError(String(cur.params?.fragment_plan_error || 'AI 分镜失败'))
+ setBusy(false)
+ return
+ }
+ }
+ setBusy(false)
+ return
+ }
const st = applyGenerateStatus(await dramaApi.generateStatus(eid))
if (st.running > 0) startGeneratePolling()
} catch {
@@ -160,6 +310,11 @@ function EpisodeEditInner() {
}
}
+ // 打开全屏分镜故事板画布
+ function openEpisodeStoryboard() {
+ navigate(`/drama/projects/${pid}/episodes/${eid}/canvas`)
+ }
+
// 重新加载分集
async function reload() {
const ep = await dramaApi.getEpisode(eid)
@@ -189,12 +344,27 @@ function EpisodeEditInner() {
.listAssets(pid)
.then(setAssets)
.catch(() => setAssets([]))
- // 加载项目默认画面风格到顶栏
+ // 加载项目默认画面风格 / 镜间衔接等到顶栏
dramaApi
.getProject(pid)
.then((project) => {
const styleId = getImageStyleId(project.script, project)
if (styleId) setVideoStyleId(styleId as ImageStyleId)
+ const params =
+ project.params && typeof project.params === 'object' && !Array.isArray(project.params)
+ ? (project.params as Record<string, unknown>)
+ : {}
+ setProjectParams(params)
+ const linkRaw = params.linkLastFrame ?? params.link_last_frame
+ if (typeof linkRaw === 'boolean') setLinkLastFrame(linkRaw)
+ const ratio = String(params.aspect_ratio || '')
+ if ((RATIO_OPTIONS as readonly string[]).includes(ratio)) {
+ setAspectRatio(ratio as (typeof RATIO_OPTIONS)[number])
+ }
+ const res = String(params.resolution || '')
+ if ((RES_OPTIONS as readonly string[]).includes(res)) {
+ setResolution(res as (typeof RES_OPTIONS)[number])
+ }
})
.catch(() => {
/* ignore */
@@ -294,16 +464,64 @@ function EpisodeEditInner() {
}
}
- // 保存后生成并轮询
- async function generate() {
- if (!window.confirm('将基于当前分镜脚本生成视频,是否继续?')) return
+ // 仅生成当前选中分镜(save 会重建分镜 id,必须用保存后的 id)
+ async function generateSelected() {
+ if (!selected) {
+ setError('请先选择一条分镜')
+ return
+ }
+ if (selectedGenerateLocked) {
+ if (selectedIsGenerating) {
+ setError('当前分镜正在生成,请等待完成后再试')
+ } else {
+ setError('请等待当前操作完成后再试')
+ }
+ return
+ }
+
+ const { blocking, warnings } = collectDramaGenerateGateIssues(selected, assets)
+ if (blocking.length > 0) {
+ setError(blocking.map((i) => i.message).join(';'))
+ await dialog.alert({
+ title: '无法生成',
+ message: formatDramaGateMessage(blocking, warnings, '请先按分集规则修复脚本后再生成。'),
+ })
+ return
+ }
+
+ const fragLabel = formatFragLabel(selectedIndex, selectedDuration)
+ const ok = await dialog.confirm({
+ title: '生成分镜视频',
+ message: formatDramaGateMessage(
+ [],
+ warnings,
+ `将保存当前编辑并排队生成「${fragLabel}」的视频,通常需要数分钟。是否继续?`,
+ ),
+ confirmText: warnings.length > 0 ? '仍要生成' : '开始生成',
+ })
+ if (!ok) return
setBusy(true)
setError('')
- setStatus('保存并排队生成…')
+ setStatus('保存并排队生成当前分镜…')
try {
- await save()
+ const ep = await save()
setBusy(true)
- await dramaApi.generateEpisode(eid)
+ const frag = (ep.fragments || [])[selectedIndex]
+ if (!frag?.id) {
+ throw new Error('保存后未找到当前分镜,请刷新后重试')
+ }
+ await dramaApi.generateEpisode(eid, [frag.id])
+ enqueueEpisodeVideoJobs({
+ projectId: pid,
+ episodeId: eid,
+ episodeName: ep.name || episode?.name,
+ fragments: (ep.fragments || []).map((f, i) => ({
+ id: f.id,
+ sort_order: f.sort_order ?? i,
+ })),
+ fragmentIds: [frag.id],
+ })
+ setBusy(false)
startGeneratePolling()
} catch (err) {
setError(err instanceof Error ? err.message : '生成失败')
@@ -311,11 +529,138 @@ function EpisodeEditInner() {
}
}
+ // 全部生成:入队本集所有分镜(用保存后的新 id)
+ async function generateAll() {
+ if (fragments.length === 0) {
+ setError('没有可生成的分镜')
+ return
+ }
+ if (generateAllLocked) {
+ setError('已有分镜正在生成,请等待完成后再试')
+ return
+ }
+
+ const allBlocking: string[] = []
+ const allWarnings: string[] = []
+ for (let i = 0; i < fragments.length; i++) {
+ const { blocking, warnings } = collectDramaGenerateGateIssues(fragments[i], assets)
+ const label = formatFragLabel(i, fragments[i]?.duration_sec)
+ for (const issue of blocking) allBlocking.push(`${label}:${issue.message}`)
+ for (const issue of warnings) allWarnings.push(`${label}:${issue.message}`)
+ }
+ if (allBlocking.length > 0) {
+ setError(allBlocking[0] || '分镜脚本校验未通过')
+ await dialog.alert({
+ title: '无法全部生成',
+ message: ['请先修复以下问题:', '', ...allBlocking.slice(0, 8).map((m) => `· ${m}`)].join(
+ '\n',
+ ),
+ })
+ return
+ }
+
+ const ok = await dialog.confirm({
+ title: '生成全部分镜视频',
+ message: formatDramaGateMessage(
+ [],
+ allWarnings.slice(0, 8).map((message) => ({ level: 'warn' as const, message })),
+ `将保存当前编辑并排队生成本集全部 ${fragments.length} 条分镜视频,耗时较长且会覆盖已有视频。是否继续?`,
+ ),
+ confirmText: allWarnings.length > 0 ? '仍要全部生成' : '全部生成',
+ tone: 'danger',
+ })
+ if (!ok) return
+ setBusy(true)
+ setError('')
+ setStatus(`保存并排队生成全部 ${fragments.length} 条…`)
+ try {
+ const ep = await save()
+ setBusy(true)
+ const ids = (ep.fragments || [])
+ .map((f) => f.id)
+ .filter((id): id is number => typeof id === 'number' && id > 0)
+ if (ids.length === 0) {
+ throw new Error('保存后没有可生成的分镜')
+ }
+ await dramaApi.generateEpisode(eid, ids)
+ enqueueEpisodeVideoJobs({
+ projectId: pid,
+ episodeId: eid,
+ episodeName: ep.name || episode?.name,
+ fragments: (ep.fragments || []).map((f, i) => ({
+ id: f.id,
+ sort_order: f.sort_order ?? i,
+ })),
+ fragmentIds: ids,
+ })
+ setBusy(false)
+ startGeneratePolling()
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '全部生成失败')
+ setBusy(false)
+ }
+ }
+
// 返回分集步骤
function handleBack() {
navigate(`/drama/projects/${pid}`, { state: { returnStep: 'episodes' } })
}
+ // 单集 LLM 重新分镜:入队后轮询至完成
+ async function planFragmentsWithLlm() {
+ if (planFragmentsLocked) {
+ setError('当前有视频生成任务进行中,请稍候再重新分镜')
+ return
+ }
+ const ok = await dialog.confirm({
+ title: 'AI 重新分镜',
+ message:
+ '将调用大模型按本集剧本重新规划分镜(覆盖现有分镜与已生成视频),通常需要数十秒,是否继续?',
+ confirmText: '开始分镜',
+ tone: 'danger',
+ })
+ if (!ok) return
+
+ setBusy(true)
+ setError('')
+ setStatus('AI 分镜规划中…')
+ try {
+ await dramaApi.planEpisodeFragments(eid, { force: true, fallback_rules: true })
+ const started = Date.now()
+ while (Date.now() - started < 10 * 60 * 1000) {
+ await new Promise((r) => setTimeout(r, 2500))
+ const ep = await dramaApi.getEpisode(eid)
+ const st = readFragmentPlanStatus(ep)
+ if (st === 'completed') {
+ setEpisode(ep)
+ setFragments(ep.fragments || [])
+ setSelectedIndex(0)
+ setEditing(false)
+ const mode = String(ep.params?.fragment_plan_mode || 'llm')
+ const count = Number(ep.params?.fragment_plan_count) || (ep.fragments || []).length
+ setStatus(
+ mode === 'rules_fallback'
+ ? `分镜完成(模型失败已回退规则切分)· ${count} 条`
+ : `AI 分镜完成 · ${count} 条`,
+ )
+ setBusy(false)
+ return
+ }
+ if (st === 'failed') {
+ const msg = String(ep.params?.fragment_plan_error || 'AI 分镜失败')
+ setError(msg)
+ setBusy(false)
+ return
+ }
+ setStatus('AI 分镜规划中…')
+ }
+ throw new Error('AI 分镜超时,请稍后刷新查看')
+ } catch (err) {
+ setError(err instanceof Error ? err.message : 'AI 分镜失败')
+ setBusy(false)
+ }
+ }
+
// 点击资产插入 @ 引用
function mentionAsset(asset: DramaAsset) {
if (!selected) return
@@ -337,6 +682,31 @@ function EpisodeEditInner() {
setAssetScope('series')
}
+ // 更新角色资产(音色绑定后刷新列表)
+ function handleCharacterUpdated(updated: DramaAsset) {
+ setAssets((prev) => prev.map((a) => (a.id === updated.id ? updated : a)))
+ }
+
+ // 一键 AI 生成角色音色并绑定(各角色独立 busy,互不阻塞)
+ async function handleGenerateCharacterVoice(asset: DramaAsset) {
+ if (characterVoiceBusyIds.has(asset.id)) return
+ setCharacterVoiceBusyIds((prev) => new Set(prev).add(asset.id))
+ setError('')
+ try {
+ const { character, voice } = await generateAndBindCharacterVoice(pid, asset)
+ handleCharacterUpdated(character)
+ setAssets((prev) => (prev.some((a) => a.id === voice.id) ? prev : [...prev, voice]))
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '音色生成失败')
+ } finally {
+ setCharacterVoiceBusyIds((prev) => {
+ const next = new Set(prev)
+ next.delete(asset.id)
+ return next
+ })
+ }
+ }
+
if (!episode) {
return (
<div className="drama-ep-fullscreen drama-ep-center">
@@ -345,8 +715,16 @@ function EpisodeEditInner() {
)
}
- const previewUrl = selected?.video ? resolveDramaMediaUrl(selected.video) : ''
- const previewCover = selected?.cover ? resolveDramaMediaUrl(selected.cover) : ''
+ // 当前预览/选中分镜 id(与底部分镜条、脚本编辑联动)
+ const playingFragmentId = selected?.id ?? null
+
+ // 切换预览分镜时同步底部分镜选中态
+ function handlePlayingFragmentChange(fragmentId: number) {
+ const index = fragments.findIndex((f) => f.id === fragmentId)
+ if (index >= 0) {
+ setSelectedIndex(index)
+ }
+ }
return (
<div className="drama-ep-fullscreen">
@@ -363,12 +741,38 @@ function EpisodeEditInner() {
modelId={modelId}
aspectRatio={aspectRatio}
resolution={resolution}
+ linkLastFrame={linkLastFrame}
onStyleChange={setVideoStyleId}
onModelChange={setModelId}
onAspectRatioChange={setAspectRatio}
onResolutionChange={setResolution}
+ onLinkLastFrameChange={(enabled) => void handleLinkLastFrameChange(enabled)}
disabled={busy}
/>
+ <button
+ type="button"
+ className="drama-ep-btn-ghost"
+ disabled={busy}
+ onClick={() => setStoryboardImportOpen(true)}
+ >
+ 导入分镜板
+ </button>
+ <button
+ type="button"
+ className="drama-ep-btn-ghost"
+ disabled={planFragmentsLocked}
+ onClick={() => void planFragmentsWithLlm()}
+ >
+ {busy && status.includes('分镜') ? '分镜中…' : 'AI 重新分镜'}
+ </button>
+ <button
+ type="button"
+ className="drama-ep-btn-dark drama-ep-header-gen-all"
+ disabled={generateAllLocked || fragments.length === 0}
+ onClick={() => void generateAll()}
+ >
+ {generateAllLocked ? '处理中…' : '全部生成'}
+ </button>
</div>
</header>
@@ -387,8 +791,11 @@ function EpisodeEditInner() {
activeIds={selectedRefIds}
onScopeChange={setAssetScope}
onTabChange={setAssetTab}
- onOpenCanvas={() => navigate(`/drama/projects/${pid}/canvas`)}
+ onOpenCanvas={openEpisodeStoryboard}
onMention={mentionAsset}
+ onGenerateVoice={(asset) => void handleGenerateCharacterVoice(asset)}
+ voiceBusyIds={characterVoiceBusyIds}
+ onVoiceError={(message) => setError(message)}
/>
<section className="drama-ep-editor">
@@ -430,6 +837,33 @@ function EpisodeEditInner() {
/>
</div>
+ {selectedGateIssues.length > 0 ? (
+ <ul className="drama-ep-script-issues" aria-live="polite">
+ {selectedGateIssues.map((issue) => (
+ <li
+ key={`${issue.level}:${issue.message}`}
+ className={
+ issue.level === 'error'
+ ? 'drama-ep-script-issue is-error'
+ : 'drama-ep-script-issue is-warn'
+ }
+ >
+ {issue.message}
+ </li>
+ ))}
+ </ul>
+ ) : null}
+
+ {linkLastFrame && selectedIndex > 0 ? (
+ <p
+ className={`drama-ep-continuity-hint${prevLastFrameUrl ? ' is-ready' : ' is-wait'}`}
+ >
+ {prevLastFrameUrl
+ ? '将使用上一镜尾帧作为衔接参考(与角色参考图一并提交)'
+ : '已开启镜间衔接:请先生成上一镜以获取尾帧'}
+ </p>
+ ) : null}
+
<div className="drama-ep-editor-actions">
{editing ? (
<>
@@ -458,7 +892,7 @@ function EpisodeEditInner() {
<button
type="button"
className="drama-ep-btn-ghost"
- disabled={!selected}
+ disabled={!selected || selectedIsGenerating || busy}
onClick={() => setEditing(true)}
>
编辑
@@ -466,41 +900,24 @@ function EpisodeEditInner() {
<button
type="button"
className="drama-ep-btn-dark"
- disabled={busy || !selected}
- onClick={() => void generate()}
+ disabled={selectedGenerateLocked || !selected}
+ title={selectedIsGenerating ? '当前分镜正在生成' : undefined}
+ onClick={() => void generateSelected()}
>
- {busy ? '处理中…' : '生成'}
+ {selectedIsGenerating ? '生成中…' : busy ? '处理中…' : '生成'}
</button>
</>
)}
</div>
</section>
- <aside className="drama-ep-preview">
- {!selected ? (
- <p className="drama-ep-empty">请选择底部分镜</p>
- ) : (
- <div className={`drama-ep-player ratio-${aspectRatio.replace(':', 'x')}`}>
- {previewUrl ? (
- <video
- ref={videoRef}
- key={previewUrl}
- src={previewUrl}
- poster={previewCover || undefined}
- controls
- playsInline
- />
- ) : previewCover ? (
- <img src={previewCover} alt="" />
- ) : (
- <div className="drama-ep-player-placeholder">
- <span>暂无预览</span>
- <small>生成后将在此播放</small>
- </div>
- )}
- </div>
- )}
- </aside>
+ <EpisodeEditSidePane
+ fragments={fragments}
+ playingFragmentId={playingFragmentId}
+ onPlayingFragmentChange={handlePlayingFragmentChange}
+ aspectRatio={aspectRatio}
+ onOpenStoryboard={openEpisodeStoryboard}
+ />
</div>
<footer className="drama-ep-storyboard">
@@ -514,9 +931,8 @@ function EpisodeEditInner() {
+
</button>
{fragments.map((frag, index) => {
- const fragStatus =
- (frag.id ? genProgress[frag.id] : undefined) ||
- readFragmentGenerationStatus(frag).status
+ const fragStatus = readFragmentGenerationStatus(frag).status
+ const fragBusy = fragStatus === 'running' || fragStatus === 'queued'
const clipVideo = frag.video ? resolveDramaMediaUrl(frag.video) : ''
const clipCover = frag.cover ? resolveDramaMediaUrl(frag.cover) : ''
return (
@@ -524,7 +940,7 @@ function EpisodeEditInner() {
<button
type="button"
className={`drama-ep-clip ${selectedIndex === index ? 'active' : ''}${
- fragStatus === 'running' || fragStatus === 'queued' ? ' is-generating' : ''
+ fragBusy ? ' is-generating' : ''
}${fragStatus === 'failed' ? ' is-failed' : ''}`}
onClick={() => setSelectedIndex(index)}
>
@@ -534,22 +950,22 @@ function EpisodeEditInner() {
<video src={clipVideo} muted />
) : (
<span className="drama-ep-clip-empty">
- {fragStatus === 'running' || fragStatus === 'queued' ? '…' : '+'}
+ {fragBusy ? '…' : '+'}
</span>
)}
<em>{formatFragLabel(index, frag.duration_sec)}</em>
</button>
<div className="drama-ep-clip-ops">
- <button type="button" aria-label="插入" onClick={() => insertFrag(index + 1)}>
+ <button type="button" aria-label="插入" onClick={() => insertFrag(index + 1)} disabled={busy}>
+
</button>
- <button type="button" aria-label="复制" onClick={() => duplicateFrag(index)}>
+ <button type="button" aria-label="复制" onClick={() => duplicateFrag(index)} disabled={busy}>
⧉
</button>
<button
type="button"
aria-label="删除"
- disabled={fragments.length <= 1}
+ disabled={busy || fragments.length <= 1}
onClick={() => deleteFrag(index)}
>
⌫
@@ -560,6 +976,27 @@ function EpisodeEditInner() {
})}
</div>
</footer>
+
+ <StoryboardGridImportModal
+ open={storyboardImportOpen}
+ onClose={() => setStoryboardImportOpen(false)}
+ projectId={pid}
+ episodeId={eid}
+ fragments={fragments}
+ onImported={(next, uploaded) => {
+ setFragments(next)
+ setSelectedIndex(0)
+ setEditing(false)
+ setAssets((prev) => {
+ const byId = new Map(prev.map((a) => [a.id, a]))
+ for (const asset of uploaded) byId.set(asset.id, asset)
+ return Array.from(byId.values())
+ })
+ setStatus(
+ `分镜板已导入 · ${next.length} 镜 · 新增素材 ${uploaded.length}`,
+ )
+ }}
+ />
</div>
)
}
diff --git a/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx b/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx
index 5be3a6c..04f7ec0 100644
--- a/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx
+++ b/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx
@@ -6,6 +6,7 @@ import {
getCaretClientRect,
insertDurationChipAtRange,
insertMentionChipAtRange,
+ insertPlainTextAtRange,
renderPromptEditorContent,
resolveChipFromAsset,
serializePromptEditorContent,
@@ -157,6 +158,21 @@ export function EpisodeEditPromptEditor({
[closeMentionPopover, emitContent],
)
+ // 插入景别 / 运镜前缀纯文本
+ const handleSelectCameraPhrase = useCallback(
+ (text: string) => {
+ const editor = editorRef.current
+ const triggerRange = mentionTriggerRangeRef.current
+ if (!editor || !triggerRange || !text) return
+ insertPlainTextAtRange(triggerRange, text)
+ mentionTriggerRangeRef.current = null
+ closeMentionPopover()
+ emitContent()
+ editor.focus()
+ },
+ [closeMentionPopover, emitContent],
+ )
+
const contentDurationTotal = sumContentDurationSeconds(
mentionOpen && editorRef.current
? serializePromptEditorContent(editorRef.current)
@@ -226,6 +242,7 @@ export function EpisodeEditPromptEditor({
onItemsCountChange={setMentionItemsCount}
onSelectAsset={handleSelectAsset}
onSelectDuration={handleSelectDuration}
+ onSelectCameraPhrase={handleSelectCameraPhrase}
onClose={closeMentionPopover}
/>
</>
diff --git a/frontend/src/pages/drama/EpisodeEditReferenceStrip.tsx b/frontend/src/pages/drama/EpisodeEditReferenceStrip.tsx
index 9632634..f29b716 100644
--- a/frontend/src/pages/drama/EpisodeEditReferenceStrip.tsx
+++ b/frontend/src/pages/drama/EpisodeEditReferenceStrip.tsx
@@ -22,8 +22,12 @@ export function EpisodeEditReferenceStrip({ items, onSelect }: Props) {
<button
key={item.assetId}
type="button"
- className="drama-ep-ref-chip"
- title={`${item.name}${item.type ? ` · ${item.type}` : ''}`}
+ className={`drama-ep-ref-chip${item.isCharacter ? ' is-character' : ''}${
+ item.voiceUrl ? ' has-voice' : item.isCharacter ? ' no-voice' : ''
+ }`}
+ title={`${item.name}${item.type ? ` · ${item.type}` : ''}${
+ item.isCharacter ? (item.voiceLabel ? ` · 音色:${item.voiceLabel}` : ' · 未绑定音色') : ''
+ }`}
onClick={() => onSelect?.(item.assetId)}
>
{item.previewUrl ? (
@@ -31,6 +35,11 @@ export function EpisodeEditReferenceStrip({ items, onSelect }: Props) {
) : (
<span className="drama-ep-ref-chip-fallback">{(item.name || '?')[0]}</span>
)}
+ {item.isCharacter ? (
+ <span className={`drama-ep-ref-voice-badge${item.voiceUrl ? ' bound' : ''}`}>
+ {item.voiceUrl ? '音' : '无音'}
+ </span>
+ ) : null}
<em>{item.name}</em>
</button>
))}
diff --git a/frontend/src/pages/drama/EpisodeEditSidePane.tsx b/frontend/src/pages/drama/EpisodeEditSidePane.tsx
new file mode 100644
index 0000000..afc7e09
--- /dev/null
+++ b/frontend/src/pages/drama/EpisodeEditSidePane.tsx
@@ -0,0 +1,53 @@
+/** 分集编辑右侧:分段视频预览 + 入口打开全屏分镜画布 */
+import type { DramaFragment } from '../../api/drama'
+import { DramaFragmentSegmentedVideoPlayer } from '../../components/drama/DramaFragmentSegmentedVideoPlayer'
+
+type Props = {
+ fragments: DramaFragment[]
+ playingFragmentId: number | null
+ onPlayingFragmentChange: (fragmentId: number) => void
+ aspectRatio: string
+ onOpenStoryboard: () => void
+}
+
+// 渲染分集右侧预览与画布入口
+export function EpisodeEditSidePane({
+ fragments,
+ playingFragmentId,
+ onPlayingFragmentChange,
+ aspectRatio,
+ onOpenStoryboard,
+}: Props) {
+ const hasSelection = playingFragmentId !== null
+
+ return (
+ <aside className="drama-ep-preview">
+ <div className="drama-ep-side-tabs" role="tablist" aria-label="右侧面板">
+ <button type="button" role="tab" aria-selected className="active">
+ 预览
+ </button>
+ <button type="button" role="tab" onClick={onOpenStoryboard}>
+ 画布
+ </button>
+ </div>
+
+ {!hasSelection || fragments.length === 0 ? (
+ <p className="drama-ep-empty">请选择底部分镜</p>
+ ) : (
+ <div className="drama-ep-preview-inner">
+ <DramaFragmentSegmentedVideoPlayer
+ fragments={fragments}
+ playingFragmentId={playingFragmentId}
+ onPlayingFragmentChange={onPlayingFragmentChange}
+ aspectRatio={aspectRatio}
+ />
+ {!fragments.some((f) => f.video) && (
+ <button type="button" className="drama-ep-open-canvas" onClick={onOpenStoryboard}>
+ 打开分镜画布
+ </button>
+ )}
+ </div>
+ )}
+ </aside>
+ )
+}
diff --git a/frontend/src/pages/drama/EpisodesStep.tsx b/frontend/src/pages/drama/EpisodesStep.tsx
index 56b9a7b..8c4088e 100644
--- a/frontend/src/pages/drama/EpisodesStep.tsx
+++ b/frontend/src/pages/drama/EpisodesStep.tsx
@@ -1,33 +1,85 @@
-/** 分集视频步骤:进入时按剧本切分镜,支持强制重切 */
+/** 分集视频步骤:进页规则切分;支持全集规则重切与单集 AI 分镜 */
import { useEffect, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
-import { dramaApi, type DramaEpisode } from '../../api/drama'
+import { Clapperboard, Film, Layers, Sparkles, Wand2 } from 'lucide-react'
+import { dramaApi, resolveDramaMediaUrl, type DramaEpisode } from '../../api/drama'
import { dialog } from '../../lib/dialog'
+import { readFragmentGenerationStatus } from './dramaEpisodeEditUtils'
type EpisodesStepProps = {
projectId: number
onError: (m: string) => void
}
+type EpisodeSummary = {
+ epNo: number
+ fragmentCount: number
+ videoDone: number
+ videoRunning: number
+ videoFailed: number
+ totalSec: number
+ previewUrl: string
+ planStatus: string
+}
+
+// 读取分集 AI 分镜状态
+function readPlanStatus(ep: DramaEpisode): string {
+ const st = ep.params?.fragment_plan_status
+ return typeof st === 'string' ? st : ''
+}
+
+// 汇总单集分镜与视频进度
+function summarizeEpisode(ep: DramaEpisode): EpisodeSummary {
+ const frags = ep.fragments || []
+ let videoDone = 0
+ let videoRunning = 0
+ let videoFailed = 0
+ let totalSec = 0
+ let previewUrl = ''
+ for (const frag of frags) {
+ totalSec += frag.duration_sec && frag.duration_sec > 0 ? frag.duration_sec : 8
+ const st = readFragmentGenerationStatus(frag).status
+ if (st === 'done') videoDone += 1
+ else if (st === 'queued' || st === 'running') videoRunning += 1
+ else if (st === 'failed') videoFailed += 1
+ if (!previewUrl) {
+ const raw = (frag.cover || frag.video || '').trim()
+ if (raw) previewUrl = resolveDramaMediaUrl(raw)
+ }
+ }
+ const epNo = Number(ep.params?.episodeNumber) || 0
+ return {
+ epNo,
+ fragmentCount: frags.length,
+ videoDone,
+ videoRunning,
+ videoFailed,
+ totalSec,
+ previewUrl,
+ planStatus: readPlanStatus(ep),
+ }
+}
+
+// 分集标题竖排展示用(过长截断)
+function verticalTitleLabel(name: string, max = 14): string {
+ const clean = (name || '').replace(/\s+/g, '')
+ if (clean.length <= max) return clean
+ return `${clean.slice(0, max - 1)}…`
+}
+
// 渲染分集视频步骤
export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
const navigate = useNavigate()
- /*
- * episodes 分集列表
- * loading 加载中
- * reseeding 强制重切中
- * seeded 是否已执行过进页 seed
- */
const [episodes, setEpisodes] = useState<DramaEpisode[]>([])
const [loading, setLoading] = useState(true)
const [reseeding, setReseeding] = useState(false)
+ const [planningId, setPlanningId] = useState<number | null>(null)
const seeded = useRef(false)
useEffect(() => {
seeded.current = false
}, [projectId])
- // 拉取 / 切分分镜
async function loadEpisodes(force = false) {
const rows = await dramaApi.seedEpisodes(projectId, force)
setEpisodes(rows)
@@ -40,7 +92,6 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
try {
if (!seeded.current) {
seeded.current = true
- // 进页自动检测旧场记分镜并重切(后端 force=false 时也会 auto-replan)
await loadEpisodes(false)
} else {
setEpisodes(await dramaApi.listEpisodes(projectId))
@@ -59,13 +110,12 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
void enter()
}, [projectId, onError])
- // 按最新分集剧本强制重切全部分镜
async function handleReseed() {
- if (reseeding) return
+ if (reseeding || planningId != null) return
const ok = await dialog.confirm({
- title: '重新切分分镜',
+ title: '规则重切全部分镜',
message:
- '将按最新分集剧本强制重切全部分镜(含已编辑、已生成视频的分集),是否继续?',
+ '将按规则引擎快速重切全部分镜(含已编辑、已生成视频的分集)。单集精细分镜请用「AI 分镜」。是否继续?',
confirmText: '继续切分',
tone: 'danger',
})
@@ -85,43 +135,203 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
}
}
+ async function handlePlanEpisode(ep: DramaEpisode) {
+ if (reseeding || planningId != null) return
+ const ok = await dialog.confirm({
+ title: 'AI 重新分镜',
+ message: `将调用大模型重新规划「${ep.name}」的分镜(覆盖本集现有分镜与视频),通常需要数十秒,是否继续?`,
+ confirmText: '开始分镜',
+ tone: 'danger',
+ })
+ if (!ok) return
+ setPlanningId(ep.id)
+ try {
+ await dramaApi.planEpisodeFragments(ep.id, { force: true, fallback_rules: true })
+ const started = Date.now()
+ while (Date.now() - started < 10 * 60 * 1000) {
+ await new Promise((r) => setTimeout(r, 2500))
+ const cur = await dramaApi.getEpisode(ep.id)
+ const st = readPlanStatus(cur)
+ if (st === 'completed') {
+ setEpisodes((prev) => prev.map((row) => (row.id === cur.id ? cur : row)))
+ const count = Number(cur.params?.fragment_plan_count) || (cur.fragments || []).length
+ const mode = String(cur.params?.fragment_plan_mode || 'llm')
+ await dialog.alert({
+ title: '分镜完成',
+ message:
+ mode === 'rules_fallback'
+ ? `「${cur.name}」已回退规则切分,共 ${count} 条。`
+ : `「${cur.name}」AI 分镜完成,共 ${count} 条。`,
+ tone: 'success',
+ })
+ return
+ }
+ if (st === 'failed') {
+ throw new Error(String(cur.params?.fragment_plan_error || 'AI 分镜失败'))
+ }
+ }
+ throw new Error('AI 分镜超时,请稍后刷新')
+ } catch (err) {
+ onError(err instanceof Error ? err.message : 'AI 分镜失败')
+ } finally {
+ setPlanningId(null)
+ }
+ }
+
+ const totalFragments = episodes.reduce((n, ep) => n + (ep.fragments?.length || 0), 0)
+ const totalVideos = episodes.reduce(
+ (n, ep) =>
+ n + (ep.fragments || []).filter((f) => readFragmentGenerationStatus(f).status === 'done').length,
+ 0,
+ )
+
return (
<div className="drama-episodes-step">
- <div className="drama-episodes-head">
- <div>
- <h2>分集视频</h2>
- <p className="drama-muted">共 {episodes.length} 集</p>
+ <header className="drama-episodes-hero">
+ <div className="drama-episodes-hero-main">
+ <div className="drama-episodes-hero-icon" aria-hidden>
+ <Film size={22} strokeWidth={1.75} />
+ </div>
+ <div>
+ <h2>分集视频</h2>
+ <p className="drama-episodes-hero-sub">
+ 共 <strong>{episodes.length}</strong> 集 ·{' '}
+ <strong>{totalFragments}</strong> 个分镜 · 已出片{' '}
+ <strong>{totalVideos}</strong>
+ </p>
+ </div>
</div>
- <button
- type="button"
- className="drama-btn-primary"
- disabled={reseeding}
- onClick={() => void handleReseed()}
- >
- {reseeding ? '切分中…' : '重新切分分镜'}
- </button>
- </div>
- {loading ? <p className="drama-muted">正在创建分集与分镜…</p> : null}
- <div className="drama-episode-cards">
- {episodes.map((ep) => (
- <article key={ep.id} className="drama-episode-card">
- <div className="drama-episode-card-thumb" aria-hidden>
- ▶
- </div>
- <div className="drama-episode-card-body">
- <strong>{ep.name}</strong>
- <span>{ep.fragments?.length || 0} 个分镜</span>
- </div>
- <button
- type="button"
- className="drama-btn-primary"
- onClick={() => navigate(`/drama/projects/${projectId}/episodes/${ep.id}`)}
- >
- 编辑
- </button>
- </article>
- ))}
+ <div className="drama-episodes-hero-actions">
+ <button
+ type="button"
+ className="drama-btn-ghost drama-episodes-reseed-btn"
+ disabled={reseeding || planningId != null || loading}
+ onClick={() => void handleReseed()}
+ >
+ <Layers size={16} strokeWidth={1.75} aria-hidden />
+ {reseeding ? '切分中…' : '规则重切全部'}
+ </button>
+ </div>
+ </header>
+
+ <div className="drama-episodes-tips" role="note">
+ <Sparkles size={15} strokeWidth={1.75} aria-hidden />
+ <span>单集可点 <strong>AI 分镜</strong> 精细规划;进入 <strong>编辑</strong> 可改脚本并生成视频。</span>
</div>
+
+ {loading ? (
+ <div className="drama-episode-grid" aria-busy="true" aria-label="加载分集">
+ {Array.from({ length: 6 }).map((_, i) => (
+ <div key={i} className="drama-ep-card drama-ep-card-skeleton" />
+ ))}
+ </div>
+ ) : episodes.length === 0 ? (
+ <div className="drama-episodes-empty">
+ <Clapperboard size={40} strokeWidth={1.25} aria-hidden />
+ <p>暂无分集,请先完成分集剧本步骤。</p>
+ </div>
+ ) : (
+ <div className="drama-episode-grid">
+ {episodes.map((ep) => {
+ const planning = planningId === ep.id
+ const summary = summarizeEpisode(ep)
+ const progress =
+ summary.fragmentCount > 0
+ ? Math.round((summary.videoDone / summary.fragmentCount) * 100)
+ : 0
+ const epLabel =
+ summary.epNo > 0 ? `第 ${summary.epNo} 集` : `分集 ${ep.id}`
+ const statusLabel = planning
+ ? 'AI 分镜中'
+ : summary.videoRunning > 0
+ ? `${summary.videoRunning} 条生成中`
+ : summary.videoFailed > 0
+ ? `${summary.videoFailed} 条失败`
+ : summary.videoDone > 0
+ ? `已出片 ${summary.videoDone}/${summary.fragmentCount}`
+ : `${summary.fragmentCount} 个分镜`
+
+ return (
+ <article
+ key={ep.id}
+ className={`drama-ep-card${planning ? ' is-planning' : ''}${
+ summary.videoRunning > 0 ? ' is-generating' : ''
+ }`}
+ >
+ <button
+ type="button"
+ className="drama-ep-card-poster"
+ onClick={() => navigate(`/drama/projects/${projectId}/episodes/${ep.id}`)}
+ aria-label={`编辑 ${ep.name}`}
+ >
+ {summary.previewUrl ? (
+ <img src={summary.previewUrl} alt="" className="drama-ep-card-poster-img" />
+ ) : (
+ <div className="drama-ep-card-poster-fallback">
+ <span className="drama-ep-card-poster-vertical">
+ {verticalTitleLabel(ep.name)}
+ </span>
+ </div>
+ )}
+ <span className="drama-ep-card-ep-badge">{epLabel}</span>
+ {summary.previewUrl ? (
+ <span className="drama-ep-card-play" aria-hidden>
+ <Film size={18} strokeWidth={1.75} />
+ </span>
+ ) : null}
+ {summary.videoRunning > 0 ? (
+ <span className="drama-ep-card-busy" aria-hidden />
+ ) : null}
+ </button>
+
+ <div className="drama-ep-card-body">
+ <h3 className="drama-ep-card-title">{ep.name}</h3>
+ <div className="drama-ep-card-meta">
+ <span className="drama-ep-card-meta-item">
+ <Layers size={14} strokeWidth={1.75} aria-hidden />
+ {statusLabel}
+ </span>
+ {summary.totalSec > 0 ? (
+ <span className="drama-ep-card-meta-item">
+ <Clapperboard size={14} strokeWidth={1.75} aria-hidden />
+ 约 {summary.totalSec}s
+ </span>
+ ) : null}
+ </div>
+ {summary.fragmentCount > 0 ? (
+ <div className="drama-ep-card-progress" aria-hidden>
+ <div
+ className="drama-ep-card-progress-bar"
+ style={{ width: `${progress}%` }}
+ />
+ </div>
+ ) : null}
+ </div>
+
+ <div className="drama-ep-card-actions">
+ <button
+ type="button"
+ className="drama-ep-card-ai-btn"
+ disabled={reseeding || planningId != null}
+ onClick={() => void handlePlanEpisode(ep)}
+ >
+ <Wand2 size={15} strokeWidth={1.75} aria-hidden />
+ {planning ? '分镜中…' : 'AI 分镜'}
+ </button>
+ <button
+ type="button"
+ className="drama-btn-primary drama-ep-card-edit-btn"
+ disabled={planning}
+ onClick={() => navigate(`/drama/projects/${projectId}/episodes/${ep.id}`)}
+ >
+ 编辑
+ </button>
+ </div>
+ </article>
+ )
+ })}
+ </div>
+ )}
</div>
)
}
diff --git a/frontend/src/pages/drama/NarratorVoiceBindModal.tsx b/frontend/src/pages/drama/NarratorVoiceBindModal.tsx
new file mode 100644
index 0000000..5d1f9c6
--- /dev/null
+++ b/frontend/src/pages/drama/NarratorVoiceBindModal.tsx
@@ -0,0 +1,188 @@
+/**
+ * 旁白音色绑定:从漫剧 voice 资产选择,写入 project.params.narrationVoiceAudio
+ * 供 Seedance 生成时作为全局 reference_audio 注入。
+ */
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { AudioLines } from 'lucide-react'
+import { dramaApi, resolveDramaMediaUrl, type DramaAsset, type DramaProject } from '../../api/drama'
+import Modal from '../../components/ui/Modal'
+import type { VoiceBinding } from './CharacterVoiceBindModal'
+
+type Props = {
+ project: DramaProject
+ open: boolean
+ onClose: () => void
+ onUpdated: (project: DramaProject) => void
+ onError: (message: string) => void
+}
+
+function readNarrationVoiceBinding(project: DramaProject): VoiceBinding | null {
+ const params = project.params || {}
+ const raw = (params as Record<string, unknown>).narrationVoiceAudio
+ if (!raw || typeof raw !== 'object') return null
+ const data = raw as Record<string, unknown>
+ const sourceAssetId = typeof data.sourceAssetId === 'number' ? data.sourceAssetId : null
+ const url = typeof data.url === 'string' ? data.url : ''
+ const label = typeof data.label === 'string' ? data.label : '旁白音色'
+ if (!sourceAssetId || !url) return null
+ return {
+ sourceAssetId,
+ url,
+ label,
+ voicePrompt: typeof data.voicePrompt === 'string' ? data.voicePrompt : undefined,
+ }
+}
+
+export function NarratorVoiceBindModal({ project, open, onClose, onUpdated, onError }: Props) {
+ const [voiceAssets, setVoiceAssets] = useState<DramaAsset[]>([])
+ const [selectedId, setSelectedId] = useState<number | null>(null)
+ const [busy, setBusy] = useState(false)
+
+ const current = useMemo(() => readNarrationVoiceBinding(project), [project])
+
+ const selectedVoice = useMemo(
+ () => voiceAssets.find((v) => v.id === selectedId) || null,
+ [voiceAssets, selectedId],
+ )
+ const previewUrl = selectedVoice?.url ? resolveDramaMediaUrl(selectedVoice.url) : ''
+
+ const boundRef = useRef(false)
+ useEffect(() => {
+ if (!open) {
+ boundRef.current = false
+ return
+ }
+ if (boundRef.current) return
+ boundRef.current = true
+
+ setSelectedId(current?.sourceAssetId ?? null)
+ dramaApi
+ .listAssets(project.id)
+ .then((list) => {
+ const voices = list.filter((a) => (a.type || '').toLowerCase() === 'voice')
+ setVoiceAssets(voices)
+ })
+ .catch((err) => onError(err instanceof Error ? err.message : '加载音色资产失败'))
+ }, [current?.sourceAssetId, onError, open, project.id])
+
+ const handleConfirm = useCallback(async () => {
+ if (!selectedVoice?.url || busy) {
+ onError('请选择已合成试听的旁白音色')
+ return
+ }
+ setBusy(true)
+ try {
+ const binding: VoiceBinding = {
+ sourceAssetId: selectedVoice.id,
+ url: selectedVoice.url,
+ label: selectedVoice.name || '旁白音色',
+ // Narrator 端当前不依赖 voicePrompt;但保留字段给后续扩展
+ voicePrompt:
+ selectedVoice.params && typeof selectedVoice.params === 'object' && typeof (selectedVoice.params as any).voicePrompt === 'string'
+ ? (selectedVoice.params as any).voicePrompt
+ : undefined,
+ }
+ const nextParams = {
+ ...(project.params || {}),
+ narrationVoiceAudio: binding,
+ }
+ const updated = await dramaApi.updateProject(project.id, { params: nextParams })
+ onUpdated(updated)
+ onClose()
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '绑定失败')
+ } finally {
+ setBusy(false)
+ }
+ }, [busy, onClose, onError, onUpdated, project.id, project.params, selectedVoice])
+
+ const handleUnbind = useCallback(async () => {
+ if (busy) return
+ setBusy(true)
+ try {
+ const nextParams = { ...(project.params || {}) }
+ delete (nextParams as Record<string, unknown>).narrationVoiceAudio
+ const updated = await dramaApi.updateProject(project.id, { params: nextParams })
+ onUpdated(updated)
+ onClose()
+ } catch (err) {
+ onError(err instanceof Error ? err.message : '解绑失败')
+ } finally {
+ setBusy(false)
+ }
+ }, [busy, onClose, onError, onUpdated, project.id, project.params])
+
+ if (!open) return null
+
+ return (
+ <Modal
+ open={open}
+ onClose={onClose}
+ title="绑定旁白音色"
+ size="lg"
+ dismissible={!busy}
+ footer={
+ <>
+ <button type="button" className="pf-btn" onClick={onClose} disabled={busy}>
+ 取消
+ </button>
+ {current ? (
+ <button type="button" className="pf-btn" onClick={() => void handleUnbind()} disabled={busy}>
+ 解除绑定
+ </button>
+ ) : null}
+ <button
+ type="button"
+ className="pf-btn pf-btn-lime"
+ onClick={() => void handleConfirm()}
+ disabled={!selectedVoice?.url || busy}
+ >
+ {busy ? '绑定中…' : '确认绑定'}
+ </button>
+ </>
+ }
+ >
+ <p className="drama-muted">
+ 全局旁白音色将作为 Seedance 的 <strong>reference_audio</strong> 注入,用于所有镜头的旁白口播一致性。
+ </p>
+
+ <div className="drama-voice-mode-tabs" style={{ marginTop: 12 }}>
+ <button type="button" className="active">
+ 选择已有
+ </button>
+ </div>
+
+ <div className="drama-voice-list" style={{ marginTop: 10 }}>
+ {voiceAssets.length === 0 ? (
+ <p className="drama-muted">暂无音色资产,请先在「音色」分类合成旁白音色</p>
+ ) : (
+ voiceAssets.map((voice) => {
+ const hasAudio = Boolean(voice.url)
+ const selected = selectedId === voice.id
+ return (
+ <label key={voice.id} className="drama-voice-option" style={{ cursor: 'pointer' }}>
+ <input
+ type="radio"
+ name="drama-narrator-voice"
+ checked={selected}
+ onChange={() => setSelectedId(voice.id)}
+ />
+ <span>
+ {voice.name || `音色#${voice.id}`} <small>{hasAudio ? '已合成' : '未合成'}</small>
+ </span>
+ </label>
+ )
+ })
+ )}
+ </div>
+
+ {previewUrl ? (
+ <div style={{ marginTop: 14, display: 'flex', gap: 12, alignItems: 'center' }}>
+ <AudioLines size={16} />
+ <audio className="drama-voice-audio" controls src={previewUrl} />
+ </div>
+ ) : null}
+ </Modal>
+ )
+}
+
diff --git a/frontend/src/pages/drama/OutlineStep.tsx b/frontend/src/pages/drama/OutlineStep.tsx
index 8778e83..b7ee9f8 100644
--- a/frontend/src/pages/drama/OutlineStep.tsx
+++ b/frontend/src/pages/drama/OutlineStep.tsx
@@ -1,5 +1,6 @@
/** 剧情大纲步骤:自动摘要 + 分集剧本流水线 */
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
+import { BookOpen } from 'lucide-react'
import {
dramaApi,
type DramaProject,
@@ -12,6 +13,7 @@ import {
getSummaryStatus,
parseEpisodeBodies,
} from './dramaWorkspaceUtils'
+import { dialog } from '../../lib/dialog'
type OutlineSectionKey = 'source' | 'summary' | 'episodes'
@@ -195,7 +197,14 @@ export function OutlineStep({
// 手动强制重写全部分集正文
async function handleRegenerateEpisodes() {
if (episodeGenerating) return
- if (!window.confirm('将清空当前分集正文并按新提示词重新生成,是否继续?')) return
+ const ok = await dialog.confirm({
+ title: '重新生成分集剧本',
+ message:
+ '将清空当前分集正文并按最新剧本摘要重新生成全部集数,已有编辑将丢失。是否继续?',
+ confirmText: '重新生成',
+ tone: 'danger',
+ })
+ if (!ok) return
onOutlineReadyChange(false)
await runEpisodeScripts(undefined, true)
}
@@ -323,9 +332,22 @@ export function OutlineStep({
) : null}
<div className="drama-outline-main">
- <div className="drama-outline-toolbar">
- <h2>{episodeCount ? `共 ${episodeCount} 集` : '共 — 集'}</h2>
- <label className="drama-style-select">
+ <header className="drama-outline-hero">
+ <div className="drama-step-hero-main">
+ <div className="drama-step-hero-icon" aria-hidden>
+ <BookOpen size={22} strokeWidth={1.75} />
+ </div>
+ <div>
+ <h2>剧情大纲</h2>
+ <p className="drama-step-hero-sub">
+ {episodeCount ? `共 ${episodeCount} 集` : '集数待定'}
+ {imageStyleId
+ ? ` · ${IMAGE_STYLE_OPTIONS.find((o) => o.id === imageStyleId)?.label || '已选风格'}`
+ : ' · 未选画面风格'}
+ </p>
+ </div>
+ </div>
+ <label className="drama-style-select drama-outline-style">
项目风格
<select
value={imageStyleId}
@@ -339,7 +361,7 @@ export function OutlineStep({
))}
</select>
</label>
- </div>
+ </header>
<div className="drama-accordions">
<Accordion
diff --git a/frontend/src/pages/drama/ProjectWorkspacePage.tsx b/frontend/src/pages/drama/ProjectWorkspacePage.tsx
index a94321a..124f1ce 100644
--- a/frontend/src/pages/drama/ProjectWorkspacePage.tsx
+++ b/frontend/src/pages/drama/ProjectWorkspacePage.tsx
@@ -1,6 +1,7 @@
/** 漫剧项目工作流:剧情大纲 / 资产库 / 分集视频 */
import { useEffect, useMemo, useRef, useState } from 'react'
import { useLocation, useNavigate, useParams } from 'react-router-dom'
+import { ChevronLeft } from 'lucide-react'
import AppShell from '../../components/layout/AppShell'
import { dramaApi, type DramaProject } from '../../api/drama'
import {
@@ -149,7 +150,7 @@ function WorkspaceInner() {
aria-label="返回"
onClick={() => navigate('/drama/dramas')}
>
- ←
+ <ChevronLeft size={20} strokeWidth={1.75} />
</button>
{editingTitle ? (
<input
diff --git a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
index 9501fbf..0fe7a23 100644
--- a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx
@@ -34,6 +34,7 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA
const showUpload = selected && CANVAS_UPLOADABLE_KINDS.has(data.kind)
const showGenerate = selected && CANVAS_GENERATABLE_KINDS.has(data.kind)
const voiceLabel = typeof data.voiceLabel === 'string' ? data.voiceLabel : ''
+ const voiceUrl = typeof data.voiceUrl === 'string' ? data.voiceUrl : ''
const footerLabel =
data.kind === 'character'
? voiceLabel
@@ -58,6 +59,7 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA
nodeId={id}
kind={data.kind}
voiceLabel={data.kind === 'character' ? voiceLabel || null : null}
+ voiceUrl={data.kind === 'character' ? voiceUrl || null : null}
/>
</NodeToolbar>
) : null}
diff --git a/frontend/src/pages/drama/canvas/CanvasStore.tsx b/frontend/src/pages/drama/canvas/CanvasStore.tsx
index 709b6bb..49eebe5 100644
--- a/frontend/src/pages/drama/canvas/CanvasStore.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasStore.tsx
@@ -24,7 +24,7 @@ import {
} from '@xyflow/react'
import { dramaApi } from '../../../api/drama'
import type { DramaAsset } from '../../../api/drama'
-import { enqueueDramaImageGen } from '../../../lib/dramaImageGenQueue'
+import { enqueueDramaImageGen, resumeDramaImageGensFromAssets } from '../../../lib/dramaImageGenQueue'
import type { ImageGenerationOptions } from '../../../lib/dramaGenerationOptions'
import { getImageStyleId } from '../dramaWorkspaceUtils'
import {
@@ -139,6 +139,7 @@ export function CanvasStoreProvider({ projectId, children }: CanvasStoreProvider
if (project) {
setProjectImageStyleId(getImageStyleId(project.script, project))
}
+ resumeDramaImageGensFromAssets(projectId, assets)
readyRef.current = true
})
.catch((err) => {
diff --git a/frontend/src/pages/drama/canvas/CanvasTopBar.tsx b/frontend/src/pages/drama/canvas/CanvasTopBar.tsx
index 86bcfd4..2dfbd22 100644
--- a/frontend/src/pages/drama/canvas/CanvasTopBar.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasTopBar.tsx
@@ -1,32 +1,39 @@
/** 画布顶栏:返回、标题、已保存指示、设置占位 */
import { useState } from 'react'
-import { ChevronLeft, Settings } from 'lucide-react'
+import { ChevronLeft, Maximize2, Settings } from 'lucide-react'
import { useNavigate } from 'react-router-dom'
import { useCanvasStore } from './CanvasStore'
+type Props = {
+ variant?: 'fullscreen' | 'embedded'
+}
+
/** 渲染画布页顶部工具栏 */
-export function CanvasTopBar() {
+export function CanvasTopBar({ variant = 'fullscreen' }: Props) {
const navigate = useNavigate()
const { saveStatusVisible, projectId } = useCanvasStore()
const [settingsOpen, setSettingsOpen] = useState(false)
+ const embedded = variant === 'embedded'
return (
<>
<div className="fc-overlay fc-topbar">
<div className="fc-topbar-left">
- <button
- type="button"
- className="fc-icon-btn"
- aria-label="返回"
- title="返回"
- onClick={() => {
- if (window.history.length > 1) navigate(-1)
- else navigate(`/drama/projects/${projectId}`)
- }}
- >
- <ChevronLeft size={20} strokeWidth={1.8} />
- </button>
- <span className="fc-topbar-title">资产库编排</span>
+ {embedded ? null : (
+ <button
+ type="button"
+ className="fc-icon-btn"
+ aria-label="返回"
+ title="返回"
+ onClick={() => {
+ if (window.history.length > 1) navigate(-1)
+ else navigate(`/drama/projects/${projectId}`)
+ }}
+ >
+ <ChevronLeft size={20} strokeWidth={1.8} />
+ </button>
+ )}
+ <span className="fc-topbar-title">{embedded ? '资产画布' : '资产库编排'}</span>
{saveStatusVisible ? (
<span className="fc-save-pill">
<span className="fc-save-dot" />
@@ -35,16 +42,29 @@ export function CanvasTopBar() {
) : null}
</div>
- <button
- type="button"
- className="fc-icon-btn"
- aria-label="设置"
- title="设置"
- aria-expanded={settingsOpen}
- onClick={() => setSettingsOpen((v) => !v)}
- >
- <Settings size={18} strokeWidth={1.8} />
- </button>
+ <div className="fc-topbar-right">
+ {embedded ? (
+ <button
+ type="button"
+ className="fc-icon-btn"
+ aria-label="全屏画布"
+ title="全屏画布"
+ onClick={() => navigate(`/drama/projects/${projectId}/canvas`)}
+ >
+ <Maximize2 size={18} strokeWidth={1.8} />
+ </button>
+ ) : null}
+ <button
+ type="button"
+ className="fc-icon-btn"
+ aria-label="设置"
+ title="设置"
+ aria-expanded={settingsOpen}
+ onClick={() => setSettingsOpen((v) => !v)}
+ >
+ <Settings size={18} strokeWidth={1.8} />
+ </button>
+ </div>
</div>
{settingsOpen ? (
diff --git a/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx b/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx
index 9d54482..70756b0 100644
--- a/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx
+++ b/frontend/src/pages/drama/canvas/CanvasWorkspace.tsx
@@ -13,10 +13,15 @@ import './canvas.css'
type CanvasWorkspaceProps = {
projectId: number
+ /** fullscreen 独立页;embedded 嵌入分集编辑右侧 */
+ variant?: 'fullscreen' | 'embedded'
}
/** 渲染画布主体与各区域 overlay */
-function CanvasWorkspaceContent({ projectId }: CanvasWorkspaceProps) {
+function CanvasWorkspaceContent({
+ projectId,
+ variant = 'fullscreen',
+}: CanvasWorkspaceProps) {
const {
showNodeSelector,
errorMessage,
@@ -27,6 +32,7 @@ function CanvasWorkspaceContent({ projectId }: CanvasWorkspaceProps) {
loading,
} = useCanvasStore()
const { screenToFlowPosition } = useReactFlow()
+ const embedded = variant === 'embedded'
const handleSelectNode = useCallback(
(kind: CanvasNodeKind) => {
@@ -56,9 +62,9 @@ function CanvasWorkspaceContent({ projectId }: CanvasWorkspaceProps) {
}, [undo, redo])
return (
- <div className="free-canvas-page">
+ <div className={`free-canvas-page${embedded ? ' is-embedded' : ''}`}>
<FreeCanvasFlow projectId={projectId} />
- <CanvasTopBar />
+ <CanvasTopBar variant={variant} />
<CanvasLeftToolbar onSelectNode={handleSelectNode} />
<CanvasBottomControls />
{showNodeSelector ? <CanvasNodeSelector onSelect={handleSelectNode} /> : null}
@@ -77,11 +83,14 @@ function CanvasWorkspaceContent({ projectId }: CanvasWorkspaceProps) {
}
/** 提供 React Flow 与画布状态上下文 */
-export function CanvasWorkspace({ projectId }: CanvasWorkspaceProps) {
+export function CanvasWorkspace({
+ projectId,
+ variant = 'fullscreen',
+}: CanvasWorkspaceProps) {
return (
<ReactFlowProvider>
<CanvasStoreProvider projectId={projectId}>
- <CanvasWorkspaceContent projectId={projectId} />
+ <CanvasWorkspaceContent projectId={projectId} variant={variant} />
</CanvasStoreProvider>
</ReactFlowProvider>
)
diff --git a/frontend/src/pages/drama/canvas/canvas.css b/frontend/src/pages/drama/canvas/canvas.css
index 7fb7cab..a5fc3ea 100644
--- a/frontend/src/pages/drama/canvas/canvas.css
+++ b/frontend/src/pages/drama/canvas/canvas.css
@@ -18,6 +18,35 @@
z-index: 50;
}
+/* 嵌入分集编辑右侧:填满父容器,非全屏遮罩 */
+.free-canvas-page.is-embedded {
+ position: relative;
+ inset: auto;
+ width: 100%;
+ height: 100%;
+ min-height: 0;
+ z-index: 1;
+ border-radius: 0;
+}
+
+.free-canvas-page.is-embedded .fc-topbar {
+ padding: 10px 12px;
+}
+
+.free-canvas-page.is-embedded .fc-left-toolbar {
+ left: 10px;
+}
+
+.free-canvas-page.is-embedded .fc-bottom-controls {
+ left: 10px;
+ bottom: 10px;
+}
+
+.free-canvas-page.is-embedded .fc-node-selector {
+ transform: scale(0.92);
+ transform-origin: center;
+}
+
.free-canvas-page .react-flow {
background: var(--fc-bg);
}
@@ -62,6 +91,13 @@
min-width: 0;
}
+.fc-topbar-right {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ flex-shrink: 0;
+}
+
.fc-topbar-title {
font-size: 14px;
font-weight: 500;
diff --git a/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx b/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx
index cd492e8..6f35333 100644
--- a/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx
+++ b/frontend/src/pages/drama/canvas/nodes/CanvasNodeUploadBar.tsx
@@ -1,32 +1,36 @@
-/** 选中节点顶部:本地上传 + 从全局资产库选择 + 角色音色绑定 */
+/** 选中节点顶部:本地上传 + 从全局资产库选择 + 角色音色生成/试听 */
import { useCallback, useRef, useState, type ChangeEvent, type MouseEvent } from 'react'
import { AudioLines, FolderOpen, Loader2, Upload } from 'lucide-react'
-import { dramaApi, type DramaAsset } from '../../../../api/drama'
+import { dramaApi } from '../../../../api/drama'
+import { CharacterVoicePreviewButton } from '../../../../components/drama/CharacterVoicePreviewButton'
+import { generateAndBindCharacterVoice } from '../../../../lib/characterVoiceGenerate'
import { useCanvasStore } from '../CanvasStore'
import { CANVAS_UPLOADABLE_KINDS, type CanvasNodeKind } from '../canvasTypes'
import {
canvasKindToLibraryTypes,
GlobalAssetPickerModal,
} from '../../GlobalAssetPickerModal'
-import {
- CharacterVoiceBindModal,
-} from '../../CharacterVoiceBindModal'
type CanvasNodeUploadBarProps = {
nodeId: string
kind: CanvasNodeKind
- /** 角色节点已绑定音色名(展示「更换音色」) */
+ /** 角色节点已绑定音色名 */
voiceLabel?: string | null
+ /** 角色节点已绑定音色试听地址 */
+ voiceUrl?: string | null
}
/** 渲染选中节点的上传与资产库操作条 */
-export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUploadBarProps) {
+export function CanvasNodeUploadBar({
+ nodeId,
+ kind,
+ voiceLabel,
+ voiceUrl,
+}: CanvasNodeUploadBarProps) {
/*
* uploading 本地上传中
* pickerOpen 资产库弹窗
- * voiceOpen 音色绑定弹窗
- * voiceAsset 打开弹窗时的角色资产
- * voiceLoading 拉取角色资产中
+ * voiceLoading 音色生成或拉取角色资产中
*/
const {
uploadNodeMedia,
@@ -39,8 +43,6 @@ export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUplo
const fileInputRef = useRef<HTMLInputElement>(null)
const [uploading, setUploading] = useState(false)
const [pickerOpen, setPickerOpen] = useState(false)
- const [voiceOpen, setVoiceOpen] = useState(false)
- const [voiceAsset, setVoiceAsset] = useState<DramaAsset | null>(null)
const [voiceLoading, setVoiceLoading] = useState(false)
const stopFlowEvent = useCallback((event: MouseEvent) => {
@@ -50,7 +52,7 @@ export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUplo
if (!CANVAS_UPLOADABLE_KINDS.has(kind)) return null
const isCharacter = kind === 'character'
- const hasVoice = Boolean(voiceLabel)
+ const hasVoice = Boolean(voiceUrl || voiceLabel)
const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0]
@@ -72,8 +74,8 @@ export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUplo
.finally(() => setUploading(false))
}
- // 打开音色绑定:确保资产存在并拉取最新 params
- async function openVoiceBind() {
+ // 一键 AI 生成音色并绑定到角色节点
+ async function handleGenerateVoice() {
if (voiceLoading) return
setVoiceLoading(true)
try {
@@ -81,10 +83,10 @@ export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUplo
const list = await dramaApi.listAssets(projectId)
const asset = list.find((a) => a.id === assetId)
if (!asset) throw new Error('角色资产不存在')
- setVoiceAsset(asset)
- setVoiceOpen(true)
+ const { character } = await generateAndBindCharacterVoice(projectId, asset)
+ syncNodeFromAsset(nodeId, character)
} catch (err) {
- setErrorMessage(err instanceof Error ? err.message : '打开音色绑定失败')
+ setErrorMessage(err instanceof Error ? err.message : '音色生成失败')
} finally {
setVoiceLoading(false)
}
@@ -119,20 +121,30 @@ export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUplo
从资产库选择
</button>
{isCharacter ? (
- <button
- type="button"
- className={`fc-toolbar-chip${hasVoice ? ' is-active' : ''}`}
- disabled={uploading || voiceLoading}
- onClick={() => void openVoiceBind()}
- title={hasVoice ? `已绑定:${voiceLabel}` : '为角色绑定 Seedance 参考音色'}
- >
- {voiceLoading ? (
- <Loader2 size={14} className="fc-spin" />
- ) : (
- <AudioLines size={14} strokeWidth={1.8} />
- )}
- {voiceLoading ? '加载中…' : hasVoice ? '更换音色' : '绑定音色'}
- </button>
+ hasVoice && voiceUrl ? (
+ <CharacterVoicePreviewButton
+ url={voiceUrl}
+ label={voiceLabel || undefined}
+ variant="chip"
+ className="is-active"
+ onError={setErrorMessage}
+ />
+ ) : (
+ <button
+ type="button"
+ className="fc-toolbar-chip"
+ disabled={uploading || voiceLoading}
+ onClick={() => void handleGenerateVoice()}
+ title="按角色设定 AI 生成音色"
+ >
+ {voiceLoading ? (
+ <Loader2 size={14} className="fc-spin" />
+ ) : (
+ <AudioLines size={14} strokeWidth={1.8} />
+ )}
+ {voiceLoading ? '生成中…' : '生成音色'}
+ </button>
+ )
) : null}
</div>
@@ -148,23 +160,6 @@ export function CanvasNodeUploadBar({ nodeId, kind, voiceLabel }: CanvasNodeUplo
await applyLibraryMediaToNode(nodeId, source)
}}
/>
-
- {voiceAsset ? (
- <CharacterVoiceBindModal
- asset={voiceAsset}
- projectId={projectId}
- open={voiceOpen}
- onClose={() => {
- setVoiceOpen(false)
- setVoiceAsset(null)
- }}
- onBound={(updated) => {
- syncNodeFromAsset(nodeId, updated)
- setVoiceAsset(updated)
- }}
- onError={setErrorMessage}
- />
- ) : null}
</>
)
}
diff --git a/frontend/src/pages/drama/drama.css b/frontend/src/pages/drama/drama.css
index 3c40a77..06d989c 100644
--- a/frontend/src/pages/drama/drama.css
+++ b/frontend/src/pages/drama/drama.css
@@ -14,59 +14,139 @@
}
.drama-agent-page {
- max-width: 920px;
+ max-width: 960px;
}
.drama-agent-hero {
- text-align: center;
- padding: 28px 0 8px;
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ margin-bottom: 14px;
}
-.drama-agent-hero-row {
+.drama-agent-hero-main {
display: flex;
- flex-wrap: wrap;
- align-items: center;
- justify-content: center;
- gap: 16px;
+ align-items: flex-start;
+ gap: 14px;
+}
+
+.drama-agent-hero-icon {
+ width: 44px;
+ height: 44px;
+ border-radius: 14px;
+ background: linear-gradient(145deg, #f4fce8 0%, #e8f9c8 100%);
+ color: #3d5c1f;
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+ border: 1px solid rgba(190, 242, 100, 0.45);
}
.drama-agent-hero h1 {
+ margin: 0 0 6px;
+ font-size: clamp(1.75rem, 3.5vw, 2.25rem);
+ font-weight: 700;
+ letter-spacing: -0.02em;
+ color: var(--drama-ink);
+}
+
+.drama-agent-hero-sub {
margin: 0;
- font-size: clamp(2rem, 4vw, 2.75rem);
+ font-size: 14px;
+ color: var(--drama-muted);
+ line-height: 1.5;
+ max-width: 36rem;
+}
+
+.drama-agent-hero-sub strong {
+ color: var(--drama-ink);
font-weight: 600;
- letter-spacing: 0.04em;
+}
+
+.drama-agent-hero-actions {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex-shrink: 0;
+}
+
+.drama-agent-assets-link {
+ gap: 8px;
+}
+
+.drama-agent-tips {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 18px;
+ padding: 10px 14px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.72);
+ border: 1px solid var(--drama-line);
+ font-size: 13px;
+ color: var(--drama-muted);
+ line-height: 1.45;
+}
+
+.drama-agent-tips strong {
color: var(--drama-ink);
+ font-weight: 600;
}
.drama-agent-panel {
background: var(--drama-card);
border: 1px solid var(--drama-line);
- border-radius: var(--drama-radius);
+ border-radius: 18px;
overflow: hidden;
- margin: 20px 0 28px;
- box-shadow: 0 1px 0 rgba(15, 23, 42, 0.04);
+ margin-bottom: 28px;
+ box-shadow:
+ 0 1px 0 rgba(15, 23, 42, 0.04),
+ 0 12px 32px rgba(15, 23, 42, 0.04);
+}
+
+.drama-agent-panel-head {
+ padding: 14px 16px 0;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.04);
}
.drama-agent-tabs {
- display: flex;
- background: #e8e8ec;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ padding: 4px;
+ border-radius: 999px;
+ background: #f1f5f9;
}
.drama-agent-tabs button {
- flex: 1;
- height: 42px;
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ height: 36px;
+ padding: 0 14px;
border: none;
+ border-radius: 999px;
background: transparent;
font: inherit;
+ font-size: 13px;
font-weight: 600;
color: var(--drama-muted);
cursor: pointer;
+ transition:
+ background 0.15s ease,
+ color 0.15s ease,
+ box-shadow 0.15s ease;
}
.drama-agent-tabs button.active {
- background: var(--drama-card);
+ background: #fff;
+ color: var(--drama-ink);
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.08);
+}
+
+.drama-agent-tabs button:not(:disabled):hover {
color: var(--drama-ink);
- border-radius: var(--drama-radius) var(--drama-radius) 0 0;
}
.drama-agent-tabs button:disabled {
@@ -75,27 +155,59 @@
}
.drama-agent-ai {
- padding: 16px;
+ padding: 18px 18px 16px;
display: flex;
flex-direction: column;
gap: 12px;
}
+.drama-agent-ai-label {
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--drama-ink);
+}
+
+.drama-agent-ai-field {
+ position: relative;
+}
+
.drama-agent-ai textarea {
width: 100%;
box-sizing: border-box;
- min-height: 144px;
+ min-height: 156px;
border: 1px solid var(--drama-line);
- border-radius: 12px;
- padding: 12px 14px;
+ border-radius: 14px;
+ padding: 14px 16px 32px;
font: inherit;
+ font-size: 15px;
+ line-height: 1.55;
resize: vertical;
- background: #fff;
+ background: #fafafa;
+ transition:
+ border-color 0.15s ease,
+ background 0.15s ease,
+ box-shadow 0.15s ease;
}
.drama-agent-ai textarea:focus {
- outline: 2px solid color-mix(in srgb, var(--drama-lime) 55%, transparent);
- border-color: var(--drama-lime);
+ outline: none;
+ background: #fff;
+ border-color: color-mix(in srgb, var(--drama-lime) 55%, #cbd5e1);
+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--drama-lime) 28%, transparent);
+}
+
+.drama-agent-char-count {
+ position: absolute;
+ right: 12px;
+ bottom: 10px;
+ font-size: 12px;
+ color: #94a3b8;
+ pointer-events: none;
+}
+
+.drama-agent-char-count.is-ok {
+ color: #3d5c1f;
+ font-weight: 600;
}
.drama-agent-ai-footer {
@@ -104,6 +216,7 @@
align-items: center;
justify-content: space-between;
gap: 12px;
+ padding-top: 4px;
}
.drama-agent-ai-options {
@@ -112,6 +225,17 @@
align-items: center;
gap: 0;
min-width: 0;
+ padding: 4px 6px;
+ border-radius: 12px;
+ background: #f8fafc;
+ border: 1px solid var(--drama-line);
+}
+
+.drama-agent-generate-btn {
+ gap: 8px;
+ min-width: 148px;
+ height: 40px;
+ font-size: 14px;
}
.drama-agent-opt-trigger {
@@ -355,74 +479,180 @@
filter: brightness(0.97);
}
+.drama-btn-ghost {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ height: 36px;
+ padding: 0 16px;
+ border: 1px solid var(--drama-line);
+ border-radius: 999px;
+ background: transparent;
+ color: var(--drama-ink);
+ font: inherit;
+ font-weight: 600;
+ cursor: pointer;
+}
+
+.drama-btn-ghost:disabled {
+ color: #9ca3af;
+ cursor: not-allowed;
+}
+
+.drama-btn-ghost:not(:disabled):hover {
+ background: rgba(0, 0, 0, 0.04);
+}
+
.drama-agent-error {
+ margin-bottom: 16px;
text-align: center;
}
-.drama-project-section h2 {
- margin: 0 0 14px;
- font-size: 18px;
+.drama-project-section {
+ margin-top: 8px;
+}
+
+.drama-project-section-head {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: flex-end;
+ justify-content: space-between;
+ gap: 8px 16px;
+ margin-bottom: 16px;
+}
+
+.drama-project-section-title {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.drama-project-section-title h2 {
+ margin: 0;
+ font-size: 20px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+}
+
+.drama-project-section-count {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ min-width: 22px;
+ height: 22px;
+ padding: 0 7px;
+ border-radius: 999px;
+ background: #f1f5f9;
+ color: var(--drama-muted);
+ font-size: 12px;
+ font-weight: 600;
+}
+
+.drama-project-section-sub {
+ margin: 0;
+ font-size: 13px;
+ color: var(--drama-muted);
+}
+
+.drama-project-section-sub strong {
+ color: var(--drama-ink);
+ font-weight: 600;
}
.drama-project-empty {
- padding: 28px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 56px 24px;
+ border-radius: var(--drama-radius);
+ background: var(--drama-card);
+ border: 1px dashed var(--drama-line);
+ color: var(--drama-muted);
text-align: center;
- border-radius: 16px;
- background: #fff;
- border: 1px solid var(--drama-line);
}
-.drama-project-grid {
- display: grid;
- grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
- gap: 14px;
+.drama-project-empty p {
+ margin: 0;
}
-.drama-project-card {
+.drama-project-list {
display: flex;
flex-direction: column;
- border: 1px solid rgba(0, 0, 0, 0.05);
- border-radius: 16px;
+ gap: 10px;
+}
+
+.drama-project-row {
+ display: grid;
+ grid-template-columns: 88px 1fr auto;
+ gap: 14px;
+ align-items: center;
+ padding: 12px 14px 12px 12px;
background: var(--drama-card);
- overflow: hidden;
- box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
- transition: transform 0.15s ease, box-shadow 0.15s ease;
+ border-radius: 16px;
+ border: 1px solid var(--drama-line);
+ transition:
+ border-color 0.18s ease,
+ box-shadow 0.18s ease,
+ transform 0.18s ease;
+}
+
+.drama-project-row:hover {
+ border-color: rgba(0, 0, 0, 0.1);
+ box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06);
}
-.drama-project-card:hover {
- transform: translateY(-2px);
- box-shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
+.drama-project-row.is-selected {
+ border-color: rgba(15, 23, 42, 0.85);
+ box-shadow: 0 0 0 1px rgba(15, 23, 42, 0.85);
}
-.drama-project-card.is-selected {
- box-shadow: 0 0 0 2px rgba(15, 23, 42, 0.85);
+.drama-project-row-skeleton {
+ min-height: 88px;
+ background: linear-gradient(90deg, #f1f5f9 0%, #e8edf3 50%, #f1f5f9 100%);
+ background-size: 200% 100%;
+ animation: drama-ep-skeleton 1.2s ease-in-out infinite;
+ border-color: transparent;
}
-.drama-project-card-cover {
+.drama-project-row-poster {
position: relative;
- aspect-ratio: 16 / 10;
+ width: 88px;
+ height: 64px;
border: none;
padding: 0;
- background: #ececef;
- display: grid;
- place-items: center;
+ border-radius: 12px;
+ overflow: hidden;
cursor: pointer;
font: inherit;
color: inherit;
+ flex-shrink: 0;
}
-.drama-project-card-clapper {
- color: #cbd5e1;
+.drama-project-row-poster-fallback {
+ width: 100%;
+ height: 100%;
+ display: grid;
+ place-items: center;
+ background: linear-gradient(145deg, #eef2f7 0%, #e2e8f0 100%);
}
-.drama-project-card:hover .drama-project-card-clapper {
- color: #94a3b8;
+.drama-project-row-poster-vertical {
+ writing-mode: vertical-rl;
+ text-orientation: mixed;
+ font-size: 13px;
+ font-weight: 600;
+ letter-spacing: 0.08em;
+ color: #64748b;
+ max-height: 52px;
+ overflow: hidden;
}
-.drama-project-card-check {
+.drama-project-row-check {
position: absolute;
- top: 12px;
- left: 12px;
+ top: 6px;
+ left: 6px;
z-index: 2;
display: flex;
align-items: center;
@@ -436,43 +666,35 @@
transition: opacity 0.15s ease;
}
-.drama-project-card:hover .drama-project-card-check,
-.drama-project-card-check.is-visible {
+.drama-project-row:hover .drama-project-row-check,
+.drama-project-row-check.is-visible {
opacity: 1;
}
-.drama-project-card-check input {
+.drama-project-row-check input {
width: 14px;
height: 14px;
accent-color: #111;
cursor: pointer;
}
-.drama-project-card-eps {
+.drama-project-row-ep-badge {
position: absolute;
- right: 12px;
- bottom: 12px;
- padding: 2px 8px;
+ right: 6px;
+ bottom: 6px;
+ padding: 2px 7px;
border-radius: 6px;
- background: rgba(0, 0, 0, 0.45);
+ background: rgba(0, 0, 0, 0.5);
color: #fff;
- font-size: 12px;
+ font-size: 11px;
backdrop-filter: blur(4px);
}
-.drama-project-card-body {
- display: flex;
- align-items: flex-start;
- gap: 4px;
- padding: 14px 12px 14px 16px;
-}
-
-.drama-project-card-meta {
- flex: 1;
+.drama-project-row-body {
min-width: 0;
display: flex;
flex-direction: column;
- gap: 4px;
+ gap: 6px;
border: none;
background: transparent;
padding: 0;
@@ -482,76 +704,106 @@
color: inherit;
}
-.drama-project-card-meta strong {
- font-size: 14px;
+.drama-project-row-title {
+ font-size: 15px;
font-weight: 600;
+ line-height: 1.35;
+ color: var(--drama-ink);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
-.drama-project-card-meta span {
+.drama-project-row-meta {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px 12px;
font-size: 12px;
- color: #94a3b8;
+ color: var(--drama-muted);
}
-.drama-project-card-more {
- position: relative;
- flex-shrink: 0;
+.drama-project-row-meta > span:first-child {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
}
-.drama-project-card-more summary {
- list-style: none;
- display: grid;
- place-items: center;
- width: 28px;
- height: 28px;
- border-radius: 8px;
+.drama-project-row-tag {
+ padding: 2px 8px;
+ border-radius: 999px;
+ background: #f1f5f9;
+ color: #64748b;
+ font-size: 11px;
+ font-weight: 600;
+}
+
+.drama-project-row-tag.is-script {
+ background: #f4fce8;
+ color: #3d5c1f;
+}
+
+.drama-project-row-time {
color: #94a3b8;
+}
+
+.drama-project-row-more {
+ position: relative;
+ flex-shrink: 0;
+}
+
+.drama-project-row-more summary {
+ display: grid;
+ place-items: center;
+ width: 32px;
+ height: 32px;
+ border-radius: 10px;
cursor: pointer;
+ color: var(--drama-muted);
+ list-style: none;
}
-.drama-project-card-more summary::-webkit-details-marker {
+.drama-project-row-more summary::-webkit-details-marker {
display: none;
}
-.drama-project-card-more summary:hover {
- background: #f8fafc;
- color: #475569;
+.drama-project-row-more summary:hover {
+ background: #f1f5f9;
+ color: var(--drama-ink);
}
-.drama-project-card-menu {
+.drama-project-row-menu {
position: absolute;
right: 0;
- bottom: calc(100% + 4px);
+ top: calc(100% + 4px);
z-index: 5;
- min-width: 110px;
+ min-width: 120px;
padding: 6px;
- border: 1px solid var(--drama-line);
border-radius: 12px;
background: #fff;
- box-shadow: 0 12px 28px rgba(15, 23, 42, 0.12);
+ border: 1px solid var(--drama-line);
+ box-shadow: 0 12px 32px rgba(15, 23, 42, 0.12);
}
-.drama-project-card-menu button {
+.drama-project-row-menu button {
display: block;
width: 100%;
- border: none;
- background: transparent;
padding: 8px 10px;
+ border: none;
border-radius: 8px;
- text-align: left;
+ background: transparent;
font: inherit;
font-size: 13px;
- color: #334155;
+ text-align: left;
cursor: pointer;
+ color: var(--drama-ink);
}
-.drama-project-card-menu button:hover {
+.drama-project-row-menu button:hover {
background: #f8fafc;
}
-.drama-project-card-menu button.is-danger {
+.drama-project-row-menu button.is-danger {
color: #dc2626;
}
@@ -1340,8 +1592,9 @@
}
.drama-step-bar button.active .drama-step-num {
- background: #111;
- color: #fff;
+ background: var(--drama-lime);
+ color: #111;
+ box-shadow: 0 0 0 2px rgba(182, 255, 0, 0.35);
}
.drama-step-bar button.done .drama-step-num {
@@ -1365,6 +1618,11 @@
font: inherit;
font-weight: 600;
cursor: pointer;
+ transition: filter 0.15s ease, background 0.15s ease;
+}
+
+.drama-next-btn:not(:disabled):hover {
+ filter: brightness(1.05);
}
.drama-next-btn:disabled {
@@ -1373,6 +1631,86 @@
cursor: not-allowed;
}
+/* Shared step section headers */
+.drama-step-hero-main,
+.drama-episodes-hero-main {
+ display: flex;
+ align-items: flex-start;
+ gap: 14px;
+}
+
+.drama-step-hero-icon,
+.drama-episodes-hero-icon {
+ width: 44px;
+ height: 44px;
+ border-radius: 14px;
+ background: linear-gradient(145deg, #f4fce8 0%, #e8f9c8 100%);
+ color: #3d5c1f;
+ display: grid;
+ place-items: center;
+ flex-shrink: 0;
+ border: 1px solid rgba(190, 242, 100, 0.45);
+}
+
+.drama-step-hero-sub,
+.drama-episodes-hero-sub {
+ margin: 0;
+ font-size: 14px;
+ color: var(--drama-muted);
+ line-height: 1.5;
+}
+
+.drama-step-hero-sub strong,
+.drama-episodes-hero-sub strong {
+ color: var(--drama-ink);
+ font-weight: 600;
+}
+
+.drama-outline-hero,
+.drama-assets-hero,
+.drama-episodes-hero {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 16px;
+ margin-bottom: 14px;
+}
+
+.drama-outline-hero h2,
+.drama-assets-hero h2,
+.drama-episodes-hero h2 {
+ margin: 0 0 6px;
+ font-size: 26px;
+ font-weight: 700;
+ letter-spacing: -0.02em;
+}
+
+.drama-outline-style {
+ flex-shrink: 0;
+ align-self: flex-start;
+}
+
+.drama-assets-tips,
+.drama-episodes-tips {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ margin-bottom: 18px;
+ padding: 10px 14px;
+ border-radius: 12px;
+ background: rgba(255, 255, 255, 0.72);
+ border: 1px solid var(--drama-line);
+ font-size: 13px;
+ color: var(--drama-muted);
+ line-height: 1.45;
+}
+
+.drama-assets-tips strong,
+.drama-episodes-tips strong {
+ color: var(--drama-ink);
+ font-weight: 600;
+}
+
.drama-workspace-banner {
max-width: 920px;
margin: 12px auto 0;
@@ -1455,28 +1793,17 @@
flex: 1;
min-width: 0;
max-width: 920px;
- padding: 24px 12px 48px;
-}
-
-.drama-outline-toolbar {
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 12px;
- margin-bottom: 12px;
-}
-
-.drama-outline-toolbar h2 {
- margin: 0;
- font-size: 15px;
- font-weight: 600;
+ padding: 28px 12px 48px;
}
.drama-accordions {
background: var(--drama-card);
- border-radius: var(--drama-radius) var(--drama-radius) 0 0;
+ border-radius: 18px;
+ border: 1px solid var(--drama-line);
overflow: hidden;
- box-shadow: 0 1px 0 rgba(15, 23, 42, 0.04);
+ box-shadow:
+ 0 1px 0 rgba(15, 23, 42, 0.04),
+ 0 8px 24px rgba(15, 23, 42, 0.04);
}
.drama-accordion {
@@ -1525,6 +1852,11 @@
background: #0f172a;
color: #fff;
cursor: pointer;
+ transition: filter 0.15s ease;
+}
+
+.drama-regen-btn:not(:disabled):hover {
+ filter: brightness(1.08);
}
.drama-regen-btn:disabled {
@@ -1649,9 +1981,9 @@
/* Assets / Episodes steps */
.drama-assets-step,
.drama-episodes-step {
- max-width: 920px;
+ max-width: 1080px;
margin: 0 auto;
- padding: 28px 16px 64px;
+ padding: 28px 20px 72px;
}
.drama-assets-toolbar {
@@ -1660,845 +1992,1978 @@
align-items: center;
justify-content: space-between;
gap: 12px;
- margin-bottom: 8px;
+ margin-bottom: 12px;
}
-.drama-episodes-head {
- margin-bottom: 20px;
+.drama-episodes-hero-actions {
display: flex;
- align-items: flex-start;
- justify-content: space-between;
- gap: 12px;
+ align-items: center;
+ gap: 10px;
+ flex-shrink: 0;
}
-.drama-episodes-head h2 {
- margin: 0 0 4px;
- font-size: 26px;
+.drama-episodes-reseed-btn {
+ gap: 8px;
}
-.drama-episode-cards {
+.drama-episodes-empty {
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 12px;
+ padding: 56px 24px;
+ border-radius: var(--drama-radius);
+ background: var(--drama-card);
+ border: 1px dashed var(--drama-line);
+ color: var(--drama-muted);
+ text-align: center;
+}
+
+.drama-episode-grid {
display: grid;
- grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
- gap: 14px;
+ grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
+ gap: 16px;
}
-.drama-episode-card {
- display: flex;
- align-items: center;
+.drama-ep-card {
+ display: grid;
+ grid-template-columns: 88px 1fr auto;
gap: 14px;
+ align-items: center;
+ padding: 12px 14px 12px 12px;
background: var(--drama-card);
- border-radius: var(--drama-radius);
- padding: 14px;
+ border-radius: 16px;
border: 1px solid var(--drama-line);
+ transition:
+ border-color 0.18s ease,
+ box-shadow 0.18s ease,
+ transform 0.18s ease;
}
-.drama-episode-card-thumb {
- width: 72px;
- height: 72px;
- border-radius: 12px;
- background: #efeff4;
- display: grid;
- place-items: center;
- color: var(--drama-muted);
- flex-shrink: 0;
+.drama-ep-card:hover {
+ border-color: rgba(0, 0, 0, 0.1);
+ box-shadow: 0 10px 28px rgba(15, 23, 42, 0.06);
}
-.drama-episode-card-body {
- flex: 1;
- min-width: 0;
- display: flex;
- flex-direction: column;
- gap: 4px;
+.drama-ep-card.is-planning,
+.drama-ep-card.is-generating {
+ border-color: rgba(190, 242, 100, 0.55);
+ box-shadow: 0 0 0 1px rgba(190, 242, 100, 0.25);
}
-.drama-episode-card-body span {
- font-size: 13px;
- color: var(--drama-muted);
+.drama-ep-card-skeleton {
+ min-height: 108px;
+ background: linear-gradient(90deg, #f3f4f6 0%, #eceff3 50%, #f3f4f6 100%);
+ background-size: 200% 100%;
+ animation: drama-ep-skeleton 1.2s ease-in-out infinite;
}
-/* Episode edit ? manju-style fullscreen workspace */
-.drama-ep-fullscreen {
- --ep-bg: #f5f5f5;
- --ep-panel: #ffffff;
- --ep-muted: #6b7280;
- --ep-ink: #0f172a;
- --ep-line: rgba(0, 0, 0, 0.05);
- --ep-soft: #efeff4;
- height: 100svh;
- display: flex;
- flex-direction: column;
- overflow: hidden;
- background: var(--ep-bg);
- color: var(--ep-ink);
- font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
+@keyframes drama-ep-skeleton {
+ 0% {
+ background-position: 100% 0;
+ }
+ 100% {
+ background-position: -100% 0;
+ }
}
-.drama-ep-center {
- align-items: center;
- justify-content: center;
- color: var(--ep-muted);
- font-size: 14px;
+.drama-ep-card-poster {
+ position: relative;
+ width: 88px;
+ height: 112px;
+ border: none;
+ border-radius: 12px;
+ padding: 0;
+ overflow: hidden;
+ cursor: pointer;
+ background: #e8eaef;
+ flex-shrink: 0;
}
-.drama-ep-header {
- height: 56px;
- flex-shrink: 0;
- display: flex;
- align-items: center;
- justify-content: space-between;
- gap: 16px;
- padding: 0 16px;
- border-bottom: 1px solid var(--ep-line);
- background: rgba(245, 245, 245, 0.95);
- backdrop-filter: blur(8px);
+.drama-ep-card-poster-img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
}
-.drama-ep-header-left {
+.drama-ep-card-poster-fallback {
+ width: 100%;
+ height: 100%;
display: flex;
align-items: center;
- gap: 8px;
- min-width: 0;
+ justify-content: center;
+ background: linear-gradient(165deg, #f8f9fb 0%, #eceff4 55%, #e2e6ee 100%);
}
-.drama-ep-header-left h1 {
- margin: 0;
- font-size: 16px;
+.drama-ep-card-poster-vertical {
+ writing-mode: vertical-rl;
+ text-orientation: mixed;
+ font-size: 13px;
font-weight: 600;
- white-space: nowrap;
+ letter-spacing: 0.12em;
+ color: #64748b;
+ max-height: 88px;
overflow: hidden;
text-overflow: ellipsis;
+ white-space: nowrap;
}
-.drama-ep-header-controls {
- display: flex;
- flex-wrap: wrap;
- align-items: center;
- gap: 8px;
- justify-content: flex-end;
- min-width: 0;
+.drama-ep-card-ep-badge {
+ position: absolute;
+ top: 6px;
+ left: 6px;
+ padding: 2px 7px;
+ border-radius: 999px;
+ font-size: 10px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ background: rgba(15, 23, 42, 0.72);
+ color: #fff;
+ backdrop-filter: blur(4px);
}
-.drama-ep-header-gen-opts {
- margin-top: 0;
+.drama-ep-card-play {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-items: center;
+ background: rgba(15, 23, 42, 0.22);
+ color: #fff;
+ opacity: 0;
+ transition: opacity 0.18s ease;
}
-.drama-ep-header-gen-opts .fc-gen-opt-btn {
- background: #fff;
- box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06);
- color: var(--ep-ink, #111);
- max-width: 180px;
+.drama-ep-card-poster:hover .drama-ep-card-play {
+ opacity: 1;
}
-.drama-ep-header-gen-opts .fc-gen-opt-btn.active {
- background: #f5f3ff;
- color: #6d28d9;
- box-shadow: 0 0 0 1px rgba(124, 58, 237, 0.28);
+.drama-ep-card-busy {
+ position: absolute;
+ inset: auto 6px 6px 6px;
+ height: 3px;
+ border-radius: 999px;
+ background: rgba(255, 255, 255, 0.35);
+ overflow: hidden;
}
-.drama-ep-header-gen-opts .drama-ep-opt-panel {
- left: auto;
- right: 0;
- bottom: auto;
- top: calc(100% + 8px);
+.drama-ep-card-busy::after {
+ content: '';
+ display: block;
+ width: 40%;
+ height: 100%;
+ border-radius: inherit;
+ background: var(--drama-lime);
+ animation: drama-ep-busy 1.1s ease-in-out infinite;
}
-.drama-ep-icon-btn {
- width: 36px;
- height: 36px;
- border: none;
- border-radius: 999px;
- background: transparent;
- color: #475569;
- font-size: 22px;
- line-height: 1;
- cursor: pointer;
+@keyframes drama-ep-busy {
+ 0% {
+ transform: translateX(-120%);
+ }
+ 100% {
+ transform: translateX(280%);
+ }
}
-.drama-ep-icon-btn:hover {
- background: rgba(0, 0, 0, 0.05);
+.drama-ep-card-body {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
}
-.drama-ep-icon-btn.solid {
- background: #fff;
- font-size: 18px;
+.drama-ep-card-title {
+ margin: 0;
+ font-size: 15px;
+ font-weight: 650;
+ line-height: 1.35;
+ color: var(--drama-ink);
+ display: -webkit-box;
+ -webkit-line-clamp: 2;
+ -webkit-box-orient: vertical;
+ overflow: hidden;
}
-.drama-ep-banner {
- padding: 6px 16px;
+.drama-ep-card-meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 8px 12px;
font-size: 12px;
- color: var(--ep-muted);
- border-bottom: 1px solid var(--ep-line);
+ color: var(--drama-muted);
}
-.drama-ep-banner-error {
- color: #dc2626;
+.drama-ep-card-meta-item {
+ display: inline-flex;
+ align-items: center;
+ gap: 5px;
}
-.drama-ep-body {
- flex: 1;
- min-height: 0;
- display: grid;
- grid-template-columns: 300px minmax(0, 1fr) 420px;
+.drama-ep-card-progress {
+ height: 4px;
+ border-radius: 999px;
+ background: #eceff4;
+ overflow: hidden;
}
-.drama-ep-assets {
- display: flex;
- flex-direction: column;
- min-height: 0;
- border-right: 1px solid var(--ep-line);
- background: #f7f7f8;
+.drama-ep-card-progress-bar {
+ height: 100%;
+ border-radius: inherit;
+ background: linear-gradient(90deg, #bef264 0%, #a3e635 100%);
+ transition: width 0.35s ease;
}
-.drama-ep-assets-top {
+.drama-ep-card-actions {
display: flex;
- align-items: center;
- justify-content: space-between;
+ flex-direction: column;
+ align-items: stretch;
gap: 8px;
- padding: 12px;
- border-bottom: 1px solid var(--ep-line);
+ flex-shrink: 0;
}
-.drama-ep-scope {
+.drama-ep-card-ai-btn {
display: inline-flex;
- padding: 2px;
+ align-items: center;
+ justify-content: center;
+ gap: 6px;
+ height: 34px;
+ padding: 0 12px;
+ border: 1px solid var(--drama-line);
border-radius: 999px;
background: #fff;
-}
-
-.drama-ep-scope button {
- border: none;
- background: transparent;
- border-radius: 999px;
- padding: 4px 12px;
+ color: var(--drama-ink);
+ font: inherit;
font-size: 12px;
- color: #64748b;
+ font-weight: 600;
cursor: pointer;
+ transition: background 0.15s ease;
}
-.drama-ep-scope button.active {
- background: #0f172a;
- color: #fff;
+.drama-ep-card-ai-btn:not(:disabled):hover {
+ background: rgba(0, 0, 0, 0.04);
}
-.drama-ep-asset-tabs {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
- padding: 8px 12px;
+.drama-ep-card-ai-btn:disabled {
+ color: #9ca3af;
+ cursor: not-allowed;
}
-.drama-ep-asset-tabs button {
- border: none;
- border-radius: 999px;
- padding: 4px 10px;
- font-size: 12px;
- background: #fff;
- color: #475569;
- cursor: pointer;
+.drama-ep-card-edit-btn {
+ height: 36px;
+ padding: 0 18px;
+ font-size: 13px;
}
-.drama-ep-asset-tabs button.active {
- background: #0f172a;
- color: #fff;
-}
+@media (max-width: 720px) {
+ .drama-agent-hero {
+ flex-direction: column;
+ }
-.drama-ep-asset-grid {
- flex: 1;
- min-height: 0;
- overflow: auto;
- padding: 0 12px 16px;
- display: grid;
- grid-template-columns: 1fr 1fr;
- gap: 8px;
- align-content: start;
-}
+ .drama-agent-hero-actions {
+ width: 100%;
+ }
-.drama-ep-asset-card {
- position: relative;
- border: none;
- border-radius: 12px;
- background: #fff;
- padding: 0;
- overflow: hidden;
- cursor: pointer;
- text-align: left;
- transition: box-shadow 0.15s ease, outline-color 0.15s ease;
-}
+ .drama-agent-assets-link {
+ width: 100%;
+ justify-content: center;
+ }
-.drama-ep-asset-card:hover {
- box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
-}
+ .drama-agent-ai-footer {
+ flex-direction: column;
+ align-items: stretch;
+ }
-.drama-ep-asset-card.is-linked {
- outline: 2px solid var(--drama-lime, #b7f34a);
- outline-offset: -2px;
-}
+ .drama-agent-generate-btn {
+ width: 100%;
+ }
-.drama-ep-asset-linked {
- position: absolute;
- top: 6px;
- right: 6px;
- z-index: 1;
- font-size: 10px;
- line-height: 1;
- padding: 3px 5px;
- border-radius: 999px;
- background: rgba(17, 17, 17, 0.78);
- color: #fff;
-}
+ .drama-project-row {
+ grid-template-columns: 72px 1fr;
+ grid-template-rows: auto auto;
+ }
-.drama-ep-asset-card.scene {
- grid-column: 1 / -1;
-}
+ .drama-project-row-poster {
+ width: 72px;
+ height: 56px;
+ }
-.drama-ep-asset-thumb {
- aspect-ratio: 3 / 4;
- background: var(--ep-soft);
- display: grid;
- place-items: center;
- overflow: hidden;
- color: #cbd5e1;
- font-weight: 700;
-}
+ .drama-project-row-more {
+ grid-column: 2;
+ justify-self: end;
+ }
-.drama-ep-asset-card.scene .drama-ep-asset-thumb {
- aspect-ratio: 4 / 3;
-}
+ .drama-episodes-hero {
+ flex-direction: column;
+ }
-.drama-ep-asset-thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
-}
+ .drama-episodes-hero-actions {
+ width: 100%;
+ }
-.drama-ep-asset-name {
- display: block;
- padding: 8px 6px;
- font-size: 12px;
- color: #475569;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
-}
+ .drama-episodes-reseed-btn {
+ width: 100%;
+ }
-.drama-ep-empty {
- grid-column: 1 / -1;
- margin: 24px 0;
- text-align: center;
- font-size: 12px;
- color: #94a3b8;
- line-height: 1.5;
-}
+ .drama-ep-card {
+ grid-template-columns: 72px 1fr;
+ grid-template-rows: auto auto;
+ }
-.drama-ep-editor {
- min-width: 0;
- min-height: 0;
- display: flex;
- flex-direction: column;
- padding: 20px 24px 16px;
- background: transparent;
+ .drama-ep-card-poster {
+ width: 72px;
+ height: 96px;
+ }
+
+ .drama-ep-card-actions {
+ grid-column: 1 / -1;
+ flex-direction: row;
+ }
+
+ .drama-ep-card-edit-btn,
+ .drama-ep-card-ai-btn {
+ flex: 1;
+ }
}
-.drama-ep-editor-head {
+/* legacy episode card (keep for any stale refs) */
+.drama-episodes-head {
+ margin-bottom: 20px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 12px;
- margin-bottom: 12px;
}
-.drama-ep-editor-head strong {
- display: block;
- font-size: 15px;
+.drama-episodes-head h2 {
+ margin: 0 0 4px;
+ font-size: 26px;
}
-.drama-ep-editor-head p {
- margin: 4px 0 0;
- font-size: 12px;
- color: var(--ep-muted);
+.drama-episode-cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 14px;
}
-.drama-ep-duration {
- display: inline-flex;
+.drama-episode-card {
+ display: flex;
align-items: center;
- gap: 6px;
- font-size: 12px;
- color: var(--ep-muted);
- white-space: nowrap;
-}
-
-.drama-ep-duration input {
+ gap: 14px;
+ background: var(--drama-card);
+ border-radius: var(--drama-radius);
+ padding: 14px;
+ border: 1px solid var(--drama-line);
+}
+
+.drama-episode-card-thumb {
+ width: 72px;
+ height: 72px;
+ border-radius: 12px;
+ background: #efeff4;
+ display: grid;
+ place-items: center;
+ color: var(--drama-muted);
+ flex-shrink: 0;
+}
+
+.drama-episode-card-body {
+ flex: 1;
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+}
+
+.drama-episode-card-body span {
+ font-size: 13px;
+ color: var(--drama-muted);
+}
+
+.drama-episode-card-actions {
+ display: flex;
+ flex-shrink: 0;
+ align-items: center;
+ gap: 8px;
+}
+
+/* Episode edit ? manju-style fullscreen workspace */
+.drama-ep-fullscreen {
+ --ep-bg: #f5f5f5;
+ --ep-panel: #ffffff;
+ --ep-muted: #6b7280;
+ --ep-ink: #0f172a;
+ --ep-line: rgba(0, 0, 0, 0.05);
+ --ep-soft: #efeff4;
+ height: 100svh;
+ display: flex;
+ flex-direction: column;
+ overflow: hidden;
+ background: var(--ep-bg);
+ color: var(--ep-ink);
+ font-family: 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
+}
+
+.drama-ep-center {
+ align-items: center;
+ justify-content: center;
+ color: var(--ep-muted);
+ font-size: 14px;
+}
+
+.drama-ep-header {
+ height: 56px;
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 16px;
+ padding: 0 16px;
+ border-bottom: 1px solid var(--ep-line);
+ background: rgba(245, 245, 245, 0.95);
+ backdrop-filter: blur(8px);
+}
+
+.drama-ep-header-left {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ min-width: 0;
+}
+
+.drama-ep-header-left h1 {
+ margin: 0;
+ font-size: 16px;
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.drama-ep-header-controls {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 8px;
+ justify-content: flex-end;
+ min-width: 0;
+}
+
+.drama-ep-header-gen-all {
+ white-space: nowrap;
+ height: 34px;
+ padding: 0 14px;
+ font-size: 13px;
+}
+
+.drama-ep-header-gen-opts {
+ margin-top: 0;
+}
+
+.drama-ep-header-gen-opts .fc-gen-opt-btn {
+ background: #fff;
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06);
+ color: var(--ep-ink, #111);
+ max-width: 180px;
+}
+
+.drama-ep-header-gen-opts .fc-gen-opt-btn.active {
+ background: #f5f3ff;
+ color: #6d28d9;
+ box-shadow: 0 0 0 1px rgba(124, 58, 237, 0.28);
+}
+
+.drama-ep-header-gen-opts .drama-ep-opt-panel {
+ left: auto;
+ right: 0;
+ bottom: auto;
+ top: calc(100% + 8px);
+}
+
+.drama-ep-header-gen-opts .drama-seedance-help-btn {
+ width: 34px;
+ min-width: 34px;
+ max-width: 34px;
+ padding: 0;
+ justify-content: center;
+ color: #64748b;
+}
+
+.drama-ep-header-gen-opts .drama-seedance-help-btn:hover {
+ color: #6d28d9;
+ background: #f5f3ff;
+}
+
+.seedance-rules-modal .seedance-rules-section {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.seedance-rules-modal .seedance-rules-section h4 {
+ margin: 8px 0 0;
+ font-size: 14px;
+ font-weight: 700;
+ color: var(--drama-ink, #111);
+}
+
+.seedance-rules-modal .seedance-rules-list {
+ margin: 0;
+ padding-left: 1.15rem;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 13px;
+ line-height: 1.55;
+ color: var(--drama-ink, #111);
+}
+
+.seedance-rules-modal .seedance-rules-list code,
+.seedance-rules-modal .seedance-rules-note code {
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 12px;
+ padding: 1px 5px;
+ border-radius: 4px;
+ background: rgba(17, 17, 17, 0.06);
+}
+
+.seedance-rules-modal .seedance-rules-note {
+ margin: 0;
+ font-size: 12px;
+ line-height: 1.55;
+ color: var(--drama-muted, #64748b);
+}
+
+.seedance-rules-modal .seedance-rules-examples {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 10px 12px;
+ border-radius: 10px;
+ background: #f8fafc;
+ border: 1px solid var(--drama-line, #e2e8f0);
+}
+
+.seedance-rules-modal .seedance-rules-examples code {
+ display: block;
+ font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ white-space: pre-wrap;
+ word-break: break-word;
+ color: #334155;
+}
+
+.drama-ep-icon-btn {
+ width: 36px;
+ height: 36px;
+ border: none;
+ border-radius: 999px;
+ background: transparent;
+ color: #475569;
+ font-size: 22px;
+ line-height: 1;
+ cursor: pointer;
+}
+
+.drama-ep-icon-btn:hover {
+ background: rgba(0, 0, 0, 0.05);
+}
+
+.drama-ep-icon-btn.solid {
+ background: #fff;
+ font-size: 18px;
+}
+
+.drama-ep-banner {
+ padding: 6px 16px;
+ font-size: 12px;
+ color: var(--ep-muted);
+ border-bottom: 1px solid var(--ep-line);
+}
+
+.drama-ep-banner-error {
+ color: #dc2626;
+}
+
+.drama-ep-body {
+ flex: 1;
+ min-height: 0;
+ display: grid;
+ grid-template-columns: 300px minmax(0, 1fr) 420px;
+}
+
+.drama-ep-assets {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ border-right: 1px solid var(--ep-line);
+ background: #f7f7f8;
+}
+
+.drama-ep-assets-top {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ padding: 12px;
+ border-bottom: 1px solid var(--ep-line);
+}
+
+.drama-ep-scope {
+ display: inline-flex;
+ padding: 2px;
+ border-radius: 999px;
+ background: #fff;
+}
+
+.drama-ep-scope button {
+ border: none;
+ background: transparent;
+ border-radius: 999px;
+ padding: 4px 12px;
+ font-size: 12px;
+ color: #64748b;
+ cursor: pointer;
+}
+
+.drama-ep-scope button.active {
+ background: #0f172a;
+ color: #fff;
+}
+
+.drama-ep-asset-tabs {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ padding: 8px 12px;
+}
+
+.drama-ep-asset-tabs button {
+ border: none;
+ border-radius: 999px;
+ padding: 4px 10px;
+ font-size: 12px;
+ background: #fff;
+ color: #475569;
+ cursor: pointer;
+}
+
+.drama-ep-asset-tabs button.active {
+ background: #0f172a;
+ color: #fff;
+}
+
+.drama-ep-asset-grid {
+ flex: 1;
+ min-height: 0;
+ overflow: auto;
+ padding: 0 12px 16px;
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 8px;
+ align-content: start;
+ grid-auto-rows: max-content;
+}
+
+.drama-ep-asset-card {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ width: 100%;
+ min-width: 0;
+ border: none;
+ border-radius: 12px;
+ background: #fff;
+ padding: 0;
+ overflow: hidden;
+ cursor: pointer;
+ text-align: left;
+ transition: box-shadow 0.15s ease, outline-color 0.15s ease;
+}
+
+.drama-ep-asset-card:hover {
+ box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
+}
+
+.drama-ep-asset-card.is-linked {
+ outline: 2px solid var(--drama-lime, #b7f34a);
+ outline-offset: -2px;
+}
+
+.drama-ep-asset-linked {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 1;
+ font-size: 10px;
+ line-height: 1;
+ padding: 3px 5px;
+ border-radius: 999px;
+ background: rgba(17, 17, 17, 0.78);
+ color: #fff;
+}
+
+.drama-ep-asset-card.scene {
+ grid-column: 1 / -1;
+}
+
+/* 用 padding 占位保证缩略图高度:button + overflow 下 aspect-ratio 易塌成细条 */
+.drama-ep-asset-thumb {
+ position: relative;
+ width: 100%;
+ height: 0;
+ padding-bottom: 133.333%; /* 3:4 */
+ background: var(--ep-soft);
+ overflow: hidden;
+ color: #cbd5e1;
+ font-weight: 700;
+ flex: none;
+}
+
+.drama-ep-asset-card.scene .drama-ep-asset-thumb {
+ padding-bottom: 75%; /* 4:3 */
+}
+
+.drama-ep-asset-thumb img,
+.drama-ep-asset-thumb > span {
+ position: absolute;
+ inset: 0;
+ width: 100%;
+ height: 100%;
+ display: grid;
+ place-items: center;
+}
+
+.drama-ep-asset-thumb img {
+ object-fit: cover;
+}
+
+.drama-ep-asset-name {
+ display: block;
+ flex: none;
+ padding: 8px 6px;
+ font-size: 12px;
+ color: #475569;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.drama-ep-empty {
+ grid-column: 1 / -1;
+ margin: 24px 0;
+ text-align: center;
+ font-size: 12px;
+ color: #94a3b8;
+ line-height: 1.5;
+}
+
+.drama-ep-editor {
+ min-width: 0;
+ min-height: 0;
+ display: flex;
+ flex-direction: column;
+ padding: 20px 24px 16px;
+ background: transparent;
+}
+
+.drama-ep-editor-head {
+ display: flex;
+ align-items: flex-start;
+ justify-content: space-between;
+ gap: 12px;
+ margin-bottom: 12px;
+}
+
+.drama-ep-editor-head strong {
+ display: block;
+ font-size: 15px;
+}
+
+.drama-ep-editor-head p {
+ margin: 4px 0 0;
+ font-size: 12px;
+ color: var(--ep-muted);
+}
+
+.drama-ep-duration {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 12px;
+ color: var(--ep-muted);
+ white-space: nowrap;
+}
+
+.drama-ep-duration input {
width: 56px;
border: 1px solid #e5e7eb;
border-radius: 8px;
- padding: 4px 8px;
- font: inherit;
+ padding: 4px 8px;
+ font: inherit;
+}
+
+.drama-ep-editor-box {
+ flex: 1;
+ min-height: 0;
+ border-radius: 16px;
+ background: rgba(255, 255, 255, 0.72);
+ border: 1px solid transparent;
+ padding: 16px;
+ box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
+}
+
+.drama-ep-editor-box.editing {
+ background: #fff;
+ border-color: rgba(0, 0, 0, 0.08);
+}
+
+.drama-ep-script-issues {
+ list-style: none;
+ margin: 8px 0 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.drama-ep-script-issue {
+ margin: 0;
+ padding: 8px 12px;
+ border-radius: 10px;
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+.drama-ep-script-issue.is-error {
+ color: #9f1239;
+ background: rgba(244, 63, 94, 0.08);
+ border: 1px solid rgba(244, 63, 94, 0.22);
+}
+
+.drama-ep-script-issue.is-warn {
+ color: #92400e;
+ background: rgba(245, 158, 11, 0.1);
+ border: 1px solid rgba(245, 158, 11, 0.28);
+}
+
+.drama-ep-link-last-frame {
+ display: flex;
+ align-items: flex-start;
+ gap: 8px;
+ margin-top: 4px;
+ font-size: 12px;
+ color: #0f172a;
+ cursor: pointer;
+}
+
+.drama-ep-link-last-frame input {
+ margin-top: 2px;
+}
+
+.drama-ep-link-last-frame span {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.drama-ep-link-last-frame em {
+ font-style: normal;
+ font-size: 11px;
+ color: #64748b;
+}
+
+.drama-ep-continuity-hint {
+ margin: 8px 0 0;
+ padding: 8px 12px;
+ border-radius: 10px;
+ font-size: 12px;
+ line-height: 1.4;
+}
+
+.drama-ep-continuity-hint.is-ready {
+ color: #065f46;
+ background: rgba(16, 185, 129, 0.1);
+ border: 1px solid rgba(16, 185, 129, 0.25);
+}
+
+.drama-ep-continuity-hint.is-wait {
+ color: #64748b;
+ background: #f8fafc;
+ border: 1px solid #e2e8f0;
+}
+
+.drama-storyboard-import {
+ display: flex;
+ flex-direction: column;
+ gap: 14px;
+}
+
+.drama-storyboard-import-lede {
+ margin: 0;
+ font-size: 13px;
+ line-height: 1.5;
+ color: #475569;
+}
+
+.drama-storyboard-import-file {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: 12px;
+ color: #0f172a;
+}
+
+.drama-storyboard-import-row {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 12px;
+ font-size: 12px;
+}
+
+.drama-storyboard-import-row label {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.drama-storyboard-import-row input {
+ width: 64px;
+ height: 30px;
+ border: 1px solid #e2e8f0;
+ border-radius: 8px;
+ padding: 0 8px;
+ font: inherit;
+}
+
+.drama-storyboard-import-row em {
+ font-style: normal;
+ color: #64748b;
+}
+
+.drama-storyboard-import-rhythm strong {
+ display: block;
+ margin-bottom: 8px;
+ font-size: 12px;
+}
+
+.drama-storyboard-import-rhythm-chips {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.drama-storyboard-import-rhythm-chips button {
+ height: 28px;
+ padding: 0 10px;
+ border: 1px solid #e2e8f0;
+ border-radius: 999px;
+ background: #fff;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.drama-storyboard-import-rhythm-chips button.is-active {
+ border-color: #111;
+ background: #0f172a;
+ color: #fff;
+}
+
+.drama-storyboard-import-rhythm p,
+.drama-storyboard-import-note,
+.drama-storyboard-import-warn {
+ margin: 8px 0 0;
+ font-size: 12px;
+ line-height: 1.45;
+ color: #64748b;
+}
+
+.drama-storyboard-import-warn {
+ color: #9a3412;
+}
+
+.drama-storyboard-import-error {
+ margin: 0;
+ font-size: 12px;
+ color: #be123c;
+}
+
+.drama-ep-ref-strip {
+ display: flex;
+ gap: 8px;
+ overflow-x: auto;
+ padding: 0 2px 10px;
+}
+
+.drama-ep-ref-strip.is-empty {
+ min-height: 28px;
+ align-items: center;
+}
+
+.drama-ep-ref-strip-hint {
+ font-size: 12px;
+ color: var(--drama-muted, #888);
+}
+
+.drama-ep-ref-chip {
+ display: inline-flex;
+ flex-direction: column;
+ align-items: stretch;
+ width: 64px;
+ flex-shrink: 0;
+ padding: 0;
+ border: 1px solid rgba(0, 0, 0, 0.08);
+ border-radius: 12px;
+ background: #fff;
+ overflow: hidden;
+ cursor: pointer;
+ text-align: left;
+}
+
+.drama-ep-ref-chip:hover {
+ border-color: #111;
+}
+
+.drama-ep-ref-chip img,
+.drama-ep-ref-chip-fallback {
+ width: 100%;
+ aspect-ratio: 1;
+ object-fit: cover;
+ background: #efeff4;
+}
+
+.drama-ep-ref-chip-fallback {
+ display: grid;
+ place-items: center;
+ font-size: 16px;
+ color: #888;
+}
+
+.drama-ep-ref-chip em {
+ display: block;
+ margin: 0;
+ padding: 4px 6px;
+ font-style: normal;
+ font-size: 11px;
+ line-height: 1.2;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ color: #333;
+}
+
+.drama-ep-ref-chip.is-character {
+ position: relative;
+}
+
+.drama-ep-ref-voice-badge {
+ position: absolute;
+ top: 4px;
+ right: 4px;
+ z-index: 1;
+ font-size: 9px;
+ line-height: 1;
+ padding: 2px 4px;
+ border-radius: 999px;
+ background: rgba(185, 28, 28, 0.88);
+ color: #fff;
+}
+
+.drama-ep-ref-voice-badge.bound {
+ background: rgba(17, 17, 17, 0.82);
+ color: #b7f34a;
+}
+
+.drama-ep-voice-row {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 0 2px 12px;
+ border-bottom: 1px solid rgba(0, 0, 0, 0.06);
+ margin-bottom: 10px;
+}
+
+.drama-ep-voice-row-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+
+.drama-ep-voice-row-label {
+ font-size: 12px;
+ font-weight: 600;
+ color: var(--drama-muted, #888);
+}
+
+.drama-ep-voice-row-stat {
+ font-size: 11px;
+ color: var(--drama-muted, #888);
+}
+
+.drama-ep-voice-row-list {
+ display: flex;
+ gap: 10px;
+ overflow-x: auto;
+ padding-bottom: 2px;
+}
+
+.drama-ep-voice-card {
+ flex: 0 0 200px;
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ padding: 10px;
+ border: 1px solid rgba(0, 0, 0, 0.08);
+ border-radius: 12px;
+ background: #fafafa;
+}
+
+.drama-ep-voice-card.is-bound {
+ border-color: #86efac;
+ background: #f0fdf4;
+}
+
+.drama-ep-voice-card.is-unbound {
+ border-color: #fcd34d;
+ background: #fffbeb;
+}
+
+.drama-ep-voice-card-head {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+}
+
+.drama-ep-voice-avatar {
+ width: 36px;
+ height: 36px;
+ border-radius: 999px;
+ overflow: hidden;
+ flex-shrink: 0;
+ background: #efeff4;
+}
+
+.drama-ep-voice-avatar img,
+.drama-ep-voice-avatar span {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: grid;
+ place-items: center;
+ font-size: 14px;
+ font-weight: 600;
+}
+
+.drama-ep-voice-meta {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ min-width: 0;
+}
+
+.drama-ep-voice-meta strong {
+ font-size: 13px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.drama-ep-voice-meta span {
+ font-size: 11px;
+}
+
+.drama-ep-voice-meta span.is-bound {
+ color: #166534;
+}
+
+.drama-ep-voice-meta span.is-unbound {
+ color: #b45309;
+}
+
+.drama-ep-voice-audio {
+ width: 100%;
+ height: 28px;
+}
+
+.drama-ep-voice-actions {
+ display: flex;
+ gap: 6px;
+}
+
+.drama-ep-voice-btn {
+ flex: 1;
+ font-size: 11px !important;
+ padding: 4px 8px !important;
+ min-height: 28px;
+}
+
+.drama-ep-voice-btn-full {
+ width: 100%;
+}
+
+.drama-ep-asset-card-wrap {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ min-width: 0;
+}
+
+.drama-ep-asset-voice {
+ position: absolute;
+ bottom: 28px;
+ left: 6px;
+ z-index: 1;
+ font-size: 9px;
+ line-height: 1;
+ padding: 2px 5px;
+ border-radius: 999px;
+ background: rgba(17, 17, 17, 0.78);
+ color: #b7f34a;
+}
+
+.drama-ep-asset-voice-btn {
+ border: none;
+ border-radius: 8px;
+ background: #111;
+ color: #fff;
+ font-size: 10px;
+ padding: 5px 8px;
+ cursor: pointer;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.drama-ep-asset-voice-btn.is-bound {
+ background: #f0fdf4;
+ color: #166534;
+ border: 1px solid #86efac;
+}
+
+.drama-ep-asset-voice-btn:hover {
+ background: #333;
+}
+
+.drama-ep-asset-voice-btn.is-bound:hover {
+ background: #dcfce7;
+ color: #14532d;
+}
+
+.drama-voice-preview-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+}
+
+.drama-ep-content-view {
+ min-height: 280px;
+ height: 100%;
+ overflow: auto;
+ font-size: 14px;
+ line-height: 1.7;
+ color: var(--ep-ink, #222);
+ word-break: break-word;
+}
+
+.drama-ep-content-empty {
+ margin: 0;
+ padding: 12px 0;
+ color: var(--drama-muted, #888);
+ font-size: 13px;
+}
+
+.drama-ep-prompt-editor {
+ min-height: 280px;
+ height: 100%;
+ overflow: auto;
+ outline: none;
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-size: 14px;
+ line-height: 1.7;
+ color: var(--ep-ink, #222);
+}
+
+.drama-ep-prompt-editor.is-editing:empty::before {
+ content: attr(data-placeholder);
+ color: #94a3b8;
+ pointer-events: none;
+}
+
+.drama-ep-editor-chip {
+ user-select: none;
+ vertical-align: middle;
+ margin: 0 2px;
+}
+
+.drama-ep-mention-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ max-width: 100%;
+ margin: 0 2px;
+ padding: 2px 8px 2px 2px;
+ border: 1px solid #e5e7eb;
+ border-radius: 999px;
+ background: #fff;
+ vertical-align: middle;
+ cursor: pointer;
+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
+}
+
+.drama-ep-mention-chip:hover {
+ border-color: #111;
+}
+
+.drama-ep-mention-chip img,
+.drama-ep-mention-chip-thumb,
+.drama-ep-mention-chip-fallback {
+ width: 22px;
+ height: 22px;
+ border-radius: 7px;
+ object-fit: cover;
+ background: #efeff4;
+ flex-shrink: 0;
+}
+
+.drama-ep-mention-chip-thumb {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ overflow: hidden;
+}
+
+.drama-ep-mention-chip-thumb img {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
}
-.drama-ep-editor-box {
- flex: 1;
- min-height: 0;
- border-radius: 16px;
- background: rgba(255, 255, 255, 0.72);
- border: 1px solid transparent;
- padding: 16px;
- box-shadow: 0 1px 2px rgba(15, 23, 42, 0.04);
+.drama-ep-mention-chip-thumb.is-fallback,
+.drama-ep-mention-chip-fallback {
+ display: grid;
+ place-items: center;
+ font-size: 11px;
+ color: #888;
}
-.drama-ep-editor-box.editing {
- background: #fff;
- border-color: rgba(0, 0, 0, 0.08);
+.drama-ep-mention-chip-label {
+ font-size: 13px;
+ line-height: 1.2;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 160px;
}
-.drama-ep-ref-strip {
- display: flex;
- gap: 8px;
- overflow-x: auto;
- padding: 0 2px 10px;
+.drama-ep-duration-chip {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ padding: 2px 8px;
+ border: 1px solid #e2e8f0;
+ border-radius: 999px;
+ background: #efeff4;
+ color: #334155;
+ font-size: 13px;
+ font-weight: 600;
+ line-height: 20px;
+ vertical-align: middle;
}
-.drama-ep-ref-strip.is-empty {
- min-height: 28px;
+.drama-ep-chip-icon {
+ display: inline-flex;
+ width: 14px;
+ height: 14px;
align-items: center;
+ justify-content: center;
+ color: #64748b;
}
-.drama-ep-ref-strip-hint {
- font-size: 12px;
- color: var(--drama-muted, #888);
+.drama-ep-chip-icon svg {
+ display: block;
}
-.drama-ep-ref-chip {
- display: inline-flex;
+.drama-ep-editor-box textarea {
+ display: none;
+}
+
+.drama-ep-mention-pop {
+ position: fixed;
+ z-index: 120;
+ width: 320px;
+ max-height: 340px;
+ display: flex;
flex-direction: column;
- align-items: stretch;
- width: 64px;
- flex-shrink: 0;
- padding: 0;
- border: 1px solid rgba(0, 0, 0, 0.08);
- border-radius: 12px;
- background: #fff;
overflow: hidden;
+ border: 1px solid #e2e8f0;
+ border-radius: 14px;
+ background: #fff;
+ box-shadow: 0 16px 40px rgba(15, 23, 42, 0.16);
+}
+
+.drama-ep-mention-pop-tabs,
+.drama-ep-mention-pop-scopes {
+ display: flex;
+ gap: 4px;
+ padding: 10px 10px 0;
+}
+
+.drama-ep-mention-pop-tabs button,
+.drama-ep-mention-pop-scopes button {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ height: 28px;
+ padding: 0 10px;
+ border: 0;
+ border-radius: 999px;
+ background: transparent;
+ color: #64748b;
+ font-size: 12px;
cursor: pointer;
+}
+
+.drama-ep-mention-pop-tabs button.is-active,
+.drama-ep-mention-pop-scopes button.is-active {
+ background: #efeff4;
+ color: #111;
+ font-weight: 600;
+}
+
+.drama-ep-mention-pop-list {
+ flex: 1;
+ overflow: auto;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.drama-ep-mention-pop-empty {
+ margin: 16px 8px;
+ font-size: 13px;
+ color: #94a3b8;
+ text-align: center;
+}
+
+.drama-ep-mention-pop-item {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 100%;
+ padding: 6px 8px;
+ border: 0;
+ border-radius: 10px;
+ background: transparent;
text-align: left;
+ cursor: pointer;
}
-.drama-ep-ref-chip:hover {
- border-color: #111;
+.drama-ep-mention-pop-item.is-active,
+.drama-ep-mention-pop-item:hover {
+ background: #efeff4;
}
-.drama-ep-ref-chip img,
-.drama-ep-ref-chip-fallback {
+.drama-ep-mention-pop-thumb {
+ width: 36px;
+ height: 36px;
+ border-radius: 8px;
+ overflow: hidden;
+ background: #efeff4;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ color: #94a3b8;
+ flex-shrink: 0;
+}
+
+.drama-ep-mention-pop-thumb img {
width: 100%;
- aspect-ratio: 1;
+ height: 100%;
object-fit: cover;
+}
+
+.drama-ep-mention-pop-meta {
+ min-width: 0;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+
+.drama-ep-mention-pop-meta strong {
+ font-size: 13px;
+ font-weight: 600;
+ color: #0f172a;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.drama-ep-mention-pop-meta em {
+ font-style: normal;
+ font-size: 11px;
+ color: #64748b;
+}
+
+.drama-ep-mention-pop-tools {
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.drama-ep-mention-pop-tools button {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ width: 100%;
+ padding: 10px;
+ border: 0;
+ border-radius: 10px;
+ background: #f8fafc;
+ text-align: left;
+ cursor: pointer;
+}
+
+.drama-ep-mention-pop-tools button:hover {
background: #efeff4;
}
-.drama-ep-ref-chip-fallback {
- display: grid;
- place-items: center;
- font-size: 16px;
- color: #888;
+.drama-ep-mention-pop-tools strong {
+ display: block;
+ font-size: 13px;
+ color: #0f172a;
+}
+
+.drama-ep-mention-pop-tools em {
+ display: block;
+ margin-top: 2px;
+ font-style: normal;
+ font-size: 11px;
+ color: #64748b;
+}
+
+.drama-ep-mention-pop-duration {
+ padding: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+}
+
+.drama-ep-mention-pop-duration-presets {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+}
+
+.drama-ep-mention-pop-duration-presets button {
+ height: 30px;
+ padding: 0 12px;
+ border: 1px solid #e2e8f0;
+ border-radius: 999px;
+ background: #fff;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.drama-ep-mention-pop-duration-presets button:hover:not(:disabled) {
+ border-color: #111;
+}
+
+.drama-ep-mention-pop-duration-presets button:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
+}
+
+.drama-ep-mention-pop-duration-custom {
+ display: flex;
+ gap: 6px;
}
-.drama-ep-ref-chip em {
- display: block;
- margin: 0;
- padding: 4px 6px;
- font-style: normal;
- font-size: 11px;
- line-height: 1.2;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- color: #333;
+.drama-ep-mention-pop-duration-custom input {
+ flex: 1;
+ height: 32px;
+ border: 1px solid #e2e8f0;
+ border-radius: 8px;
+ padding: 0 10px;
+ font: inherit;
}
-.drama-ep-content-view {
- min-height: 280px;
- height: 100%;
- overflow: auto;
- font-size: 14px;
- line-height: 1.7;
- color: var(--ep-ink, #222);
- word-break: break-word;
+.drama-ep-mention-pop-duration-custom button {
+ height: 32px;
+ padding: 0 12px;
+ border: 0;
+ border-radius: 8px;
+ background: #111;
+ color: #fff;
+ font-size: 12px;
+ cursor: pointer;
}
-.drama-ep-content-empty {
- margin: 0;
- padding: 12px 0;
- color: var(--drama-muted, #888);
- font-size: 13px;
+.drama-ep-mention-pop-back {
+ align-self: flex-start;
+ border: 0;
+ background: transparent;
+ padding: 0 2px 4px;
+ font-size: 12px;
+ color: #64748b;
+ cursor: pointer;
}
-.drama-ep-prompt-editor {
- min-height: 280px;
- height: 100%;
- overflow: auto;
- outline: none;
- white-space: pre-wrap;
- word-break: break-word;
- font-size: 14px;
- line-height: 1.7;
- color: var(--ep-ink, #222);
+.drama-ep-mention-pop-back:hover {
+ color: #0f172a;
}
-.drama-ep-prompt-editor.is-editing:empty::before {
- content: attr(data-placeholder);
- color: #94a3b8;
- pointer-events: none;
+.drama-ep-mention-pop-camera {
+ padding: 10px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ max-height: 360px;
+ overflow-y: auto;
}
-.drama-ep-editor-chip {
- user-select: none;
- vertical-align: middle;
- margin: 0 2px;
+.drama-ep-mention-pop-camera-heading {
+ margin: 0 0 6px;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ color: #64748b;
}
-.drama-ep-mention-chip {
- display: inline-flex;
- align-items: center;
+.drama-ep-mention-pop-camera-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
gap: 6px;
- max-width: 100%;
- margin: 0 2px;
- padding: 2px 8px 2px 2px;
- border: 1px solid #e5e7eb;
- border-radius: 999px;
+}
+
+.drama-ep-mention-pop-camera-grid button {
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 2px;
+ padding: 8px 10px;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
background: #fff;
- vertical-align: middle;
+ text-align: left;
cursor: pointer;
- box-shadow: 0 1px 2px rgba(0, 0, 0, 0.04);
}
-.drama-ep-mention-chip:hover {
+.drama-ep-mention-pop-camera-grid button:hover {
border-color: #111;
+ background: #f8fafc;
}
-.drama-ep-mention-chip img,
-.drama-ep-mention-chip-thumb,
-.drama-ep-mention-chip-fallback {
- width: 22px;
- height: 22px;
- border-radius: 7px;
- object-fit: cover;
- background: #efeff4;
- flex-shrink: 0;
+.drama-ep-mention-pop-camera-grid strong {
+ font-size: 12px;
+ color: #0f172a;
}
-.drama-ep-mention-chip-thumb {
- display: inline-flex;
- align-items: center;
- justify-content: center;
- overflow: hidden;
+.drama-ep-mention-pop-camera-grid em {
+ font-style: normal;
+ font-size: 10px;
+ line-height: 1.35;
+ color: #64748b;
}
-.drama-ep-mention-chip-thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
+.drama-ep-mention-pop-camera-tips {
+ margin: 0;
+ padding: 8px 10px;
+ list-style: none;
+ border-radius: 10px;
+ background: #f8fafc;
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
}
-.drama-ep-mention-chip-thumb.is-fallback,
-.drama-ep-mention-chip-fallback {
- display: grid;
- place-items: center;
- font-size: 11px;
- color: #888;
+.drama-ep-mention-pop-camera-tips li {
+ font-size: 10px;
+ line-height: 1.4;
+ color: #64748b;
}
-.drama-ep-mention-chip-label {
- font-size: 13px;
- line-height: 1.2;
- white-space: nowrap;
- overflow: hidden;
- text-overflow: ellipsis;
- max-width: 160px;
+.drama-ep-editor-actions {
+ display: flex;
+ justify-content: flex-end;
+ gap: 10px;
+ margin-top: 14px;
}
-.drama-ep-duration-chip {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- padding: 2px 8px;
- border: 1px solid #e2e8f0;
+.drama-ep-btn-ghost,
+.drama-ep-btn-dark {
+ border: none;
border-radius: 999px;
- background: #efeff4;
- color: #334155;
+ padding: 8px 18px;
+ font: inherit;
font-size: 13px;
- font-weight: 600;
- line-height: 20px;
- vertical-align: middle;
+ cursor: pointer;
}
-.drama-ep-chip-icon {
- display: inline-flex;
- width: 14px;
- height: 14px;
- align-items: center;
- justify-content: center;
- color: #64748b;
+.drama-ep-btn-ghost {
+ background: #fff;
+ color: var(--ep-ink);
+ box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06);
}
-.drama-ep-chip-icon svg {
- display: block;
+.drama-ep-btn-dark {
+ background: #0f172a;
+ color: #fff;
}
-.drama-ep-editor-box textarea {
- display: none;
+.drama-ep-btn-ghost:disabled,
+.drama-ep-btn-dark:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
}
-.drama-ep-mention-pop {
- position: fixed;
- z-index: 120;
- width: 320px;
- max-height: 340px;
+.drama-ep-preview {
+ min-height: 0;
+ border-left: 1px solid var(--ep-line);
+ background: #fff;
display: flex;
flex-direction: column;
+ align-items: stretch;
+ justify-content: flex-start;
+ padding: 0;
overflow: hidden;
- border: 1px solid #e2e8f0;
- border-radius: 14px;
- background: #fff;
- box-shadow: 0 16px 40px rgba(15, 23, 42, 0.16);
+ position: relative;
}
-.drama-ep-mention-pop-tabs,
-.drama-ep-mention-pop-scopes {
+.drama-ep-side-tabs {
display: flex;
+ flex-shrink: 0;
gap: 4px;
- padding: 10px 10px 0;
+ padding: 10px 12px 8px;
+ border-bottom: 1px solid var(--ep-line);
+ background: #fafafa;
}
-.drama-ep-mention-pop-tabs button,
-.drama-ep-mention-pop-scopes button {
- display: inline-flex;
- align-items: center;
- gap: 4px;
- height: 28px;
- padding: 0 10px;
- border: 0;
+.drama-ep-side-tabs button {
+ border: none;
border-radius: 999px;
+ padding: 4px 12px;
+ font-size: 12px;
background: transparent;
color: #64748b;
- font-size: 12px;
cursor: pointer;
}
-.drama-ep-mention-pop-tabs button.is-active,
-.drama-ep-mention-pop-scopes button.is-active {
- background: #efeff4;
- color: #111;
- font-weight: 600;
+.drama-ep-side-tabs button.active {
+ background: #0f172a;
+ color: #fff;
}
-.drama-ep-mention-pop-list {
+.drama-ep-preview .drama-ep-player,
+.drama-ep-preview .drama-ep-empty {
+ margin: auto;
+}
+
+.drama-ep-preview .drama-ep-player {
+ margin-top: 16px;
+ margin-bottom: 24px;
+}
+
+.drama-ep-preview-inner {
flex: 1;
- overflow: auto;
- padding: 8px;
+ min-height: 0;
display: flex;
flex-direction: column;
- gap: 2px;
+ align-items: stretch;
+ padding: 16px 16px 20px;
+ overflow-y: auto;
}
-.drama-ep-mention-pop-empty {
- margin: 16px 8px;
- font-size: 13px;
- color: #94a3b8;
- text-align: center;
+.drama-ep-segmented-player {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ width: 100%;
+ max-width: 320px;
+ margin: 0 auto;
}
-.drama-ep-mention-pop-item {
- display: flex;
- align-items: center;
- gap: 8px;
- width: 100%;
- padding: 6px 8px;
- border: 0;
- border-radius: 10px;
- background: transparent;
- text-align: left;
- cursor: pointer;
+.drama-ep-segmented-screen {
+ position: relative;
+ margin: 0;
}
-.drama-ep-mention-pop-item.is-active,
-.drama-ep-mention-pop-item:hover {
+.drama-ep-segmented-screen.is-empty {
+ border: 1px dashed #e2e8f0;
background: #efeff4;
}
-.drama-ep-mention-pop-thumb {
- width: 36px;
- height: 36px;
- border-radius: 8px;
- overflow: hidden;
- background: #efeff4;
+.drama-ep-video-download {
+ position: absolute;
+ top: 10px;
+ right: 10px;
+ width: 32px;
+ height: 32px;
+ border: none;
+ border-radius: 999px;
+ background: rgba(0, 0, 0, 0.45);
+ color: #fff;
display: inline-flex;
align-items: center;
justify-content: center;
- color: #94a3b8;
- flex-shrink: 0;
+ cursor: pointer;
+ backdrop-filter: blur(4px);
+ transition: background 0.15s ease;
}
-.drama-ep-mention-pop-thumb img {
- width: 100%;
- height: 100%;
- object-fit: cover;
+.drama-ep-video-download:hover {
+ background: rgba(0, 0, 0, 0.6);
}
-.drama-ep-mention-pop-meta {
- min-width: 0;
+.drama-ep-video-controls {
display: flex;
flex-direction: column;
- gap: 2px;
-}
-
-.drama-ep-mention-pop-meta strong {
- font-size: 13px;
- font-weight: 600;
- color: #0f172a;
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
+ gap: 8px;
}
-.drama-ep-mention-pop-meta em {
- font-style: normal;
- font-size: 11px;
+.drama-ep-video-clock {
+ margin: 0;
+ text-align: center;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
color: #64748b;
}
-.drama-ep-mention-pop-tools {
- padding: 8px;
+.drama-ep-video-toolbar {
+ display: flex;
+ align-items: center;
+ gap: 8px;
}
-.drama-ep-mention-pop-tools button {
- display: flex;
+.drama-ep-video-icon-btn {
+ flex-shrink: 0;
+ width: 28px;
+ height: 28px;
+ border: none;
+ background: transparent;
+ color: #0f172a;
+ display: inline-flex;
align-items: center;
- gap: 10px;
- width: 100%;
- padding: 10px;
- border: 0;
- border-radius: 10px;
- background: #f8fafc;
- text-align: left;
+ justify-content: center;
cursor: pointer;
+ padding: 0;
+ transition: color 0.15s ease;
}
-.drama-ep-mention-pop-tools button:hover {
- background: #efeff4;
+.drama-ep-video-icon-btn:hover:not(:disabled) {
+ color: #475569;
}
-.drama-ep-mention-pop-tools strong {
- display: block;
- font-size: 13px;
- color: #0f172a;
+.drama-ep-video-icon-btn:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
}
-.drama-ep-mention-pop-tools em {
- display: block;
- margin-top: 2px;
- font-style: normal;
- font-size: 11px;
+.drama-ep-video-icon-btn.is-muted {
color: #64748b;
}
-.drama-ep-mention-pop-duration {
- padding: 10px;
+.drama-ep-video-track {
+ position: relative;
+ flex: 1;
+ min-width: 0;
+ height: 12px;
display: flex;
- flex-direction: column;
- gap: 10px;
+ align-items: stretch;
+ overflow: hidden;
+ border-radius: 4px;
+ background: #ececf1;
+ cursor: pointer;
}
-.drama-ep-mention-pop-duration-presets {
- display: flex;
- flex-wrap: wrap;
- gap: 6px;
+.drama-ep-video-track.is-disabled {
+ opacity: 0.6;
+ cursor: not-allowed;
}
-.drama-ep-mention-pop-duration-presets button {
- height: 30px;
- padding: 0 12px;
- border: 1px solid #e2e8f0;
- border-radius: 999px;
- background: #fff;
- font-size: 12px;
- cursor: pointer;
+.drama-ep-video-track-seg {
+ position: relative;
+ min-width: 0;
+ background: #ececf1;
}
-.drama-ep-mention-pop-duration-presets button:hover:not(:disabled) {
- border-color: #111;
+.drama-ep-video-track-seg.has-divider {
+ border-right: 1px solid #fff;
}
-.drama-ep-mention-pop-duration-presets button:disabled {
- opacity: 0.4;
- cursor: not-allowed;
+.drama-ep-video-track-fill {
+ position: absolute;
+ inset: 0 auto 0 0;
+ background: #0f172a;
}
-.drama-ep-mention-pop-duration-custom {
- display: flex;
- gap: 6px;
+.drama-ep-video-playhead {
+ pointer-events: none;
+ position: absolute;
+ top: -3px;
+ bottom: -3px;
+ width: 1px;
+ background: #a78bfa;
}
-.drama-ep-mention-pop-duration-custom input {
- flex: 1;
- height: 32px;
- border: 1px solid #e2e8f0;
- border-radius: 8px;
- padding: 0 10px;
- font: inherit;
+.drama-ep-video-autolink {
+ flex-shrink: 0;
+ border: none;
+ background: transparent;
+ color: #64748b;
+ display: inline-flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ cursor: pointer;
+ padding: 0 2px;
+ transition: color 0.15s ease;
}
-.drama-ep-mention-pop-duration-custom button {
- height: 32px;
- padding: 0 12px;
- border: 0;
- border-radius: 8px;
- background: #111;
- color: #fff;
- font-size: 12px;
- cursor: pointer;
+.drama-ep-video-autolink:hover:not(:disabled) {
+ color: #334155;
}
-.drama-ep-editor-actions {
- display: flex;
- justify-content: flex-end;
- gap: 10px;
- margin-top: 14px;
+.drama-ep-video-autolink:disabled {
+ opacity: 0.4;
+ cursor: not-allowed;
}
-.drama-ep-btn-ghost,
-.drama-ep-btn-dark {
- border: none;
+.drama-ep-video-autolink-bar {
+ width: 20px;
+ height: 6px;
border-radius: 999px;
- padding: 8px 18px;
- font: inherit;
- font-size: 13px;
- cursor: pointer;
+ background: #d8d8de;
+ transition: background 0.15s ease;
}
-.drama-ep-btn-ghost {
- background: #fff;
- color: var(--ep-ink);
- box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.06);
+.drama-ep-video-autolink.is-on .drama-ep-video-autolink-bar {
+ background: #10b981;
}
-.drama-ep-btn-dark {
- background: #0f172a;
- color: #fff;
+.drama-ep-preview-inner .drama-ep-open-canvas {
+ align-self: center;
}
-.drama-ep-btn-ghost:disabled,
-.drama-ep-btn-dark:disabled {
- opacity: 0.45;
- cursor: not-allowed;
+.drama-ep-open-canvas {
+ margin-top: 10px;
+ border: none;
+ border-radius: 999px;
+ padding: 6px 12px;
+ font-size: 12px;
+ background: #fff;
+ color: #0f172a;
+ cursor: pointer;
}
-.drama-ep-preview {
- min-height: 0;
- border-left: 1px solid var(--ep-line);
- background: #fff;
- display: flex;
- align-items: center;
- justify-content: center;
- padding: 20px 30px;
+.drama-ep-body.is-side-canvas {
+ grid-template-columns: 260px minmax(0, 1fr) minmax(420px, 1.15fr);
}
.drama-ep-player {
@@ -2830,8 +4295,30 @@
background: #222;
}
-.drama-gen-fab-btn.is-busy {
- box-shadow: 0 10px 28px rgba(0, 0, 0, 0.22), 0 0 0 3px rgba(182, 255, 0, 0.45);
+.drama-gen-fab-btn.is-failed {
+ box-shadow: 0 10px 28px rgba(0, 0, 0, 0.22), 0 0 0 3px rgba(239, 68, 68, 0.45);
+}
+
+.drama-gen-fab-kind {
+ display: inline-flex;
+ align-items: center;
+ gap: 4px;
+ margin-bottom: 2px;
+ color: #64748b;
+ font-size: 11px;
+}
+
+.drama-gen-fab-kind em {
+ font-style: normal;
+ font-weight: 600;
+}
+
+.drama-gen-fab-msg {
+ display: block;
+ margin-top: 2px;
+ font-size: 11px;
+ color: #64748b;
+ line-height: 1.35;
}
.drama-gen-fab-badge {
@@ -3119,3 +4606,63 @@
.drama-btn-danger-text {
color: #b91c1c;
}
+
+/* 批量角色音色生成进度 */
+.drama-batch-voice-list {
+ display: flex;
+ flex-direction: column;
+ gap: 8px;
+ margin: 14px 0;
+ max-height: 320px;
+ overflow: auto;
+ list-style: none;
+ padding: 0;
+}
+
+.drama-batch-voice-item {
+ padding: 10px 12px;
+ border: 1px solid var(--drama-line);
+ border-radius: 10px;
+ background: #fafafa;
+}
+
+.drama-batch-voice-item.is-done {
+ border-color: #86efac;
+ background: #f0fdf4;
+}
+
+.drama-batch-voice-item.is-error {
+ border-color: #fca5a5;
+ background: #fef2f2;
+}
+
+.drama-batch-voice-item.is-prompt,
+.drama-batch-voice-item.is-synth,
+.drama-batch-voice-item.is-bind {
+ border-color: #fde047;
+ background: #fefce8;
+}
+
+.drama-batch-voice-item-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.drama-batch-voice-status {
+ font-size: 12px;
+ color: var(--drama-muted);
+}
+
+.drama-batch-voice-prompt {
+ margin: 6px 0 0;
+ font-size: 12px;
+ line-height: 1.45;
+}
+
+.drama-batch-voice-error {
+ margin: 6px 0 0;
+ font-size: 12px;
+ color: #b91c1c;
+}
diff --git a/frontend/src/pages/drama/dramaEpisodeEditUtils.ts b/frontend/src/pages/drama/dramaEpisodeEditUtils.ts
index 90dcf0e..94299a1 100644
--- a/frontend/src/pages/drama/dramaEpisodeEditUtils.ts
+++ b/frontend/src/pages/drama/dramaEpisodeEditUtils.ts
@@ -48,6 +48,9 @@ export type FragmentRefStripItem = {
name: string
type: string
previewUrl: string
+ isCharacter?: boolean
+ voiceLabel?: string
+ voiceUrl?: string
}
// 组装当前分镜关联资产条
@@ -55,16 +58,22 @@ export function buildFragmentRefStripItems(
frag: DramaFragment | null | undefined,
assets: DramaAsset[],
resolveUrl: (url: string | null | undefined) => string,
+ readVoice?: (asset: DramaAsset) => { label: string; url: string } | null,
): FragmentRefStripItem[] {
const byId = new Map(assets.map((a) => [a.id, a]))
return collectFragmentAssetIds(frag).map((assetId) => {
const asset = byId.get(assetId)
const preview = asset ? resolveUrl(asset.cover || asset.url) : ''
+ const isCharacter = asset ? normalizeAssetTab(asset.type) === 'character' : false
+ const voice = asset && readVoice ? readVoice(asset) : null
return {
assetId,
name: asset?.name || `资产 ${assetId}`,
type: asset?.type || '',
previewUrl: preview,
+ isCharacter,
+ voiceLabel: voice?.label,
+ voiceUrl: voice?.url,
}
})
}
@@ -94,14 +103,16 @@ export function sumFragmentContentDuration(content: string): number {
// 解析分镜生成状态(params.generation 或已有 video)
export function readFragmentGenerationStatus(
frag: DramaFragment,
-): { status: string; error?: string } {
+): { status: string; error?: string; message?: string; phase?: string } {
if (frag.video) return { status: 'done' }
const gen = frag.params?.generation
if (gen && typeof gen === 'object') {
const row = gen as Record<string, unknown>
const status = typeof row.status === 'string' ? row.status : 'idle'
const error = typeof row.error === 'string' ? row.error : undefined
- return { status, error }
+ const message = typeof row.message === 'string' ? row.message : undefined
+ const phase = typeof row.phase === 'string' ? row.phase : undefined
+ return { status, error, message, phase }
}
return { status: 'idle' }
}
diff --git a/frontend/src/pages/drama/episodeCanvas/EpisodeAssetNode.tsx b/frontend/src/pages/drama/episodeCanvas/EpisodeAssetNode.tsx
new file mode 100644
index 0000000..c24b521
--- /dev/null
+++ b/frontend/src/pages/drama/episodeCanvas/EpisodeAssetNode.tsx
@@ -0,0 +1,42 @@
+/** 出境资产节点:缩略图卡片,连线到分镜视频 */
+import { memo } from 'react'
+import { Handle, Position, type Node, type NodeProps } from '@xyflow/react'
+import { X } from 'lucide-react'
+import type { EpisodeAssetNodeData } from './buildEpisodeFlow'
+
+type Props = NodeProps<Node<EpisodeAssetNodeData>> & {
+ onUnlinkAsset?: (fragmentId: number, assetId: number) => void
+}
+
+// 渲染出境资产节点
+function EpisodeAssetNodeComponent({ data, selected, onUnlinkAsset }: Props) {
+ return (
+ <div className={`ep-asset-node${selected ? ' is-selected' : ''}`}>
+ <div className="ep-asset-node-head">
+ <span>{data.typeLabel}</span>
+ {selected ? (
+ <button
+ type="button"
+ className="ep-asset-node-unlink nodrag nopan"
+ aria-label={`取消关联 ${data.name}`}
+ title="取消关联"
+ onClick={() => onUnlinkAsset?.(data.fragmentId, data.assetId)}
+ >
+ <X size={12} strokeWidth={2.2} />
+ </button>
+ ) : null}
+ </div>
+ <div className="ep-asset-node-thumb">
+ {data.previewUrl ? (
+ <img src={data.previewUrl} alt="" draggable={false} />
+ ) : (
+ <span>{(data.name || '?')[0]}</span>
+ )}
+ </div>
+ <div className="ep-asset-node-name">{data.name}</div>
+ <Handle className="ep-frag-handle" type="source" position={Position.Right} />
+ </div>
+ )
+}
+
+export const EpisodeAssetNode = memo(EpisodeAssetNodeComponent)
diff --git a/frontend/src/pages/drama/episodeCanvas/EpisodeFragmentNode.tsx b/frontend/src/pages/drama/episodeCanvas/EpisodeFragmentNode.tsx
new file mode 100644
index 0000000..0c8cd35
--- /dev/null
+++ b/frontend/src/pages/drama/episodeCanvas/EpisodeFragmentNode.tsx
@@ -0,0 +1,93 @@
+/** 分镜故事板节点:上方视频,下方提示词;出境资产通过左侧节点连线关联 */
+import { memo, useCallback, type ChangeEvent } from 'react'
+import { Handle, Position, type Node, type NodeProps } from '@xyflow/react'
+import { Clapperboard, Plus } from 'lucide-react'
+import type { EpisodeFragmentNodeData } from './buildEpisodeFlow'
+
+type Props = NodeProps<Node<EpisodeFragmentNodeData>> & {
+ onPromptChange?: (fragmentId: number, content: string) => void
+ onRequestLinkAsset?: (fragmentId: number) => void
+}
+
+// 渲染单个分镜视频节点
+function EpisodeFragmentNodeComponent({
+ data,
+ selected,
+ onPromptChange,
+ onRequestLinkAsset,
+}: Props) {
+ const hasVideo = Boolean(data.videoUrl)
+ const media = data.coverUrl || data.videoUrl
+
+ const handlePromptChange = useCallback(
+ (event: ChangeEvent<HTMLTextAreaElement>) => {
+ onPromptChange?.(data.fragmentId, event.target.value)
+ },
+ [data.fragmentId, onPromptChange],
+ )
+
+ return (
+ <div className={`ep-frag-node${selected ? ' is-selected' : ''}`}>
+ <div className="ep-frag-node-head">
+ <Clapperboard size={14} strokeWidth={1.8} aria-hidden />
+ <span>{data.label}</span>
+ {selected ? (
+ <button
+ type="button"
+ className="ep-frag-link-btn nodrag nopan"
+ title="关联出境资产"
+ aria-label="关联出境资产"
+ onClick={() => onRequestLinkAsset?.(data.fragmentId)}
+ >
+ <Plus size={14} strokeWidth={2} />
+ </button>
+ ) : (
+ <em className="ep-frag-link-count">{data.linkedCount || 0} 资产</em>
+ )}
+ </div>
+
+ <div className="ep-frag-media">
+ {hasVideo ? (
+ <video
+ className="ep-frag-video"
+ src={data.videoUrl}
+ poster={data.coverUrl || undefined}
+ controls
+ playsInline
+ preload="metadata"
+ />
+ ) : media ? (
+ <img src={media} alt="" draggable={false} />
+ ) : (
+ <div className="ep-frag-media-empty">
+ <span>暂无成片</span>
+ <small>生成后显示在此</small>
+ </div>
+ )}
+ </div>
+
+ <div className="ep-frag-prompt">
+ <label>提示词</label>
+ {selected ? (
+ <textarea
+ className="ep-frag-prompt-input nodrag nowheel"
+ value={data.content}
+ onChange={handlePromptChange}
+ placeholder="分镜脚本 / Seedance 提示词…"
+ rows={5}
+ />
+ ) : (
+ <p className="ep-frag-prompt-text">
+ {(data.content || '').trim() || '(空提示词)'}
+ </p>
+ )}
+ </div>
+
+ <Handle className="ep-frag-handle" type="target" position={Position.Left} id="assets" />
+ <Handle className="ep-frag-handle" type="target" position={Position.Top} id="prev" />
+ <Handle className="ep-frag-handle" type="source" position={Position.Right} id="next" />
+ </div>
+ )
+}
+
+export const EpisodeFragmentNode = memo(EpisodeFragmentNodeComponent)
diff --git a/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx b/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx
new file mode 100644
index 0000000..c3ae778
--- /dev/null
+++ b/frontend/src/pages/drama/episodeCanvas/EpisodeStoryboardPage.tsx
@@ -0,0 +1,407 @@
+/** 分集分镜故事板全屏画布:按分镜连线,节点含视频 / 出境资产 / 提示词 */
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import {
+ Background,
+ Controls,
+ MiniMap,
+ ReactFlow,
+ ReactFlowProvider,
+ useEdgesState,
+ useNodesState,
+ useReactFlow,
+ type Edge,
+ type Node,
+ type NodeTypes,
+} from '@xyflow/react'
+import '@xyflow/react/dist/style.css'
+import { ChevronLeft } from 'lucide-react'
+import { useNavigate, useParams } from 'react-router-dom'
+import {
+ dramaApi,
+ resolveDramaMediaUrl,
+ type DramaAsset,
+ type DramaEpisode,
+ type DramaFragment,
+} from '../../../api/drama'
+import Modal from '../../../components/ui/Modal'
+import {
+ collectFragmentAssetIds,
+ normalizeAssetTab,
+} from '../dramaEpisodeEditUtils'
+import RequireAuth from '../RequireAuth'
+import {
+ buildEpisodeFragmentFlow,
+ type EpisodeFragmentNodeData,
+ type EpisodeFlowNodeData,
+} from './buildEpisodeFlow'
+import { EpisodeAssetNode } from './EpisodeAssetNode'
+import { EpisodeFragmentNode } from './EpisodeFragmentNode'
+import './episodeCanvas.css'
+
+const SAVE_DEBOUNCE_MS = 800
+
+// 正文补上 @asset 提及
+function ensureAssetMention(content: string, assetId: number): string {
+ const token = `@asset:${assetId}`
+ if ((content || '').includes(token)) return content || ''
+ const trimmed = (content || '').trimEnd()
+ return trimmed ? `${trimmed} ${token}` : token
+}
+
+// 正文去掉 @asset 提及
+function removeAssetMention(content: string, assetId: number): string {
+ return (content || '')
+ .replace(new RegExp(`\\s*@asset:${assetId}\\b`, 'g'), ' ')
+ .replace(/[ \t]{2,}/g, ' ')
+ .replace(/\n{3,}/g, '\n\n')
+ .trim()
+}
+
+// 鉴权后进入分镜故事板
+export default function EpisodeStoryboardPage() {
+ return (
+ <RequireAuth>
+ <ReactFlowProvider>
+ <EpisodeStoryboardInner />
+ </ReactFlowProvider>
+ </RequireAuth>
+ )
+}
+
+// 加载分集并渲染全屏故事板
+function EpisodeStoryboardInner() {
+ const { projectId, episodeId } = useParams()
+ const pid = Number(projectId)
+ const eid = Number(episodeId)
+ const navigate = useNavigate()
+ const { fitView } = useReactFlow()
+
+ /*
+ * episode / fragments / assets 数据
+ * linkTargetFragId 正在选资产关联的分镜
+ * dirty / busy / error / status 状态
+ */
+ const [episode, setEpisode] = useState<DramaEpisode | null>(null)
+ const [fragments, setFragments] = useState<DramaFragment[]>([])
+ const [assets, setAssets] = useState<DramaAsset[]>([])
+ const [linkTargetFragId, setLinkTargetFragId] = useState<number | null>(null)
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [status, setStatus] = useState('')
+ const [dirty, setDirty] = useState(false)
+ const fittedRef = useRef(false)
+ const fragmentsRef = useRef<DramaFragment[]>([])
+ const assetsRef = useRef<DramaAsset[]>([])
+ const saveTimer = useRef<number | null>(null)
+
+ const [nodes, setNodes, onNodesChange] = useNodesState<Node<EpisodeFlowNodeData>>([])
+ const [edges, setEdges, onEdgesChange] = useEdgesState<Edge>([])
+
+ useEffect(() => {
+ fragmentsRef.current = fragments
+ }, [fragments])
+
+ useEffect(() => {
+ assetsRef.current = assets
+ }, [assets])
+
+ // 结构键:成片 + 关联资产变化时重建;提示词编辑走局部更新
+ const structureKey = fragments
+ .map((f) => {
+ const aids = collectFragmentAssetIds(f).join(',')
+ return `${f.id}:${f.sort_order}:${f.video || ''}:${f.cover || ''}:${f.duration_sec ?? 0}:${aids}`
+ })
+ .join('|')
+
+ useEffect(() => {
+ const flow = buildEpisodeFragmentFlow(fragmentsRef.current, assetsRef.current)
+ setNodes(flow.nodes)
+ setEdges(flow.edges)
+ }, [structureKey, assets, setNodes, setEdges])
+
+ useEffect(() => {
+ fittedRef.current = false
+ }, [eid])
+
+ useEffect(() => {
+ if (fittedRef.current || nodes.length === 0) return
+ fittedRef.current = true
+ void fitView({ padding: 0.22, duration: 280 })
+ }, [nodes.length, fitView])
+
+ // 拉取分集 + 项目资产
+ useEffect(() => {
+ if (!eid || !pid) return
+ let cancelled = false
+ setBusy(true)
+ setError('')
+ Promise.all([dramaApi.getEpisode(eid), dramaApi.listAssets(pid)])
+ .then(([ep, assetList]) => {
+ if (cancelled) return
+ setEpisode(ep)
+ setFragments(ep.fragments || [])
+ setAssets(assetList || [])
+ })
+ .catch((err) => {
+ if (!cancelled) setError(err instanceof Error ? err.message : '加载分集失败')
+ })
+ .finally(() => {
+ if (!cancelled) setBusy(false)
+ })
+ return () => {
+ cancelled = true
+ if (saveTimer.current) window.clearTimeout(saveTimer.current)
+ }
+ }, [eid, pid])
+
+ // 持久化全部分镜(保序,保留成片与引用)
+ const persistFragments = useCallback(
+ async (next: DramaFragment[]) => {
+ if (!eid) return
+ setBusy(true)
+ setError('')
+ try {
+ const saved = await dramaApi.saveFragments(
+ eid,
+ next.map((f, index) => {
+ const prevParams =
+ f.params && typeof f.params === 'object' && !Array.isArray(f.params)
+ ? (f.params as Record<string, unknown>)
+ : {}
+ return {
+ sort_order: index,
+ content: f.content || '',
+ cover: f.cover || '',
+ video: f.video || '',
+ duration_sec: f.duration_sec ?? 8,
+ params: prevParams,
+ asset_ids: collectFragmentAssetIds(f),
+ }
+ }),
+ )
+ setEpisode(saved)
+ setFragments(saved.fragments || [])
+ setDirty(false)
+ setStatus('已保存')
+ window.setTimeout(() => setStatus(''), 1600)
+ } catch (err) {
+ setError(err instanceof Error ? err.message : '保存失败')
+ } finally {
+ setBusy(false)
+ }
+ },
+ [eid],
+ )
+
+ // 防抖保存
+ const scheduleSave = useCallback(() => {
+ setDirty(true)
+ if (saveTimer.current) window.clearTimeout(saveTimer.current)
+ saveTimer.current = window.setTimeout(() => {
+ void persistFragments(fragmentsRef.current)
+ }, SAVE_DEBOUNCE_MS)
+ }, [persistFragments])
+
+ // 刷新单个分镜节点提示词(关联资产变化靠 structureKey 重建)
+ const patchFragmentPrompt = useCallback(
+ (fragmentId: number, content: string) => {
+ setNodes((prev) =>
+ prev.map((node) => {
+ if (node.type !== 'episodeFragment') return node
+ const data = node.data as EpisodeFragmentNodeData
+ if (data.fragmentId !== fragmentId) return node
+ return { ...node, data: { ...data, content } }
+ }),
+ )
+ },
+ [setNodes],
+ )
+
+ // 改提示词
+ const handlePromptChange = useCallback(
+ (fragmentId: number, content: string) => {
+ setFragments((prev) =>
+ prev.map((f) => {
+ if (f.id !== fragmentId) return f
+ const updated = { ...f, content }
+ return { ...updated, asset_ids: collectFragmentAssetIds(updated) }
+ }),
+ )
+ patchFragmentPrompt(fragmentId, content)
+ scheduleSave()
+ },
+ [patchFragmentPrompt, scheduleSave],
+ )
+
+ // 取消关联出境资产
+ const handleUnlinkAsset = useCallback(
+ (fragmentId: number, assetId: number) => {
+ setFragments((prev) =>
+ prev.map((f) => {
+ if (f.id !== fragmentId) return f
+ const content = removeAssetMention(f.content || '', assetId)
+ const asset_ids = (f.asset_ids || []).filter((id) => id !== assetId)
+ return { ...f, content, asset_ids }
+ }),
+ )
+ scheduleSave()
+ },
+ [scheduleSave],
+ )
+
+ // 打开关联选择
+ const handleRequestLinkAsset = useCallback((fragmentId: number) => {
+ setLinkTargetFragId(fragmentId)
+ }, [])
+
+ // 确认关联资产
+ const handlePickAsset = useCallback(
+ (asset: DramaAsset) => {
+ if (linkTargetFragId == null) return
+ const fragmentId = linkTargetFragId
+ setFragments((prev) =>
+ prev.map((f) => {
+ if (f.id !== fragmentId) return f
+ const content = ensureAssetMention(f.content || '', asset.id)
+ const asset_ids = Array.from(new Set([...(f.asset_ids || []), asset.id]))
+ return { ...f, content, asset_ids }
+ }),
+ )
+ setLinkTargetFragId(null)
+ scheduleSave()
+ },
+ [linkTargetFragId, scheduleSave],
+ )
+
+ const nodeTypes: NodeTypes = useMemo(
+ () => ({
+ episodeFragment: (props) => (
+ <EpisodeFragmentNode
+ {...props}
+ onPromptChange={handlePromptChange}
+ onRequestLinkAsset={handleRequestLinkAsset}
+ />
+ ),
+ episodeAsset: (props) => (
+ <EpisodeAssetNode {...props} onUnlinkAsset={handleUnlinkAsset} />
+ ),
+ }),
+ [handlePromptChange, handleRequestLinkAsset, handleUnlinkAsset],
+ )
+
+ const linkFrag = fragments.find((f) => f.id === linkTargetFragId) || null
+ const linkedIdSet = new Set(linkFrag ? collectFragmentAssetIds(linkFrag) : [])
+ const pickerAssets = assets.filter((a) => {
+ const tab = normalizeAssetTab(a.type || '')
+ return Boolean(tab) && !linkedIdSet.has(a.id)
+ })
+
+ const backHref = `/drama/projects/${pid}/episodes/${eid}`
+
+ return (
+ <div className="ep-storyboard-page">
+ <header className="ep-storyboard-topbar">
+ <div className="ep-storyboard-topbar-left">
+ <button
+ type="button"
+ className="ep-storyboard-back"
+ aria-label="返回分集"
+ title="返回分集"
+ onClick={() => navigate(backHref)}
+ >
+ <ChevronLeft size={20} strokeWidth={1.8} />
+ </button>
+ <div className="ep-storyboard-title">
+ <strong>{episode?.name || `分集 ${eid}`}</strong>
+ <span>
+ 分镜故事板 · {fragments.length} 镜
+ {dirty ? ' · 未保存' : status ? ` · ${status}` : ''}
+ </span>
+ </div>
+ </div>
+ <div className="ep-storyboard-actions">
+ <button
+ type="button"
+ className="ep-storyboard-btn ghost"
+ onClick={() => navigate(`/drama/projects/${pid}/canvas`)}
+ >
+ 资产画布
+ </button>
+ <button
+ type="button"
+ className="ep-storyboard-btn dark"
+ disabled={busy || !dirty}
+ onClick={() => void persistFragments(fragments)}
+ >
+ {busy ? '保存中…' : '保存'}
+ </button>
+ </div>
+ </header>
+
+ <div className="ep-storyboard-flow">
+ {fragments.length === 0 && !busy ? (
+ <div className="ep-storyboard-empty">
+ <strong>暂无分镜</strong>
+ <span>请先回分集编辑页添加分镜</span>
+ </div>
+ ) : null}
+ <ReactFlow
+ nodes={nodes}
+ edges={edges}
+ onNodesChange={onNodesChange}
+ onEdgesChange={onEdgesChange}
+ nodeTypes={nodeTypes}
+ fitView
+ minZoom={0.35}
+ maxZoom={1.6}
+ proOptions={{ hideAttribution: true }}
+ defaultEdgeOptions={{ type: 'smoothstep' }}
+ >
+ <Background gap={20} size={1} color="#dbe2ea" />
+ <Controls showInteractive={false} />
+ <MiniMap pannable zoomable />
+ </ReactFlow>
+ {error ? (
+ <p className="ep-storyboard-toast" role="alert">
+ {error}
+ </p>
+ ) : null}
+ {busy && fragments.length === 0 ? (
+ <p className="ep-storyboard-toast">加载中…</p>
+ ) : null}
+ </div>
+
+ <Modal
+ open={linkTargetFragId != null}
+ onClose={() => setLinkTargetFragId(null)}
+ title="关联出境资产"
+ size="lg"
+ >
+ <p className="ep-storyboard-picker-hint">选择本镜出场的角色 / 场景 / 道具 / 素材</p>
+ {pickerAssets.length === 0 ? (
+ <p className="ep-storyboard-picker-empty">暂无可选资产,请先到资产画布生成</p>
+ ) : (
+ <div className="ep-storyboard-picker-grid">
+ {pickerAssets.map((asset) => {
+ const cover = resolveDramaMediaUrl(asset.cover || asset.url)
+ return (
+ <button
+ key={asset.id}
+ type="button"
+ className="ep-storyboard-picker-card"
+ onClick={() => handlePickAsset(asset)}
+ >
+ <div className="ep-storyboard-picker-thumb">
+ {cover ? <img src={cover} alt="" /> : <span>{(asset.name || '?')[0]}</span>}
+ </div>
+ <strong>{asset.name || `资产 ${asset.id}`}</strong>
+ <em>{normalizeAssetTab(asset.type || '') || asset.type || '资产'}</em>
+ </button>
+ )
+ })}
+ </div>
+ )}
+ </Modal>
+ </div>
+ )
+}
diff --git a/frontend/src/pages/drama/episodeCanvas/buildEpisodeFlow.ts b/frontend/src/pages/drama/episodeCanvas/buildEpisodeFlow.ts
new file mode 100644
index 0000000..75671b6
--- /dev/null
+++ b/frontend/src/pages/drama/episodeCanvas/buildEpisodeFlow.ts
@@ -0,0 +1,138 @@
+/** 分集分镜 → 资产节点连线到分镜视频节点 */
+import type { Edge, Node } from '@xyflow/react'
+import {
+ resolveDramaMediaUrl,
+ type DramaAsset,
+ type DramaFragment,
+} from '../../../api/drama'
+import {
+ collectFragmentAssetIds,
+ formatFragLabel,
+ normalizeAssetTab,
+} from '../dramaEpisodeEditUtils'
+
+export type EpisodeFragmentNodeData = {
+ fragmentId: number
+ sortOrder: number
+ label: string
+ content: string
+ videoUrl: string
+ coverUrl: string
+ durationSec: number
+ linkedCount: number
+ [key: string]: unknown
+}
+
+export type EpisodeAssetNodeData = {
+ assetId: number
+ fragmentId: number
+ name: string
+ typeLabel: string
+ previewUrl: string
+ [key: string]: unknown
+}
+
+export type EpisodeFlowNodeData = EpisodeFragmentNodeData | EpisodeAssetNodeData
+
+export const EPISODE_FRAGMENT_NODE_WIDTH = 220
+export const EPISODE_ASSET_NODE_WIDTH = 148
+export const EPISODE_COL_GAP = 56
+export const EPISODE_ASSET_ROW_GAP = 16
+export const EPISODE_ASSET_TO_VIDEO_GAP = 48
+
+// 分镜视频节点 id
+export function episodeFragmentNodeId(fragmentId: number): string {
+ return `frag-${fragmentId}`
+}
+
+// 分镜下某个出境资产节点 id(按镜复制,便于排布与取消关联)
+export function episodeAssetNodeId(fragmentId: number, assetId: number): string {
+ return `frag-${fragmentId}-asset-${assetId}`
+}
+
+// 构建:左列出境资产 → 连线 → 右列分镜视频(下挂提示词),分镜之间顺序相连
+export function buildEpisodeFragmentFlow(
+ fragments: DramaFragment[],
+ assets: DramaAsset[] = [],
+): {
+ nodes: Node<EpisodeFlowNodeData>[]
+ edges: Edge[]
+} {
+ const ordered = [...fragments].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0))
+ const byId = new Map(assets.map((a) => [a.id, a]))
+ const nodes: Node<EpisodeFlowNodeData>[] = []
+ const edges: Edge[] = []
+
+ const colWidth = EPISODE_ASSET_NODE_WIDTH + EPISODE_ASSET_TO_VIDEO_GAP + EPISODE_FRAGMENT_NODE_WIDTH
+
+ ordered.forEach((frag, index) => {
+ const fragNodeId = episodeFragmentNodeId(frag.id)
+ const linkedIds = collectFragmentAssetIds(frag)
+ const colX = index * (colWidth + EPISODE_COL_GAP)
+ const videoX = colX + EPISODE_ASSET_NODE_WIDTH + EPISODE_ASSET_TO_VIDEO_GAP
+ const videoY = 120
+
+ linkedIds.forEach((assetId, assetIndex) => {
+ const asset = byId.get(assetId)
+ const assetNodeId = episodeAssetNodeId(frag.id, assetId)
+ const tab = normalizeAssetTab(asset?.type || '')
+ nodes.push({
+ id: assetNodeId,
+ type: 'episodeAsset',
+ position: {
+ x: colX,
+ y: 40 + assetIndex * (EPISODE_ASSET_NODE_WIDTH + EPISODE_ASSET_ROW_GAP),
+ },
+ data: {
+ assetId,
+ fragmentId: frag.id,
+ name: asset?.name || `资产 ${assetId}`,
+ typeLabel: tab || asset?.type || '资产',
+ previewUrl: resolveDramaMediaUrl(asset?.cover || asset?.url) || '',
+ },
+ draggable: true,
+ })
+ edges.push({
+ id: `ea-${frag.id}-${assetId}`,
+ source: assetNodeId,
+ target: fragNodeId,
+ targetHandle: 'assets',
+ type: 'smoothstep',
+ animated: false,
+ })
+ })
+
+ nodes.push({
+ id: fragNodeId,
+ type: 'episodeFragment',
+ position: { x: videoX, y: videoY },
+ data: {
+ fragmentId: frag.id,
+ sortOrder: frag.sort_order ?? index,
+ label: formatFragLabel(index, frag.duration_sec),
+ content: frag.content || '',
+ videoUrl: resolveDramaMediaUrl(frag.video) || '',
+ coverUrl: resolveDramaMediaUrl(frag.cover) || '',
+ durationSec: frag.duration_sec && frag.duration_sec > 0 ? frag.duration_sec : 8,
+ linkedCount: linkedIds.length,
+ },
+ draggable: true,
+ })
+
+ if (index > 0) {
+ const prev = ordered[index - 1]
+ edges.push({
+ id: `ef-${prev.id}-${frag.id}`,
+ source: episodeFragmentNodeId(prev.id),
+ sourceHandle: 'next',
+ target: fragNodeId,
+ targetHandle: 'prev',
+ type: 'smoothstep',
+ animated: false,
+ style: { strokeDasharray: '6 4' },
+ })
+ }
+ })
+
+ return { nodes, edges }
+}
diff --git a/frontend/src/pages/drama/episodeCanvas/episodeCanvas.css b/frontend/src/pages/drama/episodeCanvas/episodeCanvas.css
new file mode 100644
index 0000000..e18a990
--- /dev/null
+++ b/frontend/src/pages/drama/episodeCanvas/episodeCanvas.css
@@ -0,0 +1,424 @@
+/* 分集分镜故事板全屏画布 */
+
+.ep-storyboard-page {
+ --epc-bg: #eef1f4;
+ --epc-ink: #0f172a;
+ --epc-muted: #64748b;
+ --epc-line: rgba(15, 23, 42, 0.08);
+ --epc-panel: #fff;
+ position: fixed;
+ inset: 0;
+ z-index: 50;
+ display: flex;
+ flex-direction: column;
+ background: var(--epc-bg);
+ color: var(--epc-ink);
+ font-family: inherit;
+}
+
+.ep-storyboard-topbar {
+ flex-shrink: 0;
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 14px 18px;
+ background: rgba(255, 255, 255, 0.92);
+ border-bottom: 1px solid var(--epc-line);
+ backdrop-filter: blur(8px);
+ z-index: 2;
+}
+
+.ep-storyboard-topbar-left {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ min-width: 0;
+}
+
+.ep-storyboard-back {
+ width: 36px;
+ height: 36px;
+ border: none;
+ border-radius: 999px;
+ background: #f1f5f9;
+ color: var(--epc-ink);
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+}
+
+.ep-storyboard-back:hover {
+ background: #e2e8f0;
+}
+
+.ep-storyboard-title {
+ display: grid;
+ gap: 2px;
+ min-width: 0;
+}
+
+.ep-storyboard-title strong {
+ font-size: 14px;
+ font-weight: 600;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ep-storyboard-title span {
+ font-size: 12px;
+ color: var(--epc-muted);
+}
+
+.ep-storyboard-actions {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-shrink: 0;
+}
+
+.ep-storyboard-btn {
+ border: none;
+ border-radius: 999px;
+ height: 34px;
+ padding: 0 14px;
+ font-size: 13px;
+ cursor: pointer;
+}
+
+.ep-storyboard-btn.ghost {
+ background: #f1f5f9;
+ color: #334155;
+}
+
+.ep-storyboard-btn.dark {
+ background: #0f172a;
+ color: #fff;
+}
+
+.ep-storyboard-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.ep-storyboard-flow {
+ flex: 1;
+ min-height: 0;
+ position: relative;
+}
+
+.ep-storyboard-flow .react-flow__attribution {
+ display: none;
+}
+
+.ep-storyboard-flow .react-flow__edge-path {
+ stroke: #94a3b8;
+ stroke-width: 2;
+}
+
+.ep-storyboard-empty {
+ position: absolute;
+ inset: 0;
+ display: grid;
+ place-content: center;
+ gap: 8px;
+ text-align: center;
+ color: var(--epc-muted);
+ z-index: 1;
+ pointer-events: none;
+}
+
+.ep-storyboard-toast {
+ position: absolute;
+ left: 50%;
+ bottom: 24px;
+ transform: translateX(-50%);
+ z-index: 5;
+ margin: 0;
+ padding: 8px 14px;
+ border-radius: 999px;
+ background: #0f172a;
+ color: #fff;
+ font-size: 12px;
+ box-shadow: 0 8px 24px rgba(15, 23, 42, 0.18);
+}
+
+/* —— 分镜节点:视频在上,提示词在下 —— */
+.ep-frag-node {
+ width: 220px;
+ border-radius: 16px;
+ background: var(--epc-panel);
+ border: 1px solid var(--epc-line);
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06), 0 8px 24px rgba(15, 23, 42, 0.04);
+ overflow: hidden;
+}
+
+.ep-frag-node.is-selected {
+ outline: 2px solid #111;
+ outline-offset: 2px;
+}
+
+.ep-frag-node-head {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ padding: 8px 10px;
+ font-size: 12px;
+ font-weight: 600;
+ color: #334155;
+ border-bottom: 1px solid var(--epc-line);
+ background: #fafafa;
+}
+
+.ep-frag-node-head > span {
+ flex: 1;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ep-frag-link-btn {
+ width: 22px;
+ height: 22px;
+ border: none;
+ border-radius: 999px;
+ background: #0f172a;
+ color: #fff;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+ flex-shrink: 0;
+}
+
+.ep-frag-link-count {
+ font-style: normal;
+ font-size: 11px;
+ font-weight: 500;
+ color: #94a3b8;
+ flex-shrink: 0;
+}
+
+.ep-frag-media {
+ aspect-ratio: 9 / 16;
+ background: #111;
+ display: grid;
+ place-items: center;
+ overflow: hidden;
+}
+
+.ep-frag-media img,
+.ep-frag-video {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: block;
+ background: #111;
+}
+
+.ep-frag-media-empty {
+ color: #94a3b8;
+ text-align: center;
+ display: grid;
+ gap: 4px;
+ font-size: 12px;
+ padding: 12px;
+}
+
+.ep-frag-media-empty small {
+ font-size: 11px;
+ opacity: 0.8;
+}
+
+.ep-asset-node {
+ width: 148px;
+ border-radius: 14px;
+ background: #fff;
+ border: 1px solid var(--epc-line);
+ box-shadow: 0 1px 3px rgba(15, 23, 42, 0.06);
+ overflow: hidden;
+}
+
+.ep-asset-node.is-selected {
+ outline: 2px solid #111;
+ outline-offset: 2px;
+}
+
+.ep-asset-node-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 6px;
+ padding: 6px 8px;
+ font-size: 11px;
+ font-weight: 600;
+ color: #64748b;
+ background: #f8fafc;
+ border-bottom: 1px solid var(--epc-line);
+}
+
+.ep-asset-node-unlink {
+ width: 18px;
+ height: 18px;
+ border: none;
+ border-radius: 999px;
+ background: rgba(15, 23, 42, 0.8);
+ color: #fff;
+ display: grid;
+ place-items: center;
+ cursor: pointer;
+ padding: 0;
+}
+
+.ep-asset-node-thumb {
+ aspect-ratio: 3 / 4;
+ background: #e2e8f0;
+ overflow: hidden;
+}
+
+.ep-asset-node-thumb img,
+.ep-asset-node-thumb span {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: grid;
+ place-items: center;
+ font-size: 22px;
+ font-weight: 700;
+ color: #94a3b8;
+}
+
+.ep-asset-node-name {
+ padding: 6px 8px;
+ font-size: 12px;
+ color: #334155;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ep-frag-prompt {
+ display: grid;
+ gap: 6px;
+ padding: 10px;
+ border-top: 1px solid var(--epc-line);
+ background: #fff;
+}
+
+.ep-frag-prompt label {
+ font-size: 11px;
+ font-weight: 600;
+ color: #64748b;
+}
+
+.ep-frag-prompt-text {
+ margin: 0;
+ min-height: 96px;
+ max-height: 140px;
+ overflow: auto;
+ font-size: 12px;
+ line-height: 1.45;
+ color: #334155;
+ white-space: pre-wrap;
+ word-break: break-word;
+}
+
+.ep-frag-prompt-input {
+ width: 100%;
+ min-height: 110px;
+ resize: vertical;
+ border: 1px solid #e2e8f0;
+ border-radius: 10px;
+ padding: 8px;
+ font: inherit;
+ font-size: 12px;
+ line-height: 1.45;
+ color: #0f172a;
+ background: #f8fafc;
+}
+
+.ep-frag-prompt-input:focus {
+ outline: 2px solid rgba(15, 23, 42, 0.2);
+ outline-offset: 0;
+ background: #fff;
+}
+
+.ep-frag-handle {
+ width: 10px !important;
+ height: 10px !important;
+ background: #0f172a !important;
+ border: 2px solid #fff !important;
+}
+
+.ep-storyboard-picker-hint {
+ margin: 0 0 12px;
+ font-size: 13px;
+ color: #64748b;
+}
+
+.ep-storyboard-picker-empty {
+ margin: 12px 0;
+ font-size: 13px;
+ color: #94a3b8;
+ text-align: center;
+}
+
+.ep-storyboard-picker-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 10px;
+ max-height: min(56vh, 480px);
+ overflow: auto;
+ padding-bottom: 4px;
+}
+
+.ep-storyboard-picker-card {
+ border: 1px solid #e2e8f0;
+ border-radius: 12px;
+ background: #fff;
+ padding: 0;
+ overflow: hidden;
+ text-align: left;
+ cursor: pointer;
+}
+
+.ep-storyboard-picker-card:hover {
+ border-color: #94a3b8;
+}
+
+.ep-storyboard-picker-thumb {
+ aspect-ratio: 3 / 4;
+ background: #f1f5f9;
+ overflow: hidden;
+}
+
+.ep-storyboard-picker-thumb img,
+.ep-storyboard-picker-thumb span {
+ width: 100%;
+ height: 100%;
+ object-fit: cover;
+ display: grid;
+ place-items: center;
+ font-size: 22px;
+ font-weight: 700;
+ color: #cbd5e1;
+}
+
+.ep-storyboard-picker-card strong {
+ display: block;
+ padding: 6px 8px 0;
+ font-size: 12px;
+ color: #0f172a;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.ep-storyboard-picker-card em {
+ display: block;
+ padding: 2px 8px 8px;
+ font-style: normal;
+ font-size: 11px;
+ color: #94a3b8;
+}
diff --git a/frontend/src/styles/printfilm.css b/frontend/src/styles/printfilm.css
index ee7b1ac..b4051af 100644
--- a/frontend/src/styles/printfilm.css
+++ b/frontend/src/styles/printfilm.css
@@ -3018,14 +3018,20 @@ button.pf-shot-editable:disabled {
border-radius: 14px;
display: grid;
place-items: center;
- font-family: 'Noto Serif SC', Georgia, serif;
- font-size: 1.35rem;
- font-weight: 600;
background: var(--pf-lime-soft);
color: #3d6500;
border: 1px solid rgba(182, 255, 0, 0.45);
position: relative;
z-index: 1;
+ flex-shrink: 0;
+}
+
+.pf-dialog-header {
+ position: relative;
+ z-index: 1;
+ display: flex;
+ align-items: flex-start;
+ gap: 0.85rem;
}
.pf-dialog--danger .pf-dialog-mark {
@@ -3045,17 +3051,18 @@ button.pf-shot-editable:disabled {
z-index: 1;
display: flex;
flex-direction: column;
- gap: 0.45rem;
+ gap: 0.35rem;
+ min-width: 0;
+ flex: 1;
}
.pf-dialog-title {
margin: 0;
- font-family: 'Noto Serif SC', Georgia, serif;
- font-size: 1.35rem;
- font-weight: 500;
+ font-size: 1.15rem;
+ font-weight: 700;
letter-spacing: -0.02em;
color: var(--pf-ink);
- line-height: 1.25;
+ line-height: 1.3;
}
.pf-dialog-message {
@@ -3066,7 +3073,9 @@ button.pf-shot-editable:disabled {
}
.pf-dialog-input {
- margin-top: 0.35rem;
+ position: relative;
+ z-index: 1;
+ margin-top: 0;
border: 1px solid var(--pf-line);
border-radius: 10px;
padding: 0.65rem 0.8rem;