nex_animation/backend/app/api/storyboard.py

633 lines
34 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""分镜与脚本管理接口(图1 模块②):分镜 CRUD/排序、关键帧上传、资产绑定、
提示词编辑与版本、脚本图片批量导入、素材与参数前置检查(图2 节点 2/3/5)。"""
from __future__ import annotations
from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from fastapi.responses import PlainTextResponse
from sqlalchemy import select
from sqlalchemy.orm import Session
from sqlalchemy.exc import IntegrityError
from app import schemas
from app.api import deps
from app.constants import AssetKind, CameraAngle, CameraMovement, GenerationMode, ShotSize, Transition
from app.db import get_db
from app.models import PromptRevision, Shot
from app.services import events, importer, preflight, preview as preview_service
from app.services import prompt as prompt_service, status, storage
router = APIRouter(tags=["storyboard"])
# 枚举字段白名单:写脏值会让提示词组装与出片阶段静默降级(如 mode 拼错 → 模型收到未知模式)
_ENUM_FIELDS: dict[str, list[str]] = {
"shot_size": ShotSize.ALL,
"camera_angle": CameraAngle.ALL,
"camera_movement": CameraMovement.ALL,
"transition_out": Transition.ALL,
"mode": GenerationMode.ALL,
}
# 允许显式清空的字段:前端清空输入框时必须能写回 NULL / 空串,否则「改不回去」
_NULLABLE_FIELDS = {"seed"}
def _validate_shot_fields(patch: dict) -> None:
for field, allowed in _ENUM_FIELDS.items():
value = patch.get(field)
if value not in (None, "") and value not in allowed:
raise HTTPException(400, f"{field} 不支持取值「{value}」,可选:{', '.join(allowed)}")
if patch.get("duration") is not None and float(patch["duration"]) <= 0:
raise HTTPException(400, "镜头时长必须大于 0 秒")
def _apply_shot_fields(shot: Shot, patch: dict) -> None:
"""把补丁写进镜头:None 一律跳过(未填 = 不改),但白名单字段允许显式清空。
``lines`` 必须**最后**写:``set_lines`` 会把它拼接成 ``dialogue`` 全文,
放在前面就会被同一次请求里的 ``dialogue`` 覆盖掉。
"""
for key, value in patch.items():
if key == "lines":
continue
if value is None and key not in _NULLABLE_FIELDS:
continue
setattr(shot, key, value)
if patch.get("lines") is not None:
shot.set_lines(patch["lines"])
def _resequence(db: Session, project) -> None:
"""删除/新增后把镜号重排成连续序号,避免出现 1、2、5、9 这种断号。"""
db.expire(project, ["shots"])
remaining = db.scalars(select(Shot).where(Shot.project_id == project.id)
.order_by(Shot.order_index, Shot.id)).all()
for index, row in enumerate(remaining, start=1):
row.order_index = index
def _ordered_shots(db: Session, project) -> list[Shot]:
db.expire(project, ["shots"])
return list(db.scalars(select(Shot).where(Shot.project_id == project.id)
.order_by(Shot.order_index, Shot.id)).all())
def _next_code(db: Session, project_id: int, taken: set[str]) -> str:
"""为复制出来的镜头找一个未占用的镜号。"""
used = taken | {c for (c,) in db.execute(select(Shot.code).where(Shot.project_id == project_id))}
index = len(used) + 1
while f"S{index:03d}" in used:
index += 1
return f"S{index:03d}"
# ---------------------------------------------------------------- 分镜列表 / CRUD
@router.get("/api/projects/{project_id}/shots")
def list_shots(project_id: int, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shots = db.scalars(select(Shot).where(Shot.project_id == project.id).order_by(Shot.order_index, Shot.id)).all()
return {"shots": [status.shot_dict(db, s) for s in shots], "count": len(shots)}
@router.get("/api/projects/{project_id}/shots/board")
def shots_board(project_id: int, db: Session = Depends(get_db)):
"""分镜工作台一次取全:轻量的镜头卡片 + 逐镜预检 + 汇总。
`/shots` 会为每个镜头回吐完整提示词版本、审核记录与素材版本历史,
几十个镜头时首屏要传几百 KB 且服务端要做等量的关联查询;工作台只需要
缩略图与状态,因此单独给一个轻量视图,并顺手把预检结论并进来。
"""
project = deps.get_project(db, project_id)
shots = db.scalars(select(Shot).where(Shot.project_id == project.id)
.order_by(Shot.order_index, Shot.id)).all()
readiness = preflight.project_readiness(db, project)
issues_by_shot = {c["shot_id"]: c for c in readiness["checks"]}
rows: list[dict] = []
for shot in shots:
assets = [asset for asset in storage.assets_of(db, "shot", shot.id)
if storage.belongs_to_owner(db, "shot", shot.id, asset)]
def thumb(kind: str) -> str:
for asset in assets:
if asset.kind == kind:
return storage.url_for(asset.path)
return ""
check = issues_by_shot.get(shot.id, {"ok": True, "issues": []})
rows.append({
"id": shot.id, "order_index": shot.order_index, "code": shot.code,
"title": shot.title, "description": shot.description, "synopsis": shot.synopsis,
"duration": shot.duration, "shot_size": shot.shot_size,
"camera_angle": shot.camera_angle, "camera_movement": shot.camera_movement,
"transition_out": shot.transition_out, "mode": shot.mode,
"dialogue": shot.dialogue, "speaker_name": shot.speaker.name if shot.speaker else "",
"speaker_character_id": shot.speaker_character_id,
"voice_asset_id": shot.voice_asset_id, "voice_name": shot.voice.name if shot.voice else "",
"subtitle_text": shot.subtitle_text, "subtitle_enabled": shot.subtitle_enabled,
"provider": shot.provider, "model": shot.model,
"effective_provider": shot.provider or project.default_provider,
"effective_model": shot.model or project.default_model,
"status": shot.status, "stage": shot.stage,
"stage_label": status.STAGE_LABELS.get(shot.stage, shot.stage),
"error_code": shot.error_code, "error_message": shot.error_message, "attempts": shot.attempts,
"output_url": storage.url_for(shot.output_path), "output_exists": storage.exists(shot.output_path),
"output_duration": shot.output_duration, "generated_at": shot.generated_at,
"voiceover_url": storage.url_for(shot.voiceover_path),
**preview_service.preview_state(db, shot),
"review_state": shot.review_state, "review_notes": shot.review_notes,
"qc_score": shot.qc_score, "qc_issues": (shot.qc_json or {}).get("issues", []),
"prompt_length": len(shot.prompt or ""),
"prompt_overridden": bool((shot.params_json or {}).get("prompt_override")),
"characters": [{"id": c.id, "name": c.name} for c in (shot.characters or [])],
"scenes": [{"id": s.id, "name": s.name} for s in (shot.scenes or [])],
"keyframe_url": thumb(AssetKind.KEYFRAME), "last_frame_url": thumb(AssetKind.LAST_FRAME),
"reference_count": sum(1 for a in assets if a.kind in (AssetKind.REFERENCE_IMAGE,
AssetKind.REFERENCE_VIDEO)),
"asset_count": len(assets),
"ready": bool(check.get("ok", True)),
"issues": check.get("issues", []),
})
durations = sum(float(s.duration or 0) for s in shots)
return {
"shots": rows, "count": len(rows),
"preflight": {k: v for k, v in readiness.items() if k != "checks"},
"planned_duration": round(durations, 2),
}
@router.get("/api/projects/{project_id}/shots/export")
def export_shots(project_id: int, fmt: str = "md", db: Session = Depends(get_db)):
"""把当前分镜导出成可再次导入的脚本(md / csv / json),改动可以带回编导流程。"""
project = deps.get_project(db, project_id)
shots = db.scalars(select(Shot).where(Shot.project_id == project.id)
.order_by(Shot.order_index, Shot.id)).all()
fmt = (fmt or "md").lower()
if fmt == "json":
payload = [{"order_index": s.order_index, "code": s.code, "title": s.title,
"description": s.description, "shot_size": s.shot_size,
"camera_angle": s.camera_angle, "camera_movement": s.camera_movement,
"duration": s.duration, "transition": s.transition_out, "dialogue": s.dialogue,
"speaker": s.speaker.name if s.speaker else "",
"characters": [c.name for c in (s.characters or [])],
"scene": (s.scenes[0].name if s.scenes else ""), "mode": s.mode, "seed": s.seed}
for s in shots]
return {"project": project.name, "shots": payload, "count": len(payload)}
if fmt in ("csv", "tsv"):
sep = "\t" if fmt == "tsv" else ","
headers = ["镜号", "标题", "画面", "景别", "视角", "运镜", "时长", "转场", "台词", "说话人",
"出镜角色", "场景", "生成模式", "状态"]
lines = [sep.join(headers)]
for s in shots:
cells = [s.code, s.title, s.description,
ShotSize.LABELS.get(s.shot_size, s.shot_size),
CameraAngle.LABELS.get(s.camera_angle, s.camera_angle),
CameraMovement.LABELS.get(s.camera_movement, s.camera_movement),
f"{s.duration:g}", Transition.LABELS.get(s.transition_out, s.transition_out),
s.dialogue, s.speaker.name if s.speaker else "",
"、".join(c.name for c in (s.characters or [])),
s.scenes[0].name if s.scenes else "", s.mode, s.status]
lines.append(sep.join('"%s"' % str(c or "").replace('"', '""') for c in cells))
return PlainTextResponse("\ufeff" + "\n".join(lines) + "\n", media_type="text/csv; charset=utf-8")
blocks = [f"# {project.name} · 分镜脚本(共 {len(shots)} 镜 / "
f"{sum(float(s.duration or 0) for s in shots):.1f} 秒)"]
for s in shots:
lines = [f"## 镜头 {s.order_index}:{s.title or s.code}",
f"画面: {s.description}",
f"景别: {ShotSize.LABELS.get(s.shot_size, s.shot_size)}",
f"视角: {CameraAngle.LABELS.get(s.camera_angle, s.camera_angle)}",
f"运镜: {CameraMovement.LABELS.get(s.camera_movement, s.camera_movement)}",
f"时长: {s.duration:g}"]
if s.transition_out and s.transition_out != Transition.CUT:
lines.append(f"转场: {Transition.LABELS.get(s.transition_out, s.transition_out)}")
if s.dialogue:
lines.append(f"台词: {s.dialogue}")
if s.speaker:
lines.append(f"说话人: {s.speaker.name}")
if s.characters:
lines.append("出镜角色: " + "、".join(c.name for c in s.characters))
if s.scenes:
lines.append("场景: " + "、".join(x.name for x in s.scenes))
blocks.append("\n".join(lines))
return PlainTextResponse("\n\n".join(blocks) + "\n", media_type="text/plain; charset=utf-8")
@router.get("/api/projects/{project_id}/shots/{shot_id}")
def read_shot(project_id: int, shot_id: int, db: Session = Depends(get_db)):
"""单镜头完整详情(含素材、提示词版本、审核记录):工作台缩略图不够用时按需拉取。"""
deps.get_project(db, project_id)
shot = deps.get_shot(db, project_id, shot_id)
return {"shot": status.shot_dict(db, shot)}
@router.post("/api/projects/{project_id}/shots")
def create_shot(project_id: int, data: schemas.ShotCreate, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
payload = data.model_dump(exclude={"params", "order_index"})
_validate_shot_fields(payload)
last = db.scalars(select(Shot.order_index).where(Shot.project_id == project.id)
.order_by(Shot.order_index.desc())).first()
shot = Shot(project_id=project.id, params_json=data.params or {},
order_index=data.order_index or ((last or 0) + 1))
for key, value in payload.items():
if value is not None:
setattr(shot, key, value)
if not shot.code:
shot.code = f"S{shot.order_index:02d}"
if shot.provider is None:
shot.provider = project.default_provider
db.add(shot)
try:
db.flush()
except IntegrityError as exc:
db.rollback()
raise HTTPException(400, f"新建失败:镜号「{shot.code}」已存在,请改用唯一镜号"
f"(原始错误:{exc.orig})") from exc
prompt_service.sync_prompt(db, project, shot, reason="新建分镜自动组装提示词")
events.log_event(db, "shot.created", project_id=project.id, shot_id=shot.id,
message=f"新增分镜 {shot.code}「{shot.title}」", entity_type="shot", entity_id=shot.id)
deps.recheck(db, project)
return deps.done(db, project, status.shot_dict(db, shot))
@router.patch("/api/projects/{project_id}/shots/{shot_id}")
def update_shot(project_id: int, shot_id: int, data: schemas.ShotUpdate, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shot = deps.get_shot(db, project_id, shot_id)
patch = data.model_dump(exclude_unset=True, exclude={"params"})
if data.params:
shot.params_json = {**(shot.params_json or {}), **data.params}
_validate_shot_fields(patch)
structural = {"shot_size", "camera_angle", "camera_movement", "style_note", "description",
"lens_note", "duration", "ambience", "sound_effects"}
# 台词、说话人、声线三样都直接写进提示词(「小燕子台词:「…」,说话音色:女声,青年声」)。
# 过去它们不在重算触发集里:在分镜里把说话人从郭靖改成小燕子,界面立刻对了,
# 提示词却还留着上一个角色的名字和嗓子,生成的视频于是继续用错人配音。
spoken = {"dialogue", "lines", "speaker_character_id", "voice_asset_id"}
touched_prompt = bool((structural | spoken) & set(patch))
reason = ("台词/说话人/声线变更后重算提示词"
if spoken & set(patch) else "分镜参数变更重算提示词")
old_dialogue = shot.dialogue or ""
_apply_shot_fields(shot, patch)
if ("dialogue" in patch or patch.get("lines")) and \
(not shot.subtitle_text or shot.subtitle_text == old_dialogue):
shot.subtitle_text = shot.dialogue or "" # 字幕默认跟随台词,人工改过的字幕保持不动
try:
db.flush()
except IntegrityError as exc:
db.rollback()
raise HTTPException(400, f"保存失败:镜号「{shot.code}」已被其他镜头占用,请换一个镜号"
f"(原始错误:{exc.orig})") from exc
if data.prompt is not None: # 直接写提示词 → 视为人工覆盖
shot.params_json = {**(shot.params_json or {}), "prompt_override": data.prompt}
if data.negative_prompt is not None:
shot.params_json = {**(shot.params_json or {}), "negative_override": data.negative_prompt}
if touched_prompt:
prompt_service.sync_prompt(db, project, shot, reason=reason)
events.log_event(db, "shot.updated", project_id=project.id, shot_id=shot.id,
message=f"更新分镜 {shot.code}", entity_type="shot", entity_id=shot.id, data=patch)
deps.recheck(db, project)
return deps.done(db, project, status.shot_dict(db, shot))
@router.delete("/api/projects/{project_id}/shots/{shot_id}")
def delete_shot(project_id: int, shot_id: int, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shot = deps.get_shot(db, project_id, shot_id)
code = shot.code
removed_files = storage.purge_shot_assets(db, shot)
db.delete(shot)
db.flush()
_resequence(db, project)
deps.recheck(db, project)
events.log_event(db, "shot.deleted", project_id=project.id, message=f"删除分镜 {code}",
data={"shot_id": shot_id, "removed_files": removed_files})
return deps.done(db, project, {"deleted": shot_id})
@router.post("/api/projects/{project_id}/shots/reorder")
def reorder_shots(project_id: int, data: schemas.Reorder, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shots = {s.id: s for s in (project.shots or [])}
if sorted(data.shot_ids) != sorted(shots):
raise HTTPException(400, "重排列表必须完整覆盖当前所有分镜(不多不少)")
for index, sid in enumerate(data.shot_ids, start=1):
shots[sid].order_index = index
db.flush()
for sid in data.shot_ids:
prompt_service.sync_prompt(db, project, shots[sid], reason="分镜顺序调整后重算提示词", record=False)
deps.recheck(db, project)
events.log_event(db, "shot.reordered", project_id=project.id, message="调整分镜顺序",
data={"order": data.shot_ids})
return deps.done(db, project, {"order": data.shot_ids,
"shots": [status.shot_dict(db, shots[s]) for s in data.shot_ids]})
@router.post("/api/projects/{project_id}/shots/bulk")
def bulk_update_shots(project_id: int, data: schemas.ShotBulk, db: Session = Depends(get_db)):
"""分镜工作台批量操作:一次请求完成复制 / 删除 / 移动 / 统一改字段。
逐条发请求会让 N 个镜头触发 N 次预检与流程刷新(每次都要重算全项目),
在几十个镜头的分镜表上会明显卡顿,因此这里合并成一次事务。
"""
project = deps.get_project(db, project_id)
if not data.shot_ids:
raise HTTPException(400, "请先选择镜头")
ordered = _ordered_shots(db, project)
by_id = {s.id: s for s in ordered}
picked = [by_id[sid] for sid in data.shot_ids if sid in by_id]
if not picked:
raise HTTPException(404, "所选镜头不属于该项目")
result: dict = {"action": data.action, "count": len(picked)}
if data.action == "duplicate":
clones: list[Shot] = []
taken = {s.code for s in ordered}
for source in picked:
clone = Shot(project_id=project.id, order_index=source.order_index,
code=_next_code(db, project.id, taken),
title=f"{source.title} 副本" if (source.title or "").strip() else "",
synopsis=source.synopsis, description=source.description,
style_note=source.style_note, shot_size=source.shot_size,
camera_angle=source.camera_angle, camera_movement=source.camera_movement,
lens_note=source.lens_note, duration=source.duration,
transition_out=source.transition_out,
transition_duration_ms=source.transition_duration_ms,
dialogue=source.dialogue, subtitle_text=source.subtitle_text,
subtitle_enabled=source.subtitle_enabled,
speaker_character_id=source.speaker_character_id,
voice_asset_id=source.voice_asset_id, provider=source.provider,
model=source.model, mode=source.mode, seed=source.seed,
params_json={k: v for k, v in (source.params_json or {}).items()
if k in ("prompt_override", "negative_override")})
clone.characters = list(source.characters or [])
clone.scenes = list(source.scenes or [])
db.add(clone)
taken.add(clone.code)
clones.append(clone)
db.flush()
# 副本沿用来源镜头的 order_index,重排时按 (order_index, id) 自然紧跟在来源之后
_resequence(db, project)
for clone in clones:
prompt_service.sync_prompt(db, project, clone, reason="复制分镜自动组装提示词")
_resequence(db, project)
result.update({"created": [s.id for s in clones], "codes": [s.code for s in clones]})
elif data.action == "delete":
for shot in picked:
storage.purge_shot_assets(db, shot)
db.delete(shot)
db.flush()
_resequence(db, project)
result["deleted"] = [s.id for s in picked]
elif data.action == "move":
ids = [s.id for s in ordered]
moving = [sid for sid in ids if sid in set(data.shot_ids)]
rest = [sid for sid in ids if sid not in set(data.shot_ids)]
if data.index is not None:
target = max(1, min(len(ids), int(data.index))) - 1
else:
first = ids.index(moving[0])
target = max(0, min(len(rest), first + int(data.delta)))
order = rest[:target] + moving + rest[target:]
for index, sid in enumerate(order, start=1):
by_id[sid].order_index = index
db.flush()
result["order"] = order
elif data.action == "patch":
patch = dict(data.fields or {})
if not patch:
raise HTTPException(400, "patch 需要提供要统一修改的 fields")
_validate_shot_fields(patch)
unknown = set(patch) - set(schemas.ShotUpdate.model_fields)
if unknown:
raise HTTPException(400, f"不支持批量修改字段:{', '.join(sorted(unknown))}")
structural = {"shot_size", "camera_angle", "camera_movement", "style_note",
"description", "lens_note", "duration"}
touched = bool(structural & set(patch))
for shot in picked:
if patch.get("code"): # 镜号必须唯一,批量统一改号没有意义
raise HTTPException(400, "批量修改不支持镜号(镜号需唯一)")
_apply_shot_fields(shot, patch)
if "duration" in patch:
shot.duration = float(patch["duration"])
try:
db.flush()
except IntegrityError as exc:
db.rollback()
raise HTTPException(400, f"批量修改失败:镜号冲突({exc.orig})") from exc
if touched:
for shot in picked:
prompt_service.sync_prompt(db, project, shot, reason="批量修改分镜参数重算提示词",
record=False)
result["fields"] = sorted(patch)
else: # pragma: no cover - Literal 已约束
raise HTTPException(400, f"不支持的批量操作:{data.action}")
db.flush()
deps.recheck(db, project)
events.log_event(db, f"shot.bulk_{data.action}", project_id=project.id,
message=f"批量{ {'duplicate': '复制', 'delete': '删除', 'move': '移动', 'patch': '修改'}[data.action] } "
f"{result['count']} 个分镜",
data={"shot_ids": data.shot_ids, "fields": data.fields})
return deps.done(db, project, result)
# ---------------------------------------------------------------- 关键帧 / 参考图
@router.post("/api/projects/{project_id}/shots/{shot_id}/assets")
async def upload_shot_asset(project_id: int, shot_id: int, kind: str = Form(AssetKind.KEYFRAME),
name: str = Form(""), note: str = Form(""),
file: UploadFile = File(...), db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shot = deps.get_shot(db, project_id, shot_id)
asset = await deps.save_asset_file(db, file, project=project, owner_type=AssetKind.SHOT,
owner_id=shot.id, kind=kind, name=name, note=note,
stem=f"shot-{shot.id}-{kind}")
prompt_service.sync_prompt(db, project, shot, reason="分镜素材更新重算提示词", record=False)
deps.recheck(db, project)
return deps.done(db, project, {"asset": storage.asset_dict(asset), "shot": status.shot_dict(db, shot)})
# ---------------------------------------------------------------- 资产绑定(图2 节点 3)
@router.post("/api/projects/{project_id}/shots/{shot_id}/bindings")
def bind_shot(project_id: int, shot_id: int, data: schemas.ShotBindings, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shot = deps.get_shot(db, project_id, shot_id)
if data.character_ids is not None:
chars = [deps.get_character(db, project_id, cid) for cid in data.character_ids]
shot.characters = chars
if data.scene_ids is not None:
scenes = [deps.get_scene(db, project_id, sid) for sid in data.scene_ids]
shot.scenes = scenes
if data.speaker_character_id is not None:
if data.speaker_character_id:
deps.get_character(db, project_id, data.speaker_character_id)
shot.speaker_character_id = data.speaker_character_id or None
if data.voice_asset_id is not None:
if data.voice_asset_id:
deps.get_voice(db, project_id, data.voice_asset_id)
shot.voice_asset_id = data.voice_asset_id or None
db.flush()
composed = prompt_service.sync_prompt(db, project, shot, reason="绑定人物/场景/声线后重算提示词")
deps.recheck(db, project)
events.log_event(db, "shot.bound", project_id=project.id, shot_id=shot.id,
message=f"分镜 {shot.code} 绑定资产", entity_type="shot", entity_id=shot.id,
data={"characters": [c.id for c in (shot.characters or [])],
"scenes": [s.id for s in (shot.scenes or [])],
"speaker": shot.speaker_character_id, "voice": shot.voice_asset_id})
return deps.done(db, project, {"shot": status.shot_dict(db, shot), "assembled_prompt": composed})
# ---------------------------------------------------------------- 提示词(调整 → 重新生成)
@router.post("/api/projects/{project_id}/shots/{shot_id}/prompt")
def edit_prompt(project_id: int, shot_id: int, data: schemas.PromptEdit, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
shot = deps.get_shot(db, project_id, shot_id)
params = dict(shot.params_json or {})
if data.auto_sync:
params.pop("prompt_override", None)
params.pop("negative_override", None)
shot.params_json = params
prompt = prompt_service.sync_prompt(db, project, shot, reason=data.reason or "恢复自动组装提示词",
actor=data.actor)
negative = shot.negative_prompt
else:
if data.prompt is None and data.negative_prompt is None:
raise HTTPException(400, "请提供 prompt / negative_prompt,或设置 auto_sync=true")
if data.prompt is not None:
params["prompt_override"] = data.prompt
if data.negative_prompt is not None:
params["negative_override"] = data.negative_prompt
shot.params_json = params
prompt = prompt_service.sync_prompt(db, project, shot, reason=data.reason, actor=data.actor, record=False)
negative = shot.negative_prompt
db.add(PromptRevision(shot_id=shot.id, prompt=prompt, negative_prompt=negative,
params_json={"mode": shot.mode, "model": shot.model, "seed": shot.seed,
"duration": shot.duration, "override": True},
reason=data.reason, actor=data.actor, applied=True))
db.flush()
deps.recheck(db, project)
events.log_event(db, "prompt.updated", project_id=project.id, shot_id=shot.id,
message=f"分镜 {shot.code} 提示词已更新", entity_type="shot", entity_id=shot.id,
data={"reason": data.reason, "auto_sync": data.auto_sync})
return deps.done(db, project, {"prompt": prompt, "negative_prompt": negative,
"overrides": {k: params.get(k, "") for k in ("prompt_override", "negative_override")}})
@router.get("/api/projects/{project_id}/shots/{shot_id}/prompt-revisions")
def prompt_revisions(project_id: int, shot_id: int, db: Session = Depends(get_db)):
deps.get_shot(db, project_id, shot_id)
rows = db.scalars(select(PromptRevision).where(PromptRevision.shot_id == shot_id)
.order_by(PromptRevision.id.desc())).all()
return {"revisions": [{"id": r.id, "prompt": r.prompt, "negative_prompt": r.negative_prompt,
"reason": r.reason, "actor": r.actor, "applied": r.applied,
"params": r.params_json or {}, "created_at": r.created_at} for r in rows]}
# ---------------------------------------------------------------- 前置检查(图2 节点 5)
@router.get("/api/projects/{project_id}/preflight")
def read_preflight(project_id: int, strict: bool = True, apply: bool = True, db: Session = Depends(get_db)):
project = deps.get_project(db, project_id)
readiness = preflight.project_readiness(db, project, strict=strict)
if apply:
preflight.apply_status(db, project, readiness)
db.commit()
return {"preflight": readiness, "summary": deps.summary(db, project)}
# ---------------------------------------------------------------- 批量导入(图2 节点 2)
@router.post("/api/projects/{project_id}/import")
async def import_storyboard(project_id: int,
script: UploadFile | None = File(None),
script_text: str = Form(""),
script_name: str = Form(""),
default_duration: float = Form(5.0),
dry_run: bool = Form(False),
replace: bool = Form(False),
keep_existing: bool = Form(True),
images: list[UploadFile] = File(default_factory=list),
archive: UploadFile | None = File(None),
db: Session = Depends(get_db)):
"""支持:脚本文件 / 脚本文本 / 图片批量 / zip(图片+脚本混合)。"""
project = deps.get_project(db, project_id)
image_bytes: dict[str, bytes] = {}
script_bytes: dict[str, bytes] = {}
for item in images or []:
if not item or not item.filename:
continue
data = await item.read()
if data:
image_bytes[item.filename] = data
if archive is not None and archive.filename:
payload = await archive.read()
if payload:
importer.read_archive(payload, images=image_bytes, scripts=script_bytes)
text = (script_text or "").strip()
name = script_name
if script is not None and script.filename:
raw = await script.read()
text = raw.decode("utf-8-sig", errors="replace").strip()
name = script.filename
if not text:
for key in sorted(script_bytes):
text = script_bytes[key].decode("utf-8-sig", errors="replace").strip()
name = name or key
if text:
break
try:
result = importer.import_storyboard(db, project, script_text=text, script_name=name or "",
images=image_bytes, default_duration=default_duration,
replace=replace, dry_run=dry_run, keep_existing=keep_existing)
except ValueError as exc:
db.rollback()
raise HTTPException(400, str(exc)) from exc
except IntegrityError as exc:
db.rollback()
raise HTTPException(400, f"脚本导入失败:镜号等字段与已有分镜冲突({exc.orig})。"
f"请为每个镜头使用唯一镜号,或勾选「替换现有分镜」后重试。") from exc
if not dry_run:
deps.recheck(db, project)
return {"ok": True, "result": result, "summary": deps.summary(db, project)}
@router.post("/api/projects/{project_id}/shots/preview")
def preview_import(project_id: int, data: schemas.ImportOptions, db: Session = Depends(get_db)):
"""纯文本预览(不落库),用于导入前的格式确认。"""
project = deps.get_project(db, project_id)
try:
rows = importer.parse_script(data.script_text, filename=data.script_name,
default_duration=data.default_duration)
except ValueError as exc:
raise HTTPException(400, str(exc)) from exc
if data.image_names: # 前端已知所选图片,预览即可看到匹配结果
importer.match_images(rows, list(data.image_names))
return {"project_id": project.id, "parsed": len(rows),
"unmatched_images": [n for n in data.image_names
if not any(n in (r.images or []) for r in rows)],
"shots": [r.as_dict() for r in rows]}
@router.post("/api/projects/{project_id}/shots/{shot_id}/preview")
def build_shot_preview_api(project_id: int, shot_id: int, data: schemas.PreviewOptions | None = None,
db: Session = Depends(get_db)):
"""镜头审片预览:画面沿用模型产物,音轨换成平台配音,评审听到的就是成片语音。"""
project = deps.get_project(db, project_id)
shot = db.get(Shot, shot_id)
if shot is None or shot.project_id != project.id:
raise HTTPException(404, f"镜头 {shot_id} 不存在")
options = data or schemas.PreviewOptions()
result = preview_service.build_shot_preview(db, project, shot, force=options.force,
actor=options.actor)
if not result.get("ok"):
raise HTTPException(400, result.get("message") or "审片预览封装失败")
return {"ok": True, "shot": status.shot_dict(db, shot), "preview": result}
@router.post("/api/projects/{project_id}/previews")
def build_project_previews_api(project_id: int, data: schemas.PreviewOptions | None = None,
db: Session = Depends(get_db)):
"""批量封装全片镜头的审片预览(不给 shot_ids 就是全片)。"""
project = deps.get_project(db, project_id)
options = data or schemas.PreviewOptions()
result = preview_service.build_project_previews(db, project, shot_ids=options.shot_ids,
force=options.force, actor=options.actor)
return {"ok": result["failed"] == 0, "project_id": project.id, "result": result}