406 lines
15 KiB
Python
406 lines
15 KiB
Python
"""独立 v3 故事模型及确定性编译,不读数据库或调用语言模型。"""
|
|
|
|
from dataclasses import dataclass
|
|
import hashlib
|
|
import json
|
|
from typing import Literal
|
|
|
|
from pydantic import Field, model_validator, model_serializer
|
|
from app.domain.timeline import Strict, Render, MAX_WORKFLOW_SHOTS
|
|
from app.domain.video_generation import H3_PROFILES, H3_TP2_PROFILE
|
|
|
|
ID = r"^[0-9a-f]{32}$"
|
|
|
|
|
|
def digest(value):
|
|
return hashlib.sha256(
|
|
json.dumps(
|
|
value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False
|
|
).encode()
|
|
).hexdigest()
|
|
|
|
|
|
class Context(Strict):
|
|
era: str = ""
|
|
style: str = ""
|
|
palette: str = ""
|
|
lighting: str = ""
|
|
negative_prompt: str = ""
|
|
|
|
|
|
class Variant(Strict):
|
|
id: str = Field(pattern=ID)
|
|
name: str = ""
|
|
description: str = ""
|
|
reference_asset_ids: list[str] = Field(default_factory=list)
|
|
|
|
|
|
class Entity(Variant):
|
|
kind: Literal["person", "creature", "prop"] = "person"
|
|
forms: list[Variant] = Field(default_factory=list)
|
|
appearances: list[Variant] = Field(default_factory=list)
|
|
|
|
|
|
class Scene(Variant):
|
|
location: str = ""
|
|
time: str = ""
|
|
weather: str = ""
|
|
lighting: str = ""
|
|
|
|
|
|
class Cast(Strict):
|
|
id: str = Field(pattern=ID)
|
|
entity_id: str = Field(pattern=ID)
|
|
form_id: str | None = Field(default=None, pattern=ID)
|
|
appearance_id: str | None = Field(default=None, pattern=ID)
|
|
position: str = ""
|
|
action: str = ""
|
|
|
|
|
|
class Overrides(Strict):
|
|
time: str | None = None
|
|
weather: str | None = None
|
|
lighting: str | None = None
|
|
palette: str | None = None
|
|
|
|
@model_validator(mode="before")
|
|
@classmethod
|
|
def no_null(cls, value):
|
|
if isinstance(value, dict) and any(v is None for v in value.values()):
|
|
raise ValueError("override must be a string; remove key to inherit")
|
|
return value
|
|
|
|
def model_dump(self, **kwargs):
|
|
return super().model_dump(exclude_unset=True, **kwargs)
|
|
|
|
|
|
class FrameParameters(Strict):
|
|
seed: int = Field(default=42, ge=0, le=2**32 - 1)
|
|
|
|
|
|
class VideoParameters(FrameParameters):
|
|
profile: (
|
|
Literal["minimax-h3-fl2va-bf16-v1", "minimax-h3-fl2va-bf16-tp2-v1", "wan2.2-ti2v-5b-v1"]
|
|
| None
|
|
) = None
|
|
source_seconds: int = Field(default=5, ge=1, le=15)
|
|
num_inference_steps: int = Field(default=50, ge=1, le=100)
|
|
guidance_scale: float = Field(default=5.0, ge=1, le=20, allow_inf_nan=False)
|
|
upscale: bool = True
|
|
|
|
@model_validator(mode="after")
|
|
def tp2_contract(self):
|
|
if self.profile == H3_TP2_PROFILE and (self.upscale or self.num_inference_steps < 2):
|
|
raise ValueError("H3双卡不支持画质增强且至少需要2步")
|
|
return self
|
|
|
|
@model_serializer(mode="wrap")
|
|
def preserve_legacy_shape(self, handler):
|
|
result = handler(self)
|
|
if self.profile is None:
|
|
result.pop("profile", None)
|
|
if self.profile in H3_PROFILES:
|
|
result.pop("guidance_scale", None)
|
|
return result
|
|
|
|
|
|
class Edit(Strict):
|
|
start_frame: int = Field(default=0, ge=0)
|
|
duration_frames: int = Field(default=120, ge=24, le=360)
|
|
|
|
|
|
class StoryShot(Strict):
|
|
id: str = Field(pattern=ID)
|
|
name: str = ""
|
|
scene_id: str | None = Field(default=None, pattern=ID)
|
|
cast: list[Cast] = Field(default_factory=list)
|
|
visual_prompt: str = Field(default="", max_length=8000)
|
|
motion_prompt: str = Field(default="", max_length=8000)
|
|
overrides: Overrides = Field(default_factory=Overrides)
|
|
frame_parameters: FrameParameters = Field(default_factory=FrameParameters)
|
|
video_parameters: VideoParameters = Field(default_factory=VideoParameters)
|
|
edit: Edit = Field(default_factory=Edit)
|
|
|
|
|
|
class StorySpecV3(Strict):
|
|
schema_version: Literal[3] = 3
|
|
profile: Literal["landscape_1080_v1", "portrait_1080_v1"] = "landscape_1080_v1"
|
|
context: Context = Field(default_factory=Context)
|
|
scenes: list[Scene] = Field(default_factory=list)
|
|
entities: list[Entity] = Field(default_factory=list)
|
|
shots: list[StoryShot] = Field(min_length=1, max_length=MAX_WORKFLOW_SHOTS)
|
|
render: Render = Field(default_factory=Render)
|
|
|
|
@model_validator(mode="after")
|
|
def consistent(self):
|
|
all_ids = []
|
|
for collection in (self.scenes, self.entities, self.shots):
|
|
all_ids.extend(x.id for x in collection)
|
|
for entity in self.entities:
|
|
all_ids.extend(x.id for x in entity.forms + entity.appearances)
|
|
for shot in self.shots:
|
|
all_ids.extend(x.id for x in shot.cast)
|
|
if len(set(all_ids)) != len(all_ids):
|
|
raise ValueError("duplicate stable id")
|
|
scenes = {x.id for x in self.scenes}
|
|
entities = {x.id: x for x in self.entities}
|
|
for shot in self.shots:
|
|
if shot.scene_id and shot.scene_id not in scenes:
|
|
raise ValueError("scene reference missing")
|
|
for cast in shot.cast:
|
|
entity = entities.get(cast.entity_id)
|
|
if (
|
|
entity is None
|
|
or (cast.form_id and cast.form_id not in {x.id for x in entity.forms})
|
|
or (
|
|
cast.appearance_id
|
|
and cast.appearance_id not in {x.id for x in entity.appearances}
|
|
)
|
|
):
|
|
raise ValueError("entity/form/appearance reference missing")
|
|
# 生成源长度不代表人工素材长度;实际选用范围由候选来源与媒体帧数校验。
|
|
frames = sum(
|
|
s.edit.duration_frames - getattr(s.edit, "dedup_frames", 0) for s in self.shots
|
|
)
|
|
if self.render.total_frames is not None and self.render.total_frames != frames:
|
|
raise ValueError("total_frames differs from edits")
|
|
self.render.total_frames = frames
|
|
if any(s.end_frame > frames for s in self.render.subtitles):
|
|
raise ValueError("subtitle exceeds canvas")
|
|
audio = self.render.audio
|
|
if audio and hasattr(audio, "source_end_sample"):
|
|
if (
|
|
audio.offset_sample + audio.source_end_sample - audio.source_start_sample
|
|
> frames * 2000
|
|
):
|
|
raise ValueError("audio exceeds canvas")
|
|
elif audio and (
|
|
audio.offset_frame >= frames
|
|
or (audio.source_end_ms - audio.source_start_ms) * 24
|
|
> (frames - audio.offset_frame) * 1000
|
|
):
|
|
raise ValueError("audio exceeds canvas")
|
|
return self
|
|
|
|
def model_dump(self, **kwargs):
|
|
data = super().model_dump(**kwargs)
|
|
for shot, model in zip(data["shots"], self.shots):
|
|
shot["overrides"] = model.overrides.model_dump()
|
|
return data
|
|
|
|
|
|
def parse_story_spec(raw):
|
|
from app.domain.continuity import StorySpecV4
|
|
|
|
if isinstance(raw, StorySpecV3):
|
|
return raw
|
|
if not isinstance(raw, dict):
|
|
raise ValueError("expected story object")
|
|
version = raw.get("schema_version", 3)
|
|
if version == 4:
|
|
return StorySpecV4.model_validate(raw)
|
|
if version == 3:
|
|
return StorySpecV3.model_validate(raw)
|
|
raise ValueError("unsupported story version")
|
|
|
|
|
|
def ordered_reference_ids(references):
|
|
"""编号与模型输入共享同一首次去重顺序,角色清单自身不去重。"""
|
|
return list(dict.fromkeys(ref["asset_id"] for ref in references))
|
|
|
|
|
|
def reference_binding_suffix(references):
|
|
if not references:
|
|
return ""
|
|
lines = []
|
|
for index, asset_id in enumerate(ordered_reference_ids(references), 1):
|
|
labels = list(
|
|
dict.fromkeys(
|
|
(ref["role"], ref["label"]) for ref in references if ref["asset_id"] == asset_id
|
|
)
|
|
)
|
|
bindings = "; ".join(
|
|
f"{role} {json.dumps(label, ensure_ascii=False)}" for role, label in labels
|
|
)
|
|
lines.append(f"Picture {index}: {bindings}.")
|
|
return (
|
|
"\n\nReference image bindings (Picture numbers follow the attached image order):\n"
|
|
+ "\n".join(lines)
|
|
+ "\nUse scene references for the setting and background. Use entity, form and appearance references only for their named subject; preserve its identity, selected form and costume. Compose one frame according to the shot description; do not draw the Picture labels."
|
|
)
|
|
|
|
|
|
def text_frame_prompt(compiled_shot):
|
|
"""显式文生图不声称已附图,只移除编译器确定追加的映射后缀。"""
|
|
return compiled_shot["frame_prompt"].removesuffix(
|
|
reference_binding_suffix(compiled_shot["references"])
|
|
)
|
|
|
|
|
|
def compile_story(spec, assets):
|
|
spec = parse_story_spec(spec)
|
|
scenes, entities = {s.id: s for s in spec.scenes}, {e.id: e for e in spec.entities}
|
|
results = []
|
|
for shot in spec.shots:
|
|
scene = scenes.get(shot.scene_id)
|
|
effective = spec.context.model_dump()
|
|
if scene:
|
|
effective.update(
|
|
{k: getattr(scene, k) for k in ("time", "weather", "lighting") if getattr(scene, k)}
|
|
)
|
|
effective.update(shot.overrides.model_dump())
|
|
parts = [f"{k}: {v}" for k, v in effective.items() if v and k != "negative_prompt"]
|
|
bound_parts = list(parts)
|
|
aliases = {}
|
|
for cast in shot.cast:
|
|
if cast.entity_id not in aliases:
|
|
entity = entities[cast.entity_id]
|
|
kind = {"person": "Character", "creature": "Creature", "prop": "Prop"}[entity.kind]
|
|
aliases[entity.id] = f"{kind} {len(aliases) + 1} / {entity.name or entity.kind}"
|
|
bound_items = set()
|
|
refs = []
|
|
errors = []
|
|
|
|
def include(item, role, label):
|
|
parts.extend(v for v in (item.name, item.description) if v)
|
|
if (role, item.id) not in bound_items:
|
|
bound_items.add((role, item.id))
|
|
description = f": {item.description}" if item.description else ""
|
|
bound_parts.append(f"{role} {json.dumps(label, ensure_ascii=False)}{description}")
|
|
for asset_id in item.reference_asset_ids:
|
|
asset = assets.get(asset_id)
|
|
sha = (
|
|
asset.get("sha256")
|
|
if isinstance(asset, dict)
|
|
else getattr(asset, "sha256", None)
|
|
)
|
|
refs.append({"asset_id": asset_id, "sha256": sha, "role": role, "label": label})
|
|
if not sha:
|
|
errors.append(
|
|
{
|
|
"code": "reference_unavailable",
|
|
"message": "参考素材不存在或不可访问",
|
|
"asset_id": asset_id,
|
|
}
|
|
)
|
|
|
|
if scene:
|
|
scene_alias = f"Scene 1 / {scene.name or 'unnamed scene'}"
|
|
include(scene, "scene", scene_alias)
|
|
if scene.location:
|
|
parts.append(scene.location)
|
|
bound_parts.append(
|
|
f"{json.dumps(scene_alias, ensure_ascii=False)} location: {scene.location}"
|
|
)
|
|
for cast in shot.cast:
|
|
entity = entities[cast.entity_id]
|
|
alias = aliases[entity.id]
|
|
include(entity, "entity", alias)
|
|
for key, role in (("form_id", "form"), ("appearance_id", "appearance")):
|
|
selected = getattr(cast, key)
|
|
if selected:
|
|
variant = next(
|
|
v
|
|
for v in getattr(entity, "forms" if role == "form" else "appearances")
|
|
if v.id == selected
|
|
)
|
|
include(
|
|
variant,
|
|
role,
|
|
f"{alias} / {variant.name or role}",
|
|
)
|
|
parts.extend(v for v in (cast.position, cast.action) if v)
|
|
for key in ("position", "action"):
|
|
if value := getattr(cast, key):
|
|
bound_parts.append(f"{json.dumps(alias, ensure_ascii=False)} {key}: {value}")
|
|
parts.append(shot.visual_prompt)
|
|
bound_parts.append(shot.visual_prompt)
|
|
if refs:
|
|
bound_parts.insert(
|
|
0,
|
|
"Use the following subject aliases to bind descriptions and spatial relations; do not draw these alias labels or numbers as text.",
|
|
)
|
|
if spec.schema_version == 4:
|
|
context = {k: v for k, v in shot.continuity.state_in.model_dump().items() if v}
|
|
if context:
|
|
state_prompt = "Initial state: " + json.dumps(
|
|
context, ensure_ascii=False, sort_keys=True
|
|
)
|
|
parts.append(state_prompt)
|
|
bound_parts.append(state_prompt)
|
|
prompt = "\n".join(
|
|
p for p in (bound_parts if refs else parts) if p
|
|
) + reference_binding_suffix(refs)
|
|
if not prompt.strip():
|
|
errors.append({"code": "prompt_required", "message": "请输入镜头画面描述"})
|
|
if len(prompt) > 8000:
|
|
errors.append({"code": "prompt_too_long", "message": "编译提示词超过8000字符"})
|
|
visual = {
|
|
"prompt": prompt,
|
|
"settings": effective,
|
|
"references": refs,
|
|
"profile": spec.profile,
|
|
}
|
|
if spec.schema_version == 4:
|
|
continuity = shot.continuity.model_dump()
|
|
visual.update(schema_version=4, state_in=continuity["state_in"], prompt=prompt)
|
|
results.append(
|
|
{
|
|
"shot_id": shot.id,
|
|
"context_hash": digest(visual),
|
|
"frame_prompt": prompt,
|
|
"motion_prompt": shot.motion_prompt,
|
|
**(
|
|
{
|
|
"end_prompt": shot.continuity.end_prompt,
|
|
"state_out": shot.continuity.state_out.model_dump(),
|
|
"continuity": continuity,
|
|
}
|
|
if spec.schema_version == 4
|
|
else {}
|
|
),
|
|
"references": refs,
|
|
"effective_settings": effective,
|
|
"errors": errors,
|
|
}
|
|
)
|
|
return {"shots": results, "errors": []}
|
|
|
|
|
|
def canvas(profile):
|
|
return (1080, 1920) if profile == "portrait_1080_v1" else (1920, 1080)
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class StoryRenderPlan:
|
|
spec: dict
|
|
canvas: tuple
|
|
frames: int
|
|
clips: tuple
|
|
fps: int = 24
|
|
|
|
|
|
def compile_story_render(spec, render_inputs):
|
|
model = parse_story_spec(spec)
|
|
clips = render_inputs["clips"]
|
|
if (
|
|
len(clips) != len(model.shots)
|
|
or render_inputs.get("fps") != 24
|
|
or render_inputs.get("canvas") != list(canvas(model.profile))
|
|
):
|
|
raise ValueError("invalid story render inputs")
|
|
for shot, clip in zip(model.shots, clips):
|
|
if (
|
|
shot.id != clip["shot_id"]
|
|
or shot.edit.start_frame + getattr(shot.edit, "dedup_frames", 0) != clip["start_frame"]
|
|
or shot.edit.duration_frames - getattr(shot.edit, "dedup_frames", 0)
|
|
!= clip["duration_frames"]
|
|
):
|
|
raise ValueError("frozen trim differs from spec")
|
|
return StoryRenderPlan(
|
|
model.model_dump(mode="json"),
|
|
canvas(model.profile),
|
|
model.render.total_frames,
|
|
tuple(clips),
|
|
)
|