"""Versioned short-clip story contract. Public fields contain no executable paths.""" from dataclasses import dataclass from typing import Literal import re from pydantic import BaseModel, ConfigDict, Field, model_serializer, 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: str = Field(pattern=r'^shot_[1-9][0-9]{0,3}$') prompt: str = Field(min_length=1,max_length=8000) duration_frames: int = Field(default=120,ge=24,le=120) 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) end_frame: int = Field(gt=0) 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) short_policy: Literal['silence'] = 'silence' @model_validator(mode='after') def fits(self): if self.source_end_ms <= self.source_start_ms: raise ValueError('invalid_timeline: invalid audio selection') return self class Render(Strict): fps: Literal[24] = 24 total_frames: int | None = Field(default=None,ge=1,le=120000) 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,2] = 1 shots: list[Shot] = Field(min_length=1,max_length=1000) profile: Literal['landscape_1080_v1','portrait_1080_v1'] = 'landscape_1080_v1' render: Render = Field(default_factory=Render) @model_validator(mode='after') def ordered_timeline(self): if self.schema_version == 1 and (len(self.shots) != 3 or any('duration_frames' in s.model_fields_set for s in self.shots)): raise ValueError('schema_version 1 requires three full-length shots') if [s.key for s in self.shots] != [f'shot_{i}' for i in range(1,len(self.shots)+1)]: raise ValueError('exact ordered sequential shot keys required') frames = sum(s.duration_frames for s in self.shots) if self.render.total_frames is not None and self.render.total_frames != frames: raise ValueError('invalid_timeline: total_frames differs from shots') self.render.total_frames = frames if any(c.end_frame > frames for c in self.render.subtitles): raise ValueError('invalid_timeline: subtitle exceeds canvas') audio = self.render.audio if audio and (audio.offset_frame >= frames or (audio.source_end_ms-audio.source_start_ms)*24 > (frames-audio.offset_frame)*1000): raise ValueError('invalid_timeline: audio exceeds canvas') return self @model_serializer(mode='wrap') def legacy_compatible_dump(self, handler): data = handler(self) if self.schema_version == 1: for shot in data['shots']:shot.pop('duration_frames',None) return data @dataclass(frozen=True) class TimelinePlan: spec: dict generation_parameters: dict canvas: tuple[int,int] frames: int = 360 clip_frames: int = 120 fps: int = 24 shot_frames: tuple[int,...] = () def ordered_step_keys(snapshot): """The frozen shot array is authoritative, including shot_10 and later.""" return [shot['key'] for shot in snapshot['shots']] + ['compose'] 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), frames=spec.render.total_frames,shot_frames=tuple(s.duration_frames for s in spec.shots))