nex_animation/backend/app/models/storyboard.py

258 lines
13 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.

"""分镜与脚本管理:关键帧、镜头描述、景别、运镜、时长、台词、参考素材 + 资产绑定。"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import (JSON, Boolean, DateTime, Float, ForeignKey, Integer, String, Table, Text,
UniqueConstraint, Column)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from app.constants import ShotStatus, Transition
from app.models.base import TimestampMixin, now_utc
from app.db import Base
shot_characters = Table(
"shot_characters", Base.metadata,
Column("shot_id", ForeignKey("shots.id", ondelete="CASCADE"), primary_key=True),
Column("character_id", ForeignKey("characters.id", ondelete="CASCADE"), primary_key=True),
)
shot_scenes = Table(
"shot_scenes", Base.metadata,
Column("shot_id", ForeignKey("shots.id", ondelete="CASCADE"), primary_key=True),
Column("scene_id", ForeignKey("scenes.id", ondelete="CASCADE"), primary_key=True),
)
class Shot(TimestampMixin, Base):
"""单个分镜(镜头)。"""
__tablename__ = "shots"
__table_args__ = (UniqueConstraint("project_id", "code", name="uq_shot_code"),)
id: Mapped[int] = mapped_column(primary_key=True)
project_id: Mapped[int] = mapped_column(ForeignKey("projects.id", ondelete="CASCADE"), index=True)
order_index: Mapped[int] = mapped_column(Integer, default=1, index=True)
code: Mapped[str] = mapped_column(String(40), default="")
title: Mapped[str] = mapped_column(String(200), default="")
# 脚本 / 镜头描述
synopsis: Mapped[str] = mapped_column(Text, default="") # 剧情梗概(脚本行)
description: Mapped[str] = mapped_column(Text, default="") # 画面描述(生成提示词主体)
prompt: Mapped[str] = mapped_column(Text, default="") # 组装后的最终提示词
negative_prompt: Mapped[str] = mapped_column(Text, default="")
style_note: Mapped[str] = mapped_column(Text, default="")
# 摄影参数
shot_size: Mapped[str] = mapped_column(String(30), default="medium")
camera_angle: Mapped[str] = mapped_column(String(30), default="eye_level")
camera_movement: Mapped[str] = mapped_column(String(30), default="static")
lens_note: Mapped[str] = mapped_column(String(120), default="")
# 时间与转场
duration: Mapped[float] = mapped_column(Float, default=5.0)
transition_out: Mapped[str] = mapped_column(String(30), default=Transition.CUT)
transition_duration_ms: Mapped[int] = mapped_column(Integer, default=500)
# 台词 / 字幕 / 配音
# ``lines`` 是**逐条台词**:[{character_id, name, text}]。
# 一个场景里多人对话时,只有「一整段 dialogue + 单个说话人」是不夠的:
# 平台配音只能用一个嗓子念完整段,字幕也没法标出每句是谁说的。
# ``dialogue`` 继续保留 = 各行台词按顺序拼接的全文(字幕、时长估算、
# 质检对词等既有逻辑都读它),写 lines 时由 ``set_lines`` 同步维护。
lines: Mapped[list | None] = mapped_column(JSON, default=list)
dialogue: Mapped[str] = mapped_column(Text, default="")
speaker_character_id: Mapped[int | None] = mapped_column(ForeignKey("characters.id", ondelete="SET NULL"), nullable=True)
voice_asset_id: Mapped[int | None] = mapped_column(ForeignKey("voice_assets.id", ondelete="SET NULL"), nullable=True)
subtitle_text: Mapped[str] = mapped_column(Text, default="")
subtitle_enabled: Mapped[bool] = mapped_column(Boolean, default=True)
voiceover_path: Mapped[str | None] = mapped_column(String(600), nullable=True)
voiceover_duration_ms: Mapped[int | None] = mapped_column(Integer, nullable=True)
# 环境声 / 镜头级音效。联合音视频模型(MiniMax H3)能一次成片出声,
# 但它只听得懂「听得见的名词短语」:写「键盘敲击声」它就给键盘声,
# 写「这一段没有人说话」它就在片尾真念一句「没有人说话」。
# 所以「这一镜有什么环境声」必须是独立字段,只能填名词短语,不许写成句子。
ambience: Mapped[str] = mapped_column(String(300), default="")
# 镜头级音效素材(后期叠加,不依赖模型):
# [{name, asset_id, path, offset_ms, duration_ms, gain_db}]
sound_effects: Mapped[list | None] = mapped_column(JSON, default=list)
# 生成参数
# 留空表示「跟随项目默认视频模型」:换供应商(mock → ComfyUI/自建)时不必逐镜头改,
# 也不会出现「项目已切到 comfyui,镜头却还写着 mock」这种静默走错模型的情况。
provider: Mapped[str] = mapped_column(String(60), default="")
model: Mapped[str] = mapped_column(String(120), default="")
seed: Mapped[int | None] = mapped_column(Integer, nullable=True)
params_json: Mapped[dict] = mapped_column(JSON, default=dict)
mode: Mapped[str] = mapped_column(String(20), default="i2v") # t2v / i2v / fl(首尾帧)
# 流水线状态(对应业务流程图)
status: Mapped[str] = mapped_column(String(30), default=ShotStatus.DRAFT, index=True)
stage: Mapped[str] = mapped_column(String(40), default="import_storyboard")
error_code: Mapped[str] = mapped_column(String(60), default="")
error_message: Mapped[str] = mapped_column(Text, default="")
attempts: Mapped[int] = mapped_column(Integer, default=0)
current_task_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
# 产物
output_path: Mapped[str | None] = mapped_column(String(600), nullable=True)
output_duration: Mapped[float | None] = mapped_column(Float, nullable=True)
output_checksum: Mapped[str] = mapped_column(String(80), default="")
provider_job_id: Mapped[str] = mapped_column(String(200), default="")
generated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
# 审核
review_state: Mapped[str] = mapped_column(String(20), default="pending")
review_notes: Mapped[str] = mapped_column(Text, default="")
qc_score: Mapped[float | None] = mapped_column(Float, nullable=True)
qc_json: Mapped[dict] = mapped_column(JSON, default=dict)
project: Mapped["Project"] = relationship(back_populates="shots") # noqa: F821
characters: Mapped[list["Character"]] = relationship( # noqa: F821
"Character", secondary=shot_characters, lazy="selectin")
scenes: Mapped[list["Scene"]] = relationship( # noqa: F821
"Scene", secondary=shot_scenes, lazy="selectin")
speaker: Mapped["Character | None"] = relationship("Character", foreign_keys=[speaker_character_id])
voice: Mapped["VoiceAsset | None"] = relationship("VoiceAsset", foreign_keys=[voice_asset_id])
prompt_revisions: Mapped[list["PromptRevision"]] = relationship(
back_populates="shot", cascade="all, delete-orphan", order_by="PromptRevision.id.desc()", lazy="selectin")
reviews: Mapped[list["ReviewRecord"]] = relationship( # noqa: F821
back_populates="shot", cascade="all, delete-orphan", order_by="ReviewRecord.id.desc()", lazy="selectin")
@property
def effective_subtitle(self) -> str:
return (self.subtitle_text or self.dialogue or "").strip()
# ---------------------------------------------------------------- 逐条台词
def all_lines(self) -> list[dict]:
"""归一化的逐行台词。老数据(只有 dialogue + speaker)自动折算成单行。"""
raw = self.lines if isinstance(self.lines, list) else []
out: list[dict] = []
for row in raw:
if not isinstance(row, dict):
text = str(row or "").strip()
if text:
out.append({"character_id": self.speaker_character_id,
"name": (self.speaker.name if self.speaker else ""), "text": text})
continue
text = str(row.get("text") or "").strip()
if not text:
continue
cid = row.get("character_id")
try:
cid = int(cid) if cid else None
except (TypeError, ValueError):
cid = None
out.append({"character_id": cid, "name": str(row.get("name") or "").strip(), "text": text})
if out:
return out
text = (self.dialogue or "").strip()
if text:
return [{"character_id": self.speaker_character_id,
"name": (self.speaker.name if self.speaker else ""), "text": text}]
return []
def line_speaker_name(self, line: dict) -> str:
"""这一行是谁说的:行上的角色 → 镜头说话人 → 出镜名单第 1 人。"""
name = str(line.get("name") or "").strip()
if name:
return name
cid = line.get("character_id") or self.speaker_character_id
if cid:
for char in list(self.characters or []):
if char.id == cid:
return str(char.name or "").strip()
if self.speaker and self.speaker.id == cid:
return str(self.speaker.name or "").strip()
if not line.get("character_id") and self.speaker:
return str(self.speaker.name or "").strip()
chars = list(self.characters or [])
return str(chars[0].name or "").strip() if chars else ""
def set_lines(self, lines: list) -> None:
"""写入逐行台词,并把 ``dialogue`` 同步成拼接全文。"""
norm: list[dict] = []
for row in lines or []:
if not isinstance(row, dict):
text = str(row or "").strip()
row = {"text": text} if text else {}
text = str(row.get("text") or "").strip()
if not text:
continue
cid = row.get("character_id")
try:
cid = int(cid) if cid else None
except (TypeError, ValueError):
cid = None
norm.append({"character_id": cid, "name": str(row.get("name") or "").strip(), "text": text})
self.lines = norm
self.dialogue = "".join(row["text"] for row in norm)
if norm and not self.speaker_character_id:
self.speaker_character_id = norm[0].get("character_id")
if self.subtitle_text and self.subtitle_text.strip() == (self.dialogue or "").strip():
self.subtitle_text = self.dialogue
@property
def has_dialogue(self) -> bool:
return bool(self.all_lines())
# ---------------------------------------------------------------- 镜头音效
def all_sound_effects(self) -> list[dict]:
out: list[dict] = []
for row in (self.sound_effects if isinstance(self.sound_effects, list) else []):
if not isinstance(row, dict):
continue
path = str(row.get("path") or "").strip()
if not path:
continue
def _int(key: str, default: int = 0) -> int:
try:
return int(row.get(key) if row.get(key) is not None else default)
except (TypeError, ValueError):
return default
out.append({"name": str(row.get("name") or "").strip() or "音效",
"asset_id": row.get("asset_id"), "path": path,
"offset_ms": max(0, _int("offset_ms")),
"duration_ms": max(0, _int("duration_ms")),
"gain_db": float(row.get("gain_db") or 0.0)})
return out
class PromptRevision(TimestampMixin, Base):
"""提示词版本(调整提示词 → 重新生成 的历史记录)。"""
__tablename__ = "prompt_revisions"
id: Mapped[int] = mapped_column(primary_key=True)
shot_id: Mapped[int] = mapped_column(ForeignKey("shots.id", ondelete="CASCADE"), index=True)
prompt: Mapped[str] = mapped_column(Text, default="")
negative_prompt: Mapped[str] = mapped_column(Text, default="")
params_json: Mapped[dict] = mapped_column(JSON, default=dict)
reason: Mapped[str] = mapped_column(Text, default="")
actor: Mapped[str] = mapped_column(String(80), default="studio")
applied: Mapped[bool] = mapped_column(Boolean, default=True)
shot: Mapped[Shot] = relationship(back_populates="prompt_revisions")
class ReviewRecord(TimestampMixin, Base):
"""质量检查(自动)与人工审核记录。"""
__tablename__ = "review_records"
id: Mapped[int] = mapped_column(primary_key=True)
project_id: Mapped[int] = mapped_column(ForeignKey("projects.id", ondelete="CASCADE"), index=True)
shot_id: Mapped[int | None] = mapped_column(ForeignKey("shots.id", ondelete="CASCADE"), nullable=True, index=True)
task_id: Mapped[int | None] = mapped_column(Integer, nullable=True, index=True)
kind: Mapped[str] = mapped_column(String(20), default="auto") # auto / manual
verdict: Mapped[str] = mapped_column(String(20), default="pending")
score: Mapped[float | None] = mapped_column(Float, nullable=True)
checks_json: Mapped[dict] = mapped_column(JSON, default=dict)
notes: Mapped[str] = mapped_column(Text, default="")
reviewer: Mapped[str] = mapped_column(String(80), default="")
shot: Mapped[Shot] = relationship(back_populates="reviews")