PRINTFILM: AI short-video marketing and AI short-drama creation platform
Fix drama portrait video i2v fallback and ship subtitle/output settings.
yi6ffb3942e4ab
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.pyindex 8bb35f0..769539e 100644--- a/backend/app/api/drama/episodes.py+++ b/backend/app/api/drama/episodes.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport loggingimport uuid+from datetime import UTC, datetimefrom fastapi import APIRouter, Depends, HTTPExceptionfrom sqlalchemy import select@@ -17,6 +18,7 @@ from app.models_drama import DramaEpisode, DramaEpisodeFragment, DramaFragmentAsfrom app.schemas_drama import (DramaActivateVideoVersionRequest,DramaEpisodeOut,+ DramaEpisodeUpdate,DramaFragmentOut,DramaGenerateRequest,DramaPlanFragmentsRequest,@@ -195,6 +197,22 @@ async def get_episode(return await _episode_out_with_tasks(db, user, ep)[email protected]("/episodes/{episode_id}", response_model=DramaEpisodeOut)+async def update_episode(+ episode_id: int,+ body: DramaEpisodeUpdate,+ db: AsyncSession = Depends(get_db),+ user: User = Depends(get_current_user),+) -> DramaEpisodeOut:+ ep = await get_owned_episode(db, episode_id, user)+ if body.name is not None:+ ep.name = body.name.strip() or ep.name+ if body.params is not None:+ ep.params = body.params+ await db.commit()+ return await _episode_out_with_tasks(db, user, ep)++@router.post("/episodes/{episode_id}/plan_fragments", response_model=DramaEpisodeOut)async def plan_episode_fragments(episode_id: int,@@ -232,6 +250,9 @@ async def plan_episode_fragments(params["fragment_plan_status"] = "generating"params.pop("fragment_plan_error", None)params["fragment_plan_mode"] = "llm"+ if req.subtitle_enabled is not None:+ params["subtitleEnabled"] = bool(req.subtitle_enabled)+ params["subtitleMode"] = "model" if bool(req.subtitle_enabled) else "post"if req.skill_ids is None:params.pop("fragment_plan_skill_ids", None)else:@@ -253,6 +274,7 @@ async def plan_episode_fragments("fallback_rules": bool(req.fallback_rules),"force": bool(req.force),"skill_ids": parse_skill_ids(req.skill_ids) if req.skill_ids is not None else None,+ "subtitle_enabled": bool(req.subtitle_enabled) if req.subtitle_enabled is not None else None,},drama_project_id=ep.project_id,episode_id=episode_id,@@ -451,11 +473,11 @@ async def generate_episode(sequential = project_link_last_frame_enabled(project)frag_ids = [f.id for f in idle_frags]batch_key = f"drama:episode:{episode_id}:video:{uuid.uuid4().hex[:12]}"+ queued_at = datetime.now(UTC).isoformat()for f in idle_frags:params = dict(f.params or {})- params["generation"] = {"status": "queued"}+ params["generation"] = {"status": "queued", "queued_at": queued_at, "message": "已入队"}f.params = params- await db.commit()created_tasks: list[int] = []deferred_count = 0@@ -467,6 +489,7 @@ async def generate_episode(defer_activation = index >= activate_slotsif defer_activation:deferred_count += 1+ has_video = bool((f.video or "").strip())task = await create_task(db,user,@@ -483,6 +506,7 @@ async def generate_episode("sequential": sequential,"batch_key": batch_key,"batch_index": index,+ "replace_existing_video": has_video,},drama_project_id=ep.project_id,episode_id=episode_id,@@ -493,8 +517,10 @@ async def generate_episode(TaskTargetBind(target_type="fragment", target_id=f.id, sort_order=index),],),+ commit=False,)created_tasks.append(task.id)+ await db.commit()logger.info("已创建分集视频任务 episode_id=%s project_id=%s fragments=%s activated=%s deferred=%s task_ids=%s",episode_id,diff --git a/backend/app/api/drama/projects.py b/backend/app/api/drama/projects.pyindex 892bec6..523e083 100644--- a/backend/app/api/drama/projects.py+++ b/backend/app/api/drama/projects.py@@ -20,6 +20,7 @@ from app.schemas_drama import (DramaScriptOut,)from app.services.drama.access import get_owned_drama_project+from app.services.drama.generation import project_link_last_frame_enabledfrom app.services.drama.project_cover import resolve_drama_project_coverfrom app.services.drama.usage_stats import (aggregate_drama_usage_by_project_ids,@@ -27,6 +28,7 @@ from app.services.drama.usage_stats import (get_drama_project_usage,)from app.services.drama.workflow import build_project_params, resolve_drama_workflow+from app.services.tasks.service import rebalance_project_fragment_video_queuerouter = APIRouter()@@ -166,6 +168,7 @@ async def update_project(user: User = Depends(get_current_user),) -> DramaProjectOut:project = await get_owned_drama_project(db, project_id, user, with_script=True)+ prev_link = project_link_last_frame_enabled(project)if body.title is not None:project.title = body.title.strip() or project.titleif body.description is not None:@@ -175,6 +178,17 @@ async def update_project(if body.params is not None:project.params = body.paramsawait db.commit()++ # 镜间衔接开关变化时,动态重排仍排队的分镜视频任务+ next_link = project_link_last_frame_enabled(project)+ if body.params is not None and prev_link != next_link:+ await rebalance_project_fragment_video_queue(+ db,+ project_id,+ sequential=next_link,+ user_id=user.id,+ )+project = await get_owned_drama_project(db, project_id, user, with_script=True, with_assets=True, with_episodes=True)diff --git a/backend/app/schemas_drama.py b/backend/app/schemas_drama.pyindex 52ae7b9..2231ed3 100644--- a/backend/app/schemas_drama.py+++ b/backend/app/schemas_drama.py@@ -104,6 +104,11 @@ class DramaEpisodeOut(BaseModel):model_config = {"from_attributes": True}+class DramaEpisodeUpdate(BaseModel):+ name: str | None = None+ params: dict | None = None++class DramaProjectOut(BaseModel):id: intuser_id: int@@ -251,6 +256,8 @@ class DramaPlanFragmentsRequest(BaseModel):fallback_rules: bool = True# skill_ids 本次注入的 Agent Skill;None 表示全部启用,[] 表示不注入skill_ids: list[int] | None = None+ # subtitle_enabled 是否为本次分镜注入字幕提示;None 表示沿用分集当前设置+ subtitle_enabled: bool | None = Noneclass DramaActivateVideoVersionRequest(BaseModel):diff --git a/backend/app/services/drama/asset_video.py b/backend/app/services/drama/asset_video.pyindex 532ecf8..b50d741 100644--- a/backend/app/services/drama/asset_video.py+++ b/backend/app/services/drama/asset_video.py@@ -13,6 +13,7 @@ from app.models import Userfrom app.models_drama import DramaAsset, DramaProjectfrom app.services.ark import get_arkfrom app.services.billing import record_usage+from app.services.drama.billing_util import seedance_video_billing_tokensfrom app.services.drama.build_seedance_generate_body import (build_seedance_generate_body,drama_asset_to_payload,@@ -154,6 +155,7 @@ async def generate_asset_video(drama_project_id=project.id,billing_key="seedance2:video0",model=settings.model_video,+ tokens=seedance_video_billing_tokens(duration),estimated=True,)await db.commit()diff --git a/backend/app/services/drama/billing_util.py b/backend/app/services/drama/billing_util.pynew file mode 100644index 0000000..1f61ab7--- /dev/null+++ b/backend/app/services/drama/billing_util.py@@ -0,0 +1,12 @@+"""漫剧计费辅助:统一 Seedance 等 token 估算。"""++from __future__ import annotations++from app.config import get_settings+++# 按分镜时长估算 Seedance 视频 token(与科普 pipeline 一致)+def seedance_video_billing_tokens(duration_sec: int | float | None) -> int:+ settings = get_settings()+ dur = max(float(duration_sec or 8), 2.0)+ return int(dur * settings.billing_est_seedance_tokens_per_sec)diff --git a/backend/app/services/drama/build_fragments.py b/backend/app/services/drama/build_fragments.pyindex 396e031..d91cd04 100644--- a/backend/app/services/drama/build_fragments.py+++ b/backend/app/services/drama/build_fragments.py@@ -610,17 +610,32 @@ def _is_important_character(return True+def _strip_subtitle_instruction(line: str) -> str:+ # 关闭字幕时移除正文中的同步字幕提示,保留对白/旁白本身。+ trimmed = (line or "").strip()+ replacements = {+ DIALOGUE_PREFIX: "【对白·慢速清晰】",+ "【旁白·慢速清晰·同步字幕】": "【旁白·慢速清晰】",+ "【内心独白·同步字幕】": "【内心独白】",+ }+ for src, dest in replacements.items():+ if trimmed.startswith(src):+ return trimmed.replace(src, dest, 1)+ return trimmed++def _build_production_cues(location_line: str | None,narrative_lines: list[str],character_intro_lines: list[str],+ *,+ include_subtitles: bool = True,) -> list[str]:# 字幕 / BGM / 人物介绍前置提示(字幕 cue 不含「旁白」字样,避免 Seedance 整镜念白)hint = " ".join(filter(None, [location_line or "", *narrative_lines[:3]]))- lines = [- DRAMA_SUBTITLE_CUE,- f"【BGM:{_infer_bgm_mood(hint)};音量低于人声】",- ]+ lines = [f"【BGM:{_infer_bgm_mood(hint)};音量低于人声】"]+ if include_subtitles:+ lines.insert(0, DRAMA_SUBTITLE_CUE)lines.extend(character_intro_lines)return lines@@ -701,6 +716,8 @@ def plan_fragments_from_scene(scene_asset_id: int | None,character_bindings: list[dict[str, Any]],introduced: set[str] | None = None,+ *,+ include_subtitles: bool = True,) -> list[tuple[str, int]]:"""规划单场视频向分镜正文;超软上限时拆成多条,避免截断后半场。@@ -717,7 +734,12 @@ def plan_fragments_from_scene(for b in character_bindingsif b.get("important") and b.get("introText") and str(b.get("name") or "").strip()]- base_cues = _build_production_cues(location_line, narrative_lines, [])+ base_cues = _build_production_cues(+ location_line,+ narrative_lines,+ [],+ include_subtitles=include_subtitles,+ )# timed_blocks 待打包的 (时长, 文本行列表)timed_blocks: list[tuple[int, list[str]]] = []@@ -738,6 +760,8 @@ def plan_fragments_from_scene(for line in narrative_lines:raw = _inject_character_mentions(line, character_bindings)formatted = _format_narrative_line(raw)+ if not include_subtitles:+ formatted = _strip_subtitle_instruction(formatted)line_dur = _clamp_duration(_estimate_line_duration(formatted))if line_dur <= 0:continue@@ -749,6 +773,7 @@ def plan_fragments_from_scene(location_line,narrative_lines,_build_character_intro_lines(to_intro),+ include_subtitles=include_subtitles,)for b in to_intro:introduced_names.add(str(b["name"]))@@ -897,9 +922,17 @@ def plan_fragment_content_from_scene(meta: dict[str, Any],scene_asset_id: int | None,character_bindings: list[dict[str, Any]],+ *,+ include_subtitles: bool = True,) -> tuple[str, int]:# 兼容旧调用:返回本场第一条分镜- chunks = plan_fragments_from_scene(body, meta, scene_asset_id, character_bindings)+ chunks = plan_fragments_from_scene(+ body,+ meta,+ scene_asset_id,+ character_bindings,+ include_subtitles=include_subtitles,+ )return chunks[0] if chunks else ("", FRAGMENT_DURATION_MIN)@@ -924,6 +957,8 @@ def build_fragments_from_episode_body(summary: dict[str, Any] | None = None,episode_bodies: list[str] | None = None,intro_overrides: dict[str, str] | None = None,+ *,+ include_subtitles: bool = True,) -> list[dict[str, Any]]:"""将一集正文拆成多场分镜草稿。@@ -994,6 +1029,7 @@ def build_fragments_from_episode_body(scene_asset_id,character_bindings,introduced,+ include_subtitles=include_subtitles,):# 规则切分:正文里出现的道具/素材名注入 @asset 并写入 asset_idsprop_bindings: list[dict[str, Any]] = []diff --git a/backend/app/services/drama/build_seedance_generate_body.py b/backend/app/services/drama/build_seedance_generate_body.pyindex 95c7a95..f4a661c 100644--- a/backend/app/services/drama/build_seedance_generate_body.py+++ b/backend/app/services/drama/build_seedance_generate_body.py@@ -425,7 +425,8 @@ def resolve_seedance_model_endpoint(model_id: str | None) -> str:def resolve_seedance_ratio(aspect_ratio: str | None) -> str:- return (aspect_ratio or "16:9").strip() or "16:9"+ # 与漫剧默认竖屏一致;缺失时不得回落到横屏 16:9+ return (aspect_ratio or "9:16").strip() or "9:16"def resolve_seedance_resolution(resolution: str | None) -> str:diff --git a/backend/app/services/drama/fragment_plan.py b/backend/app/services/drama/fragment_plan.pyindex 554814c..c828226 100644--- a/backend/app/services/drama/fragment_plan.py+++ b/backend/app/services/drama/fragment_plan.py@@ -12,6 +12,7 @@ from app.services.drama.build_fragments import (FRAGMENT_TOTAL_MAX,_build_character_intro_lines,_build_production_cues,+ _strip_subtitle_instruction,_clamp_duration,_estimate_line_duration,_find_asset_by_name,@@ -265,6 +266,7 @@ def normalize_llm_fragment_items(episode_bodies: list[str] | None = None,intro_overrides: dict[str, str] | None = None,allow_opening: bool = True,+ include_subtitles: bool = True,) -> list[dict[str, Any]]:"""将 LLM fragments 转为落库草稿。@@ -369,6 +371,8 @@ def normalize_llm_fragment_items(for line in lines:raw = _inject_character_mentions(line, inject_bindings)formatted = _format_narrative_line(raw)+ if not include_subtitles:+ formatted = _strip_subtitle_instruction(formatted)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))@@ -442,7 +446,12 @@ def normalize_llm_fragment_items(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])+ cues = _build_production_cues(+ None,+ body_lines[:3],+ [*opening_lines, *intro_lines],+ include_subtitles=include_subtitles,+ )content = "\n".join([*cues, *body_lines]).strip()duration = min(FRAGMENT_TOTAL_MAX, max(used, FRAGMENT_DURATION_MIN))drafts.append(@@ -508,6 +517,7 @@ async def plan_fragments_with_llm(db: Any | None = None,user_id: int | None = None,skill_ids: list[int] | None = None,+ include_subtitles: bool = True,) -> list[dict[str, Any]]:"""调用 LLM 规划分镜并规范化。@@ -530,6 +540,7 @@ async def plan_fragments_with_llm(synopsis=synopsis,core_hook=core_hook,locked_summaries=locked,+ include_subtitles=include_subtitles,)raw = await run_task_json(db,@@ -563,6 +574,7 @@ async def plan_fragments_with_llm(episode_bodies=episode_bodies,intro_overrides=intro_overrides,allow_opening=not bool(locked),+ include_subtitles=include_subtitles,)if not drafts:raise RuntimeError("LLM 分镜规范化后为空")diff --git a/backend/app/services/drama/fragment_plan_prompt.py b/backend/app/services/drama/fragment_plan_prompt.pyindex 123d4c1..a194f82 100644--- a/backend/app/services/drama/fragment_plan_prompt.py+++ b/backend/app/services/drama/fragment_plan_prompt.py@@ -92,6 +92,7 @@ def build_fragment_plan_user_prompt(synopsis: str | None = None,core_hook: str | None = None,locked_summaries: list[str] | None = None,+ include_subtitles: bool = True,) -> str:# 拼装用户侧:集号/背景元信息 + 分集正文 + 资产目录ep_no = int(episode_number or 0)@@ -101,6 +102,7 @@ def build_fragment_plan_user_prompt(f"剧名:{(project_title or '').strip() or '未命名短剧'}",f"集号:{ep_label}" + (f"(episodeNumber={ep_no})" if ep_no > 0 else ""),f"分集标题:{(episode_name or '').strip() or '未命名'}",+ f"字幕需求:{'需要字幕' if include_subtitles else '不要字幕'}","",]if locked:@@ -179,4 +181,13 @@ def build_fragment_plan_user_prompt("请输出 JSON:{\"fragments\":[...]};第一条必须是开幕镜(is_opening=true,含集号与背景介绍)。",])+ if not include_subtitles:+ lines.extend(+ [+ "",+ "【额外要求|本集不要字幕】",+ "- 只写画面、动作、对白、旁白本身,不要写任何“字幕 / 叠字 / 同步字幕 / 字卡”等提示。",+ "- 开幕镜也不要设计集号、剧名、背景介绍的叠字,只用画面与对白/旁白表达。",+ ]+ )return "\n".join(lines)diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.pyindex 28277bc..aef0181 100644--- a/backend/app/services/drama/generation.py+++ b/backend/app/services/drama/generation.py@@ -5,6 +5,7 @@ from __future__ import annotationsimport loggingimport timefrom dataclasses import dataclass+from datetime import UTC, datetimefrom pathlib import Pathfrom typing import Any@@ -13,8 +14,14 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.config import get_settingsfrom app.models import User-from app.models_drama import DramaAsset, DramaEpisodeFragment, DramaFragmentAssetRef, DramaProject+from app.models_drama import DramaAsset, DramaEpisode, DramaEpisodeFragment, DramaFragmentAssetRef, DramaProjectfrom app.services.ark import get_ark+from app.services.drama.billing_util import seedance_video_billing_tokens+from app.services.drama.output_settings import (+ infer_aspect_ratio_from_pixels,+ resolve_episode_video_output,+ seedream_still_size_for_video_ratio,+)from app.services.billing import record_usagefrom app.services.drama.build_seedance_generate_body import (ASSET_MENTION_TOKEN_PATTERN,@@ -76,6 +83,51 @@ def write_fragment_last_frame_url(fragment: DramaEpisodeFragment, url: str | Nonfragment.params = params+# 写入分镜成片输出规格(配置 + 实际像素),供前端展示与拼接校验+def write_fragment_video_output_meta(+ fragment: DramaEpisodeFragment,+ *,+ aspect_ratio: str,+ resolution: str,+ video_path: Path | str | None = None,+) -> None:+ from app.services import storage as storage_svc+ from app.services.ffmpeg_compose import probe_video_dimensions++ params = dict(fragment.params or {}) if isinstance(fragment.params, dict) else {}+ width = 0+ height = 0+ path = video_path if isinstance(video_path, Path) else None+ if path is None and isinstance(video_path, str) and video_path.strip():+ path = storage_svc.local_path_from_url(video_path.strip())+ if path is None and not video_path.strip().startswith("http"):+ candidate = Path(video_path.strip())+ if candidate.exists():+ path = candidate+ if path and path.exists():+ dims = probe_video_dimensions(path)+ if dims:+ width, height = dims+ ratio_label = (+ infer_aspect_ratio_from_pixels(width, height)+ if width > 0 and height > 0+ else aspect_ratio+ )+ params["aspect_ratio"] = ratio_label+ params["resolution"] = resolution+ if width > 0 and height > 0:+ params["video_width"] = width+ params["video_height"] = height+ gen = dict(params.get("generation") or {}) if isinstance(params.get("generation"), dict) else {}+ gen["aspect_ratio"] = ratio_label+ gen["resolution"] = resolution+ if width > 0 and height > 0:+ gen["video_width"] = width+ gen["video_height"] = height+ params["generation"] = gen+ fragment.params = params++# 项目是否开启「上一镜尾帧 → 本镜首帧」衔接(默认关闭)def project_link_last_frame_enabled(project: DramaProject) -> bool:params = project.params if isinstance(project.params, dict) else {}@@ -267,15 +319,31 @@ def activate_fragment_video_version(fragment.cover = str(target.get("cover") or "")[:1024]last_frame = str(target.get("lastFrameUrl") or "").strip() or Nonewrite_fragment_last_frame_url(fragment, last_frame)+ from app.services import storage as storage_svc+params = dict(fragment.params or {})params["video_versions"] = remaining[:FRAGMENT_VIDEO_VERSION_LIMIT]- params["generation"] = {+ fragment.params = params+ ratio = str(target.get("aspect_ratio") or params.get("aspect_ratio") or "9:16")+ resolution = str(target.get("resolution") or params.get("resolution") or "480p")+ video_path = storage_svc.local_path_from_url(target_video)+ write_fragment_video_output_meta(+ fragment,+ aspect_ratio=ratio,+ resolution=resolution,+ video_path=video_path or target_video,+ )+ params = dict(fragment.params or {})+ gen = dict(params.get("generation") or {}) if isinstance(params.get("generation"), dict) else {}+ gen.update({"status": "done","video": fragment.video,"cover": fragment.cover,"lastFrameUrl": last_frame,"restoredFrom": version_id,- }+ })+ params["generation"] = gen+ params["video_versions"] = remaining[:FRAGMENT_VIDEO_VERSION_LIMIT]fragment.params = paramsreturn {"fragment_id": fragment.id,@@ -286,6 +354,27 @@ def activate_fragment_video_version(}+# 入队后、任务列表尚未可见时,保留 queued,避免被当成孤儿清掉+_ORPHAN_QUEUE_GRACE_SEC = 60+++# 判断 generation.queued_at 是否仍在宽限期内+def generation_queued_recently(gen: dict[str, Any] | None, *, now: datetime | None = None) -> bool:+ if not isinstance(gen, dict):+ return False+ raw = str(gen.get("queued_at") or "").strip()+ if not raw:+ return False+ try:+ ts = datetime.fromisoformat(raw.replace("Z", "+00:00"))+ except ValueError:+ return False+ if ts.tzinfo is None:+ ts = ts.replace(tzinfo=UTC)+ current = now or datetime.now(UTC)+ return (current - ts).total_seconds() < _ORPHAN_QUEUE_GRACE_SEC++# 无对应平台任务时,把 queued/running 分镜恢复为 idle,避免假排队async def reconcile_orphaned_fragment_generations(db: AsyncSession,@@ -300,6 +389,9 @@ async def reconcile_orphaned_fragment_generations(if fragment.id in active_fragment_ids:continueparams = dict(fragment.params or {})+ gen = params.get("generation") if isinstance(params.get("generation"), dict) else None+ if generation_queued_recently(gen if isinstance(gen, dict) else None):+ continueparams.pop("generation_attempts", None)params["generation"] = {"status": "idle",@@ -785,6 +877,11 @@ async def generate_fragment_video(prompt = (fragment.content or "").strip() or "短剧分镜"duration = int(fragment.duration_sec or 8)duration = max(settings.seedance_duration_min, min(duration, settings.seedance_duration_max))+ episode = await db.get(DramaEpisode, fragment.episode_id)+ ratio, resolution = resolve_episode_video_output(+ episode.params if episode else None,+ project.params,+ )refs = (await db.execute(@@ -833,9 +930,6 @@ async def generate_fragment_video(local_last_frame: str | None = Noneif 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,@@ -859,7 +953,6 @@ async def generate_fragment_video(content_labels=content_labels,)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,@@ -870,8 +963,21 @@ async def generate_fragment_video(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)+ still = await ark.gen_image(+ prompt[:500],+ project_id=project.id,+ shot_no=fragment.id,+ size=seedream_still_size_for_video_ratio(ratio),+ )+ await record_usage(+ db,+ user_id=user.id,+ project_id=None,+ drama_project_id=project.id,+ billing_key="seedream",+ model=settings.model_image,+ estimated=True,+ )image_url = still.local_url or ""local_video = await ark.gen_and_wait_video(still.local_url,@@ -906,9 +1012,16 @@ async def generate_fragment_video(last_frame_url = storage_svc.republish_url(local_last_frame, sync=True) or local_last_frameif not cover_url:cover_url = last_frame_url+ archive_fragment_video_version(fragment)fragment.video = video_urlfragment.cover = cover_url or ""write_fragment_last_frame_url(fragment, last_frame_url)+ write_fragment_video_output_meta(+ fragment,+ aspect_ratio=ratio,+ resolution=resolution,+ video_path=video_path,+ )await record_usage(db,user_id=user.id,@@ -916,6 +1029,7 @@ async def generate_fragment_video(drama_project_id=project.id,billing_key="seedance2:video0",model=settings.model_video,+ tokens=seedance_video_billing_tokens(fragment.duration_sec),estimated=True,)await db.commit()@@ -964,8 +1078,11 @@ async def prepare_fragment_video_for_submit(prompt = (fragment.content or "").strip() or "短剧分镜"duration = int(fragment.duration_sec or 8)duration = max(settings.seedance_duration_min, min(duration, settings.seedance_duration_max))- ratio = str((project.params or {}).get("aspect_ratio") or "").strip() or "9:16"- resolution = str((project.params or {}).get("resolution") or "").strip() or "480p"+ episode = await db.get(DramaEpisode, fragment.episode_id)+ ratio, resolution = resolve_episode_video_output(+ episode.params if episode else None,+ project.params,+ )refs = (await db.execute(@@ -1036,7 +1153,13 @@ async def prepare_fragment_video_for_submit(ark = get_ark()if not image_url:- still = await ark.gen_image(prompt[:500], project_id=project.id, shot_no=fragment.id)+ # Seedance i2v 禁止传 ratio,输出跟首帧;静帧必须先按目标画幅生成+ still = await ark.gen_image(+ prompt[:500],+ project_id=project.id,+ shot_no=fragment.id,+ size=seedream_still_size_for_video_ratio(ratio),+ )image_url = still.local_url or ""return FragmentVideoPrepared(@@ -1159,16 +1282,29 @@ async def apply_fragment_video_assets(fragment.video = video_urlfragment.cover = cover_url or ""write_fragment_last_frame_url(fragment, last_frame_url)+ episode = await db.get(DramaEpisode, fragment.episode_id)+ ratio, resolution = resolve_episode_video_output(+ episode.params if episode else None,+ project.params,+ )+ write_fragment_video_output_meta(+ fragment,+ aspect_ratio=ratio,+ resolution=resolution,+ video_path=video_path,+ )params = dict(fragment.params or {})params.pop("generation_attempts", None)- params["generation"] = {+ gen = dict(params.get("generation") or {}) if isinstance(params.get("generation"), dict) else {}+ gen.update({"status": "done","video": fragment.video,"cover": fragment.cover,"lastFrameUrl": last_frame_url or None,"attempts": attempts,"attempt_limit": attempt_limit,- }+ })+ params["generation"] = genif last_frame_url:params["lastFrameUrl"] = last_frame_urlfragment.params = params@@ -1179,6 +1315,7 @@ async def apply_fragment_video_assets(drama_project_id=project.id,billing_key="seedance2:video0",model=settings.model_video,+ tokens=seedance_video_billing_tokens(fragment.duration_sec),estimated=True,)await db.commit()diff --git a/backend/app/services/drama/jobs.py b/backend/app/services/drama/jobs.pyindex eb1550e..582a14a 100644--- a/backend/app/services/drama/jobs.py+++ b/backend/app/services/drama/jobs.py@@ -341,6 +341,18 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[}script.params = paramsawait db.commit()+ user = await db.get(User, project.user_id)+ if user:+ await record_usage(+ db,+ user_id=user.id,+ project_id=None,+ drama_project_id=project.id,+ billing_key="llm_chat",+ model=get_settings().model_llm,+ estimated=True,+ )+ await db.commit()await db.refresh(script)content = script.episode_contentif isinstance(content, dict) and isinstance(content.get("episodes"), list):@@ -366,17 +378,6 @@ async def run_episode_scripts_job(project_id: int, force: bool = False) -> dict[params["episode_count"] = totalparams["episode_content_progress"] = {"done": total, "total": total}script.params = params- user = await db.get(User, project.user_id)- if user:- await record_usage(- db,- user_id=user.id,- project_id=None,- drama_project_id=project.id,- billing_key="llm_chat",- model=get_settings().model_llm,- estimated=True,- )await db.commit()logger.info("分集剧本全部完成 project_id=%s total=%s", project_id, total)return {"ok": True, "project_id": project_id, "total": total}@@ -410,6 +411,7 @@ async def run_episode_fragment_plan_job(episode_id: int,*,fallback_rules: bool = True,+ subtitle_enabled: bool | None = None,) -> dict[str, Any]:# Worker:LLM 规划本集分镜并落库;失败可选回退规则切分from app.services.drama.build_fragments import build_fragments_from_episode_body@@ -464,6 +466,22 @@ async def run_episode_fragment_plan_job()siblings = list(siblings_result.scalars().all())ep_params = episode.params if isinstance(episode.params, dict) else {}+ raw_subtitles = (+ subtitle_enabled+ if subtitle_enabled is not None+ else (+ False+ if ep_params.get("subtitleMode") == "post"+ else True if ep_params.get("subtitleMode") == "model" else ep_params.get("subtitleEnabled", True)+ )+ )+ if isinstance(raw_subtitles, str):+ normalized = raw_subtitles.strip().lower()+ include_subtitles = normalized not in {"0", "false", "no", "off", ""}+ elif isinstance(raw_subtitles, (int, float)):+ include_subtitles = raw_subtitles != 0+ else:+ include_subtitles = raw_subtitles is not Falseep_no = int(ep_params.get("episodeNumber") or 0) or Nonefrom app.services.agent.compose import parse_skill_ids@@ -534,6 +552,7 @@ async def run_episode_fragment_plan_job(db=db,user_id=project.user_id,skill_ids=skill_ids,+ include_subtitles=include_subtitles,)except (DramaLlmUnavailableError, RuntimeError, Exception) as exc: # noqa: BLE001logger.exception("LLM 分镜失败 episode_id=%s err=%s", episode_id, exc)@@ -551,6 +570,7 @@ async def run_episode_fragment_plan_job(summary=summary,episode_bodies=all_bodies,intro_overrides=intro_overrides,+ include_subtitles=include_subtitles,)mode_used = "rules_fallback"continuation = False@@ -572,6 +592,17 @@ async def run_episode_fragment_plan_job(params["fragment_plan_count"] = len(protected_frags) + len(drafts)params["fragment_plan_preserved"] = len(protected_frags)episode.params = params+ user = await db.get(User, project.user_id)+ if user:+ await record_usage(+ db,+ user_id=user.id,+ project_id=None,+ drama_project_id=project.id,+ billing_key="llm_chat",+ model=get_settings().model_llm,+ estimated=True,+ )await db.commit()logger.info("单集分镜完成 episode_id=%s mode=%s new=%s preserved=%s continuation=%s",diff --git a/backend/app/services/drama/output_settings.py b/backend/app/services/drama/output_settings.pynew file mode 100644index 0000000..9b0613a--- /dev/null+++ b/backend/app/services/drama/output_settings.py@@ -0,0 +1,78 @@+"""漫剧输出规格:分集 params 优先,回退项目 params。"""++from __future__ import annotations++from typing import Any++VALID_RATIOS = frozenset({"9:16", "16:9", "1:1"})+VALID_RESOLUTIONS = frozenset({"480p", "720p", "1080p"})+++def _pick_ratio(raw: Any) -> str | None:+ value = str(raw or "").strip()+ return value if value in VALID_RATIOS else None+++def _pick_resolution(raw: Any) -> str | None:+ value = str(raw or "").strip()+ return value if value in VALID_RESOLUTIONS else None+++# 解析分集画幅与清晰度(分集 → 项目 → 默认)+def resolve_episode_video_output(+ episode_params: dict | None,+ project_params: dict | None,+) -> tuple[str, str]:+ ep = episode_params if isinstance(episode_params, dict) else {}+ proj = project_params if isinstance(project_params, dict) else {}+ ratio = _pick_ratio(ep.get("aspect_ratio")) or _pick_ratio(proj.get("aspect_ratio")) or "9:16"+ resolution = (+ _pick_resolution(ep.get("resolution"))+ or _pick_resolution(proj.get("resolution"))+ or "480p"+ )+ return ratio, resolution+++# Seedance / 成片常用像素(偶数边)+_RATIO_RES_PIXELS: dict[tuple[str, str], tuple[int, int]] = {+ ("9:16", "480p"): (480, 854),+ ("9:16", "720p"): (720, 1280),+ ("9:16", "1080p"): (1080, 1920),+ ("16:9", "480p"): (854, 480),+ ("16:9", "720p"): (1280, 720),+ ("16:9", "1080p"): (1920, 1080),+ ("1:1", "480p"): (480, 480),+ ("1:1", "720p"): (720, 720),+ ("1:1", "1080p"): (1080, 1080),+}+++# 分集目标成片宽高(用于拼接时统一缩放)+def target_pixel_size(aspect_ratio: str, resolution: str) -> tuple[int, int]:+ key = (aspect_ratio if aspect_ratio in VALID_RATIOS else "9:16",+ resolution if resolution in VALID_RESOLUTIONS else "480p")+ return _RATIO_RES_PIXELS.get(key, (480, 854))+++# 根据像素尺寸推断最接近的标准画幅标签+def infer_aspect_ratio_from_pixels(width: int, height: int) -> str:+ if width <= 0 or height <= 0:+ return "9:16"+ ratio = width / height+ candidates = (("9:16", 9 / 16), ("16:9", 16 / 9), ("1:1", 1.0))+ best = min(candidates, key=lambda item: abs(ratio - item[1]))+ if abs(ratio - best[1]) <= 0.08:+ return best[0]+ return f"{width}×{height}"+++# i2v 兜底静帧:按目标画幅生成,避免 Seedance「跟首帧比例」变成横屏+def seedream_still_size_for_video_ratio(aspect_ratio: str | None) -> str:+ ratio = _pick_ratio(aspect_ratio) or "9:16"+ mapping = {+ "9:16": "2304x4096",+ "16:9": "4096x2304",+ "1:1": "3072x3072",+ }+ return mapping.get(ratio, "2304x4096")diff --git a/backend/app/services/ffmpeg_compose.py b/backend/app/services/ffmpeg_compose.pyindex 63e95be..7b76dbb 100644--- a/backend/app/services/ffmpeg_compose.py+++ b/backend/app/services/ffmpeg_compose.py@@ -151,6 +151,43 @@ def probe_duration(path: Path) -> float | None:return None+def probe_video_dimensions(path: Path) -> tuple[int, int] | None:+ """读取视频宽高像素(ffprobe),失败返回 None。"""+ ffprobe = shutil.which(get_settings().ffprobe_path) or shutil.which("ffprobe")+ if not ffprobe or not path.exists():+ return None+ try:+ proc = subprocess.run(+ [+ ffprobe,+ "-v",+ "error",+ "-select_streams",+ "v:0",+ "-show_entries",+ "stream=width,height",+ "-of",+ "csv=p=0:s=x",+ str(path),+ ],+ capture_output=True,+ text=True,+ check=False,+ )+ if proc.returncode != 0:+ return None+ raw = (proc.stdout or "").strip()+ if "x" not in raw:+ return None+ w_str, h_str = raw.split("x", 1)+ width, height = int(w_str), int(h_str)+ if width <= 0 or height <= 0:+ return None+ return width, height+ except Exception: # noqa: BLE001+ return None++def is_near_silent_audio(path: Path, *, max_db: float = -70.0) -> bool:"""True when file missing/tiny or peak volume is below max_db (e.g. anullsrc)."""if not path.exists() or path.stat().st_size < 2000:diff --git a/backend/app/services/tasks/handlers.py b/backend/app/services/tasks/handlers.pyindex c6b0386..e9ecf68 100644--- a/backend/app/services/tasks/handlers.py+++ b/backend/app/services/tasks/handlers.py@@ -52,6 +52,7 @@ async def _run_drama_fragment_plan(task: TaskRun) -> dict[str, Any] | None:return await run_episode_fragment_plan_job(_require_int(task.episode_id, "episode_id"),fallback_rules=bool(payload.get("fallback_rules", True)),+ subtitle_enabled=payload.get("subtitle_enabled"),)diff --git a/backend/app/services/tasks/service.py b/backend/app/services/tasks/service.pyindex ea85ec1..e303bb9 100644--- a/backend/app/services/tasks/service.py+++ b/backend/app/services/tasks/service.py@@ -59,8 +59,14 @@ def build_task_step(task_id: int, step: TaskStepCreate) -> TaskStep:)-async def create_task(db: AsyncSession, user: User, body: TaskCreateRequest) -> TaskRun:- """Create a new task run and pre-plan its execution steps."""+async def create_task(+ db: AsyncSession,+ user: User,+ body: TaskCreateRequest,+ *,+ commit: bool = True,+) -> TaskRun:+ """创建任务并预写步骤。commit=False 时仅 flush,由调用方与业务状态同事务提交。"""await _validate_task_scope(db, user, body)handler = get_task_handler(body.domain, body.task_type)if handler is None:@@ -120,6 +126,8 @@ async def create_task(db: AsyncSession, user: User, body: TaskCreateRequest) ->),))+ if not commit:+ return taskawait db.commit()return await get_task_for_user(db, user, task.id)@@ -243,12 +251,16 @@ def task_fragment_ids(task: TaskRun) -> list[int]:# 判断分镜视频任务是否应作废;返回取消原因,None 表示保留。-def stale_pending_fragment_video_reason(frags: list[Any]) -> str | None:- """分镜已删 → 作废;全有成片且无进行中 generation → 跳过重复;否则保留(含重新生成)。"""+def stale_pending_fragment_video_reason(frags: list[Any], task: Any | None = None) -> str | None:+ """分镜已删 → 作废;全有成片且无进行中 generation、且非替换成片 → 跳过重复;否则保留。"""from app.services.drama.generation import fragment_generation_statusif not frags:return _STALE_FRAGMENT_REASON+ payload = getattr(task, "payload", None) if task is not None else None+ # 重新生成会保留旧 video,调度器不能当成重复任务取消+ if isinstance(payload, dict) and payload.get("replace_existing_video"):+ return Noneif not all((getattr(frag, "video", None) or "").strip() for frag in frags):return Nonefor frag in frags:@@ -337,7 +349,7 @@ async def reconcile_stale_pending_tasks(db: AsyncSession) -> int:if frag is not None:frags.append(frag)- reason = stale_pending_fragment_video_reason(frags)+ reason = stale_pending_fragment_video_reason(frags, task)if not reason:continue@@ -463,6 +475,170 @@ async def reconcile_sequential_batches(db: AsyncSession) -> int:return changed+# 镜间衔接开关切换后:只重排仍 pending 的分镜视频任务(已在跑的不动)。+async def rebalance_project_fragment_video_queue(+ db: AsyncSession,+ project_id: int,+ *,+ sequential: bool,+ user_id: int | None = None,+) -> dict[str, int]:+ from app.config import get_settings+ from app.services.drama.access import count_user_inflight_fragment_video_tasks++ stmt = select(TaskRun).where(+ TaskRun.drama_project_id == int(project_id),+ TaskRun.domain == "drama",+ TaskRun.task_type == "fragment_video",+ TaskRun.status.in_(("pending", "leased", "running", "awaiting_poll")),+ )+ tasks = list((await db.execute(stmt)).scalars().all())+ if not tasks:+ return {"pending": 0, "activated": 0, "deferred": 0}++ pending = [task for task in tasks if task.status == "pending" and not task.cancel_requested]+ active = [+ task+ for task in tasks+ if task.status in {"leased", "running", "awaiting_poll"} and not task.cancel_requested+ ]++ # 先统一改写 pending 的串行标记,供后续调度器按新模式激活+ for task in pending:+ payload = dict(task.payload or {}) if isinstance(task.payload, dict) else {}+ if bool(payload.get("sequential")) == bool(sequential):+ continue+ payload["sequential"] = bool(sequential)+ task.payload = payload++ activated = 0+ deferred = 0+ now = datetime.now(UTC)+ limit = max(1, int(get_settings().drama_user_video_job_limit or 12))+ owner_id = int(user_id or (pending[0].requested_by if pending else tasks[0].requested_by))++ if not sequential:+ # 关闭衔接:尽量把仍排队的 pending 激活到并发空位+ inflight = await count_user_inflight_fragment_video_tasks(db, owner_id)+ slots = max(0, limit - inflight)+ deferred_pending = [task for task in pending if task.next_action_at is None]+ for task in deferred_pending:+ if slots <= 0:+ deferred += 1+ continue+ task.next_action_at = now+ slots -= 1+ activated += 1+ await append_task_event(+ db,+ task.id,+ event_type="task.activated",+ status=task.status,+ phase=task.current_step_key,+ message="已关闭镜间衔接,恢复并发生成",+ )+ if activated or deferred or pending:+ await db.commit()+ return {"pending": len(pending), "activated": activated, "deferred": deferred}++ # 开启衔接:按分集镜序,只允许“当前最前未完成镜”占槽;其余 pending 收回激活+ frag_ids = {+ int(task.fragment_id)+ for task in pending + active+ if task.fragment_id is not None+ }+ sort_by_frag: dict[int, int] = {}+ episode_by_frag: dict[int, int] = {}+ if frag_ids:+ frag_rows = list(+ (+ await db.execute(+ select(DramaEpisodeFragment).where(DramaEpisodeFragment.id.in_(sorted(frag_ids)))+ )+ ).scalars().all()+ )+ for frag in frag_rows:+ sort_by_frag[int(frag.id)] = int(frag.sort_order or 0)+ episode_by_frag[int(frag.id)] = int(frag.episode_id)++ by_episode: dict[int, list[TaskRun]] = {}+ for task in pending + active:+ if task.fragment_id is None:+ continue+ ep_id = episode_by_frag.get(int(task.fragment_id)) or int(task.episode_id or 0)+ by_episode.setdefault(ep_id, []).append(task)++ heads_to_activate: list[TaskRun] = []+ for ep_id, ep_tasks in by_episode.items():+ ep_tasks.sort(+ key=lambda task: (+ sort_by_frag.get(int(task.fragment_id or 0), 10**9),+ int(task.id),+ )+ )+ head: TaskRun | None = None+ for task in ep_tasks:+ if task.status in {"leased", "running", "awaiting_poll"}:+ head = task+ break+ if task.status == "pending":+ head = task+ break+ for task in ep_tasks:+ if task.status != "pending":+ continue+ is_head = head is not None and int(task.id) == int(head.id) and head.status == "pending"+ if is_head:+ heads_to_activate.append(task)+ continue+ if task.next_action_at is not None:+ task.next_action_at = None+ deferred += 1+ await append_task_event(+ db,+ task.id,+ event_type="task.deferred",+ status=task.status,+ phase=task.current_step_key,+ message="已开启镜间衔接,后镜改回排队等待上一镜",+ )+ else:+ deferred += 1++ # 先 flush 收回后镜空位,再按并发上限激活各集当前首镜+ await db.flush()+ inflight = await count_user_inflight_fragment_video_tasks(db, owner_id)+ slots = max(0, limit - inflight)+ for task in heads_to_activate:+ if task.next_action_at is not None:+ continue+ if slots <= 0:+ deferred += 1+ continue+ task.next_action_at = now+ slots -= 1+ activated += 1+ await append_task_event(+ db,+ task.id,+ event_type="task.activated",+ status=task.status,+ phase=task.current_step_key,+ message="已开启镜间衔接,按镜序激活当前首镜",+ )++ await db.commit()+ logger.info(+ "rebalanced fragment_video queue project_id=%s sequential=%s pending=%s activated=%s deferred=%s",+ project_id,+ sequential,+ len(pending),+ activated,+ deferred,+ )+ return {"pending": len(pending), "activated": activated, "deferred": deferred}++# 统计用户当前占用 Worker 槽位的任务数(NIO:awaiting_poll 注册项不占槽)。async def count_user_active_runtime_tasks(db: AsyncSession, user_id: int) -> int:stmt = select(func.count()).select_from(TaskRun).where(diff --git a/backend/tests/test_drama_subtitle_toggle.py b/backend/tests/test_drama_subtitle_toggle.pynew file mode 100644index 0000000..363742b--- /dev/null+++ b/backend/tests/test_drama_subtitle_toggle.py@@ -0,0 +1,42 @@+"""分镜字幕开关:关闭时不再注入字幕 cue。"""++from app.services.drama.build_fragments import DRAMA_SUBTITLE_CUE, plan_fragments_from_scene+from app.services.drama.fragment_plan_prompt import build_fragment_plan_user_prompt+++def test_plan_fragments_from_scene_omits_subtitle_cue_when_disabled():+ chunks = plan_fragments_from_scene(+ "旁白:河岸边风声渐起。",+ meta={},+ scene_asset_id=None,+ character_bindings=[],+ include_subtitles=False,+ )+ content, _duration = chunks[0]+ assert DRAMA_SUBTITLE_CUE not in content+ assert "同步字幕" not in content+ assert "旁白" in content+++def test_plan_fragments_from_scene_omits_dialogue_subtitle_when_disabled():+ chunks = plan_fragments_from_scene(+ "阿禹:大家先后退。",+ meta={},+ scene_asset_id=None,+ character_bindings=[],+ include_subtitles=False,+ )+ content, _duration = chunks[0]+ assert "【对白·慢速清晰】" in content+ assert "同步字幕" not in content+++def test_fragment_plan_user_prompt_marks_no_subtitles():+ prompt = build_fragment_plan_user_prompt(+ episode_name="大禹治水",+ episode_body="禹来到河边。",+ asset_catalog=[],+ include_subtitles=False,+ )+ assert "字幕需求:不要字幕" in prompt+ assert "不要写任何“字幕 / 叠字 / 同步字幕 / 字卡”等提示" in promptdiff --git a/backend/tests/test_fragment_video_versions.py b/backend/tests/test_fragment_video_versions.pyindex f4995a4..b469340 100644--- a/backend/tests/test_fragment_video_versions.py+++ b/backend/tests/test_fragment_video_versions.py@@ -1,11 +1,13 @@"""分镜生成状态与视频版本。"""+from datetime import UTC, datetime, timedeltafrom types import SimpleNamespacefrom app.services.drama.generation import (activate_fragment_video_version,archive_fragment_video_version,fragment_generation_status,+ generation_queued_recently,)@@ -48,3 +50,15 @@ def test_archive_and_activate_video_version():assert out["video"] == "https://cdn/old.mp4"assert frag.video == "https://cdn/old.mp4"assert any(v.get("video") == "https://cdn/new.mp4" for v in frag.params["video_versions"])+++def test_generation_queued_recently_within_grace():+ now = datetime(2026, 8, 24, 7, 0, tzinfo=UTC)+ gen = {"status": "queued", "queued_at": (now - timedelta(seconds=10)).isoformat()}+ assert generation_queued_recently(gen, now=now) is True+++def test_generation_queued_recently_expired():+ now = datetime(2026, 8, 24, 7, 0, tzinfo=UTC)+ gen = {"status": "queued", "queued_at": (now - timedelta(seconds=90)).isoformat()}+ assert generation_queued_recently(gen, now=now) is Falsediff --git a/backend/tests/test_seedream_still_size_for_ratio.py b/backend/tests/test_seedream_still_size_for_ratio.pynew file mode 100644index 0000000..c0469ca--- /dev/null+++ b/backend/tests/test_seedream_still_size_for_ratio.py@@ -0,0 +1,23 @@+"""i2v 兜底静帧尺寸必须跟随目标画幅,避免横屏首帧传染。"""++from app.services.drama.output_settings import seedream_still_size_for_video_ratio+from app.services.drama.build_seedance_generate_body import resolve_seedance_ratio+++# 竖屏目标应对应竖屏 Seedream 像素+def test_seedream_still_size_portrait() -> None:+ assert seedream_still_size_for_video_ratio("9:16") == "2304x4096"+ assert seedream_still_size_for_video_ratio(None) == "2304x4096"+++# 横屏 / 方形映射+def test_seedream_still_size_other_ratios() -> None:+ assert seedream_still_size_for_video_ratio("16:9") == "4096x2304"+ assert seedream_still_size_for_video_ratio("1:1") == "3072x3072"+++# Seedance ratio 缺省与漫剧默认竖屏一致+def test_resolve_seedance_ratio_defaults_portrait() -> None:+ assert resolve_seedance_ratio(None) == "9:16"+ assert resolve_seedance_ratio("") == "9:16"+ assert resolve_seedance_ratio("16:9") == "16:9"diff --git a/backend/tests/test_stale_pending_fragment_video.py b/backend/tests/test_stale_pending_fragment_video.pyindex 2022106..7e3bb40 100644--- a/backend/tests/test_stale_pending_fragment_video.py+++ b/backend/tests/test_stale_pending_fragment_video.py@@ -22,6 +22,12 @@ def test_stale_reason_skip_duplicate_when_video_done():assert stale_pending_fragment_video_reason([frag]) == "分镜已生成完成,跳过重复任务"+def test_stale_reason_keep_when_replace_existing_video():+ frag = _frag(video="https://cdn/old.mp4", cover="", params={})+ task = SimpleNamespace(payload={"replace_existing_video": True})+ assert stale_pending_fragment_video_reason([frag], task) is None++def test_stale_reason_keep_when_no_video_yet():frag = _frag(video="", params={"generation": {"status": "queued"}})assert stale_pending_fragment_video_reason([frag]) is Nonediff --git a/docs/releases/2026-08-24.md b/docs/releases/2026-08-24.mdnew file mode 100644index 0000000..0349307--- /dev/null+++ b/docs/releases/2026-08-24.md@@ -0,0 +1,35 @@+# 发布记录 · 2026-08-24++## 2026-08-24 18:38 · 杭州 8.136.41.61 全量++- **操作者**:Agent(按用户要求全量发布)+- **方式**:`deploy/scripts/deploy_kepu_8136.py` 全量(未设 SETUP_NGINX / SETUP_TLS / SETUP_INFRA)+- **范围**:frontend / admin / api+- **变更摘要**:+ - 修复分镜视频「UI 显示 9:16 却出横屏」:i2v 兜底静帧按目标画幅生成(Seedance 首帧模式禁止传 ratio,会跟首帧比例)+ - Seedance `resolve_seedance_ratio` 缺省从 `16:9` 改为与漫剧一致的 `9:16`+- **验证**:+ - [x] 脚本 `DONE`(约 1.6 min);`ai-movie-api` active;health 200;poller running+ - [x] Host `kepu.printtfilm.com` / `admin.kepu.printtfilm.com` 首页 200+ - [ ] 业务冒烟:需对已横屏的片段(如《神凡殊途定乾坤》片段 06/18)重新生成后确认竖屏+- **备注 / 回滚**:+ - 未改 nginx / 证书 / Postgres·Redis 容器+ - 已生成的横屏成片不会自动纠正,须重新生成+ - 回滚上一包并 `systemctl restart ai-movie-api`++## 2026-08-24 16:36 · 杭州 8.136.41.61 全量++- **操作者**:Agent(按用户要求全量发布)+- **方式**:`deploy/scripts/deploy_kepu_8136.py` 全量(未设 SETUP_NGINX / SETUP_TLS / SETUP_INFRA)+- **范围**:frontend / admin / api+- **变更摘要**:+ - 分镜「重新生成」不再因旧成片被调度器当成重复任务取消(`replace_existing_video` + queued 与任务同事务提交 + 孤儿 queued 宽限)+ - 同步本机未提交包:分集输出规格、客户端成片拼接、分镜页相关前端改动+- **验证**:+ - [x] 脚本 `DONE`(约 1.5 min);`ai-movie-api` active;health 200;poller running+ - [x] 本机 `127.0.0.1:8000/api/health` 200+ - [x] Host `kepu.printtfilm.com` / `admin.kepu.printtfilm.com` 首页 200(`Last-Modified: Mon, 24 Aug 2026 08:34–08:35 GMT`)+- **备注 / 回滚**:+ - 未改 nginx / 证书 / Postgres·Redis 容器+ - 远端 OSS 内网探测超时,脚本改走公网 endpoint(与既有行为一致)+ - 回滚上一包并 `systemctl restart ai-movie-api`diff --git a/docs/releases/README.md b/docs/releases/README.mdindex f003a6c..ada0d39 100644--- a/docs/releases/README.md+++ b/docs/releases/README.md@@ -33,6 +33,8 @@| 日期 | 摘要 | 文件 ||------|------|------|+| 2026-08-24 | 分镜 i2v 画幅跟首帧导致横屏;杭州全量 | [2026-08-24.md](./2026-08-24.md) |+| 2026-08-24 | 重新生成误跳过修复;杭州全量 | [2026-08-24.md](./2026-08-24.md) || 2026-08-21 | 队列错误中文化+任务详情;杭州全量 | [2026-08-21.md](./2026-08-21.md) || 2026-08-21 | 分镜 upsert + 作废旧 fragment_video;杭州全量 | [2026-08-21.md](./2026-08-21.md) || 2026-08-21 | 登录去预填/多余提示;杭州全量 | [2026-08-21.md](./2026-08-21.md) |diff --git a/frontend/src/api/drama.ts b/frontend/src/api/drama.tsindex cf89c19..ce58ba1 100644--- a/frontend/src/api/drama.ts+++ b/frontend/src/api/drama.ts@@ -344,15 +344,20 @@ export const dramaApi = {listEpisodes: (projectId: number) =>request<DramaEpisode[]>(`/api/drama/episodes?project_id=${projectId}`),getEpisode: (id: number) => request<DramaEpisode>(`/api/drama/episodes/${id}`),+ updateEpisode: (id: number, body: { name?: string; params?: Record<string, unknown> | null }) =>+ request<DramaEpisode>(`/api/drama/episodes/${id}`, {+ method: 'PATCH',+ body: JSON.stringify(body),+ }),seedEpisodes: (projectId: number, force = false) =>request<DramaEpisode[]>(`/api/drama/episodes/seed_from_script?project_id=${projectId}${force ? '&force=true' : ''}`,{ method: 'POST' },),/** 单集 AI(LLM)重新分镜;轮询 episode.params.fragment_plan_status */- planEpisodeFragments: (+ planEpisodeFragments: (episodeId: number,- body?: { force?: boolean; fallback_rules?: boolean; skill_ids?: number[] },+ body?: { force?: boolean; fallback_rules?: boolean; skill_ids?: number[]; subtitle_enabled?: boolean },) =>request<DramaEpisode>(`/api/drama/episodes/${episodeId}/plan_fragments`, {method: 'POST',@@ -360,6 +365,7 @@ export const dramaApi = {force: body?.force ?? true,fallback_rules: body?.fallback_rules ?? true,skill_ids: body?.skill_ids,+ subtitle_enabled: body?.subtitle_enabled,}),}),saveFragments: (diff --git a/frontend/src/components/drama/DramaFragmentClipSpec.tsx b/frontend/src/components/drama/DramaFragmentClipSpec.tsxnew file mode 100644index 0000000..8101c41--- /dev/null+++ b/frontend/src/components/drama/DramaFragmentClipSpec.tsx@@ -0,0 +1,50 @@+/** 分镜条规格标签:优先展示成片真实像素,legacy 无 meta 时探测 video 元数据 */+import { useEffect, useState } from 'react'+import {+ formatProjectOutputLabel,+ inferAspectRatioFromPixels,+ pickDramaResolution,+ readFragmentOutputLabel,+ readFragmentVideoDimensions,+} from '../../lib/dramaProjectOutputSettings'+import { probeVideoDimensionsFromUrl } from '../../lib/dramaVideoDimensions'++type DramaFragmentClipSpecProps = {+ fragmentParams: Record<string, unknown>+ episodeParams: Record<string, unknown>+ projectParams: Record<string, unknown>+ videoUrl?: string+}++// 渲染单个分镜的画幅 · 清晰度标签+export function DramaFragmentClipSpec({+ fragmentParams,+ episodeParams,+ projectParams,+ videoUrl = '',+}: DramaFragmentClipSpecProps) {+ const stored = readFragmentVideoDimensions(fragmentParams)+ const [probed, setProbed] = useState<{ w: number; h: number } | null>(null)++ useEffect(() => {+ if (stored || !videoUrl.trim()) {+ setProbed(null)+ return+ }+ let cancelled = false+ void probeVideoDimensionsFromUrl(videoUrl).then((dims) => {+ if (!cancelled) setProbed(dims)+ })+ return () => {+ cancelled = true+ }+ }, [stored, videoUrl])++ const dims = stored ?? probed+ const resolution = pickDramaResolution(fragmentParams, episodeParams, projectParams)+ const label = dims+ ? formatProjectOutputLabel(inferAspectRatioFromPixels(dims.w, dims.h), resolution)+ : readFragmentOutputLabel(fragmentParams, episodeParams, projectParams)++ return <span className="drama-ep-clip-spec">{label}</span>+}diff --git a/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsx b/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsxindex e220f5f..ba05e3b 100644--- a/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsx+++ b/frontend/src/components/drama/DramaFragmentSegmentedVideoPlayer.tsx@@ -19,6 +19,9 @@ type Props = {playingFragmentId: number | nullonPlayingFragmentChange: (fragmentId: number) => voidaspectRatio: string+ /** 预览历史版本时覆盖当前镜视频地址 */+ overrideVideoUrl?: string | null+ overridePosterUrl?: string | null}// 渲染带分镜分段进度条的视频播放器@@ -27,6 +30,8 @@ export function DramaFragmentSegmentedVideoPlayer({playingFragmentId,onPlayingFragmentChange,aspectRatio,+ overrideVideoUrl = null,+ overridePosterUrl = null,}: Props) {// videoRef 视频元素引用const videoRef = useRef<HTMLVideoElement | null>(null)@@ -94,10 +99,14 @@ export function DramaFragmentSegmentedVideoPlayer({playingSegmentRef.current = playingSegment- // videoUrl 当前分镜视频地址- const videoUrl = playingFragment?.video ? resolveDramaMediaUrl(playingFragment.video) : null+ // videoUrl 当前分镜视频地址(可被历史版本预览覆盖)+ const videoUrl =+ overrideVideoUrl ||+ (playingFragment?.video ? resolveDramaMediaUrl(playingFragment.video) : null)// posterUrl 当前分镜封面地址- const posterUrl = playingFragment?.cover ? resolveDramaMediaUrl(playingFragment.cover) : null+ const posterUrl =+ overridePosterUrl ||+ (playingFragment?.cover ? resolveDramaMediaUrl(playingFragment.cover) : null)// hasCurrentVideo 当前分镜是否可播放const hasCurrentVideo = Boolean(videoUrl)// hasAnyVideo 是否存在任一分镜视频diff --git a/frontend/src/components/drama/DramaSubtitleBoard.tsx b/frontend/src/components/drama/DramaSubtitleBoard.tsxnew file mode 100644index 0000000..459eef2--- /dev/null+++ b/frontend/src/components/drama/DramaSubtitleBoard.tsx@@ -0,0 +1,95 @@+/** 分镜字幕板:预览整集口播字幕,支持折叠与导出。 */+import { useState } from 'react'+import { ChevronDown, ChevronUp } from 'lucide-react'+import type { DramaFragment } from '../../api/drama'+import { sanitizeMediaBasename } from '../../lib/canvasNodeMedia'+import { triggerBlobDownload } from '../../lib/clientDownload'+import {+ buildDramaSubtitleBoard,+ exportDramaSubtitleBoardSrt,+ formatSubtitleClock,+ subtitleModeUsesModelOutput,+ type DramaSubtitleMode,+} from '../../lib/dramaSubtitleBoard'++type Props = {+ fragments: DramaFragment[]+ episodeName?: string+ subtitleMode: DramaSubtitleMode+}++// 渲染可折叠的分集字幕板预览与导出按钮。+export function DramaSubtitleBoard({+ fragments,+ episodeName = '本集',+ subtitleMode,+}: Props) {+ const cues = buildDramaSubtitleBoard(fragments)+ const modelOutput = subtitleModeUsesModelOutput(subtitleMode)+ // collapsed 默认折叠,减少右侧预览占位+ const [collapsed, setCollapsed] = useState(true)++ return (+ <section className={`drama-subtitle-board${collapsed ? ' is-collapsed' : ''}`}>+ <div className="drama-subtitle-board__header">+ <button+ type="button"+ className="drama-subtitle-board__toggle"+ aria-expanded={!collapsed}+ onClick={() => setCollapsed((prev) => !prev)}+ >+ <span className="drama-subtitle-board__title-wrap">+ <h4>字幕板</h4>+ <p>+ {modelOutput ? '模型自出' : '后期拼接'} · {cues.length} 条+ </p>+ </span>+ {collapsed ? (+ <ChevronDown size={16} strokeWidth={1.8} aria-hidden />+ ) : (+ <ChevronUp size={16} strokeWidth={1.8} aria-hidden />+ )}+ </button>+ <button+ type="button"+ className="drama-subtitle-board__export"+ disabled={cues.length === 0}+ title="导出 SRT,可直接导入剪映"+ onClick={(event) => {+ event.stopPropagation()+ const srt = exportDramaSubtitleBoardSrt(fragments)+ if (!srt) return+ // 剪映桌面版可识别 UTF-8 BOM 的 .srt+ const blob = new Blob(['\uFEFF', srt], { type: 'application/x-subrip;charset=utf-8' })+ triggerBlobDownload(blob, `${sanitizeMediaBasename(episodeName)}_字幕.srt`)+ }}+ >+ 导出SRT+ </button>+ </div>+ {!collapsed ? (+ cues.length === 0 ? (+ <div className="drama-subtitle-board__empty">当前分镜里还没有可预览的对白/旁白字幕。</div>+ ) : (+ <div className="drama-subtitle-board__list">+ {cues.map((cue, index) => (+ <div+ key={`${cue.fragmentId}-${cue.startSec}-${index}`}+ className="drama-subtitle-board__item"+ >+ <div className="drama-subtitle-board__meta">+ <span>+ {formatSubtitleClock(cue.startSec)} - {formatSubtitleClock(cue.endSec)}+ </span>+ <span>片段 {String(cue.fragmentIndex + 1).padStart(2, '0')}</span>+ <span>{cue.speaker}</span>+ </div>+ <div className="drama-subtitle-board__text">{cue.text}</div>+ </div>+ ))}+ </div>+ )+ ) : null}+ </section>+ )+}diff --git a/frontend/src/components/drama/SeedanceRulesModal.tsx b/frontend/src/components/drama/SeedanceRulesModal.tsxindex 44e75a0..57cb79d 100644--- a/frontend/src/components/drama/SeedanceRulesModal.tsx+++ b/frontend/src/components/drama/SeedanceRulesModal.tsx@@ -81,7 +81,7 @@ export function SeedanceRulesModal({ open, onClose }: Props) {<strong>模型</strong> → <code>model</code>(Seedance 2.5 / 1.5)</li><li>- <strong>画幅 · 清晰度</strong> → <code>ratio</code>、<code>resolution</code>+ <strong>画幅 · 清晰度</strong>(分集顶栏设置)→ <code>ratio</code>、<code>resolution</code></li><li><strong>时长</strong> → <code>duration</code>:脚本内{' '}@@ -193,7 +193,7 @@ export function SeedanceRulesModal({ open, onClose }: Props) {<ul className="seedance-rules-list"><li>脚本校验:时长合法;空镜未被标成对白/旁白(编辑区会即时提示,有错误不可生成)</li><li>本镜「参与资产」中的角色已有参考图;需说话的角色已「生成音色」或绑定试听(缺项会警告)</li>- <li>顶栏确认视频风格、模型、画幅与清晰度后再点「生成」</li>+ <li>项目顶栏确认画幅与清晰度;分集顶栏确认视频风格、模型后再点「生成」</li></ul><h4>队列与并行</h4>@@ -210,7 +210,7 @@ export function SeedanceRulesModal({ open, onClose }: Props) {<code>params.lastFrameUrl</code></li><li>- 顶栏「画幅 · 清晰度」→「用上一镜尾帧作本镜首帧」开启时:若本镜有角色/场景参考图或音色,+ 分集顶栏「镜间衔接」开启时:若本镜有角色/场景参考图或音色,尾帧以 <code>reference_image</code> 附在末尾(Seedance 禁止与 <code>first_frame</code> 混用);无参考媒体时才用 <code>first_frame</code></li>diff --git a/frontend/src/lib/dramaProjectOutputSettings.ts b/frontend/src/lib/dramaProjectOutputSettings.tsnew file mode 100644index 0000000..259df14--- /dev/null+++ b/frontend/src/lib/dramaProjectOutputSettings.ts@@ -0,0 +1,130 @@+/** 漫剧视频输出规格(画幅 / 清晰度):分集 params 优先,可回退 project.params */+export const DRAMA_RATIO_OPTIONS = ['9:16', '16:9', '1:1'] as const+export const DRAMA_RES_OPTIONS = ['480p', '720p', '1080p'] as const++export type DramaAspectRatio = (typeof DRAMA_RATIO_OPTIONS)[number]+export type DramaResolution = (typeof DRAMA_RES_OPTIONS)[number]++// 从 project.params 读取画幅,非法值回退 9:16+export function readProjectAspectRatio(+ params: Record<string, unknown> | null | undefined,+): DramaAspectRatio {+ const ratio = String(params?.aspect_ratio || '').trim()+ if ((DRAMA_RATIO_OPTIONS as readonly string[]).includes(ratio)) {+ return ratio as DramaAspectRatio+ }+ return '9:16'+}++// 从 project.params 读取清晰度,非法值回退 480p+export function readProjectResolution(+ params: Record<string, unknown> | null | undefined,+): DramaResolution {+ const res = String(params?.resolution || '').trim()+ if ((DRAMA_RES_OPTIONS as readonly string[]).includes(res)) {+ return res as DramaResolution+ }+ return '480p'+}++// 从多层 params 中取第一个合法画幅+export function pickDramaAspectRatio(+ ...sources: Array<Record<string, unknown> | null | undefined>+): DramaAspectRatio {+ for (const params of sources) {+ const ratio = String(params?.aspect_ratio || '').trim()+ if ((DRAMA_RATIO_OPTIONS as readonly string[]).includes(ratio)) {+ return ratio as DramaAspectRatio+ }+ }+ return '9:16'+}++// 从多层 params 中取第一个合法清晰度+export function pickDramaResolution(+ ...sources: Array<Record<string, unknown> | null | undefined>+): DramaResolution {+ for (const params of sources) {+ const res = String(params?.resolution || '').trim()+ if ((DRAMA_RES_OPTIONS as readonly string[]).includes(res)) {+ return res as DramaResolution+ }+ }+ return '480p'+}++// 分集画幅:episode.params → project.params → 默认+export function readEpisodeAspectRatio(+ episodeParams: Record<string, unknown> | null | undefined,+ projectParams?: Record<string, unknown> | null | undefined,+): DramaAspectRatio {+ return pickDramaAspectRatio(episodeParams, projectParams)+}++// 分集清晰度:episode.params → project.params → 默认+export function readEpisodeResolution(+ episodeParams: Record<string, unknown> | null | undefined,+ projectParams?: Record<string, unknown> | null | undefined,+): DramaResolution {+ return pickDramaResolution(episodeParams, projectParams)+}++// 分镜规格:本镜生成时写入的 params → 分集 → 项目+export function readFragmentVideoDimensions(+ fragmentParams: Record<string, unknown> | null | undefined,+): { w: number; h: number } | null {+ const gen = fragmentParams?.generation+ const genObj =+ gen && typeof gen === 'object' && !Array.isArray(gen)+ ? (gen as Record<string, unknown>)+ : null+ const w = Number(fragmentParams?.video_width ?? genObj?.video_width)+ const h = Number(fragmentParams?.video_height ?? genObj?.video_height)+ if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) {+ return { w: Math.round(w), h: Math.round(h) }+ }+ return null+}++// 根据像素推断标准画幅;非标准时返回「宽×高」+export function inferAspectRatioFromPixels(width: number, height: number): string {+ if (width <= 0 || height <= 0) return '9:16'+ const ratio = width / height+ const candidates: Array<[string, number]> = [+ ['9:16', 9 / 16],+ ['16:9', 16 / 9],+ ['1:1', 1],+ ]+ let best = candidates[0]+ let bestDiff = Math.abs(ratio - best[1])+ for (const item of candidates.slice(1)) {+ const diff = Math.abs(ratio - item[1])+ if (diff < bestDiff) {+ best = item+ bestDiff = diff+ }+ }+ if (bestDiff <= 0.08) return best[0]+ return `${width}×${height}`+}++export function readFragmentOutputLabel(+ fragmentParams: Record<string, unknown> | null | undefined,+ episodeParams?: Record<string, unknown> | null | undefined,+ projectParams?: Record<string, unknown> | null | undefined,+): string {+ const resolution = pickDramaResolution(fragmentParams, episodeParams, projectParams)+ const dims = readFragmentVideoDimensions(fragmentParams)+ if (dims) {+ return formatProjectOutputLabel(inferAspectRatioFromPixels(dims.w, dims.h), resolution)+ }+ return formatProjectOutputLabel(+ pickDramaAspectRatio(fragmentParams, episodeParams, projectParams),+ resolution,+ )+}++// 格式化顶栏展示文案+export function formatProjectOutputLabel(aspectRatio: string, resolution: string): string {+ return `${aspectRatio} · ${resolution}`+}diff --git a/frontend/src/lib/dramaSubtitleBoard.ts b/frontend/src/lib/dramaSubtitleBoard.tsnew file mode 100644index 0000000..a3601bc--- /dev/null+++ b/frontend/src/lib/dramaSubtitleBoard.ts@@ -0,0 +1,282 @@+/** 分镜字幕板:从分镜正文提取口播字幕,供预览与导出。 */++import type { DramaFragment } from '../api/drama'++export type DramaSubtitleMode = 'model' | 'post'++export type DramaSubtitleCue = {+ fragmentId: number+ fragmentIndex: number+ startSec: number+ endSec: number+ speaker: string+ text: string+}++// 判断当前字幕方式是否由模型直接出字幕。+export function subtitleModeUsesModelOutput(mode: DramaSubtitleMode): boolean {+ return mode === 'model'+}++// 兼容历史布尔值,读取分集字幕方式;默认模型自出字幕。+export function readEpisodeSubtitleMode(+ params: Record<string, unknown> | null | undefined,+): DramaSubtitleMode {+ const mode = params?.subtitleMode+ if (mode === 'model' || mode === 'post') return mode+ return readEpisodeSubtitleEnabled(params) ? 'model' : 'post'+}++// 兼容历史字符串/数字布尔值,默认开启字幕。+export function readEpisodeSubtitleEnabled(params: Record<string, unknown> | null | undefined): boolean {+ const value = params?.subtitleEnabled+ if (value == null) return true+ if (typeof value === 'boolean') return value+ if (typeof value === 'number') return value !== 0+ if (typeof value === 'string') {+ const normalized = value.trim().toLowerCase()+ if (['0', 'false', 'no', 'off', ''].includes(normalized)) return false+ if (['1', 'true', 'yes', 'on'].includes(normalized)) return true+ }+ return Boolean(value)+}++// 提取整集字幕 cue(按 @duration 顺序累计时间轴)。+export function buildDramaSubtitleBoard(fragments: DramaFragment[]): DramaSubtitleCue[] {+ const cues: DramaSubtitleCue[] = []+ let globalSec = 0++ fragments.forEach((fragment, index) => {+ const lines = String(fragment.content || '')+ .replace(/\r\n/g, '\n')+ .split('\n')+ .map((line) => line.trim())+ .filter(Boolean)++ let blockDuration = 0+ let blockStart = globalSec+ const flushTimeOnly = () => {+ if (blockDuration > 0) {+ globalSec += blockDuration+ }+ blockDuration = 0+ blockStart = globalSec+ }++ for (const line of lines) {+ const durationMatch = line.match(/^@duration:(\d+)/)+ if (durationMatch) {+ flushTimeOnly()+ blockDuration = Math.max(0, Number(durationMatch[1]) || 0)+ blockStart = globalSec+ continue+ }+ const spoken = parseSubtitleLine(line)+ if (!spoken || blockDuration <= 0) continue+ cues.push({+ fragmentId: fragment.id,+ fragmentIndex: index,+ startSec: blockStart,+ endSec: blockStart + blockDuration,+ speaker: spoken.speaker,+ text: spoken.text,+ })+ }++ flushTimeOnly()+ })++ return cues+}++// 导出字幕板纯文本(预览用)。+export function exportDramaSubtitleBoardText(fragments: DramaFragment[]): string {+ const cues = buildDramaSubtitleBoard(fragments)+ if (cues.length === 0) return '暂无可导出的字幕内容'+ return cues+ .map(+ (cue) =>+ `${formatSubtitleClock(cue.startSec)}-${formatSubtitleClock(cue.endSec)} 片段 ${String(+ cue.fragmentIndex + 1,+ ).padStart(2, '0')} ${cue.speaker}:${cue.text}`,+ )+ .join('\n')+}++// 导出剪映可导入的 SRT(仅正文,不含说话人)。+export function exportDramaSubtitleBoardSrt(fragments: DramaFragment[]): string {+ const cues = buildDramaSubtitleBoard(fragments)+ .map((cue) => ({+ ...cue,+ text: sanitizeSrtCaptionText(cue.text),+ }))+ .filter((cue) => cue.text.length > 0)+ if (cues.length === 0) return ''+ return cues+ .map((cue, index) => {+ const start = formatSrtTimestamp(cue.startSec)+ const end = formatSrtTimestamp(Math.max(cue.endSec, cue.startSec + 0.4))+ return `${index + 1}\n${start} --> ${end}\n${cue.text}`+ })+ .join('\n\n')+}++// 秒数格式化为 00:00。+export function formatSubtitleClock(totalSec: number): string {+ const sec = Math.max(0, Math.floor(totalSec))+ const minutes = Math.floor(sec / 60)+ const seconds = sec % 60+ return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`+}++// 秒数格式化为 SRT 时间轴 00:00:00,000。+export function formatSrtTimestamp(totalSec: number): string {+ const msTotal = Math.max(0, Math.round(totalSec * 1000))+ const hours = Math.floor(msTotal / 3_600_000)+ const minutes = Math.floor((msTotal % 3_600_000) / 60_000)+ const seconds = Math.floor((msTotal % 60_000) / 1000)+ const millis = msTotal % 1000+ return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(+ seconds,+ ).padStart(2, '0')},${String(millis).padStart(3, '0')}`+}++// 清理动作说明等括注,保留可上屏的口播正文。+function sanitizeSrtCaptionText(raw: string): string {+ return String(raw || '')+ .replace(/([^)]*)/g, '')+ .replace(/\([^)]*\)/g, '')+ .replace(/\s+/g, ' ')+ .trim()+}++function parseSubtitleLine(+ line: string,+): {+ speaker: string+ text: string+} | null {+ const normalized = String(line || '')+ .replace(/@asset:\d+\s*/g, '')+ .trim()+ const stripped = normalized.replace(/^【[^】]+】/, '').trim()+ if (!stripped) return null+ if (stripped.startsWith('旁白(VO):')) {+ return { speaker: '旁白', text: stripped.slice('旁白(VO):'.length).trim() }+ }+ if (stripped.startsWith('旁白:')) {+ return { speaker: '旁白', text: stripped.slice('旁白:'.length).trim() }+ }+ if (stripped.startsWith('内心独白:')) {+ return { speaker: '内心独白', text: stripped.slice('内心独白:'.length).trim() }+ }+ const dialogue = stripped.match(/^([^:]{1,24}):(.+)$/)+ if (!dialogue) return null+ const speaker = dialogue[1].trim()+ const text = dialogue[2].trim()+ if (!speaker || !text) return null+ if (['空镜', '远景', '近景', '特写', '全景', '中景'].includes(speaker)) return null+ return { speaker, text }+}++const DRAMA_SUBTITLE_CUE = '【字幕:底部居中·简体中文·逐句轮换·与口播同步】'+const LEGACY_SUBTITLE_CUES = [+ '【字幕:底部居中·简体中文·仅标记段落同步】',+ '【字幕:底部居中·简体中文】',+ '【字幕:全程简体中文字幕,旁白逐句同步烧录】',+]++const STRIP_PREFIX_MAP: Array<[string, string]> = [+ ['【对白·慢速清晰·同步字幕】', '【对白·慢速清晰】'],+ ['【旁白·慢速清晰·同步字幕】', '【旁白·慢速清晰】'],+ ['【旁白·自然语速·同步字幕】', '【旁白·自然语速】'],+ ['【内心独白·同步字幕】', '【内心独白】'],+]++// 判断是否为字幕 cue 行(含历史文案)。+function isSubtitleCueLine(line: string): boolean {+ const trimmed = line.trim()+ if (!trimmed.startsWith('【字幕')) return false+ return (+ trimmed === DRAMA_SUBTITLE_CUE ||+ LEGACY_SUBTITLE_CUES.includes(trimmed) ||+ /同步|烧录|底部居中/.test(trimmed)+ )+}++// 从单条分镜正文去掉模型字幕提示词,保留对白/旁白本身。+export function stripSubtitlePromptsFromContent(content: string): string {+ const lines = String(content || '')+ .replace(/\r\n/g, '\n')+ .split('\n')+ const next: string[] = []+ for (const raw of lines) {+ const trimmed = raw.trim()+ if (!trimmed) {+ next.push(raw)+ continue+ }+ if (isSubtitleCueLine(trimmed)) continue+ let line = trimmed+ for (const [src, dest] of STRIP_PREFIX_MAP) {+ if (line.startsWith(src)) {+ line = line.replace(src, dest)+ break+ }+ }+ next.push(line)+ }+ return next.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()+}++// 为单条分镜正文补回模型字幕提示词(已有则不重复)。+export function applySubtitlePromptsToContent(content: string): string {+ const source = String(content || '').replace(/\r\n/g, '\n')+ if (!source.trim()) return source+ const lines = source.split('\n')+ const next: string[] = []+ let hasCue = false+ for (const raw of lines) {+ const trimmed = raw.trim()+ if (!trimmed) {+ next.push(raw)+ continue+ }+ if (isSubtitleCueLine(trimmed)) {+ if (!hasCue) {+ next.push(DRAMA_SUBTITLE_CUE)+ hasCue = true+ }+ continue+ }+ let line = trimmed+ for (const [withSub, withoutSub] of STRIP_PREFIX_MAP) {+ if (line.startsWith(withoutSub) && !line.startsWith(withSub)) {+ line = line.replace(withoutSub, withSub)+ break+ }+ }+ next.push(line)+ }+ if (!hasCue) {+ const insertAt = next.findIndex((line) => line.trim().startsWith('【BGM'))+ if (insertAt >= 0) next.splice(insertAt, 0, DRAMA_SUBTITLE_CUE)+ else next.unshift(DRAMA_SUBTITLE_CUE)+ }+ return next.join('\n').replace(/\n{3,}/g, '\n\n').trimEnd()+}++// 按字幕方式批量改写分镜正文。+export function applySubtitleModeToFragments<T extends { content?: string | null }>(+ fragments: T[],+ mode: DramaSubtitleMode,+): T[] {+ const transform =+ mode === 'model' ? applySubtitlePromptsToContent : stripSubtitlePromptsFromContent+ return fragments.map((fragment) => {+ const prev = String(fragment.content || '')+ const next = transform(prev)+ if (next === prev) return fragment+ return { ...fragment, content: next }+ })+}diff --git a/frontend/src/lib/dramaUsage.ts b/frontend/src/lib/dramaUsage.tsindex 688d52f..f7b5e18 100644--- a/frontend/src/lib/dramaUsage.ts+++ b/frontend/src/lib/dramaUsage.ts@@ -18,8 +18,9 @@ export function formatDramaChargeYuan(yuan: number | undefined | null): string {return `¥${n.toFixed(2)}`}-/** 列表/工作台短文案:费用 · 生图 · 生视频 */+/** 列表/工作台短文案:费用 · 生图 · 生视频 · 调用 */export function formatDramaUsageBrief(usage?: DramaProjectUsageStats | null): string {const u = usage || EMPTY_DRAMA_USAGE- return `${formatDramaChargeYuan(u.charge_yuan)} · 生图 ${u.image_gens} · 生视频 ${u.video_gens}`+ const calls = u.calls > 0 ? ` · 调用 ${u.calls}` : ''+ return `${formatDramaChargeYuan(u.charge_yuan)} · 生图 ${u.image_gens} · 生视频 ${u.video_gens}${calls}`}diff --git a/frontend/src/lib/dramaVideoDimensions.ts b/frontend/src/lib/dramaVideoDimensions.tsnew file mode 100644index 0000000..0e67a65--- /dev/null+++ b/frontend/src/lib/dramaVideoDimensions.ts@@ -0,0 +1,29 @@+/** 浏览器端探测视频真实宽高(legacy 分镜无 params 时使用) */+export function probeVideoDimensionsFromUrl(+ url: string,+): Promise<{ w: number; h: number } | null> {+ return new Promise((resolve) => {+ if (!url.trim()) {+ resolve(null)+ return+ }+ const video = document.createElement('video')+ video.preload = 'metadata'+ video.muted = true+ const cleanup = () => {+ video.removeAttribute('src')+ video.load()+ }+ video.onloadedmetadata = () => {+ const w = video.videoWidth+ const h = video.videoHeight+ cleanup()+ resolve(w > 0 && h > 0 ? { w, h } : null)+ }+ video.onerror = () => {+ cleanup()+ resolve(null)+ }+ video.src = url+ })+}diff --git a/frontend/src/pages/drama/DramaProjectOutputSettings.tsx b/frontend/src/pages/drama/DramaProjectOutputSettings.tsxnew file mode 100644index 0000000..e365918--- /dev/null+++ b/frontend/src/pages/drama/DramaProjectOutputSettings.tsx@@ -0,0 +1,192 @@+/** 分集 / 项目画幅与清晰度设置(写入 episode.params 或 project.params) */+import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent } from 'react'+import { createPortal } from 'react-dom'+import { ChevronDown, RectangleVertical } from 'lucide-react'+import {+ DRAMA_RATIO_OPTIONS,+ DRAMA_RES_OPTIONS,+ formatProjectOutputLabel,+ readEpisodeAspectRatio,+ readEpisodeResolution,+ readProjectAspectRatio,+ readProjectResolution,+ type DramaResolution,+} from '../../lib/dramaProjectOutputSettings'+import './drama.css'++type Props = {+ params: Record<string, unknown>+ /** 分集模式下用于展示继承的项目默认 */+ fallbackParams?: Record<string, unknown>+ scope?: 'episode' | 'project'+ disabled?: boolean+ compact?: boolean+ onChange: (nextParams: Record<string, unknown>) => void | Promise<void>+}++// 渲染输出规格控件+export function DramaProjectOutputSettings({+ params,+ fallbackParams = {},+ scope = 'episode',+ disabled = false,+ compact = false,+ onChange,+}: Props) {+ const rootRef = useRef<HTMLDivElement>(null)+ const [open, setOpen] = useState(false)+ const [panelStyle, setPanelStyle] = useState<CSSProperties | null>(null)+ const [saving, setSaving] = useState(false)++ const aspectRatio =+ scope === 'episode'+ ? readEpisodeAspectRatio(params, fallbackParams)+ : readProjectAspectRatio(params)+ const resolution =+ scope === 'episode'+ ? readEpisodeResolution(params, fallbackParams)+ : readProjectResolution(params)+ const outputLabel = formatProjectOutputLabel(aspectRatio, resolution)+ const scopeHint = scope === 'episode' ? '本集' : '项目统一'+ const panelTitle = scope === 'episode' ? '分集画幅' : '项目画幅'+ const panelNote =+ scope === 'episode'+ ? '仅本集分镜使用;未单独设置时继承项目默认。修改后请重新生成各镜视频。'+ : '全部分集共用同一规格,避免各镜比例/清晰度不一致导致无法拼接。'++ useLayoutEffect(() => {+ if (!open || !rootRef.current) {+ setPanelStyle(null)+ return+ }++ function updatePanelPosition() {+ const root = rootRef.current+ if (!root) return+ const rect = root.getBoundingClientRect()+ const width = Math.min(360, window.innerWidth - 24)+ let left = rect.right - width+ left = Math.max(12, Math.min(left, window.innerWidth - width - 12))+ const top = Math.min(rect.bottom + 8, window.innerHeight - 24)+ setPanelStyle({+ position: 'fixed',+ top,+ left,+ width,+ bottom: 'auto',+ right: 'auto',+ zIndex: 320,+ })+ }++ updatePanelPosition()+ window.addEventListener('resize', updatePanelPosition)+ window.addEventListener('scroll', updatePanelPosition, true)+ return () => {+ window.removeEventListener('resize', updatePanelPosition)+ window.removeEventListener('scroll', updatePanelPosition, true)+ }+ }, [open])++ useEffect(() => {+ if (!open) return+ function onDoc(e: Event) {+ const target = e.target as Node | null+ if (!target) return+ if (rootRef.current?.contains(target)) return+ if ((target as Element).closest?.('.fc-gen-opt-panel--portal')) return+ setOpen(false)+ }+ document.addEventListener('mousedown', onDoc)+ return () => document.removeEventListener('mousedown', onDoc)+ }, [open])++ const stop = (e: MouseEvent) => {+ e.stopPropagation()+ }++ // 合并写回 params+ async function applyPatch(patch: Partial<{ aspect_ratio: string; resolution: string }>) {+ if (disabled || saving) return+ const nextParams = { ...params, ...patch }+ setSaving(true)+ try {+ await onChange(nextParams)+ setOpen(false)+ } finally {+ setSaving(false)+ }+ }++ return (+ <div+ ref={rootRef}+ className={`fc-gen-opts drama-project-output-settings${compact ? ' drama-project-output-settings--compact' : ''}`}+ onMouseDown={stop}+ onPointerDown={stop}+ >+ <button+ type="button"+ className={`fc-gen-opt-btn drama-project-output-btn${open ? ' active' : ''}`}+ disabled={disabled || saving}+ title={+ scope === 'episode'+ ? '本集画幅与清晰度;各镜生成后可直接拼接'+ : '全项目统一画幅与清晰度,各分镜生成后可直接拼接'+ }+ onClick={() => setOpen((c) => !c)}+ >+ <RectangleVertical size={14} strokeWidth={1.8} />+ <span className="fc-gen-opt-label">{outputLabel}</span>+ {!compact ? <span className="drama-project-output-hint">{scopeHint}</span> : null}+ <ChevronDown size={12} strokeWidth={2} />+ </button>++ {open && panelStyle+ ? createPortal(+ <div+ className="fc-gen-opt-panel drama-ep-opt-panel fc-gen-opt-panel--portal"+ style={panelStyle}+ role="dialog"+ aria-label={scope === 'episode' ? '分集画幅与清晰度' : '项目画幅与清晰度'}+ >+ <div className="fc-gen-opt-panel-title">{panelTitle}</div>+ <p className="drama-project-output-note">{panelNote}</p>+ <div className="fc-gen-chip-row">+ {DRAMA_RATIO_OPTIONS.map((r) => (+ <button+ key={r}+ type="button"+ className={`fc-gen-chip${aspectRatio === r ? ' selected' : ''}`}+ disabled={disabled || saving}+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => void applyPatch({ aspect_ratio: r })}+ >+ {r}+ </button>+ ))}+ </div>+ <div className="fc-gen-opt-panel-title" style={{ marginTop: 12 }}>+ 清晰度+ </div>+ <div className="fc-gen-chip-row">+ {DRAMA_RES_OPTIONS.map((r) => (+ <button+ key={r}+ type="button"+ className={`fc-gen-chip${resolution === r ? ' selected' : ''}`}+ disabled={disabled || saving}+ onMouseDown={(e) => e.preventDefault()}+ onClick={() => void applyPatch({ resolution: r as DramaResolution })}+ >+ {r}+ </button>+ ))}+ </div>+ </div>,+ document.body,+ )+ : null}+ </div>+ )+}diff --git a/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx b/frontend/src/pages/drama/EpisodeEditHeaderControls.tsxindex caae4fb..ae6b988 100644--- a/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx+++ b/frontend/src/pages/drama/EpisodeEditHeaderControls.tsx@@ -1,291 +1,645 @@-/** 分集编辑顶栏:视频风格 / 模型 / 画幅(pill 按钮 + 下拉面板) */+/** 分集编辑顶栏:画幅/清晰度 / 视频风格 / 模型 / 镜间衔接 */+import { useEffect, useLayoutEffect, useRef, useState, type CSSProperties, type MouseEvent } from 'react'+import { createPortal } from 'react-dom'-import { BarChart3, ChevronDown, CircleHelp, RectangleVertical, Smile } from 'lucide-react'++import { BarChart3, ChevronDown, CircleHelp, Link2, Smile, Type } from 'lucide-react'+import { DramaImageStylePreviewImg } from '../../components/drama/DramaImageStylePreviewImg'+import { SeedanceRulesModal } from '../../components/drama/SeedanceRulesModal'+import {+getImageStyleLabel,+IMAGE_STYLE_OPTIONS,+type ImageStyleId,+} from '../../lib/dramaImageStyles'-import { MODEL_OPTIONS, RATIO_OPTIONS, RES_OPTIONS } from './dramaEpisodeEditUtils'+import { subtitleModeUsesModelOutput, type DramaSubtitleMode } from '../../lib/dramaSubtitleBoard'++import { MODEL_OPTIONS } from './dramaEpisodeEditUtils'++import { DramaProjectOutputSettings } from './DramaProjectOutputSettings'+import './canvas/nodes/dramaImageGenOptions.css'++type Props = {+styleId: ImageStyleId | ''+modelId: string- aspectRatio: (typeof RATIO_OPTIONS)[number]- resolution: (typeof RES_OPTIONS)[number]++ episodeParams: Record<string, unknown>++ projectParams: Record<string, unknown>+linkLastFrame: boolean++ subtitleMode: DramaSubtitleMode+onStyleChange: (id: ImageStyleId | '') => void+onModelChange: (id: string) => void- onAspectRatioChange: (r: (typeof RATIO_OPTIONS)[number]) => void- onResolutionChange: (r: (typeof RES_OPTIONS)[number]) => void++ onEpisodeOutputChange: (nextParams: Record<string, unknown>) => void | Promise<void>+onLinkLastFrameChange: (enabled: boolean) => void++ onSubtitleModeChange: (mode: DramaSubtitleMode) => void+disabled?: boolean+}-type OpenPanel = 'style' | 'model' | 'output' | null+++type OpenPanel = 'style' | 'model' | 'link' | 'subtitle' | null++const STYLE_PANEL_WIDTH = 420++// 渲染顶栏生成参数控件+export function EpisodeEditHeaderControls({+styleId,+modelId,- aspectRatio,- resolution,++ episodeParams,++ projectParams,+linkLastFrame,++ subtitleMode,+onStyleChange,+onModelChange,- onAspectRatioChange,- onResolutionChange,++ onEpisodeOutputChange,+onLinkLastFrameChange,++ onSubtitleModeChange,+disabled = false,+}: Props) {+const rootRef = useRef<HTMLDivElement>(null)+const [open, setOpen] = useState<OpenPanel>(null)+const [rulesOpen, setRulesOpen] = useState(false)+const [panelStyle, setPanelStyle] = useState<CSSProperties | null>(null)++useLayoutEffect(() => {+if (!open || !rootRef.current) {+setPanelStyle(null)+return+}++// 固定定位下拉面板,避免与 top/bottom 冲突导致高度被压扁+function updatePanelPosition() {+const root = rootRef.current+if (!root) return+const rect = root.getBoundingClientRect()+const width =+open === 'style'+? Math.min(STYLE_PANEL_WIDTH, window.innerWidth - 24)+: Math.min(360, window.innerWidth - 24)+let left = rect.right - width+left = Math.max(12, Math.min(left, window.innerWidth - width - 12))+const top = Math.min(rect.bottom + 8, window.innerHeight - 24)+setPanelStyle({+position: 'fixed',+top,+left,+width,+bottom: 'auto',+right: 'auto',+zIndex: 320,+})+}++updatePanelPosition()+window.addEventListener('resize', updatePanelPosition)+window.addEventListener('scroll', updatePanelPosition, true)+return () => {+window.removeEventListener('resize', updatePanelPosition)+window.removeEventListener('scroll', updatePanelPosition, true)+}+}, [open])++useEffect(() => {+if (!open) return+function onDoc(e: Event) {+const target = e.target as Node | null+if (!target) return+if (rootRef.current?.contains(target)) return+if ((target as Element).closest?.('.fc-gen-opt-panel--portal')) return+setOpen(null)+}+document.addEventListener('mousedown', onDoc)+return () => document.removeEventListener('mousedown', onDoc)+}, [open])++const stop = (e: MouseEvent) => {+e.stopPropagation()+}++const styleLabel = getImageStyleLabel(styleId) || '视频风格'+const modelLabel = MODEL_OPTIONS.find((m) => m.id === modelId)?.label || modelId- const outputLabel = `${aspectRatio} · ${resolution}`+ const subtitleLabel = subtitleMode === 'model' ? '模型字幕' : '后期字幕'+ const subtitleUsesModel = subtitleModeUsesModelOutput(subtitleMode)++return (+<div+ref={rootRef}+className="fc-gen-opts drama-ep-header-gen-opts"+onMouseDown={stop}+onPointerDown={stop}+>+<div className="fc-gen-opts-triggers">++ <DramaProjectOutputSettings++ scope="episode"++ params={episodeParams}++ fallbackParams={projectParams}++ disabled={disabled}++ compact++ onChange={onEpisodeOutputChange}++ />+++<button+type="button"+className={`fc-gen-opt-btn${open === 'style' || styleId ? ' active' : ''}`}+disabled={disabled}+onClick={() => setOpen((c) => (c === 'style' ? null : 'style'))}+title={styleLabel}+>+<Smile size={14} strokeWidth={1.8} />+<span className="fc-gen-opt-label">{styleLabel}</span>+<ChevronDown size={12} strokeWidth={2} />+</button>+++ <button++ type="button"++ className={`fc-gen-opt-btn${open === 'subtitle' || !subtitleUsesModel ? ' active' : ''}`}++ disabled={disabled}++ onClick={() => setOpen((c) => (c === 'subtitle' ? null : 'subtitle'))}++ title="字幕设置"++ >++ <Type size={14} strokeWidth={1.8} />++ <span className="fc-gen-opt-label">{subtitleLabel}</span>++ <ChevronDown size={12} strokeWidth={2} />++ </button>+++<button+type="button"+className={`fc-gen-opt-btn${open === 'model' ? ' active' : ''}`}+disabled={disabled}+onClick={() => setOpen((c) => (c === 'model' ? null : 'model'))}+>+<BarChart3 size={14} strokeWidth={1.8} />+<span className="fc-gen-opt-label">{modelLabel}</span>+<ChevronDown size={12} strokeWidth={2} />+</button>++<button+type="button"- className={`fc-gen-opt-btn${open === 'output' ? ' active' : ''}`}++ className={`fc-gen-opt-btn${open === 'link' || linkLastFrame ? ' active' : ''}`}+disabled={disabled}- onClick={() => setOpen((c) => (c === 'output' ? null : 'output'))}++ onClick={() => setOpen((c) => (c === 'link' ? null : 'link'))}++ title="镜间尾帧衔接"+>- <RectangleVertical size={14} strokeWidth={1.8} />- <span className="fc-gen-opt-label">{outputLabel}</span>++ <Link2 size={14} strokeWidth={1.8} />++ <span className="fc-gen-opt-label">{linkLastFrame ? '尾帧衔接' : '并发生成'}</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 && panelStyle+? createPortal(+<>+{open === 'style' ? (+<div+className="fc-gen-opt-panel fc-gen-style-panel drama-ep-opt-panel fc-gen-opt-panel--portal"+style={panelStyle}+role="dialog"+aria-label="视频风格"+>+<div className="fc-gen-opt-panel-title">视频风格</div>+<div className="fc-gen-style-grid">+{IMAGE_STYLE_OPTIONS.map((opt) => {+const selected = styleId === opt.id+return (+<button+key={opt.id}+type="button"+className={`fc-gen-style-card${selected ? ' selected' : ''}`}+onMouseDown={(e) => e.preventDefault()}+onClick={() => {+onStyleChange(opt.id)+setOpen(null)+}}+>+<DramaImageStylePreviewImg styleId={opt.id} alt={opt.label} />+<span>{opt.label}</span>+</button>+)+})}+</div>+</div>+) : null}++{open === 'model' ? (+<div+className="fc-gen-opt-panel drama-ep-opt-panel fc-gen-opt-panel--portal"+style={panelStyle}+role="dialog"+aria-label="视频模型"+>+<div className="fc-gen-opt-panel-title">视频模型</div>+<div className="fc-gen-model-list">+{MODEL_OPTIONS.map((opt) => (+<button+key={opt.id}+type="button"+className={`fc-gen-model-item${modelId === opt.id ? ' selected' : ''}`}+onMouseDown={(e) => e.preventDefault()}+onClick={() => {+onModelChange(opt.id)+setOpen(null)+}}+>+{opt.label}+</button>+))}+</div>+</div>+) : null}- {open === 'output' ? (+++ {open === 'link' ? (+<div+className="fc-gen-opt-panel drama-ep-opt-panel fc-gen-opt-panel--portal"+style={panelStyle}+role="dialog"- aria-label="画幅与清晰度"++ aria-label="镜间衔接"+>- <div className="fc-gen-opt-panel-title">画幅</div>- <div className="fc-gen-chip-row">- {RATIO_OPTIONS.map((r) => (- <button- key={r}- type="button"- className={`fc-gen-chip${aspectRatio === r ? ' selected' : ''}`}- onMouseDown={(e) => e.preventDefault()}- onClick={() => onAspectRatioChange(r)}- >- {r}- </button>- ))}- </div>- <div className="fc-gen-opt-panel-title" style={{ marginTop: 12 }}>- 清晰度- </div>- <div className="fc-gen-chip-row">- {RES_OPTIONS.map((r) => (- <button- key={r}- type="button"- className={`fc-gen-chip${resolution === r ? ' selected' : ''}`}- onMouseDown={(e) => e.preventDefault()}- onClick={() => onResolutionChange(r)}- >- {r}- </button>- ))}- </div>- <div className="fc-gen-opt-panel-title" style={{ marginTop: 12 }}>- 镜间衔接- </div>++ <div className="fc-gen-opt-panel-title">镜间衔接</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}++ {open === 'subtitle' ? (++ <div++ className="fc-gen-opt-panel drama-ep-opt-panel fc-gen-opt-panel--portal"++ style={panelStyle}++ role="dialog"++ aria-label="字幕设置"++ >++ <div className="fc-gen-opt-panel-title">字幕设置</div>++ <label className="drama-ep-link-last-frame">++ <input++ type="radio"++ name="episode-subtitle-mode"++ checked={subtitleMode === 'model'}++ disabled={disabled}++ onChange={() => onSubtitleModeChange('model')}++ />++ <span>++ 模型自出字幕++ <em>+ 切换后会立刻在当前分镜正文里补回「同步字幕 / 字幕 cue」提示词,生成时由模型直接出字幕。+ </em>++ </span>++ </label>++ <label className="drama-ep-link-last-frame">++ <input++ type="radio"++ name="episode-subtitle-mode"++ checked={subtitleMode === 'post'}++ disabled={disabled}++ onChange={() => onSubtitleModeChange('post')}++ />++ <span>++ 后期拼接字幕++ <em>+ 切换后会立刻去掉当前分镜里的字幕提示词;右侧字幕板仍可预览与导出,供后期叠字。</em>+</span>+</label>+</div>+) : null}+</>,+document.body,+)+: null}+</div>+)+}+diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsxindex b48962c..3d3dad3 100644--- a/frontend/src/pages/drama/EpisodeEditPage.tsx+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx@@ -11,7 +11,6 @@ import {import { type ImageStyleId } from '../../lib/dramaImageStyles'import {RATIO_OPTIONS,- RES_OPTIONS,buildFragmentRefStripItems,collectFragmentAssetIds,extractAssetIds,@@ -40,6 +39,12 @@ import {formatDramaGateMessage,} from '../../lib/dramaEpisodeScriptValidate'import { dialog } from '../../lib/dialog'+import {+ formatProjectOutputLabel,+ readEpisodeAspectRatio,+ readEpisodeResolution,+} from '../../lib/dramaProjectOutputSettings'+import { DramaFragmentClipSpec } from '../../components/drama/DramaFragmentClipSpec'import { FragmentPlanSkillModal } from '../../components/drama/FragmentPlanSkillModal'import { DramaGenTaskDetail } from '../../components/drama/DramaGenTaskDetail'import { CircleAlert } from 'lucide-react'@@ -55,6 +60,12 @@ import { EpisodeEditHeaderControls } from './EpisodeEditHeaderControls'import { EpisodeEditPromptEditor } from './EpisodeEditPromptEditor'import { EpisodeEditReferenceStrip } from './EpisodeEditReferenceStrip'import { EpisodeEditSidePane } from './EpisodeEditSidePane'+import {+ applySubtitleModeToFragments,+ readEpisodeSubtitleMode,+ subtitleModeUsesModelOutput,+ type DramaSubtitleMode,+} from '../../lib/dramaSubtitleBoard'import {CharacterVoiceBindModal,readAssetVoiceBinding,@@ -111,7 +122,7 @@ function EpisodeEditInner() {* selectedIndex 当前分镜* assetScope / assetTab 侧栏筛选* editing 是否编辑模式- * videoStyleId / modelId / aspectRatio / resolution 生成参数(UI)+ * videoStyleId / modelId / aspectRatio 生成参数(UI)* busy / status / error 状态*/const [episode, setEpisode] = useState<DramaEpisode | null>(null)@@ -124,13 +135,17 @@ function EpisodeEditInner() {const [videoStyleId, setVideoStyleId] = useState<ImageStyleId | ''>('')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')+ // subtitleMode 本集字幕方式:模型自出 / 后期拼接+ const [subtitleMode, setSubtitleMode] = useState<DramaSubtitleMode>('model')// linkLastFrame 是否用上一镜尾帧作本镜首帧(写入 project.params,默认关闭)const [linkLastFrame, setLinkLastFrame] = useState(false)- // projectParams 项目 params 缓存,切换衔接开关时合并写回+ // projectParams 项目 params 缓存(镜间衔接 + 分集输出规格回退)const [projectParams, setProjectParams] = useState<Record<string, unknown>>({})+ // episodeParams 分集 params 缓存(画幅 / 清晰度写入此处)+ const [episodeParams, setEpisodeParams] = useState<Record<string, unknown>>({})// planModalOpen AI 重新分镜确认(含 Skill 勾选)const [planModalOpen, setPlanModalOpen] = useState(false)+ const [previewVersionId, setPreviewVersionId] = useState<string | null>(null)const [busy, setBusy] = useState(false)const [status, setStatus] = useState('')const [error, setError] = useState('')@@ -150,6 +165,8 @@ function EpisodeEditInner() {ReturnType<typeof dramaApi.generateStatus>>>(() => ({ episode_id: 0, done: 0, failed: 0, running: 0, total: 0, tasks: [], fragments: [] }))const reloadRef = useRef<() => Promise<void>>(async () => {})+ const projectParamsRef = useRef<Record<string, unknown>>({})+ const episodeParamsRef = useRef<Record<string, unknown>>({})const selected = fragments[selectedIndex] || nullconst selectedDuration = selected?.duration_sec ?? 8@@ -180,6 +197,13 @@ function EpisodeEditInner() {const selectedHasVideo = Boolean(selected?.video)// selectedVersions 当前镜历史成片const selectedVersions = useMemo(() => readFragmentVideoVersions(selected), [selected])+ // previewVersion 当前选中待预览的历史成片+ const previewVersion = useMemo(+ () => selectedVersions.find((ver) => ver.id === previewVersionId) ?? null,+ [previewVersionId, selectedVersions],+ )+ const previewVideoUrl = previewVersion ? resolveDramaMediaUrl(previewVersion.video) : null+ const previewPosterUrl = previewVersion?.cover ? resolveDramaMediaUrl(previewVersion.cover) : null// selectedGenerateLocked 仅锁当前镜的「生成」按钮const selectedGenerateLocked = busy || selectedIsGenerating// generateAllLocked 仅提交入队时锁定,生成过程不阻塞编辑@@ -214,7 +238,7 @@ function EpisodeEditInner() {return typeof raw === 'string' ? raw.trim() : ''}, [fragments, selectedIndex])- // 持久化镜间衔接开关到项目 params+ // 持久化镜间衔接开关到项目 params,并让后端重排未开始任务async function handleLinkLastFrameChange(enabled: boolean) {const prevEnabled = linkLastFrameconst prevParams = projectParams@@ -229,10 +253,18 @@ function EpisodeEditInner() {: (nextParams as Record<string, unknown>)setProjectParams(updatedParams)setLinkLastFrame(coerceProjectBool(updatedParams.linkLastFrame ?? updatedParams.link_last_frame, enabled))+ // 刷新本集任务态,让底部分镜条立刻反映串行/并行调整+ try {+ const ep = await dramaApi.getEpisode(eid)+ setEpisode(ep)+ if (Array.isArray(ep.fragments)) setFragments(ep.fragments)+ } catch {+ /* ignore refresh errors */+ }setStatus(enabled- ? '已开启尾帧衔接:将按镜序生成,后一镜会等待上一镜尾帧'- : '已关闭尾帧衔接:将优先并发生成,各镜互不等待',+ ? '已开启尾帧衔接:未开始的任务已改成按镜序排队,进行中的任务不受影响'+ : '已关闭尾帧衔接:未开始的任务已恢复并可并发生成,进行中的任务不受影响',)} catch (err) {setLinkLastFrame(prevEnabled)@@ -241,6 +273,127 @@ function EpisodeEditInner() {}}+ // 持久化本集画幅 / 清晰度到 episode.params;已有成片时提示重新生成+ async function handleEpisodeOutputChange(nextParams: Record<string, unknown>) {+ const prevRatio = readEpisodeAspectRatio(episodeParams, projectParams)+ const prevRes = readEpisodeResolution(episodeParams, projectParams)+ const nextRatio = readEpisodeAspectRatio(nextParams, projectParams)+ const nextRes = readEpisodeResolution(nextParams, projectParams)+ if (prevRatio === nextRatio && prevRes === nextRes) return++ const prevLabel = formatProjectOutputLabel(prevRatio, prevRes)+ const nextLabel = formatProjectOutputLabel(nextRatio, nextRes)+ const generatedCount = fragments.filter((frag) => Boolean(frag.video)).length+ const ok = await dialog.confirm({+ title: '切换画幅 / 清晰度',+ message:+ generatedCount > 0+ ? `将本集从 ${prevLabel} 改为 ${nextLabel}。已生成的 ${generatedCount} 镜不会自动更新,需要重新生成才会按新规格出片。`+ : `将本集从 ${prevLabel} 改为 ${nextLabel}。之后生成的分镜将使用该规格。`,+ confirmText: generatedCount > 0 ? '保存并重新生成' : '保存',+ cancelText: '取消',+ tone: generatedCount > 0 ? 'danger' : 'default',+ })+ if (!ok) return++ const prevParams = episodeParams+ setEpisodeParams(nextParams)+ episodeParamsRef.current = nextParams+ setAspectRatio(nextRatio)+ try {+ const updated = await dramaApi.updateEpisode(eid, { params: nextParams })+ const updatedParams =+ updated.params && typeof updated.params === 'object' && !Array.isArray(updated.params)+ ? (updated.params as Record<string, unknown>)+ : nextParams+ setEpisode(updated)+ setEpisodeParams(updatedParams)+ episodeParamsRef.current = updatedParams+ setAspectRatio(readEpisodeAspectRatio(updatedParams, projectParams))+ setStatus(+ generatedCount > 0+ ? `已更新本集规格为 ${nextLabel},正在按新规格重新入队…`+ : `已更新本集规格为 ${nextLabel}`,+ )+ setError('')+ if (generatedCount > 0) {+ await generateAll({ forceRegen: true, skipConfirm: true })+ }+ } catch (err) {+ setEpisodeParams(prevParams)+ episodeParamsRef.current = prevParams+ setAspectRatio(readEpisodeAspectRatio(prevParams, projectParams))+ setError(err instanceof Error ? err.message : '本集输出规格保存失败')+ throw err+ }+ }++ // 持久化本集字幕方式,并动态改写当前分镜里的字幕提示词+ async function handleEpisodeSubtitleChange(mode: DramaSubtitleMode) {+ if (mode === subtitleMode) return+ const prevParams = episodeParams+ const prevFragments = fragments+ const nextParams = {+ ...episodeParams,+ subtitleMode: mode,+ subtitleEnabled: subtitleModeUsesModelOutput(mode),+ }+ const nextFragments = applySubtitleModeToFragments(fragments, mode)+ setSubtitleMode(mode)+ setEpisodeParams(nextParams)+ episodeParamsRef.current = nextParams+ setFragments(nextFragments)+ try {+ const updated = await dramaApi.updateEpisode(eid, { params: nextParams })+ const updatedParams =+ updated.params && typeof updated.params === 'object' && !Array.isArray(updated.params)+ ? (updated.params as Record<string, unknown>)+ : nextParams+ setEpisode(updated)+ setEpisodeParams(updatedParams)+ episodeParamsRef.current = updatedParams+ setSubtitleMode(readEpisodeSubtitleMode(updatedParams))+ const contentChanged = nextFragments.some(+ (frag, index) => frag.content !== prevFragments[index]?.content,+ )+ if (contentChanged) {+ const ep = await dramaApi.saveFragments(+ eid,+ nextFragments.map((f, i) => {+ const prevFragParams =+ f.params && typeof f.params === 'object' && !Array.isArray(f.params)+ ? (f.params as Record<string, unknown>)+ : {}+ return {+ id: typeof f.id === 'number' && f.id > 0 ? f.id : undefined,+ sort_order: i,+ content: f.content,+ cover: f.cover,+ video: f.video,+ duration_sec: resolveFragmentDurationSec(f.content, f.duration_sec),+ params: { ...prevFragParams, user_edited: true },+ asset_ids: f.asset_ids || [],+ }+ }),+ )+ setEpisode(ep)+ setFragments(ep.fragments || nextFragments)+ }+ setStatus(+ mode === 'model'+ ? '已切换为模型自出字幕,并补回分镜字幕提示词'+ : '已切换为后期拼接字幕,并去掉分镜里的字幕提示词',+ )+ setError('')+ } catch (err) {+ setSubtitleMode(readEpisodeSubtitleMode(prevParams))+ setEpisodeParams(prevParams)+ episodeParamsRef.current = prevParams+ setFragments(prevFragments)+ setError(err instanceof Error ? err.message : '本集字幕方式保存失败')+ }+ }+const referencedIds = useMemo(() => {const set = new Set<number>()for (const f of fragments) {@@ -375,6 +528,14 @@ function EpisodeEditInner() {async function reload() {const ep = await dramaApi.getEpisode(eid)setEpisode(ep)+ const epParams =+ ep.params && typeof ep.params === 'object' && !Array.isArray(ep.params)+ ? (ep.params as Record<string, unknown>)+ : {}+ setEpisodeParams(epParams)+ episodeParamsRef.current = epParams+ setSubtitleMode(readEpisodeSubtitleMode(epParams))+ setAspectRatio(readEpisodeAspectRatio(epParams, projectParamsRef.current))setFragments(ep.fragments || [])if ((ep.fragments || []).length === 0) {setFragments([@@ -406,6 +567,11 @@ function EpisodeEditInner() {})}, [eid])+ // 切换分镜时退出历史版本预览+ useEffect(() => {+ setPreviewVersionId(null)+ }, [selectedIndex, selected?.id])+useEffect(() => {if (!eid || !pid) returnreload().catch((err) => setError(err instanceof Error ? err.message : '加载失败'))@@ -424,16 +590,11 @@ function EpisodeEditInner() {? (project.params as Record<string, unknown>): {}setProjectParams(params)+ projectParamsRef.current = paramsconst linkRaw = params.linkLastFrame ?? params.link_last_framesetLinkLastFrame(coerceProjectBool(linkRaw, false))- 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])- }+ setSubtitleMode(readEpisodeSubtitleMode(episodeParamsRef.current))+ setAspectRatio(readEpisodeAspectRatio(episodeParamsRef.current, params))}).catch(() => {/* ignore */@@ -669,6 +830,7 @@ function EpisodeEditInner() {: f,),)+ setPreviewVersionId(null)setStatus('已切换历史版本')} catch (err) {setError(err instanceof Error ? err.message : '切换版本失败')@@ -677,8 +839,8 @@ function EpisodeEditInner() {}}- // 全部生成:入队本集所有分镜(用保存后的新 id)- async function generateAll() {+ // 全部生成:入队本集分镜(forceRegen 覆盖已有成片)+ async function generateAll(opts?: { forceRegen?: boolean; skipConfirm?: boolean }) {if (fragments.length === 0) {setError('没有可生成的分镜')return@@ -692,7 +854,7 @@ function EpisodeEditInner() {const allWarnings: string[] = []const doneIndices: number[] = []for (let i = 0; i < fragments.length; i++) {- if (shouldSkipGenerateAllFragment(fragments[i])) {+ if (!opts?.forceRegen && shouldSkipGenerateAllFragment(fragments[i])) {doneIndices.push(i)continue}@@ -717,19 +879,23 @@ function EpisodeEditInner() {return}- const ok = await dialog.confirm({- title: '生成全部分镜视频',- message: formatDramaGateMessage(- [],- allWarnings.slice(0, 8).map((message) => ({ level: 'warn' as const, message })),- linkLastFrame- ? `将按镜序排队生成剩余 ${pendingCount} 镜(已生成的 ${doneIndices.length} 镜会跳过)。入队后可继续编辑;后一镜会等待上一镜尾帧写好再开始。`- : `将并发生成剩余 ${pendingCount} 镜(已生成的 ${doneIndices.length} 镜会跳过)。入队后可继续编辑;各镜互不等待。`,- ),- confirmText: allWarnings.length > 0 ? '仍要全部生成' : '全部生成',- tone: 'danger',- })- if (!ok) return+ if (!opts?.skipConfirm) {+ const ok = await dialog.confirm({+ title: opts?.forceRegen ? '按新规格重新生成' : '生成全部分镜视频',+ message: formatDramaGateMessage(+ [],+ allWarnings.slice(0, 8).map((message) => ({ level: 'warn' as const, message })),+ opts?.forceRegen+ ? `将按当前画幅/清晰度重新生成 ${pendingCount} 镜。当前成片会保留为历史版本。`+ : linkLastFrame+ ? `将按镜序排队生成剩余 ${pendingCount} 镜(已生成的 ${doneIndices.length} 镜会跳过)。入队后可继续编辑;后一镜会等待上一镜尾帧写好再开始。`+ : `将并发生成剩余 ${pendingCount} 镜(已生成的 ${doneIndices.length} 镜会跳过)。入队后可继续编辑;各镜互不等待。`,+ ),+ confirmText: allWarnings.length > 0 ? '仍要全部生成' : opts?.forceRegen ? '全部重新生成' : '全部生成',+ tone: 'danger',+ })+ if (!ok) return+ }setBusy(true)setError('')setStatus(`保存并排队生成剩余 ${pendingCount} 条…`)@@ -790,7 +956,7 @@ function EpisodeEditInner() {setPlanModalOpen(true)}- // 入队后轮询至完成+ // 入队后轮询至完成(字幕方式沿用顶栏当前设置)async function startPlanFragments(skillIds: number[]) {setPlanModalOpen(false)setBusy(true)@@ -801,6 +967,7 @@ function EpisodeEditInner() {force: true,fallback_rules: true,skill_ids: skillIds,+ subtitle_enabled: subtitleModeUsesModelOutput(subtitleMode),})const started = Date.now()while (Date.now() - started < 10 * 60 * 1000) {@@ -809,6 +976,9 @@ function EpisodeEditInner() {const st = readFragmentPlanStatus(ep)if (st === 'completed') {setEpisode(ep)+ const nextParams = (ep.params as Record<string, unknown>) || {}+ setEpisodeParams(nextParams)+ episodeParamsRef.current = nextParamssetFragments(ep.fragments || [])setSelectedIndex(0)setEditing(false)@@ -990,14 +1160,15 @@ function EpisodeEditInner() {<EpisodeEditHeaderControlsstyleId={videoStyleId}modelId={modelId}- aspectRatio={aspectRatio}- resolution={resolution}+ episodeParams={episodeParams}+ projectParams={projectParams}linkLastFrame={linkLastFrame}+ subtitleMode={subtitleMode}onStyleChange={setVideoStyleId}onModelChange={setModelId}- onAspectRatioChange={setAspectRatio}- onResolutionChange={setResolution}+ onEpisodeOutputChange={handleEpisodeOutputChange}onLinkLastFrameChange={(enabled) => void handleLinkLastFrameChange(enabled)}+ onSubtitleModeChange={(mode) => void handleEpisodeSubtitleChange(mode)}disabled={busy}/><button@@ -1047,7 +1218,13 @@ function EpisodeEditInner() {<div className="drama-ep-editor-head"><div><strong>{formatFragLabel(selectedIndex, selectedDuration)}</strong>- <p>顶部显示本镜关联;键入 @ 可引用资产或插入时长标签</p>+ <p>+ 顶部显示本镜关联;键入 @ 可引用资产或插入时长标签 ·{' '}+ {formatProjectOutputLabel(+ readEpisodeAspectRatio(episodeParams, projectParams),+ readEpisodeResolution(episodeParams, projectParams),+ )}+ </p></div><label className="drama-ep-duration">时长@@ -1080,7 +1257,6 @@ function EpisodeEditInner() {updateSelected({ content: nextContent, asset_ids: ids })}}/>- </div>{selectedGateIssues.length > 0 ? (<ul className="drama-ep-script-issues" aria-live="polite">@@ -1164,25 +1340,43 @@ function EpisodeEditInner() {</>)}</div>+ </div>{selectedVersions.length > 0 && selected?.id ? (<div className="drama-ep-versions"><span className="drama-ep-versions-label">历史版本</span><div className="drama-ep-versions-list">+ {selectedHasVideo && selected.video ? (+ <button+ type="button"+ className={`drama-ep-version is-active${!previewVersionId ? ' is-current' : ''}`}+ disabled={busy || selectedIsGenerating}+ title="当前成片"+ onClick={() => setPreviewVersionId(null)}+ >+ {selected.cover ? (+ <img src={resolveDramaMediaUrl(selected.cover)} alt="" />+ ) : (+ <video src={resolveDramaMediaUrl(selected.video)} muted />+ )}+ <em>当前</em>+ </button>+ ) : null}{selectedVersions.map((ver, index) => {const cover = ver.cover ? resolveDramaMediaUrl(ver.cover) : ''const video = resolveDramaMediaUrl(ver.video)+ const versionNo = selectedVersions.length - indexreturn (<buttonkey={ver.id}type="button"- className="drama-ep-version"+ className={`drama-ep-version${previewVersionId === ver.id ? ' is-previewing' : ''}`}disabled={busy || selectedIsGenerating}- title="切换为当前成片"- onClick={() => void activateVideoVersion(ver.id)}+ title="点击预览;右侧可设为当前"+ onClick={() => setPreviewVersionId(ver.id)}>{cover ? <img src={cover} alt="" /> : <video src={video} muted />}- <em>v{selectedVersions.length - index}</em>+ <em>v{versionNo}</em></button>)})}@@ -1197,7 +1391,26 @@ function EpisodeEditInner() {onPlayingFragmentChange={handlePlayingFragmentChange}aspectRatio={aspectRatio}episodeName={episode?.name || '本集'}+ subtitleMode={subtitleMode}onOpenStoryboard={openEpisodeStoryboard}+ previewVideoUrl={previewVideoUrl}+ previewPosterUrl={previewPosterUrl}+ previewLabel={+ previewVersion+ ? `v${+ selectedVersions.length -+ selectedVersions.findIndex((ver) => ver.id === previewVersion.id)+ }`+ : ''+ }+ onClearPreview={() => setPreviewVersionId(null)}+ onActivatePreview={+ previewVersionId+ ? () => {+ void activateVideoVersion(previewVersionId)+ }+ : undefined+ }/></div>@@ -1219,6 +1432,10 @@ function EpisodeEditInner() {const clipVideo = frag.video ? resolveDramaMediaUrl(frag.video) : ''const clipCover = frag.cover ? resolveDramaMediaUrl(frag.cover) : ''const showFailHint = fragStatus === 'failed' && !fragBusy+ const fragParams =+ frag.params && typeof frag.params === 'object' && !Array.isArray(frag.params)+ ? (frag.params as Record<string, unknown>)+ : {}return (<div key={`${frag.id}-${index}`} className="drama-ep-clip-wrap"><div@@ -1247,7 +1464,15 @@ function EpisodeEditInner() {</span>)}{badge ? <span className="drama-ep-clip-badge">{badge}</span> : null}- <em>{formatFragLabel(index, frag.duration_sec)}</em>+ <em>+ {formatFragLabel(index, frag.duration_sec)}+ <DramaFragmentClipSpec+ fragmentParams={fragParams}+ episodeParams={episodeParams}+ projectParams={projectParams}+ videoUrl={clipVideo}+ />+ </em></button>{showFailHint ? (<button@@ -1285,7 +1510,7 @@ function EpisodeEditInner() {<FragmentPlanSkillModalopen={planModalOpen}- message="将调用大模型按本集剧本重新规划分镜(覆盖现有分镜与已生成视频),通常需要数十秒。可勾选本次使用的 Skill。"+ message="将调用大模型按本集剧本重新规划分镜(覆盖现有分镜与已生成视频),通常需要数十秒。可勾选本次使用的 Skill。字幕方式沿用顶栏当前设置。"onCancel={() => setPlanModalOpen(false)}onConfirm={(skillIds) => void startPlanFragments(skillIds)}/>diff --git a/frontend/src/pages/drama/EpisodeEditSidePane.tsx b/frontend/src/pages/drama/EpisodeEditSidePane.tsxindex 5820e73..cf1241a 100644--- a/frontend/src/pages/drama/EpisodeEditSidePane.tsx+++ b/frontend/src/pages/drama/EpisodeEditSidePane.tsx@@ -2,6 +2,7 @@import { useState } from 'react'import { Download, Loader2 } from 'lucide-react'import type { DramaFragment } from '../../api/drama'+import { DramaSubtitleBoard } from '../../components/drama/DramaSubtitleBoard'import { DramaFragmentSegmentedVideoPlayer } from '../../components/drama/DramaFragmentSegmentedVideoPlayer'import { triggerBlobDownload } from '../../lib/clientDownload'import {@@ -11,6 +12,7 @@ import {type EpisodeComposeProgress,} from '../../lib/composeEpisodeVideoClient'import { dialog } from '../../lib/dialog'+import type { DramaSubtitleMode } from '../../lib/dramaSubtitleBoard'type Props = {fragments: DramaFragment[]@@ -18,7 +20,14 @@ type Props = {onPlayingFragmentChange: (fragmentId: number) => voidaspectRatio: stringepisodeName?: string+ subtitleMode: DramaSubtitleModeonOpenStoryboard: () => void+ /** 预览历史版本时覆盖当前镜 video src */+ previewVideoUrl?: string | null+ previewPosterUrl?: string | null+ previewLabel?: string+ onClearPreview?: () => void+ onActivatePreview?: () => void}/** 把合成进度转成按钮文案 */@@ -36,7 +45,13 @@ export function EpisodeEditSidePane({onPlayingFragmentChange,aspectRatio,episodeName = '本集',+ subtitleMode,onOpenStoryboard,+ previewVideoUrl = null,+ previewPosterUrl = null,+ previewLabel = '',+ onClearPreview,+ onActivatePreview,}: Props) {const hasSelection = playingFragmentId !== null/*@@ -107,22 +122,49 @@ export function EpisodeEditSidePane({</div>{composeError ? <p className="drama-ep-compose-error drama-ep-compose-error--header">{composeError}</p> : null}+ {previewVideoUrl ? (+ <div className="drama-ep-preview-banner">+ <span>预览历史版本{previewLabel ? ` · ${previewLabel}` : ''}</span>+ <div className="drama-ep-preview-banner-actions">+ {onActivatePreview ? (+ <button type="button" className="drama-ep-preview-banner-btn" onClick={onActivatePreview}>+ 设为当前+ </button>+ ) : null}+ {onClearPreview ? (+ <button type="button" className="drama-ep-preview-banner-btn is-ghost" onClick={onClearPreview}>+ 退出预览+ </button>+ ) : null}+ </div>+ </div>+ ) : null}+{!hasSelection || fragments.length === 0 ? (<p className="drama-ep-empty">请选择底部分镜</p>) : (- <div className="drama-ep-preview-inner">- <DramaFragmentSegmentedVideoPlayer+ <>+ <div className="drama-ep-preview-inner">+ <DramaFragmentSegmentedVideoPlayer+ fragments={fragments}+ playingFragmentId={playingFragmentId}+ onPlayingFragmentChange={onPlayingFragmentChange}+ aspectRatio={aspectRatio}+ overrideVideoUrl={previewVideoUrl}+ overridePosterUrl={previewPosterUrl}+ />+ {!fragments.some((f) => f.video) && (+ <button type="button" className="drama-ep-open-canvas" onClick={onOpenStoryboard}>+ 打开分镜画布+ </button>+ )}+ </div>+ <DramaSubtitleBoardfragments={fragments}- playingFragmentId={playingFragmentId}- onPlayingFragmentChange={onPlayingFragmentChange}- aspectRatio={aspectRatio}+ episodeName={episodeName}+ subtitleMode={subtitleMode}/>- {!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.tsxindex 13f2a62..08367a2 100644--- a/frontend/src/pages/drama/EpisodesStep.tsx+++ b/frontend/src/pages/drama/EpisodesStep.tsx@@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'import { Clapperboard, Film, Layers, Sparkles, Wand2 } from 'lucide-react'import { dramaApi, resolveDramaMediaUrl, type DramaEpisode } from '../../api/drama'import { dialog } from '../../lib/dialog'+import { readEpisodeSubtitleMode, subtitleModeUsesModelOutput } from '../../lib/dramaSubtitleBoard'import { FragmentPlanSkillModal } from '../../components/drama/FragmentPlanSkillModal'import { readFragmentGenerationStatus } from './dramaEpisodeEditUtils'@@ -164,15 +165,17 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {setPlanTarget(ep)}- // 入队单集 LLM 分镜并轮询+ // 入队单集 LLM 分镜并轮询(字幕方式沿用该集当前设置)async function startPlanEpisode(ep: DramaEpisode, skillIds: number[]) {setPlanTarget(null)setPlanningId(ep.id)try {+ const subtitleMode = readEpisodeSubtitleMode(ep.params)await dramaApi.planEpisodeFragments(ep.id, {force: true,fallback_rules: true,skill_ids: skillIds,+ subtitle_enabled: subtitleModeUsesModelOutput(subtitleMode),})const started = Date.now()while (Date.now() - started < 10 * 60 * 1000) {@@ -361,7 +364,7 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {)}<FragmentPlanSkillModalopen={planTarget != null}- message={`将调用大模型重新规划「${planTarget?.name || ''}」的分镜(覆盖本集现有分镜与视频),通常需要数十秒。可勾选本次使用的 Skill。`}+ message={`将调用大模型重新规划「${planTarget?.name || ''}」的分镜(覆盖本集现有分镜与视频),通常需要数十秒。可勾选本次使用的 Skill。字幕方式沿用该集当前设置。`}onCancel={() => setPlanTarget(null)}onConfirm={(skillIds) => {if (planTarget) void startPlanEpisode(planTarget, skillIds)diff --git a/frontend/src/pages/drama/drama.css b/frontend/src/pages/drama/drama.cssindex 072a8b3..b4c2038 100644--- a/frontend/src/pages/drama/drama.css+++ b/frontend/src/pages/drama/drama.css@@ -1912,6 +1912,40 @@text-overflow: ellipsis;}+.drama-project-output-settings {+ flex-shrink: 0;+}++.drama-project-output-btn .drama-project-output-hint {+ margin-left: 2px;+ padding: 0.1rem 0.35rem;+ border-radius: 999px;+ background: rgba(17, 19, 24, 0.06);+ color: #6b7280;+ font-size: 0.65rem;+ font-weight: 600;+}++.drama-project-output-note {+ margin: 0 0 10px;+ color: #6b7280;+ font-size: 0.75rem;+ line-height: 1.45;+}++.drama-ep-project-output-readonly {+ display: inline-flex;+ align-items: center;+ padding: 0.35rem 0.65rem;+ border-radius: 999px;+ border: 1px dashed rgba(17, 19, 24, 0.14);+ background: rgba(255, 255, 255, 0.7);+ color: #374151;+ font-size: 0.75rem;+ font-weight: 600;+ white-space: nowrap;+}+.drama-icon-btn {width: 36px;height: 36px;@@ -2912,6 +2946,16 @@overflow: visible;}+.drama-ep-header-controls > .drama-ep-btn-ghost,+.drama-ep-header-controls > .drama-ep-btn-dark {+ height: 34px;+ padding: 0 14px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ box-sizing: border-box;+}+.drama-ep-header-gen-all {white-space: nowrap;height: 34px;@@ -2924,11 +2968,22 @@overflow: visible;}+.drama-ep-header-gen-opts.fc-gen-opts,+.drama-ep-header-gen-opts .fc-gen-opts {+ margin-top: 0;+}++.drama-ep-header-gen-opts .fc-gen-opts-triggers {+ align-items: center;+}+.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;+ height: 34px;+ box-sizing: border-box;}.drama-ep-header-gen-opts .fc-gen-opt-btn.active {@@ -3289,6 +3344,8 @@.drama-ep-editor-box {flex: 1;min-height: 0;+ display: flex;+ flex-direction: column;border-radius: 16px;background: rgba(255, 255, 255, 0.72);border: 1px solid transparent;@@ -3307,6 +3364,7 @@padding: 0;display: flex;flex-direction: column;+ flex: none;gap: 6px;}@@ -3724,8 +3782,9 @@}.drama-ep-prompt-editor {- min-height: 280px;- height: 100%;+ flex: 1;+ min-height: 160px;+ height: auto;overflow: auto;outline: none;white-space: pre-wrap;@@ -4176,8 +4235,21 @@.drama-ep-editor-actions {display: flex;justify-content: flex-end;+ align-items: center;gap: 10px;- margin-top: 14px;+ margin-top: auto;+ padding-top: 12px;+}++.drama-ep-editor-actions .drama-ep-btn-ghost,+.drama-ep-editor-actions .drama-ep-btn-dark {+ height: 34px;+ min-width: 88px;+ padding: 0 18px;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ box-sizing: border-box;}.drama-ep-btn-ghost,@@ -4797,6 +4869,173 @@font-style: normal;}+.drama-ep-version.is-active,+.drama-ep-version.is-current {+ border-color: #3b82f6;+ box-shadow: 0 0 0 1px color-mix(in srgb, #3b82f6 35%, transparent);+}++.drama-ep-version.is-previewing {+ border-color: #f59e0b;+ box-shadow: 0 0 0 2px color-mix(in srgb, #f59e0b 45%, transparent);+}++.drama-ep-preview-banner {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 10px;+ margin: 0 12px 10px;+ padding: 8px 10px;+ border-radius: 8px;+ background: color-mix(in srgb, #f59e0b 12%, #fffbeb);+ border: 1px solid color-mix(in srgb, #f59e0b 35%, #fde68a);+ font-size: 12px;+ color: #92400e;+}++.drama-ep-preview-banner-actions {+ display: flex;+ gap: 6px;+ flex: none;+}++.drama-ep-preview-banner-btn {+ padding: 4px 10px;+ border-radius: 6px;+ border: 1px solid color-mix(in srgb, #f59e0b 40%, #fcd34d);+ background: #fff;+ color: #b45309;+ font-size: 12px;+ cursor: pointer;+}++.drama-ep-preview-banner-btn.is-ghost {+ background: transparent;+ border-color: transparent;+ color: #78716c;+}++.drama-ep-preview-banner-btn:hover:not(:disabled) {+ background: #fffbeb;+}++.drama-subtitle-board {+ margin: 0 12px 12px;+ border: 1px solid #e5e7eb;+ border-radius: 12px;+ background: #fff;+ overflow: hidden;+ flex: none;+}++.drama-subtitle-board.is-collapsed {+ border-color: #e8ebf0;+}++.drama-subtitle-board__header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 8px 10px;+ border-bottom: 1px solid #eef2f7;+}++.drama-subtitle-board.is-collapsed .drama-subtitle-board__header {+ border-bottom: 0;+}++.drama-subtitle-board__toggle {+ display: flex;+ flex: 1;+ min-width: 0;+ align-items: center;+ justify-content: space-between;+ gap: 8px;+ padding: 0;+ border: 0;+ background: transparent;+ text-align: left;+ cursor: pointer;+ color: inherit;+}++.drama-subtitle-board__title-wrap {+ min-width: 0;+}++.drama-subtitle-board__header h4 {+ margin: 0;+ font-size: 13px;+ font-weight: 600;+ color: #111827;+}++.drama-subtitle-board__header p {+ margin: 2px 0 0;+ font-size: 11px;+ color: #6b7280;+ line-height: 1.4;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.drama-subtitle-board__export {+ flex: none;+ height: 28px;+ padding: 0 10px;+ border-radius: 999px;+ border: 1px solid #d1d5db;+ background: #fff;+ color: #374151;+ font-size: 12px;+ cursor: pointer;+}++.drama-subtitle-board__export:disabled {+ opacity: 0.45;+ cursor: not-allowed;+}++.drama-subtitle-board__list {+ max-height: 180px;+ overflow: auto;+ padding: 6px 8px 10px;+}++.drama-subtitle-board__item {+ padding: 8px 6px;+ border-bottom: 1px solid #f3f4f6;+}++.drama-subtitle-board__item:last-child {+ border-bottom: 0;+}++.drama-subtitle-board__meta {+ display: flex;+ flex-wrap: wrap;+ gap: 8px;+ margin-bottom: 4px;+ font-size: 11px;+ color: #6b7280;+}++.drama-subtitle-board__text {+ font-size: 12px;+ line-height: 1.55;+ color: #111827;+ white-space: pre-wrap;+}++.drama-subtitle-board__empty {+ padding: 14px 12px;+ font-size: 12px;+ color: #6b7280;+}+@keyframes drama-ep-pulse {0%,100% {@@ -4822,7 +5061,9 @@}.drama-ep-clip em {- display: block;+ display: flex;+ flex-direction: column;+ gap: 2px;margin-top: 6px;font-style: normal;font-size: 11px;@@ -4830,6 +5071,12 @@white-space: nowrap;}+.drama-ep-clip-spec {+ font-size: 10px;+ color: #94a3b8;+ letter-spacing: 0.01em;+}+.drama-ep-clip-ops {position: absolute;top: 16px;diff --git a/frontend/src/pages/drama/dramaEpisodeEditUtils.ts b/frontend/src/pages/drama/dramaEpisodeEditUtils.tsindex 6e8d5a8..b8742b7 100644--- a/frontend/src/pages/drama/dramaEpisodeEditUtils.ts+++ b/frontend/src/pages/drama/dramaEpisodeEditUtils.ts@@ -1,5 +1,13 @@/** 分集编辑页辅助:资产分类、引用解析、标签文案 */import type { DramaAsset, DramaFragment } from '../../api/drama'+import {+ DRAMA_RATIO_OPTIONS,+ DRAMA_RES_OPTIONS,+ readEpisodeAspectRatio,+ readEpisodeResolution,+ readProjectAspectRatio,+ readProjectResolution,+} from '../../lib/dramaProjectOutputSettings'export type AssetScope = 'episode' | 'series'export type AssetTab = 'character' | 'scene' | 'prop'@@ -15,8 +23,9 @@ export const MODEL_OPTIONS = [{ id: 'seedance-1.5', label: 'Seedance 1.5' },]-export const RATIO_OPTIONS = ['9:16', '16:9', '1:1'] as const-export const RES_OPTIONS = ['480p', '720p', '1080p'] as const+export const RATIO_OPTIONS = DRAMA_RATIO_OPTIONS+export const RES_OPTIONS = DRAMA_RES_OPTIONS+export { readProjectAspectRatio, readProjectResolution, readEpisodeAspectRatio, readEpisodeResolution }// 从分镜正文提取 @asset:idexport function extractAssetIds(content: string): number[] {