Skip to content

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

Keep kepu intermediates local and return fresh fragment ids after save.

yi440f79d7852f
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index 25f4847..8ea2504 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -21,7 +21,12 @@ from app.schemas_drama import (
DramaSaveFragmentsRequest,
)
from app.services.agent.compose import parse_skill_ids
-from app.services.drama.access import get_owned_drama_project, get_owned_episode
+from app.services.drama.access import (
+ get_owned_drama_project,
+ get_owned_episode,
+ load_episode_fragments,
+ match_fragments_for_generate,
+)
from app.services.drama.generation import fragment_generation_status
from app.services.drama.jobs import (
cancel_all_episode_video_jobs,
@@ -195,8 +200,8 @@ async def save_fragments(
user: User = Depends(get_current_user),
) -> DramaEpisodeOut:
ep = await get_owned_episode(db, episode_id, user)
- for old in list(ep.fragments or []):
- await db.delete(old)
+ # 用 relationship 清空,保证会话内集合与库一致(delete 旧行但不从 ep.fragments 移除会导致返回旧 id)
+ ep.fragments.clear()
await db.flush()
for item in body.fragments:
frag = DramaEpisodeFragment(
@@ -208,18 +213,26 @@ async def save_fragments(
duration_sec=item.duration_sec,
params=item.params,
)
- db.add(frag)
+ ep.fragments.append(frag)
await db.flush()
- for aid in item.asset_ids:
+ for aid in item.asset_ids or []:
db.add(DramaFragmentAssetRef(fragment_id=frag.id, asset_id=aid))
await db.commit()
- ep = await get_owned_episode(db, episode_id, user)
+ # expire_on_commit=False:必须重查,不能用会话里可能过期的 ep.fragments
+ frags = await load_episode_fragments(db, episode_id)
logger.info(
- "已保存分镜 episode_id=%s count=%s",
+ "已保存分镜 episode_id=%s count=%s ids=%s",
episode_id,
- len(body.fragments),
+ len(frags),
+ [f.id for f in frags],
+ )
+ return DramaEpisodeOut(
+ id=ep.id,
+ name=ep.name,
+ params=ep.params,
+ project_id=ep.project_id,
+ fragments=[_fragment_out(f) for f in frags],
)
- return _episode_out(ep)
@router.post("/episodes/{episode_id}/generate")
@@ -232,14 +245,19 @@ async def generate_episode(
# 入队 Celery / 进程内任务,前端用 generate_status 轮询
ep = await get_owned_episode(db, episode_id, user)
await get_owned_drama_project(db, ep.project_id, user)
- all_frags = sorted(ep.fragments or [], key=lambda f: f.sort_order)
- if body.fragment_ids:
- id_set = set(body.fragment_ids)
- frags = [f for f in all_frags if f.id in id_set]
- else:
- frags = list(all_frags)
+ all_frags = await load_episode_fragments(db, episode_id)
+ frags = match_fragments_for_generate(all_frags, body.fragment_ids)
if not frags:
- raise HTTPException(status_code=400, detail="没有可生成的分镜")
+ logger.warning(
+ "没有可生成的分镜 episode_id=%s requested=%s available=%s",
+ episode_id,
+ body.fragment_ids,
+ [f.id for f in all_frags],
+ )
+ raise HTTPException(
+ status_code=400,
+ detail="没有可生成的分镜(保存后分镜已更新,请再点一次生成)",
+ )
# 已有分镜在排队/生成时,仅禁止重复提交同一分镜
busy_same = [
diff --git a/backend/app/services/drama/access.py b/backend/app/services/drama/access.py
index f0f9ea4..45fb4b2 100644
--- a/backend/app/services/drama/access.py
+++ b/backend/app/services/drama/access.py
@@ -70,3 +70,29 @@ async def get_owned_episode(
if not episode:
raise HTTPException(status_code=404, detail="分集不存在")
return episode
+
+
+async def load_episode_fragments(
+ db: AsyncSession,
+ episode_id: int,
+) -> list[DramaEpisodeFragment]:
+ """显式查询分集下全部分镜(含资产引用),避免 expire_on_commit=False 会话缓存旧集合。"""
+ result = await db.execute(
+ select(DramaEpisodeFragment)
+ .where(DramaEpisodeFragment.episode_id == episode_id)
+ .options(selectinload(DramaEpisodeFragment.asset_references))
+ .order_by(DramaEpisodeFragment.sort_order.asc(), DramaEpisodeFragment.id.asc())
+ )
+ return list(result.scalars().all())
+
+
+def match_fragments_for_generate(
+ all_frags: list[DramaEpisodeFragment],
+ fragment_ids: list[int] | None,
+) -> list[DramaEpisodeFragment]:
+ """按请求的分镜 id 筛选;未传 id 则生成全部。"""
+ ordered = list(all_frags)
+ if not fragment_ids:
+ return ordered
+ id_set = set(fragment_ids)
+ return [f for f in ordered if f.id in id_set]
diff --git a/backend/app/services/oss_queue.py b/backend/app/services/oss_queue.py
index 65345ce..8949153 100644
--- a/backend/app/services/oss_queue.py
+++ b/backend/app/services/oss_queue.py
@@ -164,22 +164,28 @@ async def backfill_media_url(old_url: str, new_url: str) -> int:
return changed
+def collect_pending_column_targets() -> list[tuple[type, list[str]]]:
+ """补传扫描列:科普只扫成片,不含分镜图/配音/镜头视频。"""
+ from app.models import Project, Template, Work
+ from app.models_drama import DramaAsset, DramaEpisodeFragment
+
+ return [
+ (Project, ["final_video_url"]),
+ (Template, ["preview_cover"]),
+ (Work, ["cover_url", "video_url"]),
+ (DramaAsset, ["cover", "url"]),
+ (DramaEpisodeFragment, ["cover", "video"]),
+ ]
+
+
async def collect_pending_local_media_urls(*, limit: int = 2000) -> list[str]:
"""扫描库中仍指向本地 /static 的媒体 URL(含漫剧)。"""
from app.database import AsyncSessionLocal
- from app.models import Project, Shot, Template, Work
- from app.models_drama import DramaAsset, DramaEpisodeFragment
+ from app.models_drama import DramaAsset
found: set[str] = set()
async with AsyncSessionLocal() as db:
- column_targets: list[tuple[type, list[str]]] = [
- (Shot, ["image_url", "video_url", "audio_url"]),
- (Project, ["cover_url", "final_video_url", "ref_image_url"]),
- (Template, ["preview_cover"]),
- (Work, ["cover_url", "video_url"]),
- (DramaAsset, ["cover", "url"]),
- (DramaEpisodeFragment, ["cover", "video"]),
- ]
+ column_targets = collect_pending_column_targets()
for model, fields in column_targets:
clauses = []
for field in fields:
diff --git a/backend/app/services/pipeline.py b/backend/app/services/pipeline.py
index 203da38..67fc223 100644
--- a/backend/app/services/pipeline.py
+++ b/backend/app/services/pipeline.py
@@ -362,6 +362,7 @@ async def _resume_plan(project_id: int) -> tuple[bool, bool, bool, bool]:
return image_text, skip_script, skip_assets, skip_videos
[email protected]_intermediate_oss
async def run_pipeline(project_id: int) -> None:
try:
await _ensure_not_cancelled(project_id)
@@ -1502,6 +1503,7 @@ async def _compose_stage(project_id: int) -> None:
await _settle_billing(project_id)
[email protected]_intermediate_oss
async def regen_shot_image(project_id: int, shot_id: int) -> None:
"""重绘单镜首帧图,并清掉该镜视频以便后续重生。"""
ark = get_ark()
@@ -1542,6 +1544,7 @@ async def regen_shot_image(project_id: int, shot_id: int) -> None:
await db.commit()
[email protected]_intermediate_oss
async def regen_shot_video(project_id: int, shot_id: int) -> None:
ark = get_ark()
async with AsyncSessionLocal() as db:
@@ -1599,6 +1602,7 @@ async def regen_shot_video(project_id: int, shot_id: int) -> None:
await db.commit()
[email protected]_intermediate_oss
async def regen_shot_audio(project_id: int, shot_id: int) -> None:
"""Re-TTS uses continuous full-film narration (editing one shot re-voices the whole track)."""
async with AsyncSessionLocal() as db:
@@ -1632,6 +1636,7 @@ async def regen_shot_audio(project_id: int, shot_id: int) -> None:
await db.commit()
[email protected]_intermediate_oss
async def regen_project_audio_and_compose(project_id: int) -> None:
"""Force continuous re-TTS with current voice, then compose."""
async with AsyncSessionLocal() as db:
@@ -1687,6 +1692,7 @@ async def regen_project_audio_and_compose(project_id: int) -> None:
)
[email protected]_intermediate_oss
async def compose_only(project_id: int) -> None:
await _compose_stage(project_id)
async with AsyncSessionLocal() as db:
diff --git a/backend/app/services/storage.py b/backend/app/services/storage.py
index 150d171..e1b500b 100644
--- a/backend/app/services/storage.py
+++ b/backend/app/services/storage.py
@@ -3,6 +3,7 @@
When OSS is enabled:
- Default (async): return /static URL immediately and enqueue upload+DB backfill.
- sync=True: upload inline (template seed, celery unavailable, etc.).
+- skip_oss_intermediates(): 科普流水线只上传 final.mp4,分镜图/配音/镜头视频留本地。
FFmpeg always reads local files.
"""
@@ -11,12 +12,21 @@ from __future__ import annotations
import base64
import logging
import mimetypes
+from contextlib import contextmanager
+from contextvars import ContextVar
+from functools import wraps
from pathlib import Path
+from typing import Any, Callable, Iterator, TypeVar
import httpx
from app.config import get_settings
+# 科普成片文件名:仅此文件在 skip_oss_intermediates 下仍入 OSS
+_KEPU_FINAL_NAMES = frozenset({"final.mp4"})
+# True 时 publish_local 跳过中间文件的异步 OSS 入队
+_skip_oss_intermediates: ContextVar[bool] = ContextVar("skip_oss_intermediates", default=False)
+
logger = logging.getLogger(__name__)
STATIC_ROOT = Path(__file__).resolve().parents[2] / "static"
@@ -124,6 +134,35 @@ def is_local_static_url(url: str | None) -> bool:
return url.startswith(prefix)
+@contextmanager
+def skip_oss_intermediates() -> Iterator[None]:
+ """科普流水线:中间分镜不入 OSS 队列,成片 final.mp4 仍上传。"""
+ token = _skip_oss_intermediates.set(True)
+ try:
+ yield
+ finally:
+ _skip_oss_intermediates.reset(token)
+
+
+F = TypeVar("F", bound=Callable[..., Any])
+
+
+def without_intermediate_oss(fn: F) -> F:
+ """装饰科普入口:调用期间跳过中间文件异步 OSS 上传。"""
+
+ @wraps(fn)
+ async def _wrapped(*args: Any, **kwargs: Any):
+ with skip_oss_intermediates():
+ return await fn(*args, **kwargs)
+
+ return _wrapped # type: ignore[return-value]
+
+
+def is_kepu_final_media(path: Path) -> bool:
+ """是否为科普最终成片文件(当前仅 final.mp4)。"""
+ return Path(path).name.lower() in _KEPU_FINAL_NAMES
+
+
def upload_local_sync(path: Path, *, retries: int = 2) -> str:
"""Upload file to OSS synchronously; raises if OSS disabled or all retries fail."""
path = Path(path)
@@ -155,6 +194,9 @@ def publish_local(path: Path, *, sync: bool = False, retries: int = 2) -> str:
Default: return /static URL immediately; when OSS+Celery async is on, enqueue
upload and DB backfill. Use sync=True for startup seeds or when immediate OSS
URL is required.
+
+ 科普 skip_oss_intermediates 下:非 final.mp4 的异步上传会被跳过;sync=True
+ 仍上传(Seedance 参考图需要公网 https)。
"""
path = Path(path)
if not path.is_file():
@@ -166,6 +208,11 @@ def publish_local(path: Path, *, sync: bool = False, retries: int = 2) -> str:
if not oss_svc.oss_enabled():
return local_url
+ # 科普中间文件:异步不入队;显式 sync 仍走公网(方舟拉参考图)
+ skip_mid = _skip_oss_intermediates.get() and not is_kepu_final_media(path)
+ if skip_mid and not sync:
+ return local_url
+
settings = get_settings()
want_async = (
not sync
diff --git a/backend/tests/test_kepu_oss_final_only.py b/backend/tests/test_kepu_oss_final_only.py
new file mode 100644
index 0000000..52f4e55
--- /dev/null
+++ b/backend/tests/test_kepu_oss_final_only.py
@@ -0,0 +1,67 @@
+"""科普流水线:中间分镜不入 OSS,仅成片 final.mp4 上传。"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+from app.services import storage
+from app.services.oss_queue import collect_pending_column_targets
+
+
+def test_skip_intermediates_keeps_shot_files_local(tmp_path, monkeypatch):
+ # 分镜图/配音/镜头视频只返回 /static,不成队
+ shot = tmp_path / "shot_001.png"
+ shot.write_bytes(b"png")
+ enqueued: list[str] = []
+
+ monkeypatch.setattr(storage, "STATIC_ROOT", tmp_path)
+ monkeypatch.setattr("app.services.oss.oss_enabled", lambda: True)
+ monkeypatch.setattr(
+ "app.services.oss_queue.enqueue_oss_upload",
+ lambda url: enqueued.append(url) or True,
+ )
+ monkeypatch.setattr(
+ "app.services.storage.get_settings",
+ lambda: type(
+ "S", (), {"oss_upload_async": True, "use_celery": True, "public_base_url": ""}
+ )(),
+ )
+
+ with storage.skip_oss_intermediates():
+ url = storage.publish_local(shot)
+
+ assert url.startswith("/static/")
+ assert enqueued == []
+
+
+def test_skip_intermediates_still_uploads_final_mp4(tmp_path, monkeypatch):
+ # 成片文件仍入 OSS 队列
+ final = tmp_path / "final.mp4"
+ final.write_bytes(b"mp4")
+ enqueued: list[str] = []
+
+ monkeypatch.setattr(storage, "STATIC_ROOT", tmp_path)
+ monkeypatch.setattr("app.services.oss.oss_enabled", lambda: True)
+ monkeypatch.setattr(
+ "app.services.oss_queue.enqueue_oss_upload",
+ lambda url: enqueued.append(url) or True,
+ )
+ monkeypatch.setattr(
+ "app.services.storage.get_settings",
+ lambda: type(
+ "S", (), {"oss_upload_async": True, "use_celery": True, "public_base_url": ""}
+ )(),
+ )
+
+ with storage.skip_oss_intermediates():
+ url = storage.publish_local(final)
+
+ assert url.startswith("/static/")
+ assert enqueued == [url]
+
+
+def test_collect_pending_skips_kepu_shot_columns():
+ # 补传扫描不再扫分镜图/镜头视频/配音,避免把中间文件重新入队
+ models = {model.__name__: fields for model, fields in collect_pending_column_targets()}
+ assert "Shot" not in models
+ assert models["Project"] == ["final_video_url"]
diff --git a/backend/tests/test_match_fragments_generate.py b/backend/tests/test_match_fragments_generate.py
new file mode 100644
index 0000000..970335e
--- /dev/null
+++ b/backend/tests/test_match_fragments_generate.py
@@ -0,0 +1,24 @@
+"""分集生成:按 id 筛选分镜。"""
+
+from types import SimpleNamespace
+
+from app.services.drama.access import match_fragments_for_generate
+
+
+def test_match_all_when_ids_omitted():
+ # 未指定 id 时生成全部
+ frags = [SimpleNamespace(id=1), SimpleNamespace(id=2)]
+ assert match_fragments_for_generate(frags, None) == frags
+ assert match_fragments_for_generate(frags, []) == frags
+
+
+def test_match_subset_by_id():
+ frags = [SimpleNamespace(id=10), SimpleNamespace(id=11), SimpleNamespace(id=12)]
+ got = match_fragments_for_generate(frags, [12, 10])
+ assert [f.id for f in got] == [10, 12]
+
+
+def test_stale_ids_match_nothing():
+ # 保存重建后旧 id 对不上
+ frags = [SimpleNamespace(id=20), SimpleNamespace(id=21)]
+ assert match_fragments_for_generate(frags, [1, 2]) == []
diff --git a/docs/releases/2026-08-17.md b/docs/releases/2026-08-17.md
index 7f28ca8..aaec0e9 100644
--- a/docs/releases/2026-08-17.md
+++ b/docs/releases/2026-08-17.md
@@ -1,5 +1,38 @@
# 发布记录 · 2026-08-17
+## 2026-08-17 19:05 · 分集生成 400:保存后旧分镜 id(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 backend + 重启 api
+- **范围**:backend / api
+- **变更摘要**:
+ - `POST /episodes/{id}/fragments` 保存后显式重查分镜 id 再返回(`expire_on_commit=False` 会话会把已删除的旧 id 返回给前端)
+ - 生成接口对不上 id 时打日志,提示「保存后分镜已更新」
+- **验证**:
+ - [x] `test_match_fragments_generate.py` 通过
+ - [x] `ai-movie-api` 已重启
+- **备注 / 回滚**:
+ - 复现:保存分镜后立刻 `POST .../generate`,body 带着旧 fragment_ids → 400「没有可生成的分镜」
+ - 请再点一次「生成」即可
+
+## 2026-08-17 18:48 · 科普中间文件不再上传 OSS(热修)
+
+- **操作者**:Agent(按用户要求)
+- **方式**:SSH 热修 backend + 重启 api;OSS 队列积压已清空
+- **范围**:backend / api
+- **变更摘要**:
+ - 科普流水线只把成片 `final.mp4` 入 OSS 队列
+ - 分镜图、配音、镜头视频、尾帧只落本地 `/static`,供 ffmpeg 合成
+ - 管理端「补传本地媒体」不再扫描分镜中间文件,避免再次灌满 oss 队列
+- **验证**:
+ - [x] 单测 `test_kepu_oss_final_only.py` 通过
+ - [x] `ai-movie-api` active,`/api/health` ok
+ - [x] Redis `oss` 队列已 `DEL`(pending 归零)
+ - [ ] worker 待 111 出视频结束后再重启,之后新任务才走新逻辑
+- **备注 / 回滚**:
+ - 111 当时仍在 `VIDEOING`,未重启 worker,以免打断 Seedance
+ - 回滚:还原 `storage.py` / `pipeline.py` / `oss_queue.py` 后重启 api+worker
+
## 2026-08-17 17:30 · 当日汇总全量发布
- **操作者**:Agent(按用户要求)
diff --git a/docs/releases/README.md b/docs/releases/README.md
index 6c3db04..97843f8 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -33,6 +33,8 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-08-17 | 分集生成 400:保存后旧分镜 id(热修) | [2026-08-17.md](./2026-08-17.md) |
+| 2026-08-17 | 科普中间文件不再上传 OSS(热修) | [2026-08-17.md](./2026-08-17.md) |
| 2026-08-17 | **全量**:漫剧资产/分集/队列/admin/定价等当日汇总 | [2026-08-17.md](./2026-08-17.md) |
| 2026-08-17 | 分集切分镜 500 + 资产库分页(热修) | [2026-08-17.md](./2026-08-17.md) |
| 2026-08-17 | 资产已出图/上传 UX(热修) | [2026-08-17.md](./2026-08-17.md) |