cmvr-visual/backend/app/timeline.py

87 lines
3.7 KiB
Python

"""Versioned, strict three-shot contract. Public fields contain no executable paths."""
from dataclasses import dataclass
from typing import Literal
import re
from pydantic import BaseModel, ConfigDict, Field, model_validator
class Strict(BaseModel):
model_config = ConfigDict(extra='forbid', strict=True)
class ShotParameters(Strict):
seed: int = Field(default=42, ge=0, le=2**32-1)
class Shot(Strict):
key: Literal['shot_1','shot_2','shot_3']
prompt: str = Field(min_length=1,max_length=8000)
image_asset_id: str | None = Field(default=None,min_length=1,max_length=64)
parameters: ShotParameters = Field(default_factory=ShotParameters)
@model_validator(mode='after')
def prompt_required(self):
if not self.prompt.strip(): raise ValueError('prompt_required')
return self
class Subtitle(Strict):
start_frame: int = Field(ge=0,lt=360)
end_frame: int = Field(gt=0,le=360)
text: str = Field(min_length=1,max_length=2000)
@model_validator(mode='after')
def safe(self):
if self.end_frame <= self.start_frame or not self.text.strip() or re.search(r'[\\{}\x00-\x1f\x7f]',self.text):
raise ValueError('invalid_timeline: subtitle')
return self
class Audio(Strict):
asset_id: str = Field(min_length=1,max_length=64)
source_start_ms: int = Field(ge=0)
source_end_ms: int = Field(gt=0)
offset_frame: int = Field(default=0,ge=0,lt=360)
short_policy: Literal['silence'] = 'silence'
@model_validator(mode='after')
def fits(self):
if self.source_end_ms <= self.source_start_ms or (self.source_end_ms-self.source_start_ms)*24 > (360-self.offset_frame)*1000:
raise ValueError('invalid_timeline: audio exceeds canvas')
return self
class Render(Strict):
fps: Literal[24] = 24
total_frames: Literal[360] = 360
fit: Literal['contain','cover'] = 'contain'
audio: Audio | None = None
subtitles: list[Subtitle] = Field(default_factory=list,max_length=1000)
template_version: Literal['plain-v1'] = 'plain-v1'
class WorkflowSpec(Strict):
schema_version: Literal[1] = 1
shots: list[Shot] = Field(min_length=3,max_length=3)
profile: Literal['landscape_1080_v1','portrait_1080_v1'] = 'landscape_1080_v1'
render: Render = Field(default_factory=Render)
@model_validator(mode='after')
def exact_keys(self):
if [s.key for s in self.shots] != ['shot_1','shot_2','shot_3']:
raise ValueError('exact ordered shot_1,shot_2,shot_3 required')
return self
@dataclass(frozen=True)
class TimelinePlan:
spec: dict
generation_parameters: dict
canvas: tuple[int,int]
frames: int = 360
clip_frames: int = 120
fps: int = 24
def compile_timeline(spec, owned_assets) -> TimelinePlan:
spec = spec if isinstance(spec,WorkflowSpec) else WorkflowSpec.model_validate(spec)
audio = spec.render.audio
if audio:
asset = owned_assets.get(audio.asset_id)
def field(name): return asset.get(name) if isinstance(asset,dict) else getattr(asset,name,None)
if asset is None or field('kind') != 'audio' or field('duration_seconds') is None or audio.source_end_ms > round(field('duration_seconds')*1000):
raise ValueError('invalid_timeline: audio source cut exceeds source')
portrait = spec.profile == 'portrait_1080_v1'
parameters = dict(width=704 if portrait else 1280,height=1280 if portrait else 704,
num_frames=121,fps=24,upscale=True,upscale_width=1056 if portrait else 1920,
upscale_height=1920 if portrait else 1056,num_inference_steps=50,guidance_scale=5.0,tile_size=128)
return TimelinePlan(spec.model_dump(mode='json'),parameters,(1080,1920) if portrait else (1920,1080))