# Narrow external presentation documents before they enter rendering and speech logic. # # Author: Laurent Declercq # Version: 20260923 """Narrow external presentation documents before they enter rendering and speech logic.""" from dataclasses import dataclass from pathlib import Path from typing import NotRequired, TypedDict, cast @dataclass(frozen=True) class BuildOptions: """Group local encoder, cache, and speech reuse options for a language build.""" cache: Path ffmpeg: str offline: bool = False force: bool = False class VisualSlide(TypedDict): """Describe the visible contents used by the slide renderer.""" id: str title: str body: str screenshots: list[str] class Narration(TypedDict): """Describe the minimum input required to synthesize a speech clip.""" id: str narration: str class Slide(VisualSlide, Narration): """Bind validated narration and visual content to a rendered image.""" image: Path class Settings(TypedDict): """Describe validated voice, caption timing, and encoding settings.""" schemaVersion: int voices: dict[str, str] rate: str rates: NotRequired[dict[str, str]] pronunciations: NotRequired[dict[str, dict[str, str]]] fps: float leadSeconds: float tailSeconds: float fadeSeconds: float crf: float audioBitrate: str class Word(TypedDict): """Describe one speech boundary with timings in 100-nanosecond units.""" offset: int duration: int text: str def object_mapping(value: object) -> dict[str, object]: """ Require a JSON object with string keys before accessing external values. :param value: Decoded JSON value to inspect. :return: Validated string-keyed object. :raises ValueError: If the value is not a string-keyed object. """ if not isinstance(value, dict): raise ValueError("Expected a JSON object.") # noqa: TRY004 - Malformed external JSON is a value error. mapping = cast("dict[object, object]", value) if any(not isinstance(key, str) for key in mapping): raise ValueError("JSON object keys must be strings.") return cast("dict[str, object]", mapping) def string_value(value: object) -> str: """ Require text at a JSON boundary. :param value: Decoded field to inspect. :return: The supplied string. :raises ValueError: If the value is not text. """ if not isinstance(value, str): raise ValueError("Expected a string.") # noqa: TRY004 - Malformed external JSON is a value error. return value def object_list(value: object) -> list[object]: """ Require an array before examining external records. :param value: Decoded JSON array candidate. :return: Array with unknown elements awaiting validation. :raises ValueError: If the value is not an array. """ if not isinstance(value, list): raise ValueError("Expected a JSON array.") # noqa: TRY004 - Malformed external JSON is a value error. return cast("list[object]", value) def string_mapping(value: object) -> dict[str, str]: """ Validate a mapping of locale or pronunciation names to text. :param value: Decoded mapping to inspect. :return: Validated string pairs. :raises ValueError: If any key or value is not text. """ return {key: string_value(item) for key, item in object_mapping(value).items()} def number_value(value: object) -> float: """ Narrow a numeric JSON field without accepting booleans as numbers. :param value: Decoded timing or encoding field. :return: Numeric value for subsequent range checks. :raises ValueError: If the value is neither an integer nor a float. """ if isinstance(value, bool) or not isinstance(value, (int, float)): raise ValueError("Expected a number.") # noqa: TRY004 - Malformed external JSON is a value error. return value def parse_settings(value: object) -> Settings: """ Validate settings field types before domain-specific range and voice checks. :param value: Decoded settings document. :return: Typed presentation settings. :raises ValueError: If a required field is missing or malformed. """ fields = object_mapping(value) if fields.get("schemaVersion") != 1: raise ValueError("Unsupported presentation settings schema.") return Settings( schemaVersion=1, voices=string_mapping(fields.get("voices")), rate=string_value(fields.get("rate")), rates=string_mapping(fields.get("rates", {})), pronunciations={ locale: string_mapping(aliases) for locale, aliases in object_mapping(fields.get("pronunciations", {})).items() }, fps=number_value(fields.get("fps")), leadSeconds=number_value(fields.get("leadSeconds")), tailSeconds=number_value(fields.get("tailSeconds")), fadeSeconds=number_value(fields.get("fadeSeconds")), crf=number_value(fields.get("crf")), audioBitrate=string_value(fields.get("audioBitrate")), ) def parse_visual(value: object) -> VisualSlide: """ Validate one storyboard slide without changing its visible contents. :param value: Decoded storyboard record. :return: Typed slide text and screenshot identifiers. :raises ValueError: If a required field has an invalid shape. """ fields = object_mapping(value) return VisualSlide( id=string_value(fields.get("id")), title=string_value(fields.get("title")), body=string_value(fields.get("body")), screenshots=[string_value(item) for item in object_list(fields.get("screenshots"))], ) def parse_words(value: object) -> list[Word]: """ Validate cached speech boundaries before calculating captions. :param value: Decoded service or cache boundary records. :return: Typed word offsets, durations, and text. :raises ValueError: If a boundary has malformed timing or text. """ words: list[Word] = [] for item in object_list(value): fields = object_mapping(item) offset, duration = fields.get("offset"), fields.get("duration") if type(offset) is not int or type(duration) is not int: raise ValueError("Speech word timings must be integers.") words.append(Word(offset=offset, duration=duration, text=string_value(fields.get("text")))) return words