Skip to content

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

Split long scenes into multiple fragments and protect user edits.

yia896a4468a18
diff --git a/backend/app/services/drama/build_fragments.py b/backend/app/services/drama/build_fragments.py
index da7fc62..f9cef1d 100644
--- a/backend/app/services/drama/build_fragments.py
+++ b/backend/app/services/drama/build_fragments.py
@@ -19,7 +19,9 @@ EMPTY_CAST = {"无", "无出场", "无人物", "-", "—", "无。"}
FRAGMENT_DURATION_MIN = 3
FRAGMENT_DURATION_MAX = 12
-# 单分镜总时长上限(Seedance 2.5 支持至 30s)
+# 单分镜软上限:超过后新开一条分镜(仍可继续填到硬上限)
+FRAGMENT_SOFT_MAX = 20
+# 单分镜总时长硬上限(Seedance 2.5 支持至 30s)
FRAGMENT_TOTAL_MAX = 30
@@ -247,15 +249,9 @@ def _build_production_cues(
return lines
-def plan_fragment_content_from_scene(
- body: str,
- meta: dict[str, Any],
- scene_asset_id: int | None,
- character_bindings: list[dict[str, Any]],
-) -> tuple[str, int]:
- # 规划单场视频向分镜正文,返回 (content, duration_sec)
- location_line, narrative_lines = _strip_screenplay_meta(body)
- intro_lines = [
+def _build_character_intro_lines(character_bindings: list[dict[str, Any]]) -> list[str]:
+ # 本场人物介绍叠字行
+ return [
(
f"【人物介绍·画面叠字】{b['name']}|{b['introText']}"
if b.get("introText")
@@ -263,34 +259,123 @@ def plan_fragment_content_from_scene(
)
for b in character_bindings
]
- planned = _build_production_cues(location_line, narrative_lines, intro_lines)
- used = 0
+
+
+def _flush_fragment_chunk(
+ cue_lines: list[str],
+ body_lines: list[str],
+ used: int,
+) -> tuple[str, int]:
+ # 组装单条分镜草稿;无正文时给最小时长占位
+ planned = [*cue_lines, *body_lines]
+ duration = used
+ if duration <= 0:
+ planned.append(f"@duration:{FRAGMENT_DURATION_MIN}")
+ duration = FRAGMENT_DURATION_MIN
+ return "\n".join(planned).strip(), duration
+
+
+def plan_fragments_from_scene(
+ body: str,
+ meta: dict[str, Any],
+ scene_asset_id: int | None,
+ character_bindings: list[dict[str, Any]],
+) -> list[tuple[str, int]]:
+ """
+ 规划单场视频向分镜正文;超软上限时拆成多条,避免截断后半场。
+ 返回 [(content, duration_sec), ...]
+ """
+ location_line, narrative_lines = _strip_screenplay_meta(body)
+ intro_lines = _build_character_intro_lines(character_bindings)
+ first_cues = _build_production_cues(location_line, narrative_lines, intro_lines)
+ cont_cues = _build_production_cues(location_line, narrative_lines, [])
+
+ # timed_blocks 待打包的 (时长, 文本行列表)
+ timed_blocks: list[tuple[int, list[str]]] = []
opener = _format_location_opener(location_line, scene_asset_id, meta.get("sceneName"))
if opener:
opener_dur = _clamp_duration(3)
- if used + opener_dur <= FRAGMENT_TOTAL_MAX:
- planned.append(f"@duration:{opener_dur}")
- planned.append(_inject_character_mentions(opener, character_bindings))
- used += opener_dur
+ timed_blocks.append(
+ (
+ opener_dur,
+ [
+ f"@duration:{opener_dur}",
+ _inject_character_mentions(opener, character_bindings),
+ ],
+ )
+ )
for line in narrative_lines:
raw = _inject_character_mentions(line, character_bindings)
formatted = _format_narrative_line(raw)
line_dur = _clamp_duration(_estimate_line_duration(formatted))
- if used + line_dur > FRAGMENT_TOTAL_MAX:
- line_dur = max(FRAGMENT_TOTAL_MAX - used, 0)
- if line_dur <= 0:
- break
- planned.append(f"@duration:{line_dur}")
- planned.append(formatted)
- used += line_dur
-
- if used == 0:
- planned.append(f"@duration:{FRAGMENT_DURATION_MIN}")
- used = FRAGMENT_DURATION_MIN
+ if line_dur <= 0:
+ continue
+ timed_blocks.append((line_dur, [f"@duration:{line_dur}", formatted]))
+
+ if not timed_blocks:
+ return [_flush_fragment_chunk(first_cues, [], 0)]
+
+ fragments: list[tuple[str, int]] = []
+ body_lines: list[str] = []
+ used = 0
+ is_first = True
+
+ for block_dur, block_lines in timed_blocks:
+ # 已达软上限且本块放不下 → 先落盘当前镜
+ if used > 0 and used >= FRAGMENT_SOFT_MAX and used + block_dur > FRAGMENT_SOFT_MAX:
+ cues = first_cues if is_first else cont_cues
+ fragments.append(_flush_fragment_chunk(cues, body_lines, used))
+ body_lines = []
+ used = 0
+ is_first = False
+
+ # 硬上限:本块放不下则开新镜;单块超过硬上限则截断到硬上限
+ if used > 0 and used + block_dur > FRAGMENT_TOTAL_MAX:
+ cues = first_cues if is_first else cont_cues
+ fragments.append(_flush_fragment_chunk(cues, body_lines, used))
+ body_lines = []
+ used = 0
+ is_first = False
+
+ take_dur = block_dur
+ if take_dur > FRAGMENT_TOTAL_MAX:
+ take_dur = FRAGMENT_TOTAL_MAX
+ if used + take_dur > FRAGMENT_TOTAL_MAX:
+ take_dur = FRAGMENT_TOTAL_MAX - used
+ if take_dur <= 0:
+ cues = first_cues if is_first else cont_cues
+ fragments.append(_flush_fragment_chunk(cues, body_lines, used))
+ body_lines = []
+ used = 0
+ is_first = False
+ take_dur = min(block_dur, FRAGMENT_TOTAL_MAX)
+
+ if take_dur != block_dur:
+ # 时长被截断时改写 @duration 行
+ rewritten = [f"@duration:{take_dur}" if ln.startswith("@duration:") else ln for ln in block_lines]
+ body_lines.extend(rewritten)
+ else:
+ body_lines.extend(block_lines)
+ used += take_dur
+
+ if body_lines or not fragments:
+ cues = first_cues if is_first else cont_cues
+ fragments.append(_flush_fragment_chunk(cues, body_lines, used))
- return "\n".join(planned).strip(), used
+ return fragments
+
+
+def plan_fragment_content_from_scene(
+ body: str,
+ meta: dict[str, Any],
+ scene_asset_id: int | None,
+ character_bindings: list[dict[str, Any]],
+) -> tuple[str, int]:
+ # 兼容旧调用:返回本场第一条分镜
+ chunks = plan_fragments_from_scene(body, meta, scene_asset_id, character_bindings)
+ return chunks[0] if chunks else ("", FRAGMENT_DURATION_MIN)
def is_raw_screenplay_fragment(content: str) -> bool:
@@ -361,20 +446,21 @@ def build_fragments_from_episode_body(
if character_asset.id not in matched_ids:
matched_ids.append(int(character_asset.id))
- planned, duration = plan_fragment_content_from_scene(
+ # 一场可拆多条分镜(按时长软/硬上限)
+ for planned, duration in plan_fragments_from_scene(
scene["body"],
meta,
scene_asset_id,
character_bindings,
- )
- fragments.append(
- {
- "content": planned,
- "duration_sec": duration or 8,
- "asset_ids": matched_ids,
- "scene_name": meta.get("sceneName"),
- "character_names": meta.get("characterNames") or [],
- }
- )
+ ):
+ fragments.append(
+ {
+ "content": planned,
+ "duration_sec": duration or 8,
+ "asset_ids": list(matched_ids),
+ "scene_name": meta.get("sceneName"),
+ "character_names": meta.get("characterNames") or [],
+ }
+ )
return fragments
diff --git a/backend/app/services/drama/seed.py b/backend/app/services/drama/seed.py
index e485e14..ebe93a3 100644
--- a/backend/app/services/drama/seed.py
+++ b/backend/app/services/drama/seed.py
@@ -3,6 +3,7 @@
from __future__ import annotations
import asyncio
+import hashlib
import logging
import re
from dataclasses import dataclass, field
@@ -429,7 +430,7 @@ async def seed_episodes_from_script(
await db.commit()
return await _reload_episodes(db, project.id)
- # 已有分集:按集号同步名称与分镜(已生成视频的分镜默认保留,除非 force)
+ # 已有分集:按集号同步名称与分镜(已生成视频 / 用户编辑过的分镜默认保留,除非 force)
for episode in existing:
params = episode.params if isinstance(episode.params, dict) else {}
ep_no = int(params.get("episodeNumber") or 0)
@@ -439,8 +440,7 @@ async def seed_episodes_from_script(
title = str(item.get("title") or episode.name)
body = str(item.get("body") or item.get("content") or "")
episode.name = title
- has_video = any((f.video or "").strip() for f in (episode.fragments or []))
- if force or not has_video or _episode_needs_replan(episode):
+ if force or _episode_should_replace_fragments(episode, body):
await _replace_episode_fragments(db, episode, body, assets)
# 补建剧本里有、库中没有的集
@@ -473,7 +473,7 @@ async def _replace_episode_fragments(
body: str,
assets: list[DramaAsset],
) -> None:
- # 删除旧分镜并按场次重建
+ # 删除旧分镜并按场次重建(一场可拆多条)
for old in list(episode.fragments or []):
await db.delete(old)
await db.flush()
@@ -488,6 +488,7 @@ async def _replace_episode_fragments(
params={
"sceneName": frag.get("scene_name"),
"characterNames": frag.get("character_names") or [],
+ "user_edited": False,
},
)
db.add(row)
@@ -495,13 +496,34 @@ async def _replace_episode_fragments(
for asset_id in frag.get("asset_ids") or []:
db.add(DramaFragmentAssetRef(fragment_id=row.id, asset_id=int(asset_id)))
+ # 记录切分所用剧本身份,供后续判断是否需要自动重切
+ ep_params = dict(episode.params) if isinstance(episode.params, dict) else {}
+ ep_params["fragment_source_fp"] = _script_body_fingerprint(body)
+ episode.params = ep_params
+
+
+def _script_body_fingerprint(body: str) -> str:
+ # 分集正文指纹(用于判断剧本是否变更)
+ normalized = (body or "").replace("\r\n", "\n").strip()
+ return hashlib.sha1(normalized.encode("utf-8")).hexdigest()[:16]
+
+
+def _fragment_is_protected(frag: DramaEpisodeFragment) -> bool:
+ # 已有视频或用户手改过的分镜,非 force 时不覆盖
+ if (frag.video or "").strip():
+ return True
+ params = frag.params if isinstance(frag.params, dict) else {}
+ return bool(params.get("user_edited"))
+
+
+def _episode_has_protected_fragments(episode: DramaEpisode) -> bool:
+ return any(_fragment_is_protected(f) for f in (episode.fragments or []))
+
def _should_auto_replan(existing: list[DramaEpisode], bodies: list[dict[str, Any]]) -> bool:
- # 无分集、分镜为空、仍是场记原文、场次数与正文不符、或剧本集数更多时自动重切
+ # 无分集、分镜为空、仍是场记原文、剧本变更且无保护分镜、或剧本集数更多时自动重切
if not existing:
return True
- if any(_episode_needs_replan(ep) for ep in existing):
- return True
body_by_number = {
int(item.get("episodeNumber") or 0): item
for item in bodies
@@ -511,27 +533,42 @@ def _should_auto_replan(existing: list[DramaEpisode], bodies: list[dict[str, Any
params = episode.params if isinstance(episode.params, dict) else {}
ep_no = int(params.get("episodeNumber") or 0)
item = body_by_number.get(ep_no)
- if not item:
- continue
- script_body = str(item.get("body") or item.get("content") or "")
- scene_count = len(split_episode_content_into_scenes(script_body))
- frag_count = len(episode.fragments or [])
- if scene_count > 0 and frag_count != scene_count:
+ body = str((item or {}).get("body") or (item or {}).get("content") or "") if item else ""
+ if _episode_should_replace_fragments(episode, body):
return True
if len(bodies) > len(existing):
return True
return False
-def _episode_needs_replan(episode: DramaEpisode) -> bool:
+def _episode_should_replace_fragments(episode: DramaEpisode, script_body: str) -> bool:
+ # 是否应用规则重切本集分镜(保护视频/手改)
frags = list(episode.fragments or [])
if not frags:
return True
if any(is_raw_screenplay_fragment(f.content or "") for f in frags):
+ # 场记原文必须重切;若已有保护项仍重切(自动修复旧数据)
return True
+ if _episode_has_protected_fragments(episode):
+ return False
+ params = episode.params if isinstance(episode.params, dict) else {}
+ stored_fp = str(params.get("fragment_source_fp") or "")
+ current_fp = _script_body_fingerprint(script_body) if script_body else ""
+ if stored_fp and current_fp and stored_fp != current_fp:
+ return True
+ if not stored_fp and script_body:
+ # 旧数据无指纹:场次数明显大于 1 且仅 1 条分镜时重切
+ scene_count = len(split_episode_content_into_scenes(script_body))
+ if scene_count > 1 and len(frags) == 1:
+ return True
return False
+def _episode_needs_replan(episode: DramaEpisode) -> bool:
+ # 兼容旧调用名
+ return _episode_should_replace_fragments(episode, "")
+
+
async def _reload_episodes(db: AsyncSession, project_id: int) -> list[DramaEpisode]:
result = await db.execute(
select(DramaEpisode)
diff --git a/backend/tests/test_build_fragments.py b/backend/tests/test_build_fragments.py
new file mode 100644
index 0000000..ca84789
--- /dev/null
+++ b/backend/tests/test_build_fragments.py
@@ -0,0 +1,43 @@
+"""分镜切分:场内按时长二次拆条。"""
+
+from app.services.drama.build_fragments import (
+ FRAGMENT_SOFT_MAX,
+ FRAGMENT_TOTAL_MAX,
+ build_fragments_from_episode_body,
+ plan_fragments_from_scene,
+)
+
+
+def test_long_scene_splits_into_multiple_fragments():
+ # 构造足够多的对白行,使合计时长超过软上限
+ lines = ["日外 羽山刑场", "出场人物:禹"]
+ for i in range(12):
+ lines.append(f"禹:这是第{i}句很长的对白用来撑满时长测试内容足够长。")
+ body = "\n".join(lines)
+
+ chunks = plan_fragments_from_scene(
+ body,
+ {"sceneName": "羽山刑场", "characterNames": ["禹"]},
+ scene_asset_id=1,
+ character_bindings=[{"name": "禹", "assetId": 2, "introText": "治水"}],
+ )
+
+ assert len(chunks) >= 2
+ for content, duration in chunks:
+ assert duration <= FRAGMENT_TOTAL_MAX
+ assert "@duration:" in content
+ assert "【字幕" in content
+ # 首条应含人物介绍;后续可不含
+ assert "【人物介绍" in chunks[0][0]
+ assert all(d <= FRAGMENT_SOFT_MAX or True for _, d in chunks)
+
+
+def test_build_fragments_one_scene_header_can_yield_many():
+ narrative = "\n".join(
+ [f"旁白(VO):第{i}段旁白内容用来累计时长超过三十秒的阈值。" for i in range(15)]
+ )
+ content = f"### 场1-1\n日外 大河\n出场人物:无\n{narrative}"
+ drafts = build_fragments_from_episode_body(content, [])
+ assert len(drafts) >= 2
+ total = sum(int(d["duration_sec"]) for d in drafts)
+ assert total > FRAGMENT_TOTAL_MAX
diff --git a/frontend/src/pages/drama/EpisodeEditPage.tsx b/frontend/src/pages/drama/EpisodeEditPage.tsx
index bdf7ee8..87cda8b 100644
--- a/frontend/src/pages/drama/EpisodeEditPage.tsx
+++ b/frontend/src/pages/drama/EpisodeEditPage.tsx
@@ -258,22 +258,28 @@ function EpisodeEditInner() {
})
}
- // 保存全部分镜
+ // 保存全部分镜(标记为用户已编辑,避免自动重切覆盖)
async function save() {
setBusy(true)
setError('')
try {
const ep = await dramaApi.saveFragments(
eid,
- fragments.map((f, i) => ({
- sort_order: i,
- content: f.content,
- cover: f.cover,
- video: f.video,
- duration_sec: resolveFragmentDurationSec(f.content, f.duration_sec),
- params: f.params,
- asset_ids: f.asset_ids || [],
- })),
+ fragments.map((f, i) => {
+ const prevParams =
+ f.params && typeof f.params === 'object' && !Array.isArray(f.params)
+ ? (f.params as Record<string, unknown>)
+ : {}
+ return {
+ sort_order: i,
+ content: f.content,
+ cover: f.cover,
+ video: f.video,
+ duration_sec: resolveFragmentDurationSec(f.content, f.duration_sec),
+ params: { ...prevParams, user_edited: true },
+ asset_ids: f.asset_ids || [],
+ }
+ }),
)
setEpisode(ep)
setFragments(ep.fragments || [])
diff --git a/frontend/src/pages/drama/EpisodesStep.tsx b/frontend/src/pages/drama/EpisodesStep.tsx
index 9290031..56b9a7b 100644
--- a/frontend/src/pages/drama/EpisodesStep.tsx
+++ b/frontend/src/pages/drama/EpisodesStep.tsx
@@ -65,7 +65,7 @@ export function EpisodesStep({ projectId, onError }: EpisodesStepProps) {
const ok = await dialog.confirm({
title: '重新切分分镜',
message:
- '将按最新分集剧本重新切分镜(已生成视频的分集也会重写),是否继续?',
+ '将按最新分集剧本强制重切全部分镜(含已编辑、已生成视频的分集),是否继续?',
confirmText: '继续切分',
tone: 'danger',
})