diff --git a/.agents/skills/media-motion-graphics/SKILL.md b/.agents/skills/media-motion-graphics/SKILL.md index fc89dd1..ea0bacd 100644 --- a/.agents/skills/media-motion-graphics/SKILL.md +++ b/.agents/skills/media-motion-graphics/SKILL.md @@ -161,6 +161,32 @@ use new output names for iterations instead of deleting them preemptively. For spoken footage, follow `media-subtitle-pipeline`'s project glossary and cached transcript correction guidance before using transcript copy in the storyboard. +## Generated footage with TTV + +Use TTV when a reviewed scene needs generated footage. Export the selected +`STORYBOARD.md` scenes to `$PROJECT_DIR/storyboards/.json` using the +scene shape in `docs/generated-media.md`. Preserve scene IDs, scene order, +durations, entry/exit intent, references, delivery dimensions, and continuity. +Include a `motion_review` record with review mode, reviewer, disposition, and +paths and SHA-256 hashes of the storyboard, review images, and `review.md`. +Archive those files alongside the JSON revision. Mark `approved: true` only +after the selected review process has passed. + +Creative review and spending permission are separate records. Carry the user's +existing permission to use providers and the agreed budget into `DECISIONS.md`; +auto review alone does not authorize paid generation. Review the returned TTV +plan's exact prompts, model, variants, duration, references, and costs before +creating `media-generated approve`. Use a keyframe-only approval and a cited +keyframe result when first/last frames need visual review before video generation. + +Import approved results and select their takes through `media-generated`. +Use the imported clips as content layers in HyperFrames; keep text, UI, layout, +crop, timing, and overlays editable in the composition. Director notes on those +elements revise HyperFrames source. Notes that change generated footage create a +new TTV request for the affected scene IDs. Keep neighboring takes and resolve +any stale continuity dependencies. See `docs/generated-media.md` for the handoff +example, selection provenance, and portrait EDL options. + ## Verification and handoff Use `lint` for early feedback and `check --snapshots --at-transitions` for the diff --git a/.agents/skills/media-render-pipeline/SKILL.md b/.agents/skills/media-render-pipeline/SKILL.md index 8a44a39..c4ea957 100644 --- a/.agents/skills/media-render-pipeline/SKILL.md +++ b/.agents/skills/media-render-pipeline/SKILL.md @@ -30,6 +30,14 @@ Delegate to the appropriate sub-skill when a step's work falls entirely within its scope. This skill adds the conversation, strategy, self-evaluation, and iteration layers that the sub-skills do not cover. +For generated footage, export reviewed `media-motion-graphics` storyboard scenes +using `docs/generated-media.md`, preserve stable IDs and visual review evidence, +and use `media-generated` for provider plan approval, import, and take selection. +Carry existing spending permission and budgets into the plan approval. Use +imported clips as HyperFrames content layers and retain editable motion source. +`select --edl-options` preserves portrait reframing and transcript paths together +with grading, overlays, and subtitles. + ## Worker/subagent protocol If the harness supports workers, use them for independent, bounded side work to @@ -396,6 +404,15 @@ Step 8: Iterate on feedback and persist session memory. ## Toolkit commands +For TTV-generated scenes, use `media-generated` to author an approved-storyboard +request, review the provider plan, record exact variant approval, and import the +terminal result. Keep scene IDs and explicit order stable. `media-generated select` +freezes reviewed takes, trims and an ordinary EDL. `media-generated render` checks +source hashes, calls the existing renderer, and records `media-verify` findings. +Use `regenerate` for selected scene subsets and `inspect` for stale continuity. +Documents stay under `rough-cuts/manifests/`. The file/HTTP workflow is documented +in `docs/generated-media.md` in the toolkit repository. + | Command | Pipeline step | |---------|--------------| | `media-subtitle` | Step 1 (transcribe) | @@ -404,6 +421,7 @@ Step 8: Iterate on feedback and persist session memory. | `media-tts` | Step 5 (narration) | | `media-timeline-view` | Steps 1, 5, 6 (on-demand visual drill-down) | | `media-edl-render` | Steps 5, 8 (render with EDL) | +| `media-generated` | Steps 4-8 (TTV review, imports, selections and verified EDL renders) | | `media-fcpxml-export` | Step 8 (optional Resolve layer handoff) | | `media-burn-subtitles` | Step 5 (subtitle burning, usually via EDL render) | | `media-grade` | Step 5 (standalone grading outside EDL workflow; not needed when using `media-edl-render`) | diff --git a/.github/workflows/ai-pr-review.yml b/.github/workflows/ai-pr-review.yml deleted file mode 100644 index e21d440..0000000 --- a/.github/workflows/ai-pr-review.yml +++ /dev/null @@ -1,108 +0,0 @@ -name: ai-pr-review - -on: - pull_request: - types: [opened, synchronize, reopened, ready_for_review, labeled] - -permissions: {} - -concurrency: - group: ai-pr-review-${{ github.event.pull_request.number }} - cancel-in-progress: ${{ github.event.action != 'labeled' || github.event.label.name == 'review-this' }} - -jobs: - review: - name: openhands-review - if: > - github.event.pull_request.draft == false && - github.event.pull_request.head.repo.full_name == github.repository && - github.event.pull_request.user.login != 'dependabot[bot]' && - ( - github.event.action != 'labeled' || - github.event.label.name == 'review-this' - ) - runs-on: ubuntu-24.04 - timeout-minutes: 25 - permissions: - contents: read - pull-requests: write - issues: write - steps: - - name: Validate and resolve LLM configuration - id: llm - shell: bash - env: - AI_REVIEW_PROVIDER_KIND: ${{ vars.AI_REVIEW_PROVIDER_KIND }} - AI_REVIEW_MODEL_ID: ${{ vars.AI_REVIEW_MODEL_ID }} - AI_REVIEW_BASE_URL: ${{ vars.AI_REVIEW_BASE_URL }} - AI_REVIEW_STYLE: ${{ vars.AI_REVIEW_STYLE }} - AI_REVIEW_REQUIRE_EVIDENCE: ${{ vars.AI_REVIEW_REQUIRE_EVIDENCE }} - AI_REVIEW_API_KEY: ${{ secrets.AI_REVIEW_API_KEY }} - run: | - set -euo pipefail - - provider_kind="${AI_REVIEW_PROVIDER_KIND:-}" - model_id="${AI_REVIEW_MODEL_ID:-}" - base_url="${AI_REVIEW_BASE_URL:-}" - review_style="${AI_REVIEW_STYLE:-standard}" - require_evidence="${AI_REVIEW_REQUIRE_EVIDENCE:-true}" - llm_api_key="${AI_REVIEW_API_KEY:-}" - - # Trim whitespace from variables - provider_kind=$(echo "$provider_kind" | xargs) - model_id=$(echo "$model_id" | xargs) - base_url=$(echo "$base_url" | xargs) - llm_api_key=$(echo "$llm_api_key" | xargs) - - if [[ -z "$provider_kind" || -z "$model_id" ]]; then - echo "::notice::Skipping AI PR review because AI_REVIEW_PROVIDER_KIND and/or AI_REVIEW_MODEL_ID is not configured for this repository." - echo "enabled=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - if [[ "$provider_kind" == "openai-compatible" && -z "$base_url" ]]; then - echo "::notice::Skipping AI PR review because AI_REVIEW_BASE_URL is required when AI_REVIEW_PROVIDER_KIND=openai-compatible." - echo "enabled=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - if [[ -z "$llm_api_key" ]]; then - echo "::notice::Skipping AI PR review because AI_REVIEW_API_KEY is not configured for this repository." - echo "enabled=false" >> "$GITHUB_OUTPUT" - exit 0 - fi - - case "$provider_kind" in - openai-compatible) - resolved_model="openai/${model_id}" - resolved_base_url="$base_url" - ;; - litellm-native) - resolved_model="$model_id" - resolved_base_url="$base_url" - ;; - *) - echo "::error::Unsupported AI_REVIEW_PROVIDER_KIND: $provider_kind" - echo "::error::Supported values: openai-compatible, litellm-native" - exit 1 - ;; - esac - - echo "enabled=true" >> "$GITHUB_OUTPUT" - echo "model=$resolved_model" >> "$GITHUB_OUTPUT" - echo "base_url=$resolved_base_url" >> "$GITHUB_OUTPUT" - echo "style=$review_style" >> "$GITHUB_OUTPUT" - echo "require_evidence=$require_evidence" >> "$GITHUB_OUTPUT" - - - name: Run OpenHands PR Review - if: steps.llm.outputs.enabled == 'true' - uses: OpenHands/extensions/plugins/pr-review@7782172ec796216cea2091e3f20c4d2a8a67da31 - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - llm-api-key: ${{ secrets.AI_REVIEW_API_KEY }} - llm-model: ${{ steps.llm.outputs.model }} - llm-base-url: ${{ steps.llm.outputs.base_url }} - extensions-version: 7782172ec796216cea2091e3f20c4d2a8a67da31 - openhands-sdk-package: openhands-sdk==1.22.1 - review-style: ${{ steps.llm.outputs.style }} - require-evidence: ${{ steps.llm.outputs.require_evidence }} diff --git a/README.md b/README.md index 8e98048..e13795f 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,9 @@ # Media Tooling +[TTV generated-media integration](docs/generated-media.md) adds reviewed generation +requests, verified imports, immutable take selections and reproducible EDL renders +through `media-generated`. + Media Tooling helps an agent harness turn raw media into planning and editing artifacts while keeping the user centered in the project workspace. User-facing execution context lives in a project-local `AGENTS.md` generated by `media-tooling-init`. The repo-root [`AGENTS.md`](./AGENTS.md) is intentionally minimal and only supports toolkit development. Developer-only maintenance notes and quality gates live in [`docs/DEVELOPMENT.md`](./docs/DEVELOPMENT.md). diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md index 046bad2..712bfeb 100644 --- a/docs/DEVELOPMENT.md +++ b/docs/DEVELOPMENT.md @@ -41,6 +41,11 @@ uv run --group dev mypy src tests ## When editing the toolkit +The TTV adapter is `src/media_tooling/generated_media.py`. Its contract schemas +and golden fixtures are pinned data under `src/media_tooling/contracts/`. Keep +the renderer and verifier independent of TTV. See [generated-media.md](generated-media.md) +for the workflow and offline acceptance command. + - prefer updating shared helpers instead of duplicating batch logic - keep user-facing execution guidance in `src/media_tooling/templates/project_AGENTS.md` rather than the repo root - keep implementation notes and maintenance guidance here or in other files under `docs/` diff --git a/docs/generated-media.md b/docs/generated-media.md new file mode 100644 index 0000000..882fc4d --- /dev/null +++ b/docs/generated-media.md @@ -0,0 +1,193 @@ +# Generated media with TTV + +Media Tooling owns the editorial storyboard, take selection and final EDL. TTV owns provider planning and generation. `media-generated` exchanges immutable contract 1.0 JSON documents through files or HTTP. Install with `uv sync --group dev`; FFmpeg and ffprobe must be on PATH. + +Start in a project created by `media-tooling-init`. An approved storyboard JSON has `project_id`, `revision_id`, `approved: true` and `scenes`. Each scene uses the `GenerationRequest.scenes` shape in the [pinned schema](../src/media_tooling/contracts/v1_0/GenerationRequest.schema.json). Keep scene IDs stable across revisions and give each scene an explicit, unique `order`. A request for a subset preserves these values. + +## Motion-graphics storyboard handoff + +The agent exports selected scenes from the reviewed HyperFrames `STORYBOARD.md` +into this JSON shape. Markdown remains the creative source; the JSON is the +explicit generation handoff. Copy each stable scene ID and map its beat duration +to `requested_duration_s`, visual intent to `intent`, real image references to +`reference_assets`, and portrait or landscape size to `delivery`. Put typography, +UI motion, overlays, and timing edits in the HyperFrames composition. Request TTV +generation for the footage needed by those content layers. + +For example, a reviewed portrait scene can be exported as follows. Replace the +example evidence hashes with hashes of the archived files: + +```json +{ + "project_id": "product-film", "revision_id": "storyboard-1", "approved": true, + "motion_review": { + "mode": "auto", "reviewer": "agent with image input", "disposition": "passed", + "evidence": [ + {"path": "storyboards/storyboard-1/STORYBOARD.md", "sha256": "sha256:FILE_HASH"}, + {"path": "storyboards/storyboard-1/scene-01.png", "sha256": "sha256:FILE_HASH"}, + {"path": "storyboards/storyboard-1/review.md", "sha256": "sha256:FILE_HASH"}, + {"path": "storyboards/storyboard-1/DECISIONS.md", "sha256": "sha256:FILE_HASH"} + ] + }, + "scenes": [{ + "scene_id": "scene-01", "order": 1, "requested_duration_s": 5, + "intent": {"summary": "A hand opens the product on a desk", "entry_state": "Closed product", + "exit_state": "Product open", "continuity_notes": "Keep the desk and lighting consistent"}, + "transition_out": {"type": "cut", "editorial_note": null}, + "continuity": {"mode": "independent", "required_reference_asset_ids": []}, + "reference_assets": [], + "delivery": {"aspect_ratio": "9:16", "target_width": 1080, "target_height": 1920, "audio_policy": "mute"}, + "generation_policy": {"provider_preferences": ["fal"], "max_attempts": 4, + "max_estimated_cost_usd": 10, "allow_provider_fallback": false} + }] +} +``` + +In `revision` mode, record the user's storyboard review. In `auto` mode, retain +the actual scene images, visual feedback, and disposition from the skill's +bounded review. Archive the evidence at the recorded paths and verify its hashes +before exporting. The request hashes the entire storyboard JSON, including +`motion_review`; this metadata is an agent-maintained review record. The CLI +validates the generation contract and approvals rather than judging creative +review. Record existing provider spending permission and budget in `DECISIONS.md`. +Creative auto review alone grants no spending permission. + +Review the returned provider plan before execution. For a separate keyframe +review, approve `--mode keyframes`, import and visually review that result, then +cite its ID with `approve --keyframes`. Selection binds the clip's references to +that exact reviewed result and checks mandatory reference lineage through +recorded keyframe generation and provider image preparation. + +Import the generated clips as HyperFrames content layers. Edit layout, crop, +timing, copy, or overlays in HyperFrames source. Regenerate footage using a new +request containing the affected scene IDs, then select replacements and resolve +continuity decisions before assembly. + +```sh +media-generated --project /path/to/project request storyboard.json \ + --id request-1 --revision 1 +media-generated --project /path/to/project send request \ + /path/to/project/rough-cuts/manifests/requests/request-1.json \ + --server https://ttv.example.com +``` + +Planning returns a stored plan. Review its prompts, shot count, duration, provider variants, continuity and costs before approving execution: + +```sh +media-generated --project /path/to/project approve plan.json \ + --id approval-1 --key approval-1 --variant PRIMARY_VARIANT_ID \ + --variant APPROVED_FALLBACK_VARIANT_ID --budget-usd 20 +media-generated --project /path/to/project send approval \ + /path/to/project/rough-cuts/manifests/approvals/approval-1.json \ + --server https://ttv.example.com +``` + +Every scene needs an approved variant. Include a fallback only when its shot plan has been reviewed. Unknown estimates require `--allow-unknown-cost`; zero remains a known amount. Retry submissions by resending the stored approval, preserving its ID, key and canonical bytes. TTV owns paid-work deduplication and budget enforcement. Use `approve --mode keyframes` for keyframe review, import its result, then create a video approval with `--keyframes KEYFRAME_RESULT_ID`. Prompt changes require a new request and plan. + +HTTP commands accept `--token-env VARIABLE_NAME`; the token remains in process memory. Remote endpoints require HTTPS; localhost HTTP supports development. Redirects require an explicit new endpoint. + +```sh +media-generated get job --id JOB_ID --server https://ttv.example.com +media-generated --project /path/to/project get result --id JOB_ID \ + --server https://ttv.example.com --output rough-cuts/manifests/result-download.json +media-generated get cancel --id JOB_ID --server https://ttv.example.com +``` + +For file handoff, replace `--server` on `send` with `--handoff /path/to/exchange`. It writes identical canonical request or approval bytes. Run TTV's file adapter against these documents, then import the plan or terminal result. The repositories share schemas and documents as data. + +```sh +media-generated --project /path/to/project import plan plan.json +media-generated --project /path/to/project import result result.json \ + --asset-root /path/to/ttv/output +``` + +Local file URIs must resolve beneath the explicit asset root. For durable `gs://` or `s3://` URIs, pass `--deliveries deliveries.json`, a transient mapping from each durable URI to a local path or download URL. HTTPS downloads also require `--allow-origin https://storage.example.com`. Signed URLs belong only in this mapping. The importer stores canonical source URIs, local paths, content hashes and measured properties. It verifies clips, keyframes and references before committing the result import. Source files remain untouched. + +Create a selection draft naming the reviewed takes. Include every clip exactly once, with explicit edit order and source in/out points. `trim_out_s` is the exclusive source out-point. The take's `clip_order` supplies its generated sequence; edit order expresses the reviewed editorial sequence. + +```json +{ + "edit_revision_id": "edit-1", + "project_id": "my-film", + "storyboard_revision_id": "storyboard-1", + "source_results": [{"result_id": "RESULT_ID", "sha256": "sha256:RESULT_HASH"}], + "scenes": [{ + "scene_id": "scene-1", "order": 1, "take_id": "TAKE_ID", + "transition_out": {"type": "cut", "editorial_note": null}, + "clip_edits": [{ + "clip_id": "CLIP_ID", "order": 0, + "trim_in_s": 0, "trim_out_s": 3, "audio_use": "preserve" + }] + }], + "continuity_decisions": [] +} +``` + +```sh +media-generated --project /path/to/project select selection-draft.json +media-generated --project /path/to/project render \ + /path/to/project/rough-cuts/manifests/selections/edit-1.json --preview +``` + +`select` writes the immutable selection and ordinary EDL. It verifies request, plan, approval, result, storyboard and asset hashes; checks take membership, order, duration bounds and continuity; then expands clips into EDL sources and ranges. `render` repeats these checks before calling the existing renderer and `media-verify`. Render records include hashes, source and attempt provenance, reference assets, options and FFmpeg version. A failed verification remains a recorded result and returns a nonzero status. + +Pass `select --edl-options options.json` for existing EDL `grade`, `subtitles`, `overlays`, `reframe`, and `transcripts` settings. Their paths resolve inside the project. Transcript, subtitle, and overlay files are hashed with the edit. Changing settings creates a new selection and EDL revision. For example, `{"reframe":"crop=ih*9/16:ih","transcripts":{"generated_0":"transcripts/scene-01.json"}}` preserves portrait framing and the first selected clip's transcript. Generated clips can also be ordinary sources in other EDL projects. + +Contract 1.0 supports `cut` and `none` transitions and `preserve` or `mute` audio. Muting creates a derived copy. Clips without audio receive silence when other clips preserve audio. The existing concat renderer requires matching aspect ratios and frame rates; incompatible selections fail before rendering. Its 30 ms cut padding remains active. Provenance records requested and padded bounds, clamped to source duration. For completely silent audio, pass `render --no-loudnorm` to use the existing normalization bypass; this choice is recorded. + +Regenerate only selected scenes that need replacement: + +```sh +media-generated --project /path/to/project regenerate storyboard.json selection.json \ + --scene scene-2 --reason 'Revised product screen' --id request-2 --revision 2 +``` + +Send and approve the request, then import its result. A new selection combines the replacement with unchanged takes from older results. Include every referenced result ID and hash. Historical documents remain immutable. + +`media-generated inspect selection-draft.json` reports stale continuity dependencies. Each stale dependency needs an explicit `continuity_decisions` record: `scene_id`, `dependency_take_id`, `decision` and nullable `replacement_asset`. `accept_stale` records editorial acceptance. `use_boundary` requires an image AssetRef imported with `import boundary` whose hash matches the first frame consumed by the dependent take; its optional `source_take_id` must name a selected take. A different boundary requires regenerating the dependent scene. `regenerate` keeps compilation blocked until a replacement is selected. Decisions document compatibility judgments without altering historical generation. + +`media-generated cost --selection selection.json` reports all attempts, selected successful outputs and unselected attempts. USD subtotals carry unknown-attempt counts; incomplete totals remain null. Raw provider units stay separate per attempt. + +## Verification + +The five schemas, raw-byte hash manifest and shared fixtures are vendored under `src/media_tooling/contracts/v1_0`. Runtime validation pins the version and manifest hash, rejects unknown fields and verifies canonical document hashes. Updating the contract requires replacing the bundle and deliberately updating the pin. `media-generated validate KIND FILE` validates a handoff independently. + +Run `bash scripts/check.sh` for unittest, ruff and mypy. New tests exercise real FFmpeg import/render when installed, contract parity, safe paths, tampering, bounds, order, billing and regeneration. Consume TTV's emitted offline pilot without importing its runtime: + +```sh +uv run python scripts/ttv_offline_acceptance.py \ + --handoff /path/to/ttv-pilot/handoff \ + --asset-root /path/to/ttv-pilot \ + --project /path/to/fresh-media-pilot +``` + +### Live validation status (2026-09-22) + +The primary live provider check passed with MiniMax H3 Max through TTV's production `FalGenerator`, using `minimax/h3-max/image-to-video`: a supplied first frame, 5 seconds, `768P`, seed 42, safety checking enabled, prompt expansion disabled, one attempt and no fallback. One provider submission produced a clip that the shipped CLI imported, selected, rendered and verified without consumer code changes. Manual comparison matched the successful attempt to the approved variant's provider alias, model, shot and exact prompt. + +The H3 source measured 1344×768 at 24 fps, with 5.166667 seconds of video and a 5.184-second container. Its stereo AAC track used 32 kHz and contained non-silent audio. The existing renderer produced a 1920×1098, 24 fps preview with 5.166667 seconds of video, a 5.205-second container and stereo AAC at 48 kHz. Normal loudness normalization remained enabled; `media-verify` passed with no blocking findings. The cost ledger retained `8.0` raw `X-Fal-Billable-Units`; estimated and actual USD amounts remain unknown. + +Additional acceptance checks passed: + +- A local Hypercorn API, Redis and RQ SpawnWorker executed the shipped `media-generated` HTTP client with deterministic providers. Three scenes produced 1, 3 and 1 clips, including a recorded failure and approved fallback. Duplicate approvals before and after completion returned the same job. Both the original edit and a middle-scene replacement rendered and passed verification. Unchanged outer takes retained their IDs and hashes; the stale downstream dependency blocked compilation until explicitly accepted. +- A secondary real Google `veo-3.1-generate-preview` submission produced one 4-second, 1280×720, 24 fps clip. Its complete producer chain imported without provider-specific consumer changes. The existing EDL renderer produced a 1920×1080, 24 fps preview with 4 seconds of video; `media-verify` passed with no blocking findings. The silent audio track required the documented `--no-loudnorm` option. + +The consumer gate passed 696 unittest tests, ruff and mypy. A fresh 22-case cross-repository contract corpus agreed on all outcomes (7 accepted, 15 rejected), and all vendored schema and fixture JSON bytes matched the producer bundle. These checks cover local services and provider calls; they do not establish production deployment. + +To verify a successful provider result, retain the approved storyboard and request/plan/approval documents in the project, then use the same provider-independent commands: + +```sh +media-generated --project /path/to/project get result --id JOB_ID \ + --server https://ttv.example.com --token-env TTV_TOKEN \ + --output rough-cuts/manifests/result-download.json +media-generated --project /path/to/project import result \ + /path/to/project/rough-cuts/manifests/result-download.json \ + --asset-root /path/to/ttv/output +media-generated --project /path/to/project select /path/to/selection-draft.json +media-generated --project /path/to/project render \ + /path/to/project/rough-cuts/manifests/selections/edit-1.json --preview +media-verify /path/to/project/edit/edit-1-preview.mp4 \ + --edl /path/to/project/edit/edl-edit-1.json --no-timelines --max-passes 1 --json +``` + +Add `--no-loudnorm` when the media is silent. diff --git a/pyproject.toml b/pyproject.toml index 3452003..35ae074 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,6 +11,7 @@ dependencies = [ "onnxruntime<1.24; sys_platform == 'darwin' and platform_machine == 'x86_64'", "numpy>=1.26", "pillow>=12.3.0", + "jsonschema>=4.23", ] [project.optional-dependencies] @@ -47,6 +48,7 @@ media-translate-subtitles = "media_tooling.subtitle_translate:main" media-edl-render = "media_tooling.edl_render:main" media-fcpxml-export = "media_tooling.fcpxml_export:main" media-verify = "media_tooling.verify:main" +media-generated = "media_tooling.generated_media:main" [tool.ruff] target-version = "py312" @@ -79,6 +81,7 @@ module = [ "PIL", "PIL.*", "requests", + "jsonschema", ] ignore_missing_imports = true diff --git a/scripts/ttv_offline_acceptance.py b/scripts/ttv_offline_acceptance.py new file mode 100644 index 0000000..c169e6f --- /dev/null +++ b/scripts/ttv_offline_acceptance.py @@ -0,0 +1,88 @@ +"""Consume the TTV fake-provider pilot as files, then render both editorial revisions.""" +from __future__ import annotations + +import argparse +import copy +from pathlib import Path +from typing import Any + +from media_tooling import generated_media as gm + + +def choose_scene(scene: dict[str, Any]) -> dict[str, Any]: + take = scene["takes"][0] + clips = {clip["clip_id"]: clip for clip in scene["clips"]} + return {"scene_id": scene["scene_id"], "order": scene["order"], "take_id": take["take_id"], + "transition_out": {"type": "cut", "editorial_note": None}, + "clip_edits": [{"clip_id": clip_id, "order": order, "trim_in_s": 0, + "trim_out_s": clips[clip_id]["media"]["measured_duration_s"], "audio_use": "preserve"} + for clip_id, order in take["clip_order"].items()]} + + +def run(handoff: Path, asset_root: Path, project: Path) -> dict[str, Any]: + if project.exists(): + raise ValueError("Acceptance project must be a new directory") + project.mkdir(parents=True) + board = gm.read_json(handoff / "storyboard.json") + gm.immutable_write(gm.project_path(project, Path("storyboards") / (board["revision_id"] + ".json")), gm.canonical_bytes(board)) + results = [] + for prefix in ("", "regeneration-"): + for kind in ("request", "plan", "approval"): + gm.store_document(project, kind, gm.read_json(handoff / (prefix + kind + ".json"))) + result = gm.read_json(handoff / (prefix + "result.json")) + gm.import_result(project, result, asset_root=asset_root) + results.append(result) + original, replacement = results + scenes = sorted(original["scenes"], key=lambda scene: scene["order"]) + assert [len(scene["takes"][0]["clip_ids"]) for scene in scenes] == [1, 3, 1] + attempts = [attempt for scene in scenes for attempt in scene["attempts"]] + assert any(attempt["status"] == "failed" for attempt in attempts) + assert any(attempt["fallback_from_attempt_id"] for attempt in attempts) + assert len(replacement["scenes"]) == 1 and replacement["scenes"][0]["scene_id"] == scenes[1]["scene_id"] + assert scenes[1]["takes"][0]["take_id"] in replacement["scenes"][0]["takes"][0]["supersedes_take_ids"] + original_draft = {"edit_revision_id": "pilot-edit-1", "project_id": board["project_id"], + "storyboard_revision_id": board["revision_id"], + "source_results": [{"result_id": original["result_id"], "sha256": original["document_sha256"]}], + "scenes": [choose_scene(scene) for scene in reversed(scenes)]} + selection = gm.write_selection(project, original_draft) + original_record = gm.render_selection(project, selection, preview=True, no_loudnorm=True) + assert original_record["passed"] + revised_draft = copy.deepcopy(original_draft) + revised_draft["edit_revision_id"] = "pilot-edit-2" + revised_draft["source_results"].append({"result_id": replacement["result_id"], "sha256": replacement["document_sha256"]}) + revised_draft["scenes"] = [choose_scene(replacement["scenes"][0]) if scene["scene_id"] == scenes[1]["scene_id"] else scene for scene in revised_draft["scenes"]] + revised_draft["continuity_decisions"] = [] + stale = gm.stale_dependencies(revised_draft, results) + assert stale, "TTV pilot must emit a genuine dependency on the replaced middle take" + try: + gm.write_selection(project, revised_draft) + except gm.IntegrationError as exc: + assert "Stale" in str(exc) + else: + raise AssertionError("Unresolved continuity should block compilation") + revised_draft["continuity_decisions"] = [{"scene_id": item["scene_id"], "dependency_take_id": item["dependency_take_id"], + "decision": "accept_stale", "replacement_asset": None} for item in stale] + revised = gm.write_selection(project, revised_draft) + revised_record = gm.render_selection(project, revised, preview=True, no_loudnorm=True) + assert revised_record["passed"] + before = original_record["provenance"]["sources"] + after = revised_record["provenance"]["sources"] + for scene_id in (scenes[0]["scene_id"], scenes[2]["scene_id"]): + old = [(item["take_id"], item["asset_sha256"]) for item in before.values() if item["scene_id"] == scene_id] + new = [(item["take_id"], item["asset_sha256"]) for item in after.values() if item["scene_id"] == scene_id] + assert old == new + assert gm.load_document(project, "result", original["result_id"]) == original + summary = {"passed": True, "original_render": original_record, "revised_render": revised_record, + "stale_dependencies": stale, "costs": gm.cost_rollup(project, revised)} + gm.immutable_write(project / "acceptance.json", gm.canonical_bytes(summary)) + return {"passed": True, "project": str(project), "original_output": original_record["output_path"], + "revised_output": revised_record["output_path"], "stale_dependencies": len(stale)} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--handoff", type=Path, required=True) + parser.add_argument("--asset-root", type=Path, required=True) + parser.add_argument("--project", type=Path, required=True) + args = parser.parse_args() + print(gm.canonical_bytes(run(args.handoff.resolve(), args.asset_root.resolve(), args.project.resolve())).decode()) diff --git a/src/media_tooling/contracts/v1_0/EditorialSelection.schema.json b/src/media_tooling/contracts/v1_0/EditorialSelection.schema.json new file mode 100644 index 0000000..11a17ae --- /dev/null +++ b/src/media_tooling/contracts/v1_0/EditorialSelection.schema.json @@ -0,0 +1 @@ +{"$defs":{"AssetRef":{"additionalProperties":false,"properties":{"asset_id":{"maxLength":256,"minLength":1,"title":"Asset Id","type":"string"},"media":{"anyOf":[{"$ref":"#/$defs/Media"},{"type":"null"}],"default":null},"mime_type":{"title":"Mime Type","type":"string"},"rights_note":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rights Note"},"role":{"title":"Role","type":"string"},"sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Sha256","type":"string"},"source_take_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"default":null,"title":"Source Take Id"},"uri":{"title":"Uri","type":"string"}},"required":["asset_id","uri","sha256","mime_type","role","rights_note"],"title":"AssetRef","type":"object"},"ClipEdit":{"additionalProperties":false,"properties":{"audio_use":{"enum":["preserve","mute"],"title":"Audio Use","type":"string"},"clip_id":{"maxLength":256,"minLength":1,"title":"Clip Id","type":"string"},"order":{"minimum":0,"title":"Order","type":"integer"},"trim_in_s":{"minimum":0,"title":"Trim In S","type":"number"},"trim_out_s":{"exclusiveMinimum":0,"title":"Trim Out S","type":"number"}},"required":["clip_id","order","trim_in_s","trim_out_s","audio_use"],"title":"ClipEdit","type":"object"},"ContinuityDecision":{"additionalProperties":false,"properties":{"decision":{"enum":["accept_stale","use_boundary","regenerate"],"title":"Decision","type":"string"},"dependency_take_id":{"maxLength":256,"minLength":1,"title":"Dependency Take Id","type":"string"},"replacement_asset":{"anyOf":[{"$ref":"#/$defs/AssetRef"},{"type":"null"}]},"scene_id":{"maxLength":256,"minLength":1,"title":"Scene Id","type":"string"}},"required":["scene_id","dependency_take_id","decision","replacement_asset"],"title":"ContinuityDecision","type":"object"},"EDLRef":{"additionalProperties":false,"properties":{"path":{"title":"Path","type":"string"},"sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Sha256","type":"string"}},"required":["path","sha256"],"title":"EDLRef","type":"object"},"Media":{"additionalProperties":false,"properties":{"fps":{"anyOf":[{"exclusiveMinimum":0,"type":"number"},{"type":"null"}],"title":"Fps"},"has_audio":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Has Audio"},"height":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"title":"Height"},"measured_duration_s":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Measured Duration S"},"width":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"title":"Width"}},"required":["measured_duration_s","width","height","fps","has_audio"],"title":"Media","type":"object"},"ResultRef":{"additionalProperties":false,"properties":{"result_id":{"maxLength":256,"minLength":1,"title":"Result Id","type":"string"},"sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Sha256","type":"string"}},"required":["result_id","sha256"],"title":"ResultRef","type":"object"},"SelectedScene":{"additionalProperties":false,"properties":{"clip_edits":{"items":{"$ref":"#/$defs/ClipEdit"},"minItems":1,"title":"Clip Edits","type":"array"},"order":{"minimum":0,"title":"Order","type":"integer"},"scene_id":{"maxLength":256,"minLength":1,"title":"Scene Id","type":"string"},"take_id":{"maxLength":256,"minLength":1,"title":"Take Id","type":"string"},"transition_out":{"$ref":"#/$defs/Transition"}},"required":["scene_id","order","take_id","clip_edits","transition_out"],"title":"SelectedScene","type":"object"},"Transition":{"additionalProperties":false,"properties":{"editorial_note":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Editorial Note"},"type":{"enum":["cut","none"],"title":"Type","type":"string"}},"required":["type","editorial_note"],"title":"Transition","type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"continuity_decisions":{"items":{"$ref":"#/$defs/ContinuityDecision"},"title":"Continuity Decisions","type":"array"},"contract_version":{"const":"1.0","title":"Contract Version","type":"string"},"created_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Created At","type":"string"},"document_sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Document Sha256","type":"string"},"edit_revision_id":{"maxLength":256,"minLength":1,"title":"Edit Revision Id","type":"string"},"edl":{"anyOf":[{"$ref":"#/$defs/EDLRef"},{"type":"null"}]},"project_id":{"maxLength":256,"minLength":1,"title":"Project Id","type":"string"},"scenes":{"items":{"$ref":"#/$defs/SelectedScene"},"minItems":1,"title":"Scenes","type":"array"},"selection_version":{"const":1,"title":"Selection Version","type":"integer"},"source_results":{"items":{"$ref":"#/$defs/ResultRef"},"minItems":1,"title":"Source Results","type":"array"},"storyboard_revision_id":{"maxLength":256,"minLength":1,"title":"Storyboard Revision Id","type":"string"}},"required":["contract_version","created_at","document_sha256","selection_version","edit_revision_id","project_id","storyboard_revision_id","source_results","scenes","continuity_decisions","edl"],"title":"EditorialSelection","type":"object"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/GenerationPlan.schema.json b/src/media_tooling/contracts/v1_0/GenerationPlan.schema.json new file mode 100644 index 0000000..302de72 --- /dev/null +++ b/src/media_tooling/contracts/v1_0/GenerationPlan.schema.json @@ -0,0 +1 @@ +{"$defs":{"BlockReason":{"additionalProperties":false,"properties":{"code":{"title":"Code","type":"string"},"message":{"title":"Message","type":"string"},"scene_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"title":"Scene Id"}},"required":["scene_id","code","message"],"title":"BlockReason","type":"object"},"Capability":{"additionalProperties":false,"properties":{"allowed_durations_s":{"items":{"exclusiveMinimum":0,"type":"number"},"minItems":1,"title":"Allowed Durations S","type":"array"},"supports_audio":{"title":"Supports Audio","type":"boolean"},"supports_first_frame":{"title":"Supports First Frame","type":"boolean"},"supports_last_frame":{"title":"Supports Last Frame","type":"boolean"}},"required":["allowed_durations_s","supports_first_frame","supports_last_frame","supports_audio"],"title":"Capability","type":"object"},"Cost":{"additionalProperties":false,"properties":{"amount":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Amount"},"basis":{"title":"Basis","type":"string"},"currency":{"const":"USD","title":"Currency","type":"string"}},"required":["amount","currency","basis"],"title":"Cost","type":"object"},"PlanScene":{"additionalProperties":false,"properties":{"order":{"minimum":0,"title":"Order","type":"integer"},"requested_duration_s":{"exclusiveMinimum":0,"title":"Requested Duration S","type":"number"},"scene_id":{"maxLength":256,"minLength":1,"title":"Scene Id","type":"string"},"variants":{"items":{"$ref":"#/$defs/Variant"},"title":"Variants","type":"array"},"warnings":{"items":{"type":"string"},"title":"Warnings","type":"array"}},"required":["scene_id","order","requested_duration_s","variants","warnings"],"title":"PlanScene","type":"object"},"Shot":{"additionalProperties":false,"properties":{"continuity_mode":{"enum":["cut","continue"],"title":"Continuity Mode","type":"string"},"first_frame_prompt":{"title":"First Frame Prompt","type":"string"},"last_frame_prompt":{"title":"Last Frame Prompt","type":"string"},"nominal_duration_s":{"exclusiveMinimum":0,"title":"Nominal Duration S","type":"number"},"order":{"minimum":0,"title":"Order","type":"integer"},"prompt_snapshot":{"title":"Prompt Snapshot","type":"string"},"reference_asset_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Reference Asset Ids","type":"array"},"shot_id":{"maxLength":256,"minLength":1,"title":"Shot Id","type":"string"},"target_trim_s":{"minimum":0,"title":"Target Trim S","type":"number"}},"required":["shot_id","order","nominal_duration_s","target_trim_s","continuity_mode","prompt_snapshot","first_frame_prompt","last_frame_prompt","reference_asset_ids"],"title":"Shot","type":"object"},"Variant":{"additionalProperties":false,"properties":{"capability_snapshot":{"$ref":"#/$defs/Capability"},"estimated_cost":{"$ref":"#/$defs/Cost"},"model":{"title":"Model","type":"string"},"provider":{"title":"Provider","type":"string"},"shots":{"items":{"$ref":"#/$defs/Shot"},"minItems":1,"title":"Shots","type":"array"},"variant_id":{"maxLength":256,"minLength":1,"title":"Variant Id","type":"string"}},"required":["variant_id","provider","model","capability_snapshot","shots","estimated_cost"],"title":"Variant","type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"blocked_reasons":{"items":{"$ref":"#/$defs/BlockReason"},"title":"Blocked Reasons","type":"array"},"contract_version":{"const":"1.0","title":"Contract Version","type":"string"},"created_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Created At","type":"string"},"document_sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Document Sha256","type":"string"},"plan_id":{"maxLength":256,"minLength":1,"title":"Plan Id","type":"string"},"request_id":{"maxLength":256,"minLength":1,"title":"Request Id","type":"string"},"scenes":{"items":{"$ref":"#/$defs/PlanScene"},"title":"Scenes","type":"array"},"status":{"enum":["ready","blocked"],"title":"Status","type":"string"},"valid_until":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Valid Until","type":"string"}},"required":["contract_version","created_at","document_sha256","plan_id","request_id","valid_until","status","scenes","blocked_reasons"],"title":"GenerationPlan","type":"object"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/GenerationRequest.schema.json b/src/media_tooling/contracts/v1_0/GenerationRequest.schema.json new file mode 100644 index 0000000..53f522b --- /dev/null +++ b/src/media_tooling/contracts/v1_0/GenerationRequest.schema.json @@ -0,0 +1 @@ +{"$defs":{"AssetRef":{"additionalProperties":false,"properties":{"asset_id":{"maxLength":256,"minLength":1,"title":"Asset Id","type":"string"},"media":{"anyOf":[{"$ref":"#/$defs/Media"},{"type":"null"}],"default":null},"mime_type":{"title":"Mime Type","type":"string"},"rights_note":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rights Note"},"role":{"title":"Role","type":"string"},"sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Sha256","type":"string"},"source_take_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"default":null,"title":"Source Take Id"},"uri":{"title":"Uri","type":"string"}},"required":["asset_id","uri","sha256","mime_type","role","rights_note"],"title":"AssetRef","type":"object"},"Continuity":{"additionalProperties":false,"properties":{"mode":{"enum":["independent","continue_from_previous"],"title":"Mode","type":"string"},"required_reference_asset_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Required Reference Asset Ids","type":"array"}},"required":["mode","required_reference_asset_ids"],"title":"Continuity","type":"object"},"Delivery":{"additionalProperties":false,"properties":{"aspect_ratio":{"title":"Aspect Ratio","type":"string"},"audio_policy":{"enum":["preserve_if_present","mute","required"],"title":"Audio Policy","type":"string"},"target_height":{"exclusiveMinimum":0,"title":"Target Height","type":"integer"},"target_width":{"exclusiveMinimum":0,"title":"Target Width","type":"integer"}},"required":["aspect_ratio","target_width","target_height","audio_policy"],"title":"Delivery","type":"object"},"Intent":{"additionalProperties":false,"properties":{"continuity_notes":{"title":"Continuity Notes","type":"string"},"entry_state":{"title":"Entry State","type":"string"},"exit_state":{"title":"Exit State","type":"string"},"summary":{"minLength":1,"title":"Summary","type":"string"}},"required":["summary","entry_state","exit_state","continuity_notes"],"title":"Intent","type":"object"},"Media":{"additionalProperties":false,"properties":{"fps":{"anyOf":[{"exclusiveMinimum":0,"type":"number"},{"type":"null"}],"title":"Fps"},"has_audio":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Has Audio"},"height":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"title":"Height"},"measured_duration_s":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Measured Duration S"},"width":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"title":"Width"}},"required":["measured_duration_s","width","height","fps","has_audio"],"title":"Media","type":"object"},"Policy":{"additionalProperties":false,"properties":{"allow_provider_fallback":{"title":"Allow Provider Fallback","type":"boolean"},"max_attempts":{"maximum":100,"minimum":1,"title":"Max Attempts","type":"integer"},"max_estimated_cost_usd":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Max Estimated Cost Usd"},"provider_preferences":{"items":{"type":"string"},"title":"Provider Preferences","type":"array"}},"required":["provider_preferences","max_attempts","max_estimated_cost_usd","allow_provider_fallback"],"title":"Policy","type":"object"},"Regeneration":{"additionalProperties":false,"properties":{"base_result_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Base Result Ids","type":"array"},"reason":{"title":"Reason","type":"string"},"supersedes_take_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Supersedes Take Ids","type":"array"}},"required":["base_result_ids","supersedes_take_ids","reason"],"title":"Regeneration","type":"object"},"RequestScene":{"additionalProperties":false,"properties":{"continuity":{"$ref":"#/$defs/Continuity"},"delivery":{"$ref":"#/$defs/Delivery"},"generation_policy":{"$ref":"#/$defs/Policy"},"intent":{"$ref":"#/$defs/Intent"},"order":{"minimum":0,"title":"Order","type":"integer"},"reference_assets":{"items":{"$ref":"#/$defs/AssetRef"},"title":"Reference Assets","type":"array"},"requested_duration_s":{"exclusiveMinimum":0,"maximum":14440,"title":"Requested Duration S","type":"number"},"scene_id":{"maxLength":256,"minLength":1,"title":"Scene Id","type":"string"},"transition_out":{"$ref":"#/$defs/Transition"}},"required":["scene_id","order","intent","requested_duration_s","transition_out","continuity","reference_assets","delivery","generation_policy"],"title":"RequestScene","type":"object"},"Storyboard":{"additionalProperties":false,"properties":{"revision_id":{"maxLength":256,"minLength":1,"title":"Revision Id","type":"string"},"sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Sha256","type":"string"}},"required":["revision_id","sha256"],"title":"Storyboard","type":"object"},"Transition":{"additionalProperties":false,"properties":{"editorial_note":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Editorial Note"},"type":{"enum":["cut","none"],"title":"Type","type":"string"}},"required":["type","editorial_note"],"title":"Transition","type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"contract_version":{"const":"1.0","title":"Contract Version","type":"string"},"created_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Created At","type":"string"},"document_sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Document Sha256","type":"string"},"idempotency_key":{"maxLength":256,"minLength":1,"title":"Idempotency Key","type":"string"},"project_id":{"maxLength":256,"minLength":1,"title":"Project Id","type":"string"},"regeneration":{"anyOf":[{"$ref":"#/$defs/Regeneration"},{"type":"null"}]},"request_id":{"maxLength":256,"minLength":1,"title":"Request Id","type":"string"},"revision":{"minimum":1,"title":"Revision","type":"integer"},"scenes":{"items":{"$ref":"#/$defs/RequestScene"},"minItems":1,"title":"Scenes","type":"array"},"storyboard":{"$ref":"#/$defs/Storyboard"},"supersedes_request_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"title":"Supersedes Request Id"}},"required":["contract_version","created_at","document_sha256","request_id","project_id","revision","supersedes_request_id","idempotency_key","storyboard","scenes","regeneration"],"title":"GenerationRequest","type":"object"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/GenerationResult.schema.json b/src/media_tooling/contracts/v1_0/GenerationResult.schema.json new file mode 100644 index 0000000..0ca2381 --- /dev/null +++ b/src/media_tooling/contracts/v1_0/GenerationResult.schema.json @@ -0,0 +1 @@ +{"$defs":{"ActualShot":{"additionalProperties":false,"properties":{"continuity_mode":{"enum":["cut","continue"],"title":"Continuity Mode","type":"string"},"nominal_duration_s":{"exclusiveMinimum":0,"title":"Nominal Duration S","type":"number"},"order":{"minimum":0,"title":"Order","type":"integer"},"shot_id":{"maxLength":256,"minLength":1,"title":"Shot Id","type":"string"}},"required":["shot_id","order","nominal_duration_s","continuity_mode"],"title":"ActualShot","type":"object"},"AssetRef":{"additionalProperties":false,"properties":{"asset_id":{"maxLength":256,"minLength":1,"title":"Asset Id","type":"string"},"media":{"anyOf":[{"$ref":"#/$defs/Media"},{"type":"null"}],"default":null},"mime_type":{"title":"Mime Type","type":"string"},"rights_note":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Rights Note"},"role":{"title":"Role","type":"string"},"sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Sha256","type":"string"},"source_take_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"default":null,"title":"Source Take Id"},"uri":{"title":"Uri","type":"string"}},"required":["asset_id","uri","sha256","mime_type","role","rights_note"],"title":"AssetRef","type":"object"},"Attempt":{"additionalProperties":false,"properties":{"attempt_id":{"maxLength":256,"minLength":1,"title":"Attempt Id","type":"string"},"attempt_number":{"minimum":1,"title":"Attempt Number","type":"integer"},"billing":{"$ref":"#/$defs/Billing"},"error":{"anyOf":[{"$ref":"#/$defs/AttemptError"},{"type":"null"}]},"fallback_from_attempt_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"title":"Fallback From Attempt Id"},"finished_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Finished At","type":"string"},"generation_parameters":{"additionalProperties":{"anyOf":[{"type":"string"},{"type":"integer"},{"type":"number"},{"type":"boolean"},{"type":"null"}]},"title":"Generation Parameters","type":"object"},"model":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model"},"model_version":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Model Version"},"prompt_snapshot":{"title":"Prompt Snapshot","type":"string"},"provider":{"title":"Provider","type":"string"},"provider_request_id":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Provider Request Id"},"reference_asset_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Reference Asset Ids","type":"array"},"seed":{"anyOf":[{"type":"integer"},{"type":"null"}],"title":"Seed"},"shot_id":{"maxLength":256,"minLength":1,"title":"Shot Id","type":"string"},"started_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Started At","type":"string"},"status":{"enum":["succeeded","failed","canceled"],"title":"Status","type":"string"}},"required":["attempt_id","shot_id","attempt_number","provider","model","model_version","provider_request_id","prompt_snapshot","reference_asset_ids","generation_parameters","seed","started_at","finished_at","status","fallback_from_attempt_id","error","billing"],"title":"Attempt","type":"object"},"AttemptError":{"additionalProperties":false,"properties":{"code":{"title":"Code","type":"string"},"message":{"title":"Message","type":"string"}},"required":["code","message"],"title":"AttemptError","type":"object"},"Billing":{"additionalProperties":false,"properties":{"actual_usd":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Actual Usd"},"currency":{"const":"USD","title":"Currency","type":"string"},"estimated_usd":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Estimated Usd"},"raw_unit_name":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Raw Unit Name"},"raw_units":{"anyOf":[{"type":"string"},{"type":"null"}],"title":"Raw Units"}},"required":["raw_unit_name","raw_units","estimated_usd","actual_usd","currency"],"title":"Billing","type":"object"},"Clip":{"additionalProperties":false,"properties":{"asset":{"$ref":"#/$defs/AssetRef"},"attempt_id":{"maxLength":256,"minLength":1,"title":"Attempt Id","type":"string"},"clip_id":{"maxLength":256,"minLength":1,"title":"Clip Id","type":"string"},"media":{"$ref":"#/$defs/Media"}},"required":["clip_id","attempt_id","asset","media"],"title":"Clip","type":"object"},"Keyframe":{"additionalProperties":false,"properties":{"asset":{"$ref":"#/$defs/AssetRef"},"attempt_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"title":"Attempt Id"},"media":{"$ref":"#/$defs/Media"},"order":{"minimum":0,"title":"Order","type":"integer"},"position":{"enum":["first","last"],"title":"Position","type":"string"},"shot_id":{"maxLength":256,"minLength":1,"title":"Shot Id","type":"string"}},"required":["shot_id","order","position","attempt_id","asset","media"],"title":"Keyframe","type":"object"},"Media":{"additionalProperties":false,"properties":{"fps":{"anyOf":[{"exclusiveMinimum":0,"type":"number"},{"type":"null"}],"title":"Fps"},"has_audio":{"anyOf":[{"type":"boolean"},{"type":"null"}],"title":"Has Audio"},"height":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"title":"Height"},"measured_duration_s":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Measured Duration S"},"width":{"anyOf":[{"exclusiveMinimum":0,"type":"integer"},{"type":"null"}],"title":"Width"}},"required":["measured_duration_s","width","height","fps","has_audio"],"title":"Media","type":"object"},"ResultScene":{"additionalProperties":false,"properties":{"actual_shots":{"items":{"$ref":"#/$defs/ActualShot"},"title":"Actual Shots","type":"array"},"attempts":{"items":{"$ref":"#/$defs/Attempt"},"title":"Attempts","type":"array"},"clips":{"items":{"$ref":"#/$defs/Clip"},"title":"Clips","type":"array"},"keyframes":{"items":{"$ref":"#/$defs/Keyframe"},"title":"Keyframes","type":"array"},"order":{"minimum":0,"title":"Order","type":"integer"},"scene_id":{"maxLength":256,"minLength":1,"title":"Scene Id","type":"string"},"status":{"enum":["succeeded","partial","failed","canceled"],"title":"Status","type":"string"},"takes":{"items":{"$ref":"#/$defs/Take"},"title":"Takes","type":"array"},"warnings":{"items":{"type":"string"},"title":"Warnings","type":"array"}},"required":["scene_id","order","status","actual_shots","attempts","clips","keyframes","takes","warnings"],"title":"ResultScene","type":"object"},"Take":{"additionalProperties":false,"properties":{"clip_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"minItems":1,"title":"Clip Ids","type":"array"},"clip_order":{"additionalProperties":{"minimum":0,"type":"integer"},"title":"Clip Order","type":"object"},"depends_on_take_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Depends On Take Ids","type":"array"},"measured_duration_s":{"exclusiveMinimum":0,"title":"Measured Duration S","type":"number"},"nominal_duration_s":{"exclusiveMinimum":0,"title":"Nominal Duration S","type":"number"},"preview_asset_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"title":"Preview Asset Id"},"supersedes_take_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"title":"Supersedes Take Ids","type":"array"},"take_id":{"maxLength":256,"minLength":1,"title":"Take Id","type":"string"}},"required":["take_id","clip_ids","clip_order","preview_asset_id","supersedes_take_ids","depends_on_take_ids","nominal_duration_s","measured_duration_s"],"title":"Take","type":"object"}},"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"approval_id":{"maxLength":256,"minLength":1,"title":"Approval Id","type":"string"},"contract_version":{"const":"1.0","title":"Contract Version","type":"string"},"created_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Created At","type":"string"},"document_sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Document Sha256","type":"string"},"job_id":{"maxLength":256,"minLength":1,"title":"Job Id","type":"string"},"plan_id":{"maxLength":256,"minLength":1,"title":"Plan Id","type":"string"},"preview_assets":{"items":{"$ref":"#/$defs/AssetRef"},"title":"Preview Assets","type":"array"},"reference_assets":{"items":{"$ref":"#/$defs/AssetRef"},"title":"Reference Assets","type":"array"},"request_id":{"maxLength":256,"minLength":1,"title":"Request Id","type":"string"},"result_id":{"maxLength":256,"minLength":1,"title":"Result Id","type":"string"},"result_kind":{"enum":["video","keyframes"],"title":"Result Kind","type":"string"},"scenes":{"items":{"$ref":"#/$defs/ResultScene"},"title":"Scenes","type":"array"},"terminal_status":{"enum":["succeeded","partial","failed","canceled"],"title":"Terminal Status","type":"string"}},"required":["contract_version","created_at","document_sha256","result_id","result_kind","request_id","plan_id","approval_id","job_id","terminal_status","reference_assets","preview_assets","scenes"],"title":"GenerationResult","type":"object"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/PlanApproval.schema.json b/src/media_tooling/contracts/v1_0/PlanApproval.schema.json new file mode 100644 index 0000000..9700b75 --- /dev/null +++ b/src/media_tooling/contracts/v1_0/PlanApproval.schema.json @@ -0,0 +1 @@ +{"$schema":"https://json-schema.org/draft/2020-12/schema","additionalProperties":false,"properties":{"allow_unknown_cost":{"title":"Allow Unknown Cost","type":"boolean"},"approval_id":{"maxLength":256,"minLength":1,"title":"Approval Id","type":"string"},"approved_keyframe_result_id":{"anyOf":[{"maxLength":256,"minLength":1,"type":"string"},{"type":"null"}],"title":"Approved Keyframe Result Id"},"approved_variant_ids":{"items":{"maxLength":256,"minLength":1,"type":"string"},"minItems":1,"title":"Approved Variant Ids","type":"array"},"contract_version":{"const":"1.0","title":"Contract Version","type":"string"},"created_at":{"pattern":"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?Z$","title":"Created At","type":"string"},"document_sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Document Sha256","type":"string"},"execution_mode":{"enum":["keyframes","video"],"title":"Execution Mode","type":"string"},"idempotency_key":{"maxLength":256,"minLength":1,"title":"Idempotency Key","type":"string"},"max_estimated_cost_usd":{"anyOf":[{"minimum":0,"type":"number"},{"type":"null"}],"title":"Max Estimated Cost Usd"},"plan_id":{"maxLength":256,"minLength":1,"title":"Plan Id","type":"string"},"plan_sha256":{"pattern":"^sha256:[0-9a-f]{64}$","title":"Plan Sha256","type":"string"},"request_id":{"maxLength":256,"minLength":1,"title":"Request Id","type":"string"}},"required":["contract_version","created_at","document_sha256","approval_id","request_id","plan_id","plan_sha256","execution_mode","approved_variant_ids","approved_keyframe_result_id","idempotency_key","allow_unknown_cost","max_estimated_cost_usd"],"title":"PlanApproval","type":"object"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/README.md b/src/media_tooling/contracts/v1_0/README.md new file mode 100644 index 0000000..9fb579b --- /dev/null +++ b/src/media_tooling/contracts/v1_0/README.md @@ -0,0 +1,9 @@ +# Generation contract 1.0 + +TTV owns GenerationPlan and GenerationResult. The editorial client owns GenerationRequest, PlanApproval and EditorialSelection. `edit_revision_id` is the selection ID. The five JSON Schemas use JSON Schema 2020-12. Clients pin the exact version and the raw-byte SHA-256 values in schema-hashes.json. Fixtures ending in `.invalid.json` must fail validation. + +Canonical JSON is UTF-8 with Unicode characters unescaped, keys sorted by Unicode code point, no whitespace, finite JSON numbers, and integral numbers normalized to integers (including negative zero). Other numbers use Python JSON's shortest round-trip decimal representation. SHA-256 hashes are prefixed `sha256:`. Omit only the root `document_sha256` when computing a document hash. Defaults are never inserted before hashing. Documents are immutable; each ID and idempotency key binds its complete canonical bytes. Unknown costs are null; approval must explicitly allow them. + +Scene `order` and shot `order` are explicit. A take's `clip_order` records its generated sequence. A selection's clip edit `order` defines editorial playback order and may deliberately reorder those clips in a new immutable edit revision. Array position alone carries no order. `trim_out_s` is the exclusive source out-point, not a duration removed from the tail. Takes list only complete candidates. Keyframe results contain scene keyframes and may have no clips or takes. Asset source_take_id records the take that supplied a boundary reference. Preview assets have role `scene_preview`. + +HTTP: GET /v2/capabilities, POST /v2/plans, GET /v2/plans/{id}, POST /v2/jobs, GET /v2/jobs/{id}, GET /v2/jobs/{id}/result, POST /v2/jobs/{id}/cancel. Schemas are available at GET /v2/schemas/{name}. File mode: python -m api.generation_handoff --root PATH plan REQUEST.json, approve APPROVAL.json, run JOB_ID, status JOB_ID, result JOB_ID, cancel JOB_ID. The same service owns persistence, approval checks, execution, and terminal serialization in both transports. diff --git a/src/media_tooling/contracts/v1_0/fixtures/EditorialSelection.invalid.json b/src/media_tooling/contracts/v1_0/fixtures/EditorialSelection.invalid.json new file mode 100644 index 0000000..fa7be4f --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/EditorialSelection.invalid.json @@ -0,0 +1 @@ +{"continuity_decisions":[],"contract_version":"1.0","created_at":"2026-07-20T18:35:00Z","document_sha256":"sha256:c335ad86e4e554f204120660133a49d4d0986128fc99ca0644ca69034d8aec79","edit_revision_id":"edit-r18","edl":{"path":"edit/edl-r18.json","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"project_id":"launch-film","scenes":[{"clip_edits":[{"audio_use":"preserve","clip_id":"clip-scene-04-01","order":0,"trim_in_s":0,"trim_out_s":22}],"order":4,"scene_id":"scene-04","take_id":"take-scene-04-b","transition_out":{"editorial_note":null,"type":"cut"}}],"selection_version":1,"source_results":[{"result_id":"genresult-launch-film-r4","sha256":"sha256:77692b94008b2629e0ebacb0301df7b16620bfa7dfbf5f68d1abad51855bb67c"}],"storyboard_revision_id":"storyboard-r12","unexpected":true} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/EditorialSelection.valid.json b/src/media_tooling/contracts/v1_0/fixtures/EditorialSelection.valid.json new file mode 100644 index 0000000..ffffea7 --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/EditorialSelection.valid.json @@ -0,0 +1 @@ +{"continuity_decisions":[],"contract_version":"1.0","created_at":"2026-07-20T18:35:00Z","document_sha256":"sha256:749f4f91d7b9913ac4bcea542620cf03deb16028da0c52ce568f1f52d3c2a52a","edit_revision_id":"edit-r18","edl":{"path":"edit/edl-r18.json","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"project_id":"launch-film","scenes":[{"clip_edits":[{"audio_use":"preserve","clip_id":"clip-scene-04-01","order":0,"trim_in_s":0,"trim_out_s":22}],"order":4,"scene_id":"scene-04","take_id":"take-scene-04-b","transition_out":{"editorial_note":null,"type":"cut"}}],"selection_version":1,"source_results":[{"result_id":"genresult-launch-film-r4","sha256":"sha256:77692b94008b2629e0ebacb0301df7b16620bfa7dfbf5f68d1abad51855bb67c"}],"storyboard_revision_id":"storyboard-r12"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/GenerationPlan.invalid.json b/src/media_tooling/contracts/v1_0/fixtures/GenerationPlan.invalid.json new file mode 100644 index 0000000..915139e --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/GenerationPlan.invalid.json @@ -0,0 +1 @@ +{"blocked_reasons":[],"contract_version":"1.0","created_at":"2026-07-20T18:00:10Z","document_sha256":"sha256:0093409bc5c326700d958274b8fa055d8fe0dab9bc617e165fd3ae5c1b1491e4","plan_id":"genplan-launch-film-r4","request_id":"genreq-launch-film-r4","scenes":[{"order":4,"requested_duration_s":22,"scene_id":"scene-04","variants":[{"capability_snapshot":{"allowed_durations_s":[15,30],"supports_audio":true,"supports_first_frame":true,"supports_last_frame":true},"estimated_cost":{"amount":null,"basis":"provider estimate unavailable","currency":"USD"},"model":"model-profile-a","provider":"provider-a","shots":[{"continuity_mode":"continue","first_frame_prompt":"Prototype on screen","last_frame_prompt":"Working product","nominal_duration_s":30,"order":1,"prompt_snapshot":"...","reference_asset_ids":["scene-03-exit-frame"],"shot_id":"scene-04-shot-01","target_trim_s":8}],"variant_id":"scene-04-primary"}],"warnings":["The provider-compatible duration exceeds the editorial target by 8 seconds."]}],"status":"ready","unexpected":true,"valid_until":"2026-07-21T18:00:10Z"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/GenerationPlan.valid.json b/src/media_tooling/contracts/v1_0/fixtures/GenerationPlan.valid.json new file mode 100644 index 0000000..f8eac0d --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/GenerationPlan.valid.json @@ -0,0 +1 @@ +{"blocked_reasons":[],"contract_version":"1.0","created_at":"2026-07-20T18:00:10Z","document_sha256":"sha256:9147dfadf7966e2408c742d449731c3f32fb3513cf4eb143436f233864d43e7e","plan_id":"genplan-launch-film-r4","request_id":"genreq-launch-film-r4","scenes":[{"order":4,"requested_duration_s":22,"scene_id":"scene-04","variants":[{"capability_snapshot":{"allowed_durations_s":[15,30],"supports_audio":true,"supports_first_frame":true,"supports_last_frame":true},"estimated_cost":{"amount":null,"basis":"provider estimate unavailable","currency":"USD"},"model":"model-profile-a","provider":"provider-a","shots":[{"continuity_mode":"continue","first_frame_prompt":"Prototype on screen","last_frame_prompt":"Working product","nominal_duration_s":30,"order":1,"prompt_snapshot":"...","reference_asset_ids":["scene-03-exit-frame"],"shot_id":"scene-04-shot-01","target_trim_s":8}],"variant_id":"scene-04-primary"}],"warnings":["The provider-compatible duration exceeds the editorial target by 8 seconds."]}],"status":"ready","valid_until":"2026-07-21T18:00:10Z"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/GenerationRequest.invalid.json b/src/media_tooling/contracts/v1_0/fixtures/GenerationRequest.invalid.json new file mode 100644 index 0000000..433ed37 --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/GenerationRequest.invalid.json @@ -0,0 +1 @@ +{"contract_version":"1.0","created_at":"2026-07-20T18:00:00Z","document_sha256":"sha256:4bde410ab1647ef395bfd0024f3fa528ce600da2b31d7d1598238d92dd7efb8e","idempotency_key":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","project_id":"launch-film","regeneration":{"base_result_ids":["genresult-launch-film-r3"],"reason":"The product UI changed after review","supersedes_take_ids":["take-scene-04-a"]},"request_id":"genreq-launch-film-r4","revision":4,"scenes":[{"continuity":{"mode":"continue_from_previous","required_reference_asset_ids":["scene-03-exit-frame"]},"delivery":{"aspect_ratio":"16:9","audio_policy":"preserve_if_present","target_height":1080,"target_width":1920},"generation_policy":{"allow_provider_fallback":true,"max_attempts":4,"max_estimated_cost_usd":40,"provider_preferences":[]},"intent":{"continuity_notes":"Preserve the same device, room, and time of day","entry_state":"Static prototype on screen","exit_state":"Running product in a browser","summary":"The prototype becomes a complete working product."},"order":4,"reference_assets":[{"asset_id":"scene-03-exit-frame","mime_type":"image/png","rights_note":"Generated for this project","role":"first_frame","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","uri":"gs://project-media/boundaries/scene-03-exit.png"}],"requested_duration_s":22,"scene_id":"scene-04","transition_out":{"editorial_note":"Cut on the browser launch action","type":"cut"}}],"storyboard":{"revision_id":"storyboard-r12","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"supersedes_request_id":"genreq-launch-film-r3","unexpected":true} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/GenerationRequest.valid.json b/src/media_tooling/contracts/v1_0/fixtures/GenerationRequest.valid.json new file mode 100644 index 0000000..825400a --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/GenerationRequest.valid.json @@ -0,0 +1 @@ +{"contract_version":"1.0","created_at":"2026-07-20T18:00:00Z","document_sha256":"sha256:6612f0a425237a83ef98e76f47634d3fdde2a5a39374ed9cb5783dfbf798a330","idempotency_key":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","project_id":"launch-film","regeneration":{"base_result_ids":["genresult-launch-film-r3"],"reason":"The product UI changed after review","supersedes_take_ids":["take-scene-04-a"]},"request_id":"genreq-launch-film-r4","revision":4,"scenes":[{"continuity":{"mode":"continue_from_previous","required_reference_asset_ids":["scene-03-exit-frame"]},"delivery":{"aspect_ratio":"16:9","audio_policy":"preserve_if_present","target_height":1080,"target_width":1920},"generation_policy":{"allow_provider_fallback":true,"max_attempts":4,"max_estimated_cost_usd":40,"provider_preferences":[]},"intent":{"continuity_notes":"Preserve the same device, room, and time of day","entry_state":"Static prototype on screen","exit_state":"Running product in a browser","summary":"The prototype becomes a complete working product."},"order":4,"reference_assets":[{"asset_id":"scene-03-exit-frame","mime_type":"image/png","rights_note":"Generated for this project","role":"first_frame","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","uri":"gs://project-media/boundaries/scene-03-exit.png"}],"requested_duration_s":22,"scene_id":"scene-04","transition_out":{"editorial_note":"Cut on the browser launch action","type":"cut"}}],"storyboard":{"revision_id":"storyboard-r12","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"},"supersedes_request_id":"genreq-launch-film-r3"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/GenerationResult.invalid.json b/src/media_tooling/contracts/v1_0/fixtures/GenerationResult.invalid.json new file mode 100644 index 0000000..b6d23ad --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/GenerationResult.invalid.json @@ -0,0 +1 @@ +{"approval_id":"approval-launch-film-r4","contract_version":"1.0","created_at":"2026-07-20T18:22:00Z","document_sha256":"sha256:882c24ea836b38b111ee1e28fb1b243cb526075ac7f1006a8380fbc8ee9661b8","job_id":"job-7f4a","plan_id":"genplan-launch-film-r4","preview_assets":[],"reference_assets":[{"asset_id":"scene-03-exit-frame","mime_type":"image/png","rights_note":"Generated for this project","role":"first_frame","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","uri":"gs://project-media/boundaries/scene-03-exit.png"}],"request_id":"genreq-launch-film-r4","result_id":"genresult-launch-film-r4","result_kind":"video","scenes":[{"actual_shots":[{"continuity_mode":"continue","nominal_duration_s":30,"order":1,"shot_id":"scene-04-shot-01"}],"attempts":[{"attempt_id":"attempt-scene-04-01","attempt_number":1,"billing":{"actual_usd":null,"currency":"USD","estimated_usd":null,"raw_unit_name":"provider_billable_units","raw_units":"..."},"error":null,"fallback_from_attempt_id":null,"finished_at":"2026-07-20T18:21:40Z","generation_parameters":{"aspect_ratio":"16:9","duration_s":30},"model":"model-profile-a","model_version":null,"prompt_snapshot":"...","provider":"provider-a","provider_request_id":"provider-request-123","reference_asset_ids":["scene-03-exit-frame"],"seed":123456,"shot_id":"scene-04-shot-01","started_at":"2026-07-20T18:05:03Z","status":"succeeded"}],"clips":[{"asset":{"asset_id":"clip-scene-04-01","mime_type":"video/mp4","rights_note":null,"role":"generated_clip","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","uri":"gs://project-media/generated/clip-scene-04-01.mp4"},"attempt_id":"attempt-scene-04-01","clip_id":"clip-scene-04-01","media":{"fps":24,"has_audio":true,"height":1080,"measured_duration_s":30.04,"width":1920}}],"keyframes":[],"order":4,"scene_id":"scene-04","status":"succeeded","takes":[{"clip_ids":["clip-scene-04-01"],"clip_order":{"clip-scene-04-01":0},"depends_on_take_ids":["take-scene-03-c"],"measured_duration_s":30.04,"nominal_duration_s":30,"preview_asset_id":null,"supersedes_take_ids":["take-scene-04-a"],"take_id":"take-scene-04-b"}],"warnings":[]}],"terminal_status":"succeeded","unexpected":true} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/GenerationResult.valid.json b/src/media_tooling/contracts/v1_0/fixtures/GenerationResult.valid.json new file mode 100644 index 0000000..cedf22e --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/GenerationResult.valid.json @@ -0,0 +1 @@ +{"approval_id":"approval-launch-film-r4","contract_version":"1.0","created_at":"2026-07-20T18:22:00Z","document_sha256":"sha256:77692b94008b2629e0ebacb0301df7b16620bfa7dfbf5f68d1abad51855bb67c","job_id":"job-7f4a","plan_id":"genplan-launch-film-r4","preview_assets":[],"reference_assets":[{"asset_id":"scene-03-exit-frame","mime_type":"image/png","rights_note":"Generated for this project","role":"first_frame","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","uri":"gs://project-media/boundaries/scene-03-exit.png"}],"request_id":"genreq-launch-film-r4","result_id":"genresult-launch-film-r4","result_kind":"video","scenes":[{"actual_shots":[{"continuity_mode":"continue","nominal_duration_s":30,"order":1,"shot_id":"scene-04-shot-01"}],"attempts":[{"attempt_id":"attempt-scene-04-01","attempt_number":1,"billing":{"actual_usd":null,"currency":"USD","estimated_usd":null,"raw_unit_name":"provider_billable_units","raw_units":"..."},"error":null,"fallback_from_attempt_id":null,"finished_at":"2026-07-20T18:21:40Z","generation_parameters":{"aspect_ratio":"16:9","duration_s":30},"model":"model-profile-a","model_version":null,"prompt_snapshot":"...","provider":"provider-a","provider_request_id":"provider-request-123","reference_asset_ids":["scene-03-exit-frame"],"seed":123456,"shot_id":"scene-04-shot-01","started_at":"2026-07-20T18:05:03Z","status":"succeeded"}],"clips":[{"asset":{"asset_id":"clip-scene-04-01","mime_type":"video/mp4","rights_note":null,"role":"generated_clip","sha256":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","uri":"gs://project-media/generated/clip-scene-04-01.mp4"},"attempt_id":"attempt-scene-04-01","clip_id":"clip-scene-04-01","media":{"fps":24,"has_audio":true,"height":1080,"measured_duration_s":30.04,"width":1920}}],"keyframes":[],"order":4,"scene_id":"scene-04","status":"succeeded","takes":[{"clip_ids":["clip-scene-04-01"],"clip_order":{"clip-scene-04-01":0},"depends_on_take_ids":["take-scene-03-c"],"measured_duration_s":30.04,"nominal_duration_s":30,"preview_asset_id":null,"supersedes_take_ids":["take-scene-04-a"],"take_id":"take-scene-04-b"}],"warnings":[]}],"terminal_status":"succeeded"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/PlanApproval.invalid.json b/src/media_tooling/contracts/v1_0/fixtures/PlanApproval.invalid.json new file mode 100644 index 0000000..5481d7c --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/PlanApproval.invalid.json @@ -0,0 +1 @@ +{"allow_unknown_cost":true,"approval_id":"approval-launch-film-r4","approved_keyframe_result_id":null,"approved_variant_ids":["scene-04-primary"],"contract_version":"1.0","created_at":"2026-07-20T18:05:00Z","document_sha256":"sha256:81ba0688eb02403a115ec4c9f81340966ef77bf9f62ad7db0c6f62c4c55963be","execution_mode":"video","idempotency_key":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","max_estimated_cost_usd":40,"plan_id":"genplan-launch-film-r4","plan_sha256":"sha256:9147dfadf7966e2408c742d449731c3f32fb3513cf4eb143436f233864d43e7e","request_id":"genreq-launch-film-r4","unexpected":true} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/fixtures/PlanApproval.valid.json b/src/media_tooling/contracts/v1_0/fixtures/PlanApproval.valid.json new file mode 100644 index 0000000..666309a --- /dev/null +++ b/src/media_tooling/contracts/v1_0/fixtures/PlanApproval.valid.json @@ -0,0 +1 @@ +{"allow_unknown_cost":true,"approval_id":"approval-launch-film-r4","approved_keyframe_result_id":null,"approved_variant_ids":["scene-04-primary"],"contract_version":"1.0","created_at":"2026-07-20T18:05:00Z","document_sha256":"sha256:60b94e7cfda23a05a11cf5052bb35c5bdb71a9a564afb99f648753b68a7f25f1","execution_mode":"video","idempotency_key":"sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","max_estimated_cost_usd":40,"plan_id":"genplan-launch-film-r4","plan_sha256":"sha256:9147dfadf7966e2408c742d449731c3f32fb3513cf4eb143436f233864d43e7e","request_id":"genreq-launch-film-r4"} \ No newline at end of file diff --git a/src/media_tooling/contracts/v1_0/schema-hashes.json b/src/media_tooling/contracts/v1_0/schema-hashes.json new file mode 100644 index 0000000..c9dd973 --- /dev/null +++ b/src/media_tooling/contracts/v1_0/schema-hashes.json @@ -0,0 +1 @@ +{"EditorialSelection":"sha256:58052567e9304650f9ad00237023fe2dc599c96632de506f42915dfa47f39e21","GenerationPlan":"sha256:3aa7855d795b507985e3df941c52f46b9b30c44db699430b19c5e0fbf93a5e0e","GenerationRequest":"sha256:a61b1ef25ab39746d3772f91c9ddc39c93ac826b2ea447c4be0bd5308a3c4176","GenerationResult":"sha256:fa31754810ec0412407b43076a638c2694a34a6f7fe5039216f0bee48c0e371d","PlanApproval":"sha256:adfea31d1ba07d60d4cd367c603b041ae7ec099bb9fb072deeb0953062268a24"} \ No newline at end of file diff --git a/src/media_tooling/generated_media.py b/src/media_tooling/generated_media.py new file mode 100644 index 0000000..057f0f7 --- /dev/null +++ b/src/media_tooling/generated_media.py @@ -0,0 +1,1145 @@ +"""Versioned TTV handoff, verified project imports, and ordinary EDL compilation. + +TTV owns generation. This adapter owns immutable editorial revisions. No provider +SDK or TTV runtime is needed; the pinned JSON schemas are the protocol boundary. +""" + +from __future__ import annotations + +import argparse +import copy +import hashlib +import json +import math +import os +import re +import subprocess +import sys +import tempfile +from datetime import datetime, timezone +from decimal import Decimal +from fractions import Fraction +from pathlib import Path +from typing import Any, BinaryIO +from urllib.error import HTTPError, URLError +from urllib.parse import quote, unquote, urlsplit +from urllib.request import HTTPRedirectHandler, Request, build_opener +from uuid import uuid4 + +from jsonschema import Draft202012Validator, FormatChecker +from PIL import Image + +from media_tooling.edl_render import ( + EDL_VERSION, + apply_padding, + render_edl, + validate_edl, +) +from media_tooling.project_init import ensure_project_directories +from media_tooling.verify import run_verification + +CONTRACT_VERSION = "1.0" +CONTRACT_DIR = Path(__file__).parent / "contracts" / "v1_0" +SCHEMA_MANIFEST_SHA256 = "sha256:477478a4dbbfce5f653c60f11689543ccddb50cf3e7d6492065376c38ea98284" +DOCUMENTS = { + "request": ("request_id", "requests", "GenerationRequest"), + "plan": ("plan_id", "plans", "GenerationPlan"), + "approval": ("approval_id", "approvals", "PlanApproval"), + "result": ("result_id", "results", "GenerationResult"), + "selection": ("edit_revision_id", "selections", "EditorialSelection"), +} +MAX_DOCUMENT_BYTES = 16 * 1024 * 1024 +MAX_ASSET_BYTES = 20 * 1024**3 + + +class IntegrationError(ValueError): + """Invalid, incompatible, or unsafe integration input.""" + + +def canonical_bytes(value: Any) -> bytes: + def normalize(item: Any) -> Any: + if isinstance(item, float): + if not math.isfinite(item): + raise IntegrationError("Non-finite JSON number") + return int(item) if item.is_integer() else item + if isinstance(item, dict): + return {key: normalize(child) for key, child in item.items()} + if isinstance(item, list): + return [normalize(child) for child in item] + return item + + return json.dumps(normalize(value), sort_keys=True, separators=(",", ":"), + ensure_ascii=False, allow_nan=False).encode("utf-8") + + +def sha256(data: bytes) -> str: + return "sha256:" + hashlib.sha256(data).hexdigest() + + +def document_hash(document: dict[str, Any]) -> str: + return sha256(canonical_bytes({k: v for k, v in document.items() if k != "document_sha256"})) + + +def seal(document: dict[str, Any]) -> dict[str, Any]: + document = copy.deepcopy(document) + document["document_sha256"] = document_hash(document) + return document + + +def file_hash(path: Path) -> str: + with path.open("rb") as stream: + return "sha256:" + hashlib.file_digest(stream, "sha256").hexdigest() + + +def read_json(path: Path) -> dict[str, Any]: + if path.stat().st_size > MAX_DOCUMENT_BYTES: + raise IntegrationError("Document exceeds 16 MiB") + return decode_json(path.read_bytes()) + + +def decode_json(data: bytes) -> dict[str, Any]: + def unique_pairs(pairs: list[tuple[str, Any]]) -> dict[str, Any]: + result: dict[str, Any] = {} + for key, value in pairs: + if key in result: + raise IntegrationError("Duplicate JSON key") + result[key] = value + return result + + if len(data) > MAX_DOCUMENT_BYTES: + raise IntegrationError("Document exceeds 16 MiB") + value = json.loads(data, object_pairs_hook=unique_pairs) + if not isinstance(value, dict): + raise IntegrationError("Expected a JSON object") + canonical_bytes(value) + return value + + +def reject_secrets(value: Any) -> None: + if isinstance(value, dict): + for key, child in value.items(): + if re.sub(r"[^a-z]", "", key.lower()) in { + "authorization", "headers", "httpheaders", "apikey", "token", + "accesstoken", "refreshtoken", "password", "secret", "credentials", + "signedurl", "downloadurl", "privatekey", "secretkey", + }: + raise IntegrationError("Credentials and delivery URLs are forbidden in durable documents") + reject_secrets(child) + elif isinstance(value, list): + for child in value: + reject_secrets(child) + elif isinstance(value, str): + for candidate in re.findall(r"(?:https?|gs|s3|file)://[^\s\"<>]+", value, flags=re.I): + uri = urlsplit(candidate) + if uri.username or uri.password or uri.query or uri.fragment: + raise IntegrationError("Durable URIs cannot contain credentials, queries, or fragments") + if re.search(r"\bBearer\s+\S+", value, flags=re.I): + raise IntegrationError("Authorization values are forbidden in durable documents") + + +def _unique(items: list[dict[str, Any]], key: str) -> dict[Any, dict[str, Any]]: + result = {item[key]: item for item in items} + if len(result) != len(items): + raise IntegrationError(f"Duplicate {key}") + return result + + +def validate_document(kind: str, document: dict[str, Any]) -> None: + if document.get("contract_version") != CONTRACT_VERSION: + raise IntegrationError(f"Incompatible contract version; supported version is {CONTRACT_VERSION}") + reject_secrets(document) + if file_hash(CONTRACT_DIR / "schema-hashes.json") != SCHEMA_MANIFEST_SHA256: + raise IntegrationError("Pinned schema manifest hash mismatch") + manifest = read_json(CONTRACT_DIR / "schema-hashes.json") + schema_name = DOCUMENTS[kind][2] + ".schema.json" + schema_path = CONTRACT_DIR / schema_name + if file_hash(schema_path) != manifest[DOCUMENTS[kind][2]]: + raise IntegrationError("Pinned contract schema hash mismatch") + schema = read_json(schema_path) + errors = list(Draft202012Validator(schema, format_checker=FormatChecker()).iter_errors(document)) + if errors: + # Do not echo schema validator messages: they can contain rejected secrets. + raise IntegrationError("Invalid " + kind + " field: " + ".".join(map(str, errors[0].absolute_path))) + if document_hash(document) != document["document_sha256"]: + raise IntegrationError("Document SHA-256 mismatch") + try: + for key in ("created_at", "valid_until"): + if key in document: + datetime.fromisoformat(document[key].replace("Z", "+00:00")) + except ValueError: + raise IntegrationError("Invalid UTC timestamp") from None + scenes = document.get("scenes", []) + _unique(scenes, "scene_id") + if scenes and "order" in scenes[0]: + _unique(scenes, "order") + if kind == "request": + _unique([asset for scene in scenes for asset in scene["reference_assets"]], "asset_id") + for scene in scenes: + for role in ("first_frame", "last_frame"): + if sum(asset["role"] == role for asset in scene["reference_assets"]) > 1: + raise IntegrationError(f"Multiple {role} assets in one scene") + if kind == "plan": + _unique([variant for scene in scenes for variant in scene["variants"]], "variant_id") + for scene in scenes: + for variant in scene["variants"]: + _unique(variant["shots"], "shot_id") + _unique(variant["shots"], "order") + if kind == "result": + for scene in scenes: + shots = _unique(scene["actual_shots"], "shot_id") + _unique(scene["actual_shots"], "order") + attempts = _unique(scene["attempts"], "attempt_id") + clips = _unique(scene["clips"], "clip_id") + _unique(scene["takes"], "take_id") + seen: set[str] = set() + for attempt in scene["attempts"]: + if attempt["shot_id"] not in shots: + raise IntegrationError("Attempt refers to missing shot") + fallback = attempt.get("fallback_from_attempt_id") + if fallback is not None and fallback not in seen: + raise IntegrationError("Fallback refers to missing or later attempt") + seen.add(attempt["attempt_id"]) + for clip in clips.values(): + if clip["attempt_id"] not in attempts or attempts[clip["attempt_id"]]["status"] != "succeeded": + raise IntegrationError("Clip must refer to a successful attempt") + for take in scene["takes"]: + if not take["clip_ids"] or len(set(take["clip_ids"])) != len(take["clip_ids"]): + raise IntegrationError("Take requires distinct ordered clips") + if any(clip_id not in clips for clip_id in take["clip_ids"]): + raise IntegrationError("Take refers to missing clip") + if set(take["clip_order"]) != set(take["clip_ids"]) or len(set(take["clip_order"].values())) != len(take["clip_ids"]): + raise IntegrationError("Take requires explicit unique clip order") + if kind == "selection": + for scene in scenes: + for edit in scene["clip_edits"]: + if edit["trim_out_s"] <= edit["trim_in_s"]: + raise IntegrationError("Clip trim_out_s must exceed trim_in_s") + + +def _component(identifier: str) -> str: + # IDs remain opaque; only their local storage names need filesystem restrictions. + if re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,120}", identifier) and ".." not in identifier: + return identifier + return "id-" + hashlib.sha256(identifier.encode()).hexdigest() + + +def project_path(project: Path, relative: str | Path) -> Path: + root = project.resolve() + path = root / relative + if not path.resolve().is_relative_to(root): + raise IntegrationError("Path escapes project directory") + if path.is_symlink(): + raise IntegrationError("Artifact path cannot be a symlink") + return path + + +def immutable_write(path: Path, data: bytes) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=path.parent, delete=False) as stream: + temp = Path(stream.name) + stream.write(data) + stream.flush() + os.fsync(stream.fileno()) + try: + try: + os.link(temp, path) + except FileExistsError: + if path.is_symlink() or path.read_bytes() != data: + raise IntegrationError("Immutable artifact already exists with different content") from None + finally: + temp.unlink() + return path + + +def document_path(project: Path, kind: str, identifier: str) -> Path: + return project_path(project, Path("rough-cuts/manifests") / DOCUMENTS[kind][1] / (_component(identifier) + ".json")) + + +def store_document(project: Path, kind: str, document: dict[str, Any]) -> Path: + validate_document(kind, document) + identifier = document[DOCUMENTS[kind][0]] + return immutable_write(document_path(project, kind, identifier), canonical_bytes(document)) + + +def load_document(project: Path, kind: str, identifier: str) -> dict[str, Any]: + document = read_json(document_path(project, kind, identifier)) + validate_document(kind, document) + if document[DOCUMENTS[kind][0]] != identifier: + raise IntegrationError("Document identity mismatch") + return document + + +def now() -> str: + return datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + + +def build_request( + project: Path, storyboard: dict[str, Any], *, scene_ids: list[str] | None = None, + request_id: str | None = None, revision: int = 1, supersedes_request_id: str | None = None, + regeneration: dict[str, Any] | None = None, +) -> dict[str, Any]: + if storyboard.get("approved") is not True: + raise IntegrationError("Storyboard revision must be approved before request authoring") + reject_secrets(storyboard) + all_scenes = _unique(storyboard["scenes"], "scene_id") + _unique(storyboard["scenes"], "order") + targets = list(all_scenes) if scene_ids is None else scene_ids + if not targets or len(set(targets)) != len(targets) or set(targets) - all_scenes.keys(): + raise IntegrationError("Scene subset contains missing or duplicate scene IDs") + scenes = sorted((copy.deepcopy(all_scenes[key]) for key in targets), key=lambda scene: scene["order"]) + document = { + "contract_version": CONTRACT_VERSION, "request_id": request_id or str(uuid4()), + "project_id": storyboard["project_id"], "revision": revision, + "supersedes_request_id": supersedes_request_id, "created_at": now(), + "storyboard": {"revision_id": storyboard["revision_id"], "sha256": sha256(canonical_bytes(storyboard))}, + "scenes": scenes, "regeneration": regeneration, + } + document["idempotency_key"] = sha256(canonical_bytes(document)) + document = seal(document) + validate_document("request", document) + ensure_project_directories(project_dir=project, create_directories=True) + immutable_write(project_path(project, Path("storyboards") / (_component(storyboard["revision_id"]) + ".json")), canonical_bytes(storyboard)) + store_document(project, "request", document) + return document + + +def approve_plan( + project: Path, plan: dict[str, Any], variant_ids: list[str], *, execution_mode: str = "video", + approval_id: str | None = None, idempotency_key: str | None = None, + keyframe_result_id: str | None = None, + allow_unknown_cost: bool = False, max_estimated_cost_usd: float | None = None, +) -> dict[str, Any]: + validate_document("plan", plan) + if plan["status"] != "ready" or datetime.fromisoformat(plan["valid_until"].replace("Z", "+00:00")) <= datetime.now(timezone.utc): + raise IntegrationError("Plan is blocked or expired") + all_variants = {variant["variant_id"] for scene in plan["scenes"] for variant in scene["variants"]} + if len(set(variant_ids)) != len(variant_ids) or set(variant_ids) - all_variants: + raise IntegrationError("Unknown or duplicate approved variant") + if any(not set(variant_ids).intersection(v["variant_id"] for v in scene["variants"]) for scene in plan["scenes"]): + raise IntegrationError("Every planned scene requires an approved variant") + approved = [variant for scene in plan["scenes"] for variant in scene["variants"] if variant["variant_id"] in variant_ids] + if any(variant["estimated_cost"]["amount"] is None for variant in approved) and not allow_unknown_cost: + raise IntegrationError("Plan has unknown costs; approval requires --allow-unknown-cost") + if keyframe_result_id is not None: + keyframes = load_document(project, "result", keyframe_result_id) + if keyframes["result_kind"] != "keyframes" or keyframes["plan_id"] != plan["plan_id"] or keyframes["terminal_status"] != "succeeded": + raise IntegrationError("Approved keyframes must be a successful result from this plan") + document = seal({ + "contract_version": CONTRACT_VERSION, "approval_id": approval_id or str(uuid4()), + "request_id": plan["request_id"], "plan_id": plan["plan_id"], + "plan_sha256": plan["document_sha256"], "created_at": now(), + "execution_mode": execution_mode, "approved_variant_ids": variant_ids, + "approved_keyframe_result_id": keyframe_result_id, + "idempotency_key": idempotency_key or str(uuid4()), + "allow_unknown_cost": allow_unknown_cost, "max_estimated_cost_usd": max_estimated_cost_usd, + }) + store_document(project, "plan", plan) + store_document(project, "approval", document) + return document + + +class _NoRedirect(HTTPRedirectHandler): + def redirect_request(self, req: Any, fp: Any, code: int, msg: str, headers: Any, newurl: str) -> None: + raise IntegrationError("HTTP redirects require an explicit new endpoint") + + +def http_document( + base_url: str, path: str, *, document: dict[str, Any] | None = None, + token: str | None = None, method: str | None = None, +) -> dict[str, Any]: + uri = urlsplit(base_url) + if uri.scheme not in {"http", "https"} or not uri.hostname or uri.username or uri.password or uri.query or uri.fragment: + raise IntegrationError("Invalid service endpoint") + if uri.scheme == "http" and uri.hostname not in {"localhost", "127.0.0.1", "::1"}: + raise IntegrationError("Remote services require HTTPS") + headers = {"Accept": "application/json", "Content-Type": "application/json"} + if token: + headers["Authorization"] = "Bearer " + token + request = Request(base_url.rstrip("/") + path, data=None if document is None else canonical_bytes(document), headers=headers, method=method) + try: + with build_opener(_NoRedirect()).open(request, timeout=60) as response: + return decode_json(response.read(MAX_DOCUMENT_BYTES + 1)) + except HTTPError as exc: + raise IntegrationError(f"TTV returned HTTP {exc.code}") from None + except URLError: + raise IntegrationError("TTV connection failed") from None + + +def probe_media(path: Path) -> dict[str, Any]: + result = subprocess.run(["ffprobe", "-v", "error", "-show_streams", "-show_format", "-of", "json", str(path)], check=True, capture_output=True) + payload = decode_json(result.stdout) + video = next((stream for stream in payload["streams"] if stream["codec_type"] == "video"), None) + if not video: + raise IntegrationError("Imported clip has no video stream") + duration = float(payload.get("format", {}).get("duration", video.get("duration", 0))) + fps = float(Fraction(video.get("avg_frame_rate") or video["r_frame_rate"])) + if not math.isfinite(duration) or duration <= 0 or not math.isfinite(fps) or fps <= 0: + raise IntegrationError("Imported clip has invalid duration or frame rate") + return {"measured_duration_s": duration, "width": int(video["width"]), "height": int(video["height"]), + "fps": fps, "has_audio": any(stream["codec_type"] == "audio" for stream in payload["streams"])} + + +def _compare_media(expected: dict[str, Any], measured: dict[str, Any]) -> None: + for key in ("width", "height", "has_audio"): + if expected.get(key) is not None and expected[key] != measured[key]: + raise IntegrationError("Clip media property mismatch: " + key) + for key, tolerance in (("measured_duration_s", 0.05), ("fps", 0.01)): + if expected.get(key) is not None and abs(expected[key] - measured[key]) > tolerance: + raise IntegrationError("Clip media property mismatch: " + key) + + +def _copy_limited(stream: BinaryIO, destination: Path) -> None: + total = 0 + with destination.open("wb") as output: + while chunk := stream.read(1024 * 1024): + total += len(chunk) + if total > MAX_ASSET_BYTES: + raise IntegrationError("Asset exceeds 20 GiB") + output.write(chunk) + + +def import_asset( + project: Path, asset: dict[str, Any], relative: Path, *, asset_root: Path | None = None, + deliveries: dict[str, str] | None = None, allowed_origins: list[str] | None = None, + media: dict[str, Any] | None = None, +) -> dict[str, Any]: + reject_secrets(asset) + asset_schema = read_json(CONTRACT_DIR / "GenerationResult.schema.json") + schema = {"$defs": asset_schema["$defs"], "$ref": "#/$defs/AssetRef"} + if not Draft202012Validator(schema).is_valid(asset): + raise IntegrationError("Invalid AssetRef") + if media is not None and not asset["mime_type"].startswith("video/"): + raise IntegrationError("Generated clip MIME type must be video") + destination = project_path(project, relative) + destination.parent.mkdir(parents=True, exist_ok=True) + delivery = (deliveries or {}).get(asset["uri"], asset["uri"]) + uri = urlsplit(delivery) + with tempfile.TemporaryDirectory(dir=destination.parent) as stage: + staged = Path(stage) / "asset" + if uri.scheme in {"", "file"}: + if uri.netloc or uri.query or uri.fragment: + raise IntegrationError("Invalid local delivery URI") + source = Path(unquote(uri.path)).resolve() + # File roots are caller-controlled, never inferred from an imported result. + if asset_root is None or not source.is_relative_to(asset_root.resolve()) or not source.is_file(): + raise IntegrationError("Local asset is outside the explicit asset root") + with source.open("rb") as stream: + _copy_limited(stream, staged) + elif uri.scheme in {"https", "http"}: + origin = f"{uri.scheme}://{uri.netloc}" + if origin not in (allowed_origins or []) or uri.username or uri.password or uri.fragment: + raise IntegrationError("Asset delivery origin is not explicitly allowed") + if uri.scheme == "http" and uri.hostname not in {"localhost", "127.0.0.1", "::1"}: + raise IntegrationError("Remote assets require HTTPS") + try: + with build_opener(_NoRedirect()).open(delivery, timeout=60) as response: + _copy_limited(response, staged) + except (HTTPError, URLError): + raise IntegrationError("Asset download failed") from None + else: + raise IntegrationError("Supply an explicit delivery mapping for this durable object URI") + if file_hash(staged) != asset["sha256"]: + raise IntegrationError("Asset SHA-256 mismatch") + measured = probe_media(staged) if asset["mime_type"].startswith("video/") else None + if measured is not None: + _compare_media(media or asset.get("media") or {}, measured) + if asset["mime_type"].startswith("image/"): + with Image.open(staged) as image: + if Image.MIME.get(image.format or "") != asset["mime_type"]: + raise IntegrationError("Image MIME type does not match its content") + if asset.get("media"): + for key, actual in (("width", image.width), ("height", image.height)): + if asset["media"].get(key) is not None and asset["media"][key] != actual: + raise IntegrationError("Reference image dimensions mismatch") + image.verify() + try: + os.link(staged, destination) + except FileExistsError: + if destination.is_symlink() or file_hash(destination) != asset["sha256"]: + raise IntegrationError("Imported asset path already has different content") from None + return {"asset_id": asset["asset_id"], "source_uri": asset["uri"], "sha256": asset["sha256"], + "local_path": str(destination.relative_to(project.resolve())), "media": measured} + + +def import_result( + project: Path, result: dict[str, Any], *, asset_root: Path | None = None, + deliveries: dict[str, str] | None = None, allowed_origins: list[str] | None = None, +) -> dict[str, Any]: + validate_document("result", result) + records = [] + for scene in result["scenes"]: + for clip in scene["clips"]: + take_ids = [take["take_id"] for take in scene["takes"] if clip["clip_id"] in take["clip_ids"]] + take_dir = take_ids[0] if take_ids else result["result_id"] + relative = Path("rough-cuts/generated-clips") / _component(scene["scene_id"]) / _component(take_dir) / (_component(clip["clip_id"]) + ".mp4") + record = import_asset(project, clip["asset"], relative, asset_root=asset_root, deliveries=deliveries, allowed_origins=allowed_origins, media=clip["media"]) + records.append({**record, "scene_id": scene["scene_id"], "clip_id": clip["clip_id"], "attempt_id": clip["attempt_id"]}) + for keyframe in scene["keyframes"]: + asset = keyframe["asset"] + relative = Path("rough-cuts/generated-clips") / _component(scene["scene_id"]) / _component(result["result_id"]) / (_component(asset["asset_id"]) + ".png") + record = import_asset(project, asset, relative, asset_root=asset_root, deliveries=deliveries, allowed_origins=allowed_origins) + with Image.open(project_path(project, record["local_path"])) as image: + for key, actual in (("width", image.width), ("height", image.height)): + if keyframe["media"].get(key) is not None and keyframe["media"][key] != actual: + raise IntegrationError("Keyframe dimensions mismatch") + records.append({**record, "scene_id": scene["scene_id"], "shot_id": keyframe["shot_id"], "position": keyframe["position"]}) + for asset in result["preview_assets"]: + relative = Path("rough-cuts/generated-clips/previews") / _component(result["result_id"]) / (_component(asset["asset_id"]) + ".mp4") + records.append(import_asset(project, asset, relative, asset_root=asset_root, deliveries=deliveries, allowed_origins=allowed_origins, media=asset.get("media"))) + for asset in result["reference_assets"]: + relative = Path("assets/reference/generated") / _component(result["result_id"]) / _component(asset["asset_id"]) + records.append(import_asset(project, asset, relative, asset_root=asset_root, deliveries=deliveries, allowed_origins=allowed_origins)) + index = {"result_id": result["result_id"], "result_sha256": result["document_sha256"], "assets": records} + immutable_write(project_path(project, Path("rough-cuts/manifests/imports") / (_component(result["result_id"]) + ".json")), canonical_bytes(index)) + store_document(project, "result", result) + return index + + +def _selection_inputs(project: Path, selection: dict[str, Any]) -> dict[str, dict[str, Any]]: + results = {} + for reference in selection["source_results"]: + result = load_document(project, "result", reference["result_id"]) + if result["result_id"] in results or result["document_sha256"] != reference["sha256"]: + raise IntegrationError("Duplicate result or result hash mismatch in selection") + if result["result_kind"] != "video": + raise IntegrationError("A keyframe result cannot supply a video take") + request = load_document(project, "request", result["request_id"]) + plan = load_document(project, "plan", result["plan_id"]) + approval = load_document(project, "approval", result["approval_id"]) + if approval["execution_mode"] != result["result_kind"]: + raise IntegrationError("Result kind does not match approval execution mode") + if request["project_id"] != selection["project_id"]: + raise IntegrationError("Result belongs to a different project") + if (plan["request_id"] != request["request_id"] or approval["request_id"] != request["request_id"] + or approval["plan_id"] != plan["plan_id"] or approval["plan_sha256"] != plan["document_sha256"]): + raise IntegrationError("Result provenance chain does not match request, plan, and approval") + requested_scenes = {scene["scene_id"]: scene for scene in request["scenes"]} + for planned_scene in plan["scenes"]: + requested_scene = requested_scenes.get(planned_scene["scene_id"]) + if not requested_scene: + raise IntegrationError("Plan refers to an unrequested scene") + required_refs = set(requested_scene["continuity"]["required_reference_asset_ids"]) + for variant in planned_scene["variants"]: + planned_refs = {identifier for shot in variant["shots"] for identifier in shot["reference_asset_ids"]} + if not required_refs <= planned_refs: + raise IntegrationError("Plan omitted required storyboard references") + source_board = read_json(project_path(project, Path("storyboards") / (_component(request["storyboard"]["revision_id"]) + ".json"))) + if sha256(canonical_bytes(source_board)) != request["storyboard"]["sha256"]: + raise IntegrationError("Request storyboard hash mismatch") + index = read_json(project_path(project, Path("rough-cuts/manifests/imports") / (_component(result["result_id"]) + ".json"))) + if index["result_id"] != result["result_id"] or index["result_sha256"] != result["document_sha256"]: + raise IntegrationError("Asset import record refers to a different result") + results[result["result_id"]] = {"result": result, "request": request, "plan": plan, "approval": approval, "index": index} + if approval["approved_keyframe_result_id"]: + reviewed = load_document(project, "result", approval["approved_keyframe_result_id"]) + reviewed_approval = load_document(project, "approval", reviewed["approval_id"]) + if (reviewed["result_kind"] != "keyframes" or reviewed["terminal_status"] != "succeeded" + or reviewed["request_id"] != request["request_id"] or reviewed["plan_id"] != plan["plan_id"] + or reviewed_approval["execution_mode"] != "keyframes" + or reviewed_approval["request_id"] != request["request_id"] + or reviewed_approval["plan_id"] != plan["plan_id"] + or reviewed_approval["plan_sha256"] != plan["document_sha256"]): + raise IntegrationError("Reviewed keyframes do not match the approved plan") + results[result["result_id"]]["reviewed"] = reviewed + return results + + +def stale_dependencies(selection: dict[str, Any], results: list[dict[str, Any]]) -> list[dict[str, Any]]: + takes = {take["take_id"]: take for result in results for scene in result["scenes"] for take in scene["takes"]} + selected = {scene["take_id"] for scene in selection["scenes"]} + decisions = {(item["scene_id"], item["dependency_take_id"]): item for item in selection["continuity_decisions"]} + if len(decisions) != len(selection["continuity_decisions"]): + raise IntegrationError("Duplicate continuity decision") + stale = [] + for scene in selection["scenes"]: + if scene["take_id"] not in takes: + raise IntegrationError("Selected take is missing") + for dependency in takes[scene["take_id"]]["depends_on_take_ids"]: + if dependency not in selected: + decision = decisions.get((scene["scene_id"], dependency)) + stale.append({"scene_id": scene["scene_id"], "take_id": scene["take_id"], + "dependency_take_id": dependency, "decision": decision}) + return stale + + +def compile_selection(project: Path, selection: dict[str, Any], *, prepare_audio: bool = True) -> dict[str, Any]: + """Verify the complete selection before producing any FFmpeg derivatives.""" + validate_document("selection", selection) + inputs = _selection_inputs(project, selection) + board = read_json(project_path(project, Path("storyboards") / (_component(selection["storyboard_revision_id"]) + ".json"))) + if board.get("approved") is not True or board["project_id"] != selection["project_id"]: + raise IntegrationError("Selection requires this project's approved storyboard") + storyboard_scenes = _unique(board["scenes"], "scene_id") + takes: dict[str, tuple[dict[str, Any], dict[str, Any], dict[str, Any]]] = {} + for entry in inputs.values(): + for result_scene in entry["result"]["scenes"]: + for take in result_scene["takes"]: + if take["take_id"] in takes: + raise IntegrationError("Ambiguous take ID across results") + takes[take["take_id"]] = entry, result_scene, take + selected_clips: list[dict[str, Any]] = [] + for scene in sorted(selection["scenes"], key=lambda value: value["order"]): + board_scene = storyboard_scenes.get(scene["scene_id"]) + if not board_scene or scene["order"] != board_scene["order"]: + raise IntegrationError("Selected scene order must match its approved storyboard") + if scene["transition_out"]["type"] not in {"cut", "none"}: + raise IntegrationError("Transition is unsupported by EDL version 1") + if scene["take_id"] not in takes: + raise IntegrationError("Selected take is missing from referenced results") + entry, result_scene, take = takes[scene["take_id"]] + if result_scene["scene_id"] != scene["scene_id"]: + raise IntegrationError("Selected take belongs to a different scene") + edits = _unique(scene["clip_edits"], "clip_id") + _unique(scene["clip_edits"], "order") + if set(edits) != set(take["clip_ids"]): + raise IntegrationError("Selection must edit every clip in the selected take exactly once") + clips = {clip["clip_id"]: clip for clip in result_scene["clips"]} + imports = _unique([asset for asset in entry["index"]["assets"] if "clip_id" in asset], "clip_id") + asset_imports = {asset["asset_id"]: asset for asset in entry["index"]["assets"]} + reference_assets = {asset["asset_id"]: asset for asset in entry["result"]["reference_assets"]} + for source_scene in entry["result"]["scenes"]: + reference_assets.update({frame["asset"]["asset_id"]: frame["asset"] for frame in source_scene["keyframes"]}) + reference_assets.update({clip["asset"]["asset_id"]: clip["asset"] for clip in source_scene["clips"]}) + attempts = {attempt["attempt_id"]: attempt for attempt in result_scene["attempts"]} + provider_aliases = {"fal": "fal.ai"} + approved_shots = [(plan_scene["scene_id"], plan_scene["order"], variant, shot) + for plan_scene in entry["plan"]["scenes"] for variant in plan_scene["variants"] + if variant["variant_id"] in entry["approval"]["approved_variant_ids"] + for shot in variant["shots"]] + approved_positions = {(scene_id, shot["shot_id"]): (scene_order, shot["order"]) + for scene_id, scene_order, _, shot in approved_shots} + reviewed = entry.get("reviewed") + frame_source = reviewed or entry["result"] + frames = [(source_scene["scene_id"], frame) for source_scene in frame_source["scenes"] + for frame in source_scene["keyframes"]] + lineage_attempts = {(source_scene["scene_id"], attempt["attempt_id"]): attempt for source_scene in frame_source["scenes"] + for attempt in source_scene["attempts"]} + lineage_frames = {frame["asset"]["asset_id"]: (source_scene_id, frame) for source_scene_id, frame in frames} + planned_assets = {asset["asset_id"]: asset for source_scene in entry["request"]["scenes"] + for asset in source_scene["reference_assets"]} + lineage_assets = {**planned_assets, **{asset["asset_id"]: asset for asset in frame_source["reference_assets"]}, + **{frame["asset"]["asset_id"]: frame["asset"] for _, frame in frames}} + predecessor_ids = {identifier for identifier in take["depends_on_take_ids"] + if identifier in takes and takes[identifier][1]["order"] < result_scene["order"]} + predecessor_scenes = {takes[identifier][1]["scene_id"] for identifier in predecessor_ids} + first_frame_hashes = {(asset.get("source_take_id"), asset["sha256"]) + for asset in entry["result"]["reference_assets"] if asset["role"] == "first_frame"} + continuity_refs = {asset["asset_id"] for asset in entry["result"]["reference_assets"] + if asset.get("source_take_id") in predecessor_ids and + (asset["role"] == "first_frame" or + (asset["role"] == "provider_reference" and + (asset["source_take_id"], asset["sha256"]) in first_frame_hashes))} + for edit in sorted(edits.values(), key=lambda value: value["order"]): + clip = clips[edit["clip_id"]] + attempt = attempts[clip["attempt_id"]] + approved_refs = [set(shot["reference_asset_ids"]) for scene_id, _, variant, shot in approved_shots + if scene_id == scene["scene_id"] and shot["shot_id"] == attempt["shot_id"] + and provider_aliases.get(variant["provider"], variant["provider"]) == + provider_aliases.get(attempt["provider"], attempt["provider"]) + and variant["model"] == attempt["model"] and shot["prompt_snapshot"] == attempt["prompt_snapshot"]] + if not approved_refs: + raise IntegrationError("Selected clip does not match an approved shot variant") + shot_position = approved_positions[(scene["scene_id"], attempt["shot_id"])] + approved_keyframes = {frame["asset"]["asset_id"] for source_scene_id, frame in frames + if frame["asset"]["role"] == "keyframe" + and (source_scene_id == scene["scene_id"] or source_scene_id in predecessor_scenes) + and (frame_position := approved_positions.get((source_scene_id, frame["shot_id"]))) is not None + and frame_position <= shot_position} + for identifier in approved_keyframes: + if identifier in reference_assets and reference_assets[identifier]["sha256"] != lineage_assets[identifier]["sha256"]: + raise IntegrationError("Selected clip substituted a reviewed keyframe") + prepared = attempt["generation_parameters"].get("prepared_reference_sources", "{}") + try: + prepared_sources = json.loads(prepared) + except (TypeError, ValueError): + raise IntegrationError("Invalid prepared reference provenance") from None + if (not isinstance(prepared_sources, dict) or + any(not isinstance(key, str) or not isinstance(value, str) for key, value in prepared_sources.items()) or + set(prepared_sources) - set(attempt["reference_asset_ids"])): + raise IntegrationError("Invalid prepared reference provenance") + authorized = False + for refs in approved_refs: + allowed = refs | approved_keyframes | continuity_refs + allowed |= {identifier for identifier, source in prepared_sources.items() + if source in allowed and source in reference_assets + and reference_assets.get(identifier, {}).get("role") == "provider_reference"} + consumed = set(attempt["reference_asset_ids"]) + consumed.update(prepared_sources.get(identifier, identifier) for identifier in list(consumed)) + pending = list(consumed) + while pending: + identifier = pending.pop() + source_asset = lineage_assets.get(identifier) + if source_asset: + consumed.update(key for key, asset in planned_assets.items() + if asset["sha256"] == source_asset["sha256"]) + origin = lineage_frames.get(identifier) + image_attempt = lineage_attempts.get((origin[0], origin[1].get("attempt_id"))) if origin else None + if image_attempt: + image_refs = set(image_attempt["reference_asset_ids"]) + try: + image_prepared = json.loads(image_attempt["generation_parameters"].get("prepared_reference_sources", "{}")) + if (not isinstance(image_prepared, dict) + or any(not isinstance(key, str) or not isinstance(value, str) for key, value in image_prepared.items()) + or set(image_prepared) - image_refs): + raise IntegrationError("Invalid keyframe reference provenance") + image_refs.update(image_prepared.get(key, key) for key in list(image_refs)) + except (TypeError, ValueError, AttributeError): + raise IntegrationError("Invalid keyframe reference provenance") from None + pending.extend(image_refs - consumed) + consumed.update(image_refs) + required = set(refs) + if reviewed: + required.update(frame["asset"]["asset_id"] for source_scene_id, frame in frames + if source_scene_id == scene["scene_id"] and frame["shot_id"] == attempt["shot_id"]) + if consumed & planned_assets.keys(): + for identifier in consumed & planned_assets.keys(): + recorded = reference_assets.get(identifier, lineage_assets.get(identifier)) + if not recorded or recorded["sha256"] != planned_assets[identifier]["sha256"]: + raise IntegrationError("Selected clip substituted a planned reference") + imported_reference = asset_imports.get(identifier) + if not imported_reference or file_hash(project_path(project, imported_reference["local_path"])) != recorded["sha256"]: + raise IntegrationError("Required reference import is missing or modified") + if set(attempt["reference_asset_ids"]) <= allowed and required <= consumed: + authorized = True + break + if not authorized: + raise IntegrationError("Selected clip used unapproved reference assets or omitted required references") + imported = imports.get(clip["clip_id"]) + if not imported or imported["sha256"] != clip["asset"]["sha256"] or imported["source_uri"] != clip["asset"]["uri"]: + raise IntegrationError("Missing or mismatched clip import") + local = project_path(project, imported["local_path"]) + if file_hash(local) != clip["asset"]["sha256"]: + raise IntegrationError("Imported clip SHA-256 mismatch") + measured = probe_media(local) + _compare_media(clip["media"], measured) + start, end = edit["trim_in_s"], edit["trim_out_s"] + if not 0 <= start < end <= measured["measured_duration_s"]: + raise IntegrationError("Editorial trims exceed measured clip duration") + nominal = clip["media"].get("measured_duration_s") + if nominal is not None and end > nominal: + raise IntegrationError("Editorial trim exceeds declared measured duration") + provenance = {"scene_id": scene["scene_id"], "take_id": take["take_id"], "clip_id": clip["clip_id"], + "attempt_id": clip["attempt_id"], "asset_id": clip["asset"]["asset_id"], + "asset_sha256": clip["asset"]["sha256"], "source_uri": clip["asset"]["uri"], + "attempt": attempts[clip["attempt_id"]], "audio_use": edit["audio_use"]} + provenance["reference_assets"] = [] + for identifier in provenance["attempt"]["reference_asset_ids"]: + reference_asset = reference_assets.get(identifier) + reference_import = asset_imports.get(identifier) + if not reference_asset or not reference_import: + raise IntegrationError("Provider attempt references a missing imported asset") + if file_hash(project_path(project, reference_import["local_path"])) != reference_asset["sha256"]: + raise IntegrationError("Provider reference asset hash mismatch") + provenance["reference_assets"].append({**reference_asset, "local_path": reference_import["local_path"]}) + for kind in ("request", "plan", "approval", "result"): + provenance[kind + "_id"] = entry[kind][DOCUMENTS[kind][0]] + provenance[kind + "_sha256"] = entry[kind]["document_sha256"] + selected_clips.append({"path": local, "edit": edit, "media": measured, "provenance": provenance}) + stale = stale_dependencies(selection, [entry["result"] for entry in inputs.values()]) + for item in stale: + decision = item["decision"] + if decision is None or decision["decision"] == "regenerate": + raise IntegrationError("Stale continuity dependency needs an explicit accept or boundary decision") + if decision["decision"] == "use_boundary": + asset = decision["replacement_asset"] + if asset is None: + raise IntegrationError("Boundary decision requires an imported replacement asset") + if not asset["mime_type"].startswith("image/"): + raise IntegrationError("A replacement boundary must be an image") + if asset.get("source_take_id") and asset["source_take_id"] not in {scene["take_id"] for scene in selection["scenes"]}: + raise IntegrationError("Replacement boundary refers to an unselected take") + entry, dependent_scene, dependent_take = takes[item["take_id"]] + first_clip_id = min(dependent_take["clip_order"], key=dependent_take["clip_order"].get) + first_clip = next(clip for clip in dependent_scene["clips"] if clip["clip_id"] == first_clip_id) + first_attempt = next(attempt for attempt in dependent_scene["attempts"] if attempt["attempt_id"] == first_clip["attempt_id"]) + consumed = {frame["asset"]["sha256"] for frame in dependent_scene["keyframes"] + if frame["position"] == "first" and frame["asset"]["asset_id"] in first_attempt["reference_asset_ids"]} + consumed.update(reference["sha256"] for reference in entry["result"]["reference_assets"] + if reference["role"] == "first_frame" and reference["asset_id"] in first_attempt["reference_asset_ids"]) + if asset["sha256"] not in consumed: + raise IntegrationError("Compatible boundary must match the dependent take's consumed first frame; otherwise regenerate it") + boundary = project_path(project, Path("rough-cuts/manifests/boundaries") / (_component(asset["asset_id"]) + ".json")) + record = read_json(boundary) + if record["source_uri"] != asset["uri"] or file_hash(project_path(project, record["local_path"])) != asset["sha256"]: + raise IntegrationError("Replacement boundary hash mismatch") + # The existing concat renderer requires equal geometry, fps and audio topology. + formats = {(clip["media"]["width"] / clip["media"]["height"], round(clip["media"]["fps"], 3)) for clip in selected_clips} + if len(formats) != 1: + raise IntegrationError("Selected clips require matching aspect ratios and frame rates for EDL concat") + needs_audio = any(clip["media"]["has_audio"] and clip["edit"]["audio_use"] == "preserve" for clip in selected_clips) + sources: dict[str, str] = {} + ranges = [] + provenance_sources = {} + total_duration = 0.0 + for position, clip in enumerate(selected_clips): + name = "generated_" + str(position) + local = clip["path"] + media, edit, provenance = clip["media"], clip["edit"], clip["provenance"] + if edit["audio_use"] == "mute" or (needs_audio and not media["has_audio"]): + local = _audio_source(project, local, provenance["asset_sha256"], media, needs_audio, prepare_audio) + provenance["derived_asset_sha256"] = file_hash(local) if local.exists() else None + sources[name] = str(local) + start, end = edit["trim_in_s"], edit["trim_out_s"] + ranges.append({"source": name, "start": start, "end": end, "beat": provenance["scene_id"]}) + padded_start, padded_end = apply_padding(start, end, source_duration=media["measured_duration_s"]) + total_duration += padded_end - padded_start + provenance_sources[name] = {**provenance, "local_path": str(local.relative_to(project.resolve())), + "trim_in_s": start, "trim_out_s": end, + "padded_in_s": padded_start, "padded_out_s": padded_end} + edl: dict[str, Any] = {"version": EDL_VERSION, "sources": sources, "ranges": ranges, "total_duration_s": total_duration, + "generated_media": {"edit_revision_id": selection["edit_revision_id"], + "storyboard_sha256": sha256(canonical_bytes(board)), + "sources": provenance_sources, "stale_dependencies": stale}} + if selection.get("edl"): + stored = read_json(project_path(project, selection["edl"]["path"])) + if sha256(canonical_bytes(stored)) != selection["edl"]["sha256"]: + raise IntegrationError("Stored EDL hash mismatch") + for key in ("grade", "overlays", "subtitles", "reframe", "transcripts"): + if key in stored: + edl[key] = stored[key] + edl["generated_media"]["editorial_assets"] = _editorial_assets(project, edl) + validate_edl(edl) + return edl + + +def _editorial_assets(project: Path, edl: dict[str, Any]) -> list[dict[str, str]]: + paths = [overlay["source"] for overlay in edl.get("overlays", []) if isinstance(overlay.get("source"), str)] + paths.extend(edl.get("transcripts", {}).values()) + subtitles = edl.get("subtitles") + if isinstance(subtitles, str): + paths.append(subtitles) + elif isinstance(subtitles, dict) and subtitles.get("path"): + paths.append(subtitles["path"]) + return [{"path": str(project_path(project, path)), "sha256": file_hash(project_path(project, path))} for path in sorted(set(paths))] + + +def _audio_source(project: Path, source: Path, digest: str, media: dict[str, Any], needs_audio: bool, prepare: bool) -> Path: + suffix = "silent" if needs_audio else "mute" + destination = project_path(project, Path("rough-cuts/generated-clips/derived") / (digest.removeprefix("sha256:") + "-" + suffix + ".mp4")) + record_path = destination.with_suffix(".json") + if destination.exists(): + if not record_path.exists(): + raise IntegrationError("Audio derivative has no provenance record") + record = read_json(record_path) + if record["source_sha256"] != digest or record["output_sha256"] != file_hash(destination): + raise IntegrationError("Audio derivative hash mismatch") + return destination + if not prepare: + return destination + destination.parent.mkdir(parents=True, exist_ok=True) + with tempfile.TemporaryDirectory(dir=destination.parent) as temp: + output = Path(temp) / "derived.mp4" + command = ["ffmpeg", "-v", "error", "-nostdin", "-i", str(source)] + if needs_audio: + command += ["-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo", "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-t", str(media["measured_duration_s"])] + else: + command += ["-map", "0:v:0", "-c:v", "copy", "-an"] + subprocess.run([*command, "-movflags", "+faststart", str(output)], check=True, capture_output=True) + try: + os.link(output, destination) + except FileExistsError: + if file_hash(destination) != file_hash(output): + raise IntegrationError("Conflicting audio derivative") from None + immutable_write(record_path, canonical_bytes({"source_sha256": digest, "output_sha256": file_hash(destination), "audio": suffix})) + return destination + + +def write_selection(project: Path, draft: dict[str, Any], *, edl_options: dict[str, Any] | None = None) -> dict[str, Any]: + """Commit an editorial revision and the exact EDL together after validation.""" + selection = seal({"contract_version": CONTRACT_VERSION, "selection_version": 1, + "created_at": now(), "continuity_decisions": [], "edl": None, **draft}) + edl = compile_selection(project, selection) + if edl_options: + if set(edl_options) - {"grade", "overlays", "subtitles", "reframe", "transcripts"}: + raise IntegrationError("EDL options support grade, overlays, subtitles, reframe and transcripts") + options = copy.deepcopy(edl_options) + if "transcripts" in options: + options["transcripts"] = {key: str(project_path(project, path)) for key, path in options["transcripts"].items()} + for overlay in options.get("overlays", []): + if isinstance(overlay.get("source"), str): + overlay["source"] = str(project_path(project, overlay["source"])) + subtitles = options.get("subtitles") + if isinstance(subtitles, str): + options["subtitles"] = str(project_path(project, subtitles)) + elif isinstance(subtitles, dict) and subtitles.get("path"): + subtitles["path"] = str(project_path(project, subtitles["path"])) + edl.update(options) + validate_edl(edl) + edl["generated_media"]["editorial_assets"] = _editorial_assets(project, edl) + relative = Path("edit") / ("edl-" + _component(selection["edit_revision_id"]) + ".json") + selection["edl"] = {"path": str(relative), "sha256": sha256(canonical_bytes(edl))} + selection = seal(selection) + validate_document("selection", selection) + # Check identity conflicts before creating either revision file. + selection_path = document_path(project, "selection", selection["edit_revision_id"]) + if selection_path.exists() and selection_path.read_bytes() != canonical_bytes(selection): + raise IntegrationError("Selection revision already exists; use a new edit_revision_id") + immutable_write(project_path(project, relative), canonical_bytes(edl)) + store_document(project, "selection", selection) + return selection + + +def render_selection(project: Path, selection: dict[str, Any], *, preview: bool = False, no_loudnorm: bool = False) -> dict[str, Any]: + edl = compile_selection(project, selection) + reference = selection["edl"] + if reference is None or sha256(canonical_bytes(edl)) != reference["sha256"]: + raise IntegrationError("Compiled EDL no longer matches the immutable selection") + edl_path = project_path(project, reference["path"]) + if file_hash(edl_path) != reference["sha256"]: + raise IntegrationError("EDL file hash mismatch") + revision = _component(selection["edit_revision_id"]) + output = project_path(project, Path("edit") / (revision + ("-preview" if preview else "-final") + ".mp4")) + record_path = project_path(project, Path("edit") / ("render-" + output.stem + ".json")) + if record_path.exists(): + record = read_json(record_path) + if (record["selection_sha256"] != selection["document_sha256"] or file_hash(output) != record["output_sha256"] + or record["no_loudnorm"] != no_loudnorm or document_hash(record) != record["document_sha256"] + or file_hash(project_path(project, record["verification_path"])) != record["verification_sha256"]): + raise IntegrationError("Existing render record or output changed") + return record + if output.exists(): + raise IntegrationError("Unrecorded output already exists; choose a new revision") + # Renderer scratch files are isolated per render; its implementation stays unchanged. + with tempfile.TemporaryDirectory(dir=project_path(project, "edit")) as scratch: + render_edl_path = Path(scratch) / edl_path.name + render_edl_path.write_bytes(canonical_bytes(edl)) + temp_output = Path(scratch) / output.name + if render_edl(render_edl_path, temp_output, preview=preview, no_loudnorm=no_loudnorm) != 0: + raise IntegrationError("Existing EDL renderer failed") + report = run_verification(temp_output, edl, output_dir=project_path(project, Path("edit/verify") / output.stem), max_passes=1) + report.video, report.edl = str(output), str(edl_path) + verification = report.to_dict() + verification_path = project_path(project, Path("edit") / ("verification-" + output.stem + ".json")) + immutable_write(verification_path, canonical_bytes(verification)) + os.link(temp_output, output) + record = seal({"edit_revision_id": selection["edit_revision_id"], "created_at": now(), + "selection_sha256": selection["document_sha256"], "edl": reference, + "output_path": str(output.relative_to(project.resolve())), "output_sha256": file_hash(output), + "verification_path": str(verification_path.relative_to(project.resolve())), + "verification_sha256": file_hash(verification_path), "passed": report.passed, + "preview": preview, "no_loudnorm": no_loudnorm, "provenance": edl["generated_media"], + "ffmpeg_version": subprocess.run(["ffmpeg", "-version"], check=True, capture_output=True, text=True).stdout.splitlines()[0]}) + immutable_write(record_path, canonical_bytes(record)) + return record + + +def cost_rollup(project: Path, selection: dict[str, Any] | None = None) -> dict[str, Any]: + selected: set[tuple[str, str]] = set() + if selection is not None: + validate_document("selection", selection) + inputs = _selection_inputs(project, selection) + for scene in selection["scenes"]: + matches = [(result_id, take["take_id"]) for result_id, entry in inputs.items() + for result_scene in entry["result"]["scenes"] if result_scene["scene_id"] == scene["scene_id"] + for take in result_scene["takes"] if take["take_id"] == scene["take_id"]] + if len(matches) != 1: + raise IntegrationError("Selected take is missing or ambiguous in referenced results") + selected.add(matches[0]) + observations: dict[tuple[str, str, str], dict[str, Any]] = {} + for path in sorted(project_path(project, "rough-cuts/manifests/results").glob("*.json")): + result = read_json(path) + validate_document("result", result) + for scene in result["scenes"]: + selected_clips = {clip_id for take in scene["takes"] if (result["result_id"], take["take_id"]) in selected for clip_id in take["clip_ids"]} + selected_attempts = {clip["attempt_id"] for clip in scene["clips"] if clip["clip_id"] in selected_clips} + for attempt in scene["attempts"]: + row = {"attempt_id": attempt["attempt_id"], "result_id": result["result_id"], + "scene_id": scene["scene_id"], "provider": attempt["provider"], "model": attempt["model"], + "selected_output": attempt["attempt_id"] in selected_attempts, **attempt["billing"]} + key = (result["result_id"], scene["scene_id"], attempt["attempt_id"]) + if key in observations and observations[key] != row: + raise IntegrationError("Conflicting billing observations for one attempt") + observations[key] = row + + def totals(rows: list[dict[str, Any]]) -> dict[str, Any]: + sums = {} + for key in ("estimated_usd", "actual_usd"): + known = sum((Decimal(str(row[key])) for row in rows if row[key] is not None), Decimal(0)) + unknown = sum(row[key] is None for row in rows) + sums[key] = {"total": None if unknown else float(known), "known_subtotal": float(known), "unknown_attempts": unknown, "currency": "USD"} + return sums + + rows = list(observations.values()) + return {"attempts": rows, "all_attempts": totals(rows), + "selected_outputs": totals([row for row in rows if row["selected_output"]]), + "unselected_attempts": totals([row for row in rows if not row["selected_output"]])} + + +def regenerate( + project: Path, storyboard: dict[str, Any], selection: dict[str, Any], scene_ids: list[str], + *, reason: str, request_id: str | None = None, revision: int = 1, +) -> dict[str, Any]: + validate_document("selection", selection) + if storyboard.get("project_id") != selection["project_id"]: + raise IntegrationError("Regeneration storyboard belongs to a different project") + inputs = _selection_inputs(project, selection) + selected = {scene["scene_id"]: scene["take_id"] for scene in selection["scenes"]} + if not scene_ids or set(scene_ids) - selected.keys(): + raise IntegrationError("Regeneration targets must be selected scenes") + replaced = [selected[scene_id] for scene_id in scene_ids] + base_results = [entry["result"]["result_id"] for entry in inputs.values() + if any(take["take_id"] in replaced for scene in entry["result"]["scenes"] for take in scene["takes"])] + prior_requests = {inputs[result_id]["request"]["request_id"] for result_id in base_results} + return build_request(project, storyboard, scene_ids=scene_ids, request_id=request_id, revision=revision, + supersedes_request_id=next(iter(prior_requests)) if len(prior_requests) == 1 else None, + regeneration={"base_result_ids": base_results, "supersedes_take_ids": replaced, "reason": reason}) + + +def send_document( + project: Path, kind: str, document: dict[str, Any], *, server: str | None = None, + handoff: Path | None = None, token: str | None = None, +) -> dict[str, Any]: + if kind not in {"request", "approval"}: + raise IntegrationError("Send accepts request or approval documents") + store_document(project, kind, document) + if (server is None) == (handoff is None): + raise IntegrationError("Choose exactly one HTTP server or file handoff directory") + if handoff is not None: + relative = Path(DOCUMENTS[kind][1]) / (_component(document[DOCUMENTS[kind][0]]) + ".json") + destination = project_path(handoff, relative) + immutable_write(destination, canonical_bytes(document)) + return {"handoff_path": str(destination), "document_sha256": document["document_sha256"]} + response = http_document(server or "", "/v2/plans" if kind == "request" else "/v2/jobs", document=document, token=token) + if kind == "request": + if response.get("request_id") != document["request_id"]: + raise IntegrationError("Server returned a plan for a different request") + store_document(project, "plan", response) + else: + reject_secrets(response) + if response.get("approval_id") != document["approval_id"]: + raise IntegrationError("Server returned a job for a different approval") + return response + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--project", type=Path, default=Path.cwd()) + sub = parser.add_subparsers(dest="command", required=True) + request = sub.add_parser("request", help="Write an immutable request from an approved storyboard") + request.add_argument("storyboard", type=Path) + request.add_argument("--scene", action="append") + request.add_argument("--id") + request.add_argument("--revision", type=int, default=1) + request.add_argument("--supersedes") + approve = sub.add_parser("approve", help="Record approval of an exact reviewed plan") + approve.add_argument("plan", type=Path) + approve.add_argument("--variant", action="append", required=True) + approve.add_argument("--mode", choices=("video", "keyframes"), default="video") + approve.add_argument("--id") + approve.add_argument("--key") + approve.add_argument("--keyframes") + approve.add_argument("--allow-unknown-cost", action="store_true") + approve.add_argument("--budget-usd", type=float) + send = sub.add_parser("send", help="Submit exact request/approval bytes over HTTP or files") + send.add_argument("kind", choices=("request", "approval")) + send.add_argument("document", type=Path) + transport = send.add_mutually_exclusive_group(required=True) + transport.add_argument("--server") + transport.add_argument("--handoff", type=Path) + send.add_argument("--token-env") + get = sub.add_parser("get", help="Read capabilities, plan, job, or terminal result over HTTP") + get.add_argument("kind", choices=("capabilities", "plan", "job", "result", "cancel")) + get.add_argument("--id") + get.add_argument("--server", required=True) + get.add_argument("--token-env") + get.add_argument("--output", type=Path) + validate = sub.add_parser("validate", help="Validate the pinned contract and canonical hash") + validate.add_argument("kind", choices=DOCUMENTS) + validate.add_argument("document", type=Path) + ingest = sub.add_parser("import", help="Verify and import a document and its media assets") + ingest.add_argument("kind", choices=(*DOCUMENTS, "boundary")) + ingest.add_argument("document", type=Path) + ingest.add_argument("--asset-root", type=Path) + ingest.add_argument("--deliveries", type=Path, help="Transient mapping of durable URI to local path or signed delivery URL") + ingest.add_argument("--allow-origin", action="append") + select = sub.add_parser("select", help="Validate a selection draft, compile EDL, and freeze both") + select.add_argument("draft", type=Path) + select.add_argument("--edl-options", type=Path, help="Existing EDL grade, overlays and subtitle settings") + render = sub.add_parser("render", help="Revalidate, render through existing EDL pipeline, and verify") + render.add_argument("selection", type=Path) + render.add_argument("--preview", action="store_true") + render.add_argument("--no-loudnorm", action="store_true", help="Use the existing renderer's normalization bypass for silent media") + inspect = sub.add_parser("inspect", help="Show stale dependencies in a selection draft") + inspect.add_argument("selection", type=Path) + cost = sub.add_parser("cost", help="Roll up all attempts, selected outputs, and raw units") + cost.add_argument("--selection", type=Path) + regen = sub.add_parser("regenerate", help="Request replacements for only the named selected scenes") + regen.add_argument("storyboard", type=Path) + regen.add_argument("selection", type=Path) + regen.add_argument("--scene", action="append", required=True) + regen.add_argument("--reason", required=True) + regen.add_argument("--id") + regen.add_argument("--revision", type=int, required=True) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + project = args.project.resolve() + try: + result: dict[str, Any] + if args.command == "request": + result = build_request(project, read_json(args.storyboard), scene_ids=args.scene, request_id=args.id, revision=args.revision, supersedes_request_id=args.supersedes) + elif args.command == "approve": + result = approve_plan(project, read_json(args.plan), args.variant, execution_mode=args.mode, approval_id=args.id, + idempotency_key=args.key, keyframe_result_id=args.keyframes, + allow_unknown_cost=args.allow_unknown_cost, max_estimated_cost_usd=args.budget_usd) + elif args.command == "send": + result = send_document(project, args.kind, read_json(args.document), server=args.server, handoff=args.handoff, + token=os.environ.get(args.token_env) if args.token_env else None) + elif args.command == "get": + if args.kind != "capabilities" and not args.id: + raise IntegrationError("This operation requires --id") + identifier = quote(args.id or "", safe="") + path = {"capabilities": "/v2/capabilities", "plan": "/v2/plans/" + identifier, + "job": "/v2/jobs/" + identifier, "result": "/v2/jobs/" + identifier + "/result", + "cancel": "/v2/jobs/" + identifier + "/cancel"}[args.kind] + result = http_document(args.server, path, token=os.environ.get(args.token_env) if args.token_env else None, + method="POST" if args.kind == "cancel" else "GET") + if args.kind in {"plan", "result"}: + validate_document(args.kind, result) + id_field = "plan_id" if args.kind == "plan" else "job_id" + if result[id_field] != args.id: + raise IntegrationError("Server returned a different artifact identity") + reject_secrets(result) + if args.output: + immutable_write(project_path(project, args.output), canonical_bytes(result)) + if args.kind == "plan": + store_document(project, "plan", result) + elif args.command == "validate": + validate_document(args.kind, read_json(args.document)) + result = {"valid": True, "contract_version": CONTRACT_VERSION} + elif args.command == "import": + document = read_json(args.document) + deliveries = read_json(args.deliveries) if args.deliveries else None + if args.kind == "result": + result = import_result(project, document, asset_root=args.asset_root, deliveries=deliveries, allowed_origins=args.allow_origin) + elif args.kind == "boundary": + relative = Path("assets/reference/boundaries") / _component(document["asset_id"]) + result = import_asset(project, document, relative, asset_root=args.asset_root, deliveries=deliveries, allowed_origins=args.allow_origin) + immutable_write(project_path(project, Path("rough-cuts/manifests/boundaries") / (_component(document["asset_id"]) + ".json")), canonical_bytes(result)) + else: + result = {"path": str(store_document(project, args.kind, document))} + elif args.command == "select": + result = write_selection(project, read_json(args.draft), edl_options=read_json(args.edl_options) if args.edl_options else None) + elif args.command == "render": + result = render_selection(project, read_json(args.selection), preview=args.preview, no_loudnorm=args.no_loudnorm) + elif args.command == "inspect": + selection = read_json(args.selection) + results = [load_document(project, "result", ref["result_id"]) for ref in selection["source_results"]] + result = {"stale_dependencies": stale_dependencies(selection, results)} + elif args.command == "regenerate": + result = regenerate(project, read_json(args.storyboard), read_json(args.selection), args.scene, reason=args.reason, request_id=args.id, revision=args.revision) + else: + result = cost_rollup(project, read_json(args.selection) if args.selection else None) + print(canonical_bytes(result).decode()) + return 1 if args.command == "render" and not result["passed"] else 0 + except (IntegrationError, OSError, json.JSONDecodeError, KeyError, TypeError, subprocess.CalledProcessError) as exc: + # Untrusted provider output or transport details may contain secrets. + message = str(exc) if isinstance(exc, IntegrationError) else type(exc).__name__ + print("media-generated: " + message, file=sys.stderr) + return 2 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/src/media_tooling/templates/project_AGENTS.md b/src/media_tooling/templates/project_AGENTS.md index 1322c24..4f41c8d 100644 --- a/src/media_tooling/templates/project_AGENTS.md +++ b/src/media_tooling/templates/project_AGENTS.md @@ -20,6 +20,7 @@ Use installed toolkit commands from this project directory: - color grading: `media-grade` - loudness normalization: `media-loudnorm` - output verification: `media-verify` +- generated-media requests, review and import: `media-generated` - optional HTML-rendered video and motion overlays: `hyperframes` Operational defaults: @@ -28,6 +29,16 @@ Operational defaults: - keep `ELEVENLABS_API_KEY` and `ELEVENLABS_VOICE_ID_EN` in the environment, never in project files - re-run `media-tooling-init` after reinstalling or relocating the toolkit so these skill paths stay current +TTV generated-media workflow: +- keep approved editorial storyboards and stable scene IDs in `storyboards/` +- export reviewed motion-graphics scenes using the handoff in `docs/generated-media.md`; archive visual review evidence and existing provider spending permission with the storyboard revision +- use `media-generated request`, review the returned plan, and record exact approved variants with `approve` before submitting paid work +- exchange immutable documents through `send --server` or `send --handoff`; import results with an explicit asset root or allowed delivery origins +- use `select` to freeze takes, trims and EDL, then `render` to run the existing renderer and verifier with provenance records +- use `select --edl-options` for portrait `reframe`, transcripts, overlays, subtitles and grading; use imported generated clips as HyperFrames content layers +- use new revisions for edits, regenerate only affected scenes, and explicitly resolve stale continuity decisions +- keep transient signed delivery URLs separate from durable manifests and credentials out of documents + Optional Hyperframes workflow: - use `hyperframes` for HTML-rendered video, animated overlays, title cards, kinetic captions, website/UI captures, GIFs, PNG sequences, batch variants, or standalone graphic segments - keep composition source and renders under `$PROJECT_DIR/edit/hyperframes//` diff --git a/tests/test_generated_media.py b/tests/test_generated_media.py new file mode 100644 index 0000000..26a7071 --- /dev/null +++ b/tests/test_generated_media.py @@ -0,0 +1,563 @@ +from __future__ import annotations + +import copy +import json +import shutil +import subprocess +import tempfile +import threading +import unittest +from http.server import BaseHTTPRequestHandler, HTTPServer +from pathlib import Path +from typing import Any +from unittest.mock import patch + +from PIL import Image + +from media_tooling import generated_media as gm + + +def fixture(kind: str) -> dict[str, Any]: + return gm.read_json(gm.CONTRACT_DIR / "fixtures" / (gm.DOCUMENTS[kind][2] + ".valid.json")) + + +class ContractTest(unittest.TestCase): + def test_shared_golden_documents_and_hashes(self) -> None: + for path in (gm.CONTRACT_DIR / "fixtures").glob("*.json"): + kind = next(kind for kind, value in gm.DOCUMENTS.items() if path.name.startswith(value[2] + ".")) + with self.subTest(path=path.name): + if ".invalid." in path.name: + with self.assertRaises(gm.IntegrationError): + gm.validate_document(kind, gm.read_json(path)) + else: + gm.validate_document(kind, gm.read_json(path)) + self.assertEqual(gm.canonical_bytes({"b": -0.0, "a": [1.0, "ñ"]}), '{"a":[1,"ñ"],"b":0}'.encode()) + for value in (float("nan"), float("inf")): + with self.assertRaises(gm.IntegrationError): + gm.canonical_bytes(value) + with self.assertRaises(gm.IntegrationError): + gm.decode_json(b'{"a":1,"a":2}') + + def test_strict_types_versions_hashes_and_secrets(self) -> None: + request = fixture("request") + for key, value in (("contract_version", "2.0"), ("revision", "4"), ("revision", True), ("revision", 4.5)): + invalid = gm.seal({**request, key: value}) + with self.subTest(key=key, value=value), self.assertRaises(gm.IntegrationError): + gm.validate_document("request", invalid) + request["revision"] = 5 + with self.assertRaises(gm.IntegrationError): + gm.validate_document("request", request) + for secret in ({"apiKey": "x"}, "a https://example.com/file?signature=x", "Bearer xyz", "https://x/#secret"): + with self.assertRaises(gm.IntegrationError): + gm.reject_secrets(secret) + + def test_selection_trim_order(self) -> None: + selection = fixture("selection") + edit = selection["scenes"][0]["clip_edits"][0] + for start, end in ((1, 1), (1, 0.5)): + edit["trim_in_s"], edit["trim_out_s"] = start, end + with self.assertRaisesRegex(gm.IntegrationError, "trim_out_s must exceed"): + gm.validate_document("selection", gm.seal(selection)) + + def test_plan_variant_ids_are_unique_across_scenes(self) -> None: + plan = fixture("plan") + duplicate = copy.deepcopy(plan["scenes"][0]) + duplicate.update(scene_id="another-scene", order=2) + plan["scenes"].append(duplicate) + with self.assertRaisesRegex(gm.IntegrationError, "Duplicate variant_id"): + gm.validate_document("plan", gm.seal(plan)) + + def test_file_and_http_use_identical_canonical_bytes(self) -> None: + document = fixture("request") + received = [] + + class Handler(BaseHTTPRequestHandler): + def do_POST(self) -> None: + received.append(self.rfile.read(int(self.headers["Content-Length"]))) + response = gm.canonical_bytes(fixture("plan")) + self.send_response(200) + self.end_headers() + self.wfile.write(response) + + def log_message(self, format: str, *args: Any) -> None: + pass + + with tempfile.TemporaryDirectory() as temp: + project, handoff = Path(temp) / "project", Path(temp) / "handoff" + file_response = gm.send_document(project, "request", document, handoff=handoff) + with HTTPServer(("127.0.0.1", 0), Handler) as server: + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + response = gm.send_document(project, "request", document, server=f"http://127.0.0.1:{server.server_port}") + finally: + server.shutdown() + thread.join() + self.assertEqual(received, [Path(file_response["handoff_path"]).read_bytes()]) + self.assertEqual(gm.canonical_bytes(response), gm.canonical_bytes(fixture("plan"))) + changed = gm.seal({**document, "revision": 100}) + with self.assertRaises(gm.IntegrationError): + gm.send_document(project, "request", changed, handoff=handoff) + + +@unittest.skipUnless(shutil.which("ffmpeg") and shutil.which("ffprobe"), "FFmpeg required") +class AssemblyTest(unittest.TestCase): + source_temp: tempfile.TemporaryDirectory[str] + asset_root: Path + source: Path + media: dict[str, Any] + @classmethod + def setUpClass(cls) -> None: + cls.source_temp = tempfile.TemporaryDirectory() + cls.asset_root = Path(cls.source_temp.name) + cls.source = cls.asset_root / "clip.mp4" + subprocess.run(["ffmpeg", "-v", "error", "-f", "lavfi", "-i", "color=c=gray:s=320x180:r=24:d=2", + "-f", "lavfi", "-i", "anullsrc=r=48000:cl=stereo:d=2", "-c:v", "libx264", "-pix_fmt", "yuv420p", + "-c:a", "aac", "-shortest", str(cls.source)], check=True, capture_output=True) + cls.media = gm.probe_media(cls.source) + + @classmethod + def tearDownClass(cls) -> None: + cls.source_temp.cleanup() + + def setUp(self) -> None: + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.project = Path(self.temp.name) + scene = fixture("request")["scenes"][0] + scene["reference_assets"] = [] + scene["continuity"] = {"mode": "independent", "required_reference_asset_ids": []} + self.board: dict[str, Any] = {"approved": True, "project_id": "pilot", "revision_id": "board-1", + "scenes": [{**copy.deepcopy(scene), "scene_id": f"scene-{i}", "order": i, "requested_duration_s": 2} for i in (3, 1, 2)]} + self.request = gm.build_request(self.project, self.board, request_id="request-1") + self.plan = fixture("plan") + self.plan.update({"plan_id": "plan-1", "request_id": "request-1", "valid_until": "2099-01-01T00:00:00Z"}) + self.plan["scenes"] = [{**copy.deepcopy(self.plan["scenes"][0]), "scene_id": f"scene-{i}", "order": i, + "variants": [{**copy.deepcopy(self.plan["scenes"][0]["variants"][0]), "variant_id": f"variant-{i}"}]} for i in (1, 2, 3)] + for i, plan_scene in enumerate(self.plan["scenes"], 1): + template = plan_scene["variants"][0]["shots"][0] + plan_scene["variants"][0]["shots"] = [{**copy.deepcopy(template), "shot_id": f"shot-{i}-{j}", "order": j, + "reference_asset_ids": []} for j in range(2 if i == 2 else 1)] + self.plan["scenes"][0]["variants"][0]["provider"] = "fal" + self.plan["scenes"][2]["variants"][0]["provider"] = "fallback" + self.plan = gm.seal(self.plan) + self.approval = gm.approve_plan(self.project, self.plan, [f"variant-{i}" for i in (1, 2, 3)], approval_id="approval-1", allow_unknown_cost=True) + self.result = fixture("result") + self.result.update({"result_id": "result-1", "request_id": "request-1", "plan_id": "plan-1", "approval_id": "approval-1", "reference_assets": [], "scenes": []}) + reference_path = self.asset_root / "reference.png" + Image.new("RGB", (320, 180), "gray").save(reference_path) + self.result["reference_assets"] = [{"asset_id": "consumed-boundary", "uri": reference_path.as_uri(), "sha256": gm.file_hash(reference_path), + "mime_type": "image/png", "role": "first_frame", "rights_note": "Synthetic", "source_take_id": "take-2"}] + for i in (1, 2, 3): + result_scene = copy.deepcopy(fixture("result")["scenes"][0]) + result_scene.update({"scene_id": f"scene-{i}", "order": i, "actual_shots": [], "attempts": [], "clips": [], "takes": []}) + for j in range(2 if i == 2 else 1): + shot_id, attempt_id, clip_id = f"shot-{i}-{j}", f"attempt-{i}-{j}", f"clip-{i}-{j}" + result_scene["actual_shots"].append({"shot_id": shot_id, "order": j, "nominal_duration_s": 2, "continuity_mode": "cut"}) + attempt = copy.deepcopy(fixture("result")["scenes"][0]["attempts"][0]) + attempt.update({"attempt_id": attempt_id, "shot_id": shot_id, "reference_asset_ids": []}) + if i == 1: + attempt["provider"] = "fal.ai" + attempt["billing"] = {"raw_unit_name": "credits", "raw_units": "99", "estimated_usd": 0 if i == 1 else None, "actual_usd": None, "currency": "USD"} + if i == 3: + attempt["reference_asset_ids"] = ["consumed-boundary"] + failed = {**copy.deepcopy(attempt), "attempt_id": "failed-3", "status": "failed", "error": {"code": "retry", "message": "Synthetic failure"}} + result_scene["attempts"].append(failed) + attempt.update({"attempt_number": 2, "fallback_from_attempt_id": "failed-3", "provider": "fallback"}) + result_scene["attempts"].append(attempt) + asset = {"asset_id": clip_id, "uri": self.source.as_uri(), "sha256": gm.file_hash(self.source), "mime_type": "video/mp4", "role": "generated_clip", "rights_note": "Synthetic test"} + result_scene["clips"].append({"clip_id": clip_id, "attempt_id": attempt_id, "asset": asset, "media": self.media}) + clip_ids = [clip["clip_id"] for clip in result_scene["clips"]] + result_scene["takes"] = [{"take_id": f"take-{i}", "clip_ids": list(reversed(clip_ids)), "clip_order": {key: j for j, key in enumerate(clip_ids)}, + "preview_asset_id": None, "supersedes_take_ids": [], "depends_on_take_ids": ["take-2"] if i == 3 else [], + "nominal_duration_s": 2 * len(clip_ids), "measured_duration_s": 2 * len(clip_ids)}] + self.result["scenes"].append(result_scene) + self.result = gm.seal(self.result) + gm.import_result(self.project, self.result, asset_root=self.asset_root) + self.draft: dict[str, Any] = {"edit_revision_id": "edit-1", "project_id": "pilot", "storyboard_revision_id": "board-1", + "source_results": [{"result_id": "result-1", "sha256": self.result["document_sha256"]}], + "scenes": [{"scene_id": scene["scene_id"], "order": scene["order"], "take_id": scene["takes"][0]["take_id"], + "transition_out": {"type": "cut", "editorial_note": None}, + "clip_edits": [{"clip_id": key, "order": order, "trim_in_s": 0.25, "trim_out_s": 1.25, "audio_use": "preserve"} + for key, order in reversed(list(scene["takes"][0]["clip_order"].items()))]} + for scene in reversed(self.result["scenes"])]} + + def test_compile_order_provenance_trims_and_cost(self) -> None: + selection = gm.write_selection(self.project, self.draft) + edl = gm.compile_selection(self.project, selection) + self.assertEqual([row["beat"] for row in edl["ranges"]], ["scene-1", "scene-2", "scene-2", "scene-3"]) + self.assertEqual([item["clip_id"] for item in edl["generated_media"]["sources"].values()], ["clip-1-0", "clip-2-0", "clip-2-1", "clip-3-0"]) + self.assertEqual(gm.file_hash(gm.project_path(self.project, selection["edl"]["path"])), selection["edl"]["sha256"]) + cost = gm.cost_rollup(self.project, selection) + self.assertEqual(len(cost["attempts"]), 5) + self.assertIsNone(cost["all_attempts"]["estimated_usd"]["total"]) + self.assertEqual(cost["all_attempts"]["estimated_usd"]["known_subtotal"], 0) + self.assertEqual(cost["all_attempts"]["estimated_usd"]["unknown_attempts"], 4) + self.assertEqual(cost["attempts"][0]["raw_units"], "99") + + def test_fal_plan_alias_matches_recorded_provider(self) -> None: + self.assertEqual(self.plan["scenes"][0]["variants"][0]["provider"], "fal") + self.assertEqual(self.result["scenes"][0]["attempts"][0]["provider"], "fal.ai") + gm.write_selection(self.project, self.draft) + + def test_unsafe_edits_fail_before_ffmpeg_and_hash_tamper(self) -> None: + for field, value in (("trim_out_s", 10), ("trim_in_s", 1.5)): + draft = copy.deepcopy(self.draft) + draft["scenes"][0]["clip_edits"][0][field] = value + with patch.object(gm, "_audio_source") as audio, self.assertRaises(gm.IntegrationError): + gm.write_selection(self.project, draft) + audio.assert_not_called() + draft = copy.deepcopy(self.draft) + draft["scenes"][0]["transition_out"]["type"] = "dissolve" + with patch.object(gm, "probe_media") as probe, self.assertRaises(gm.IntegrationError): + gm.write_selection(self.project, draft) + probe.assert_not_called() + unapproved = copy.deepcopy(self.result) + unapproved["result_id"] = "unapproved-result" + unapproved["scenes"][0]["actual_shots"][0]["shot_id"] = "unapproved-shot" + unapproved["scenes"][0]["attempts"][0]["shot_id"] = "unapproved-shot" + unapproved = gm.seal(unapproved) + gm.import_result(self.project, unapproved, asset_root=self.asset_root) + unapproved_draft = copy.deepcopy(self.draft) + unapproved_draft["source_results"] = [{"result_id": unapproved["result_id"], "sha256": unapproved["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "approved shot"): + gm.write_selection(self.project, unapproved_draft) + index = gm.read_json(self.project / "rough-cuts/manifests/imports/result-1.json") + gm.project_path(self.project, index["assets"][0]["local_path"]).write_bytes(b"tampered") + with self.assertRaises(gm.IntegrationError): + gm.write_selection(self.project, self.draft) + + def test_selected_attempt_must_match_approved_variant(self) -> None: + plan = copy.deepcopy(self.plan) + plan["plan_id"] = "plan-variants" + primary = plan["scenes"][0]["variants"][0] + for field, value in (("provider", "other-provider"), ("model", "other-model"), ("prompt_snapshot", "other-prompt")): + variant = copy.deepcopy(primary) + variant["variant_id"] = f"unapproved-{field}" + if field == "prompt_snapshot": + variant["shots"][0][field] = value + else: + variant[field] = value + plan["scenes"][0]["variants"].append(variant) + plan = gm.seal(plan) + approval = gm.approve_plan(self.project, plan, ["variant-1", "variant-2", "variant-3"], + approval_id="approval-variants", allow_unknown_cost=True) + for field, value in (("provider", "other-provider"), ("model", "other-model"), ("prompt_snapshot", "other-prompt")): + with self.subTest(field=field): + result = copy.deepcopy(self.result) + result.update({"result_id": f"result-{field}", "plan_id": plan["plan_id"], "approval_id": approval["approval_id"]}) + result["scenes"][0]["attempts"][0][field] = value + result = gm.seal(result) + gm.import_result(self.project, result, asset_root=self.asset_root) + draft = copy.deepcopy(self.draft) + draft["source_results"] = [{"result_id": result["result_id"], "sha256": result["document_sha256"]}] + with patch.object(gm, "_audio_source") as audio, self.assertRaisesRegex(gm.IntegrationError, "approved shot variant"): + gm.write_selection(self.project, draft) + audio.assert_not_called() + + def test_selected_reference_requires_approved_lineage(self) -> None: + result = copy.deepcopy(self.result) + result["result_id"] = "unapproved-reference-result" + result["scenes"][0]["attempts"][0]["reference_asset_ids"] = ["consumed-boundary"] + result = gm.seal(result) + gm.import_result(self.project, result, asset_root=self.asset_root) + draft = copy.deepcopy(self.draft) + draft["source_results"] = [{"result_id": result["result_id"], "sha256": result["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "unapproved reference assets"): + gm.write_selection(self.project, draft) + + frame_asset = {**self.result["reference_assets"][0], "asset_id": "approved-keyframe", + "role": "keyframe", "source_take_id": None} + frame = {"shot_id": "shot-1-0", "order": 0, "position": "first", "attempt_id": None, + "asset": frame_asset, "media": {"measured_duration_s": None, "width": 320, "height": 180, + "fps": None, "has_audio": None}} + generated = copy.deepcopy(self.result) + generated["result_id"] = "generated-reference-result" + generated["scenes"][0]["keyframes"] = [frame] + generated["scenes"][0]["attempts"][0]["reference_asset_ids"] = ["approved-keyframe"] + generated = gm.seal(generated) + gm.import_result(self.project, generated, asset_root=self.asset_root) + draft["edit_revision_id"] = "edit-generated-reference" + draft["source_results"] = [{"result_id": generated["result_id"], "sha256": generated["document_sha256"]}] + gm.write_selection(self.project, draft) + + cross_scene = copy.deepcopy(generated) + cross_scene["result_id"] = "cross-scene-reference-result" + cross_scene["scenes"][1]["attempts"][0]["reference_asset_ids"] = ["approved-keyframe"] + cross_scene = gm.seal(cross_scene) + gm.import_result(self.project, cross_scene, asset_root=self.asset_root) + draft["source_results"] = [{"result_id": cross_scene["result_id"], "sha256": cross_scene["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "unapproved reference assets"): + gm.write_selection(self.project, draft) + dependent = copy.deepcopy(cross_scene) + dependent["result_id"] = "dependent-reference-result" + dependent["scenes"][1]["takes"][0]["depends_on_take_ids"] = ["take-1"] + dependent = gm.seal(dependent) + gm.import_result(self.project, dependent, asset_root=self.asset_root) + draft["edit_revision_id"] = "edit-dependent-reference" + draft["source_results"] = [{"result_id": dependent["result_id"], "sha256": dependent["document_sha256"]}] + gm.write_selection(self.project, draft) + + future = copy.deepcopy(generated) + future["result_id"] = "future-reference-result" + future["scenes"][0]["keyframes"] = [] + frame["shot_id"] = "shot-3-0" + future["scenes"][2]["keyframes"] = [frame] + future = gm.seal(future) + gm.import_result(self.project, future, asset_root=self.asset_root) + draft["source_results"] = [{"result_id": future["result_id"], "sha256": future["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "unapproved reference assets"): + gm.write_selection(self.project, draft) + + prepared_path = self.asset_root / "prepared.png" + Image.new("RGB", (320, 180), "white").save(prepared_path) + prepared = copy.deepcopy(generated) + prepared["result_id"] = "prepared-reference-result" + prepared["reference_assets"].append({"asset_id": "prepared-reference", "uri": prepared_path.as_uri(), + "sha256": gm.file_hash(prepared_path), "mime_type": "image/png", + "role": "provider_reference", "rights_note": "Synthetic", "source_take_id": None}) + attempt = prepared["scenes"][0]["attempts"][0] + attempt["reference_asset_ids"] = ["prepared-reference"] + attempt["generation_parameters"]["prepared_reference_sources"] = json.dumps({"prepared-reference": "approved-keyframe"}) + prepared = gm.seal(prepared) + gm.import_result(self.project, prepared, asset_root=self.asset_root) + draft["edit_revision_id"] = "edit-prepared-reference" + draft["source_results"] = [{"result_id": prepared["result_id"], "sha256": prepared["document_sha256"]}] + gm.write_selection(self.project, draft) + + wrong_source = copy.deepcopy(prepared) + wrong_source["result_id"] = "wrong-prepared-reference-result" + wrong_source["scenes"][0]["attempts"][0]["generation_parameters"]["prepared_reference_sources"] = json.dumps( + {"prepared-reference": "consumed-boundary"}) + wrong_source = gm.seal(wrong_source) + gm.import_result(self.project, wrong_source, asset_root=self.asset_root) + draft["source_results"] = [{"result_id": wrong_source["result_id"], "sha256": wrong_source["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "unapproved reference assets"): + gm.write_selection(self.project, draft) + + def test_video_take_requires_video_approval(self) -> None: + approval = gm.approve_plan(self.project, self.plan, ["variant-1", "variant-2", "variant-3"], + execution_mode="keyframes", approval_id="keyframe-approval", allow_unknown_cost=True) + result = copy.deepcopy(self.result) + result.update({"result_id": "result-keyframe-approval", "approval_id": approval["approval_id"]}) + result = gm.seal(result) + gm.import_result(self.project, result, asset_root=self.asset_root) + draft = copy.deepcopy(self.draft) + draft["source_results"] = [{"result_id": result["result_id"], "sha256": result["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "execution mode"): + gm.write_selection(self.project, draft) + + def test_cost_selection_uses_referenced_result_and_project(self) -> None: + selection = gm.write_selection(self.project, self.draft) + historical = copy.deepcopy(self.result) + historical["result_id"] = "historical-result" + for scene in historical["scenes"]: + ids = {attempt["attempt_id"]: "historical-" + attempt["attempt_id"] for attempt in scene["attempts"]} + for attempt in scene["attempts"]: + attempt["attempt_id"] = ids[attempt["attempt_id"]] + if attempt["fallback_from_attempt_id"]: + attempt["fallback_from_attempt_id"] = ids[attempt["fallback_from_attempt_id"]] + for clip in scene["clips"]: + clip["attempt_id"] = ids[clip["attempt_id"]] + historical = gm.seal(historical) + gm.import_result(self.project, historical, asset_root=self.asset_root) + rows = gm.cost_rollup(self.project, selection)["attempts"] + self.assertTrue(any(row["selected_output"] for row in rows if row["result_id"] == self.result["result_id"])) + self.assertFalse(any(row["selected_output"] for row in rows if row["result_id"] == historical["result_id"])) + foreign = gm.seal({**selection, "project_id": "another-project"}) + with self.assertRaisesRegex(gm.IntegrationError, "different project"): + gm.cost_rollup(self.project, foreign) + + def test_cost_attempt_ids_are_scoped_to_result_and_scene(self) -> None: + historical = copy.deepcopy(self.result) + historical["result_id"] = "historical-same-attempt-ids" + original_id = historical["scenes"][1]["attempts"][0]["attempt_id"] + historical["scenes"][1]["attempts"][0]["attempt_id"] = historical["scenes"][0]["attempts"][0]["attempt_id"] + for clip in historical["scenes"][1]["clips"]: + if clip["attempt_id"] == original_id: + clip["attempt_id"] = historical["scenes"][1]["attempts"][0]["attempt_id"] + gm.import_result(self.project, gm.seal(historical), asset_root=self.asset_root) + rows = gm.cost_rollup(self.project)["attempts"] + self.assertEqual(len(rows), 10) + self.assertEqual(len({(row["result_id"], row["scene_id"], row["attempt_id"]) for row in rows}), 10) + + def test_required_references_cannot_be_omitted_or_substituted(self) -> None: + board = copy.deepcopy(self.board) + board["revision_id"] = "required-board" + asset = {**self.result["reference_assets"][0], "asset_id": "required-reference", "source_take_id": None} + next(scene for scene in board["scenes"] if scene["scene_id"] == "scene-1")["reference_assets"] = [asset] + next(scene for scene in board["scenes"] if scene["scene_id"] == "scene-1")["continuity"]["required_reference_asset_ids"] = [asset["asset_id"]] + gm.build_request(self.project, board, request_id="required-request") + plan = copy.deepcopy(self.plan) + plan.update(plan_id="required-plan", request_id="required-request") + plan["scenes"][0]["variants"][0]["shots"][0]["reference_asset_ids"] = [asset["asset_id"]] + approval = gm.approve_plan(self.project, gm.seal(plan), [f"variant-{i}" for i in (1, 2, 3)], + approval_id="required-approval", allow_unknown_cost=True) + result = copy.deepcopy(self.result) + result.update(result_id="required-result", request_id="required-request", plan_id="required-plan", approval_id=approval["approval_id"]) + result["reference_assets"].append(asset) + draft = {**copy.deepcopy(self.draft), "storyboard_revision_id": board["revision_id"]} + for identifier, references, expected in (("omitted", [], False), ("present", [asset["asset_id"]], True)): + result["result_id"] = identifier + result["scenes"][0]["attempts"][0]["reference_asset_ids"] = references + sealed = gm.seal(result) + gm.import_result(self.project, sealed, asset_root=self.asset_root) + draft.update(edit_revision_id=identifier, source_results=[{"result_id": identifier, "sha256": sealed["document_sha256"]}]) + if expected: + gm.write_selection(self.project, draft) + else: + with self.assertRaisesRegex(gm.IntegrationError, "omitted required"): + gm.write_selection(self.project, draft) + substitute = self.asset_root / "required-substitute.png" + Image.new("RGB", (320, 180), "white").save(substitute) + generated = copy.deepcopy(result) + generated["result_id"] = "derived-required-reference" + image_attempt = {**copy.deepcopy(generated["scenes"][0]["attempts"][0]), "attempt_id": "image-attempt", "provider": "gemini"} + generated["scenes"][0]["attempts"].insert(0, image_attempt) + generated["scenes"][0]["keyframes"] = [{"shot_id": "shot-1-0", "order": 0, "position": "first", "attempt_id": "image-attempt", + "asset": {**asset, "asset_id": "derived-frame", "role": "keyframe", "uri": substitute.as_uri(), "sha256": gm.file_hash(substitute)}, + "media": {"measured_duration_s": None, "width": 320, "height": 180, "fps": None, "has_audio": None}}] + generated["scenes"][0]["attempts"][1]["reference_asset_ids"] = ["derived-frame"] + for identifier, image_refs, expected in (("derived-required-reference", [asset["asset_id"]], True), ("derived-omitted-reference", [], False)): + generated["result_id"] = identifier + image_attempt["reference_asset_ids"] = image_refs + sealed = gm.seal(generated) + gm.import_result(self.project, sealed, asset_root=self.asset_root) + draft.update(edit_revision_id=identifier, source_results=[{"result_id": identifier, "sha256": sealed["document_sha256"]}]) + if expected: + gm.write_selection(self.project, draft) + else: + with self.assertRaisesRegex(gm.IntegrationError, "omitted required"): + gm.write_selection(self.project, draft) + result["result_id"] = "substituted-reference" + result["reference_assets"][-1].update(uri=substitute.as_uri(), sha256=gm.file_hash(substitute)) + sealed = gm.seal(result) + gm.import_result(self.project, sealed, asset_root=self.asset_root) + draft["source_results"] = [{"result_id": sealed["result_id"], "sha256": sealed["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "substituted a planned"): + gm.write_selection(self.project, draft) + + def test_video_selection_binds_exact_reviewed_keyframes(self) -> None: + reviewed = copy.deepcopy(self.result) + image_approval = gm.approve_plan(self.project, self.plan, [f"variant-{i}" for i in (1, 2, 3)], + execution_mode="keyframes", approval_id="review-approval", allow_unknown_cost=True) + reviewed.update(result_id="reviewed-frames", result_kind="keyframes", approval_id=image_approval["approval_id"]) + for scene in reviewed["scenes"]: + scene["keyframes"] = [{"shot_id": shot["shot_id"], "order": shot["order"], "position": "first", "attempt_id": None, + "asset": {**self.result["reference_assets"][0], "asset_id": "frame-" + shot["shot_id"], "role": "keyframe", "source_take_id": None}, + "media": {"width": 320, "height": 180, "measured_duration_s": None, + "fps": None, "has_audio": None}} for shot in scene["actual_shots"]] + scene.update(clips=[], takes=[], attempts=[]) + gm.import_result(self.project, gm.seal(reviewed), asset_root=self.asset_root) + video_approval = gm.approve_plan(self.project, self.plan, [f"variant-{i}" for i in (1, 2, 3)], + approval_id="reviewed-video-approval", keyframe_result_id=reviewed["result_id"], allow_unknown_cost=True) + result = copy.deepcopy(self.result) + result.update(result_id="reviewed-video", approval_id=video_approval["approval_id"]) + for scene, image_scene in zip(result["scenes"], reviewed["scenes"], strict=True): + scene["keyframes"] = copy.deepcopy(image_scene["keyframes"]) + for attempt in scene["attempts"]: + attempt["reference_asset_ids"] = ["frame-" + attempt["shot_id"]] + sealed = gm.seal(result) + gm.import_result(self.project, sealed, asset_root=self.asset_root) + draft = copy.deepcopy(self.draft) + draft.update(edit_revision_id="reviewed-edit", source_results=[{"result_id": sealed["result_id"], "sha256": sealed["document_sha256"]}]) + gm.write_selection(self.project, draft) + substitute = self.asset_root / "reviewed-substitute.png" + Image.new("RGB", (320, 180), "white").save(substitute) + for identifier, same_id in (("new-id-frame", False), ("same-id-frame", True)): + changed = copy.deepcopy(result) + changed["result_id"] = identifier + frame = changed["scenes"][0]["keyframes"][0]["asset"] + frame.update(uri=substitute.as_uri(), sha256=gm.file_hash(substitute)) + if not same_id: + frame["asset_id"] = "unreviewed-frame" + changed["scenes"][0]["attempts"][0]["reference_asset_ids"] = [frame["asset_id"]] + sealed = gm.seal(changed) + gm.import_result(self.project, sealed, asset_root=self.asset_root) + draft["source_results"] = [{"result_id": identifier, "sha256": sealed["document_sha256"]}] + with self.assertRaisesRegex(gm.IntegrationError, "unapproved reference|substituted a reviewed"): + gm.write_selection(self.project, draft) + + def test_asset_roots_symlinks_hash_and_probe(self) -> None: + asset = self.result["scenes"][0]["clips"][0]["asset"] + with self.assertRaises(gm.IntegrationError): + gm.import_asset(self.project, asset, Path("bad.mp4"), asset_root=self.project) + with self.assertRaises(gm.IntegrationError): + gm.import_asset(self.project, {**asset, "sha256": "sha256:" + "0" * 64}, Path("bad.mp4"), asset_root=self.asset_root) + with self.assertRaises(gm.IntegrationError): + gm.import_asset(self.project, asset, Path("bad.mp4"), asset_root=self.asset_root, media={**self.media, "width": 1920}) + (self.project / "escape").symlink_to(self.asset_root, target_is_directory=True) + with self.assertRaises(gm.IntegrationError): + gm.project_path(self.project, "escape/overwrite.mp4") + self.assertFalse((self.project / "bad.mp4").exists()) + + def test_targeted_request_and_stale_decisions(self) -> None: + selection = gm.write_selection(self.project, self.draft) + request = gm.regenerate(self.project, self.board, selection, ["scene-2"], reason="New middle", request_id="request-2", revision=2) + self.assertEqual([scene["scene_id"] for scene in request["scenes"]], ["scene-2"]) + self.assertEqual(request["regeneration"]["supersedes_take_ids"], ["take-2"]) + foreign_board = {**self.board, "project_id": "another-project"} + with patch.object(gm, "build_request") as build, self.assertRaisesRegex(gm.IntegrationError, "different project"): + gm.regenerate(self.project, foreign_board, selection, ["scene-2"], reason="Foreign storyboard") + build.assert_not_called() + replacement = copy.deepcopy(self.result) + replacement["result_id"] = "result-2" + replacement["scenes"] = [replacement["scenes"][1]] + take = replacement["scenes"][0]["takes"][0] + take.update({"take_id": "take-2-new", "supersedes_take_ids": ["take-2"]}) + replacement = gm.seal(replacement) + gm.import_result(self.project, replacement, asset_root=self.asset_root) + draft = copy.deepcopy(self.draft) + draft["edit_revision_id"] = "edit-2" + draft["source_results"].append({"result_id": "result-2", "sha256": replacement["document_sha256"]}) + draft["scenes"][1]["take_id"] = "take-2-new" + with self.assertRaisesRegex(gm.IntegrationError, "Stale"): + gm.write_selection(self.project, draft) + draft["continuity_decisions"] = [{"scene_id": "scene-3", "dependency_take_id": "take-2", "decision": "accept_stale", "replacement_asset": None}] + revised = gm.write_selection(self.project, draft) + self.assertEqual(len(gm.stale_dependencies(revised, [self.result, replacement])), 1) + self.assertEqual(gm.load_document(self.project, "result", "result-1"), self.result) + draft["edit_revision_id"] = "edit-boundary" + draft["continuity_decisions"][0]["decision"] = "regenerate" + with self.assertRaisesRegex(gm.IntegrationError, "Stale"): + gm.write_selection(self.project, draft) + boundary_path = self.asset_root / "boundary.png" + Image.new("RGB", (320, 180), "gray").save(boundary_path) + boundary = {"asset_id": "boundary", "uri": boundary_path.as_uri(), "sha256": gm.file_hash(boundary_path), + "mime_type": "image/png", "role": "first_frame", "rights_note": "Synthetic", "source_take_id": "take-2-new"} + imported = gm.import_asset(self.project, boundary, Path("assets/reference/boundary.png"), asset_root=self.asset_root) + gm.immutable_write(self.project / "rough-cuts/manifests/boundaries/boundary.json", gm.canonical_bytes(imported)) + draft["continuity_decisions"][0].update({"decision": "use_boundary", "replacement_asset": boundary}) + boundary_selection = gm.write_selection(self.project, draft) + self.assertEqual(boundary_selection["continuity_decisions"][0]["replacement_asset"]["sha256"], gm.file_hash(boundary_path)) + + def test_actual_render_verify_and_idempotent_record(self) -> None: + selection = gm.write_selection(self.project, self.draft, edl_options={"reframe": "crop=100:180"}) + self.assertEqual(gm.compile_selection(self.project, selection)["reframe"], "crop=100:180") + record = gm.render_selection(self.project, selection, preview=True, no_loudnorm=True) + self.assertTrue(record["passed"], gm.read_json(gm.project_path(self.project, record["verification_path"]))) + self.assertEqual(record, gm.render_selection(self.project, selection, preview=True, no_loudnorm=True)) + self.assertTrue(gm.project_path(self.project, record["output_path"]).is_file()) + + def test_mute_and_editorial_asset_hashes_preserve_originals(self) -> None: + draft = copy.deepcopy(self.draft) + draft["scenes"][0]["clip_edits"][0]["audio_use"] = "mute" + subtitles = self.project / "subtitles" / "captions.srt" + subtitles.write_text("1\n00:00:00,000 --> 00:00:01,000\nSynthetic caption\n") + original_hash = gm.file_hash(self.source) + selection = gm.write_selection(self.project, draft, edl_options={"subtitles": "subtitles/captions.srt", "grade": "neutral_punch"}) + edl = gm.compile_selection(self.project, selection) + self.assertEqual(edl["generated_media"]["editorial_assets"][0]["sha256"], gm.file_hash(subtitles)) + self.assertEqual(gm.file_hash(self.source), original_hash) + muted = next(value for value in edl["generated_media"]["sources"].values() if value["audio_use"] == "mute") + self.assertIn("derived_asset_sha256", muted) + subtitles.write_text("changed") + with self.assertRaisesRegex(gm.IntegrationError, "EDL"): + gm.render_selection(self.project, selection, no_loudnorm=True) + gm.project_path(self.project, muted["local_path"]).write_bytes(b"tampered derivative") + with self.assertRaisesRegex(gm.IntegrationError, "derivative"): + gm.compile_selection(self.project, selection) + + +if __name__ == "__main__": + unittest.main() diff --git a/uv.lock b/uv.lock index 9cb834d..e3c93ab 100644 --- a/uv.lock +++ b/uv.lock @@ -33,6 +33,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/da/35/f2287558c17e29fafc8ef3daf819bb9834061cfa43bff8014f7df7f63bdc/anyio-4.14.2-py3-none-any.whl", hash = "sha256:9f505dda5ac9f0c8309b5e8bd445a8c2bf7246f3ce950121e45ea15bc41d1494", size = 125813, upload-time = "2026-07-12T20:29:05.763Z" }, ] +[[package]] +name = "attrs" +version = "26.1.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/9a/8e/82a0fe20a541c03148528be8cac2408564a6c9a0cc7e9171802bc1d26985/attrs-26.1.0.tar.gz", hash = "sha256:d03ceb89cb322a8fd706d4fb91940737b6642aa36998fe130a9bc96c985eff32", size = 952055, upload-time = "2026-03-19T14:22:25.026Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, +] + [[package]] name = "audioop-lts" version = "0.2.2" @@ -507,6 +516,33 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/62/a1/3d680cbfd5f4b8f15abc1d571870c5fc3e594bb582bc3b64ea099db13e56/jinja2-3.1.6-py3-none-any.whl", hash = "sha256:85ece4451f492d0c13c5dd7c13a64681a86afae63a5f347908daf103ce6d2f67", size = 134899, upload-time = "2025-03-05T20:05:00.369Z" }, ] +[[package]] +name = "jsonschema" +version = "4.26.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "jsonschema-specifications" }, + { name = "referencing" }, + { name = "rpds-py" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/b3/fc/e067678238fa451312d4c62bf6e6cf5ec56375422aee02f9cb5f909b3047/jsonschema-4.26.0.tar.gz", hash = "sha256:0c26707e2efad8aa1bfc5b7ce170f3fccc2e4918ff85989ba9ffa9facb2be326", size = 366583, upload-time = "2026-01-07T13:41:07.246Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/69/90/f63fb5873511e014207a475e2bb4e8b2e570d655b00ac19a9a0ca0a385ee/jsonschema-4.26.0-py3-none-any.whl", hash = "sha256:d489f15263b8d200f8387e64b4c3a75f06629559fb73deb8fdfb525f2dab50ce", size = 90630, upload-time = "2026-01-07T13:41:05.306Z" }, +] + +[[package]] +name = "jsonschema-specifications" +version = "2025.9.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "referencing" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/19/74/a633ee74eb36c44aa6d1095e7cc5569bebf04342ee146178e2d36600708b/jsonschema_specifications-2025.9.1.tar.gz", hash = "sha256:b540987f239e745613c7a9176f3edb72b832a4ac465cf02712288397832b5e8d", size = 32855, upload-time = "2025-09-08T01:34:59.186Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/41/45/1a4ed80516f02155c51f51e8cedb3c1902296743db0bbc66608a0db2814f/jsonschema_specifications-2025.9.1-py3-none-any.whl", hash = "sha256:98802fee3a11ee76ecaca44429fda8a41bff98b00a0f2838151b113f210cc6fe", size = 18437, upload-time = "2025-09-08T01:34:57.871Z" }, +] + [[package]] name = "librt" version = "0.9.0" @@ -742,6 +778,7 @@ version = "0.1.1" source = { editable = "." } dependencies = [ { name = "faster-whisper", marker = "platform_machine != 'arm64' or sys_platform != 'darwin'" }, + { name = "jsonschema" }, { name = "lightning-whisper-mlx", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, { name = "mlx", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, { name = "numpy" }, @@ -766,6 +803,7 @@ dev = [ [package.metadata] requires-dist = [ { name = "faster-whisper", marker = "platform_machine != 'arm64' or sys_platform != 'darwin'", specifier = ">=1.1.0" }, + { name = "jsonschema", specifier = ">=4.23" }, { name = "lightning-whisper-mlx", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'", specifier = ">=0.0.10" }, { name = "manim", marker = "extra == 'animations'", specifier = ">=0.20" }, { name = "mlx", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'", specifier = "<0.29.5" }, @@ -1314,6 +1352,20 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/f1/12/de94a39c2ef588c7e6455cfbe7343d3b2dc9d6b6b2f40c4c6565744c873d/pyyaml-6.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:ebc55a14a21cb14062aa4162f906cd962b28e2e9ea38f9b4391244cd8de4ae0b", size = 149341, upload-time = "2025-09-25T21:32:56.828Z" }, ] +[[package]] +name = "referencing" +version = "0.37.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "attrs" }, + { name = "rpds-py" }, + { name = "typing-extensions", marker = "python_full_version < '3.13'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/22/f5/df4e9027acead3ecc63e50fe1e36aca1523e1719559c499951bb4b53188f/referencing-0.37.0.tar.gz", hash = "sha256:44aefc3142c5b842538163acb373e24cce6632bd54bdb01b21ad5863489f50d8", size = 78036, upload-time = "2025-10-13T15:30:48.871Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/2c/58/ca301544e1fa93ed4f80d724bf5b194f6e4b945841c5bfd555878eea9fcb/referencing-0.37.0-py3-none-any.whl", hash = "sha256:381329a9f99628c9069361716891d34ad94af76e461dcb0335825aecc7692231", size = 26766, upload-time = "2025-10-13T15:30:47.625Z" }, +] + [[package]] name = "regex" version = "2026.4.4" @@ -1360,6 +1412,102 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/82/3b/64d4899d73f91ba49a8c18a8ff3f0ea8f1c1d75481760df8c68ef5235bf5/rich-15.0.0-py3-none-any.whl", hash = "sha256:33bd4ef74232fb73fe9279a257718407f169c09b78a87ad3d296f548e27de0bb", size = 310654, upload-time = "2026-04-12T08:24:02.83Z" }, ] +[[package]] +name = "rpds-py" +version = "2026.6.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/aa/2a/9618a122aeb2a169a28b03889a2995fe297588964333d4a7d67bdf46e147/rpds_py-2026.6.3.tar.gz", hash = "sha256:1cebd1337c242e4ec2293e541f712b2da849b29f48f0c293684b71c0632625d4", size = 64051, upload-time = "2026-06-30T07:17:53.009Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/5c/be/2e8974163072e7bab7df1a5acd54c4498e75e35d6d18b864d3a9d5dadc92/rpds_py-2026.6.3-cp312-cp312-macosx_10_12_x86_64.whl", hash = "sha256:a0811d33247c3d6128a3001d763f2aa056bb3425204335400ac54f89eec3a0d0", size = 343691, upload-time = "2026-06-30T07:15:14.96Z" }, + { url = "https://files.pythonhosted.org/packages/a4/73/319dfa745dd668efe89309141ded489126461fcecd2b8f3a3cda185129b6/rpds_py-2026.6.3-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:538949e262e46caa31ac01bdb3c1e8f642622922cacbabbae6a8445d9dc33eaf", size = 338542, upload-time = "2026-06-30T07:15:16.267Z" }, + { url = "https://files.pythonhosted.org/packages/21/63/4239893be1c4d09b709b1a8f6be4188f0870084ff547f46606b8a75f1b03/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:55927d532399c2c646100ff7feb48eaa940ad70f42cd68e1328f3ded9f81ca24", size = 368180, upload-time = "2026-06-30T07:15:17.62Z" }, + { url = "https://files.pythonhosted.org/packages/1c/ca/9c5de382225234ceb37b1844ebdb140db12b2a278bb9efe2fcd19f6c82ce/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:f56f1695bc5c0871cbc33dc0130fcf503aab0c57dcc5a6700a4f49eba4f2652e", size = 375067, upload-time = "2026-06-30T07:15:18.952Z" }, + { url = "https://files.pythonhosted.org/packages/87/dc/863f69d1bf04ade34b7fe0d59b9fdf6f0135fe2d7cbca74f1d665589559d/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:270b293dae9058fc9fcedab50f13cebf46fb8ed1d1d54e0521a9da5d6b211975", size = 490509, upload-time = "2026-06-30T07:15:20.434Z" }, + { url = "https://files.pythonhosted.org/packages/ce/ef/eac16a12048b45ec7c7fa94f2be3438a5f26bf9cc8580b18a1cfd609b7f6/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:127565fead0a10943b282957bd5447804ff3160ad79f2ad2635e6d249e380680", size = 382754, upload-time = "2026-06-30T07:15:21.831Z" }, + { url = "https://files.pythonhosted.org/packages/04/8f/d2f3f532616be4d06c316ef119683e832bd3d41e112bf3a88f4151c95b17/rpds_py-2026.6.3-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ecabd69db66de867690f9797f2f8fa27ba501bbc24540cbdbdc649cd15888ba6", size = 366189, upload-time = "2026-06-30T07:15:23.371Z" }, + { url = "https://files.pythonhosted.org/packages/e3/29/41a7b0e98a4b44cd676ab7598419623373eb43b20be68c084935c1a8cf88/rpds_py-2026.6.3-cp312-cp312-manylinux_2_31_riscv64.whl", hash = "sha256:58eadac9cd119677b60e1cf8ac4052f35949d71b8a9e5556efccbe82533cf22a", size = 377750, upload-time = "2026-06-30T07:15:24.659Z" }, + { url = "https://files.pythonhosted.org/packages/2e/05/ecda0bec46f9a1565090bcdc941d023f6a25aff85fda28f89f8d19878152/rpds_py-2026.6.3-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:7491ee23305ac3eb59e492b6945881f5cd77a6f731061a3f25b77fd40f9e99a4", size = 395576, upload-time = "2026-06-30T07:15:25.987Z" }, + { url = "https://files.pythonhosted.org/packages/68/a8/6ed52f03ee6cb854ce78785cc9a9a672eb880e83fd7224d471f667d151f1/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:2c99f7e8ccb3dd6e3e4bfeac657a7b208c9bac8075f4b078c02d7404c34107fa", size = 543807, upload-time = "2026-06-30T07:15:27.356Z" }, + { url = "https://files.pythonhosted.org/packages/8f/d6/156c0d3eea27ba09b92562ba2364ba124c0a061b199e17eac637cd25a5e2/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_i686.whl", hash = "sha256:62698275682bf121181861295c9181e789030a2d516071f5b8f3c23c170cd0fc", size = 611187, upload-time = "2026-06-30T07:15:28.931Z" }, + { url = "https://files.pythonhosted.org/packages/f1/31/774212ed989c62f7f310220089f9b0a3fb8f40f5443d1727abd5d9f52bc9/rpds_py-2026.6.3-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:a214c993455f99a89aaeadc9b21241900037adc9d97203e374d75513c5911822", size = 573030, upload-time = "2026-06-30T07:15:30.553Z" }, + { url = "https://files.pythonhosted.org/packages/c9/50/22f73127a41f1ce4f87fe39aadfb9a126345801c274aa93ae88456249327/rpds_py-2026.6.3-cp312-cp312-win32.whl", hash = "sha256:501f9f04a588d6a09179368c57071301445191767c64e4b52a6aa9871f1ef5ed", size = 202185, upload-time = "2026-06-30T07:15:32.027Z" }, + { url = "https://files.pythonhosted.org/packages/04/3a/f0ee4d4dde9d3b69dedf1b5f74e7a40017046d55052d173e418c6a94f960/rpds_py-2026.6.3-cp312-cp312-win_amd64.whl", hash = "sha256:2c958bf94822e9290a40aaf2a822d4bc5c88099093e3948ad6c571eca9272e5f", size = 220394, upload-time = "2026-06-30T07:15:33.359Z" }, + { url = "https://files.pythonhosted.org/packages/f3/83/3382fe37f809b59f02aac04dbc4e765b480b46ee0227ed516e3bdc4d3dfc/rpds_py-2026.6.3-cp312-cp312-win_arm64.whl", hash = "sha256:22bffe6042b9bcb0822bcd1955ec00e245daf17b4344e4ed8e9551b976b63e96", size = 215753, upload-time = "2026-06-30T07:15:34.778Z" }, + { url = "https://files.pythonhosted.org/packages/a4/9e/b818ee580026ec578138e961027a68820c40afeb1ec8f6819b54fb99e196/rpds_py-2026.6.3-cp313-cp313-macosx_10_12_x86_64.whl", hash = "sha256:3cfe765c1da0072636ca06628261e0ea05688e160d5c8a03e0217c3854037223", size = 343012, upload-time = "2026-06-30T07:15:36.005Z" }, + { url = "https://files.pythonhosted.org/packages/f3/6b/686d9dc4359a8f163cfbbf89ee0b4e586431de22fe8248edb63a8cf50d49/rpds_py-2026.6.3-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f4d78253f6996be4901669ad25319f842f740eccf4d58e3c7f3dd39e6dde1d8f", size = 338203, upload-time = "2026-06-30T07:15:37.462Z" }, + { url = "https://files.pythonhosted.org/packages/9e/9b/069aa329940f8207615e091f5eedbbd40e1e15eac68a0790fd05ccdf796c/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:54f45a148e28767bf343d33a684693c70e451c6f4c0e9904709a723fafbdfc1f", size = 367984, upload-time = "2026-06-30T07:15:39.008Z" }, + { url = "https://files.pythonhosted.org/packages/14/db/34c203e4becff3703e4d3bc121842c00b8689197f398161203a880052f4e/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:842e7b070435622248c7a2c44ae53fa1440e073cc3023bc919fed570884097a7", size = 374815, upload-time = "2026-06-30T07:15:40.253Z" }, + { url = "https://files.pythonhosted.org/packages/ee/7d/8071067d2cc453d916ad836e828c943f575e8a44612537759002a1e07381/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8020133a74bd81b4572dd8e4be028a6b1ebcd70e6726edc3918008c08bee6ee6", size = 490545, upload-time = "2026-06-30T07:15:41.729Z" }, + { url = "https://files.pythonhosted.org/packages/a3/42/da06c5aa8f0484ff07f270787434204d9f4535e2f8c3b51ed402267e63c3/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cdc7e35386f3847df728fbcb5e887e2d79c19e2fa1eba9e51b6621d23e3243af", size = 382828, upload-time = "2026-06-30T07:15:43.327Z" }, + { url = "https://files.pythonhosted.org/packages/57/d7/fe978efc2ae50abe48eb7464668ea99f53c010c60aeebb7b35ad27f23661/rpds_py-2026.6.3-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:acac386b453c2516111b50985d60ce46e7fadb5ea71ae7b25f4c946935bf27cf", size = 365678, upload-time = "2026-06-30T07:15:44.992Z" }, + { url = "https://files.pythonhosted.org/packages/69/9d/1d8922e1990b2a6eb532b6ff53d3e73d2b3bbffc84116c75826bee73dfc6/rpds_py-2026.6.3-cp313-cp313-manylinux_2_31_riscv64.whl", hash = "sha256:425560c6fa0415f27261727bb20bd097568485e5eb0c121f1949417d1c516885", size = 377811, upload-time = "2026-06-30T07:15:46.523Z" }, + { url = "https://files.pythonhosted.org/packages/b1/3d/198dceafb4fb034a6a47347e1b0735d34e0bd4a50be4e898d408ee66cb14/rpds_py-2026.6.3-cp313-cp313-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a550fb4950a06dde3beb4721f5ad4b25bf4513784665b0a8522c792e2bd822a4", size = 395382, upload-time = "2026-06-30T07:15:47.955Z" }, + { url = "https://files.pythonhosted.org/packages/1f/f1/13968e49655d40b6b19d8b9140296bbc6f1d86b3f0f6c346cf9f1adddf4b/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:4f4bca01b63096f606e095734dd56e74e175f94cfbf24ff3d63281cec61f7bb7", size = 543832, upload-time = "2026-06-30T07:15:49.33Z" }, + { url = "https://files.pythonhosted.org/packages/ac/ab/289bcb1b90bd3e40a2900c561fa0e2087345ecbb094f0b870f2345142b7c/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_i686.whl", hash = "sha256:ccffae9a092a00deb7efd545fe5e2c33c33b88e7c054337e9a74c179347d0b7d", size = 611011, upload-time = "2026-06-30T07:15:50.847Z" }, + { url = "https://files.pythonhosted.org/packages/1e/16/5043105e679436ccfbc8e5e0dd2d663ed18a8b8113515fd06a5e5d77c83e/rpds_py-2026.6.3-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:1cf01971c4f2c5553b772a542e4aaf191789cd331bc2cd4ff0e6e65ba49e1e97", size = 572431, upload-time = "2026-06-30T07:15:52.394Z" }, + { url = "https://files.pythonhosted.org/packages/85/ed/adab103321c0a6565d5ae1c2998349bc3ee175b82ccc5ae8fc04cc413075/rpds_py-2026.6.3-cp313-cp313-win32.whl", hash = "sha256:8c3d1e9c15b9d51ca0391e13da1a25a0a4df3c58a37c9dc368e0736cf7f69df0", size = 201710, upload-time = "2026-06-30T07:15:53.894Z" }, + { url = "https://files.pythonhosted.org/packages/7b/ed/a03b09668e74e5dabbf2e211f6468e1820c0552f7b0500082da31841bf7b/rpds_py-2026.6.3-cp313-cp313-win_amd64.whl", hash = "sha256:9250a9a0a6fd4648b3f868da8d91a4c52b5811a62df58e753d50ae4454a36f80", size = 219454, upload-time = "2026-06-30T07:15:55.25Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/b8642c12930b71bc2b25831f6708ccf0f75abcd11883932ec9ce54ba3a78/rpds_py-2026.6.3-cp313-cp313-win_arm64.whl", hash = "sha256:900a67df3fd1660b035a4761c4ce73c382ea6b35f90f9863c36c6fd8bf8b09bb", size = 215063, upload-time = "2026-06-30T07:15:56.573Z" }, + { url = "https://files.pythonhosted.org/packages/b6/36/7fbe9dcdaf857fb3f63c2a2284b62492d95f5e8334e947e5fb6e7f68c9be/rpds_py-2026.6.3-cp314-cp314-macosx_10_12_x86_64.whl", hash = "sha256:931908d9fc855d8f74783377822be318edb6dcb19e47169dc038f9a1bf60b06e", size = 344510, upload-time = "2026-06-30T07:15:57.921Z" }, + { url = "https://files.pythonhosted.org/packages/ba/54/f785cc3d3f60839ca57a5af4927a9f347b07b2799c373fc20f7949f87c7e/rpds_py-2026.6.3-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:d7469697dce35be237db177d42e2a2ee26e6dcc5fc052078a6fefabd288c6edd", size = 339495, upload-time = "2026-06-30T07:15:59.238Z" }, + { url = "https://files.pythonhosted.org/packages/63/ef/d4cdaf309e6b095b43597103cf8c0b951d6cca2acce68c474f75ec12e0c7/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:bcfbcf66006befb9fd2aeaa9e01feaf881b4dc330a02ba07d2322b1c11be7b5d", size = 369454, upload-time = "2026-06-30T07:16:01.021Z" }, + { url = "https://files.pythonhosted.org/packages/96/4a/9559a68b7ee15db09d7981212e8c2e219d2a1d6d4faa0391d813c3496a36/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:847927daf4cffbd4e90e42bc890069897101edd015f956cb8721b3473372edda", size = 374583, upload-time = "2026-06-30T07:16:02.287Z" }, + { url = "https://files.pythonhosted.org/packages/ef/75/8964aa7d2c6e8ac43eba8eb6e6b0fdda1f46d39f2fc3e6aa9f2cb17f485d/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:aca6c1ef08a82bfe327cc156da694660f599923e2e6665b6d81c9c2d0ac9ffc8", size = 492919, upload-time = "2026-06-30T07:16:03.723Z" }, + { url = "https://files.pythonhosted.org/packages/8f/97/6908094ac804115e65aedfd90f1b5fee4eebebd3f6c4cfc5419939267565/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:ae50181a047c871561212bb97f7932a2d45fb53e947bd9b57ebad85b529cbc53", size = 383725, upload-time = "2026-06-30T07:16:05.305Z" }, + { url = "https://files.pythonhosted.org/packages/d1/9c/0d1fdc2e7aba23e290d603bc494e97bd205bae262ce33c6b32a69768ed5e/rpds_py-2026.6.3-cp314-cp314-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:dc319e5a1de4b6913aac94bf6a2f9e847371e0a140a43dd4991db1a09bc2d504", size = 367255, upload-time = "2026-06-30T07:16:07.086Z" }, + { url = "https://files.pythonhosted.org/packages/c4/fe/f0209ca4a9ed074bc8acb44dfd0e81c3122e94c9689f5645b7973a866719/rpds_py-2026.6.3-cp314-cp314-manylinux_2_31_riscv64.whl", hash = "sha256:e4316bf32babbed84e691e352faf967ce2f0f024174a8643c37c94a1080374fc", size = 379060, upload-time = "2026-06-30T07:16:08.525Z" }, + { url = "https://files.pythonhosted.org/packages/c6/8d/f1cc54c616b9d8897de8738aac148d20afca93f68187475fe194d09a71b9/rpds_py-2026.6.3-cp314-cp314-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:8c6e5a2f750cc71c3e3b11d71661f21d6f9bc6cebc6564b1466417a1ec03ec77", size = 395960, upload-time = "2026-06-30T07:16:09.989Z" }, + { url = "https://files.pythonhosted.org/packages/fb/04/aafff00f73aeca2945f734f1d483c64ab8f472d0864ab02377fd8e89c3b2/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:4470ce197d4090875cf6affbf1f853338387428df97c4fb7b7106317b8214698", size = 545356, upload-time = "2026-06-30T07:16:11.816Z" }, + { url = "https://files.pythonhosted.org/packages/fd/cc/e229663b9e4ddac5a4acbe9085dd80a71af2a5d356b8b39d6bff233f24b0/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_i686.whl", hash = "sha256:ea964164cc9afa72d4d9b23cc28dafae93693c0a53e0b42acbff15b22c3f9ddd", size = 612319, upload-time = "2026-06-30T07:16:13.586Z" }, + { url = "https://files.pythonhosted.org/packages/e3/7a/8a0e6d3e6cd066af108b71b43122c3fe158dd9eb86acac626593a2582eb1/rpds_py-2026.6.3-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:639c8929aa0afe81be836b04de888460d6bed38b9c54cfc18da8f6bfabf5af5d", size = 573508, upload-time = "2026-06-30T07:16:15.23Z" }, + { url = "https://files.pythonhosted.org/packages/87/03/2a69ab618a789cf6cf85c86bb844c62d090e700ab1a2aa676b3741b6c516/rpds_py-2026.6.3-cp314-cp314-win32.whl", hash = "sha256:882076c00c0a608b131187055ddc5ae29f2e7eaf870d6168980420d58528a5c8", size = 202504, upload-time = "2026-06-30T07:16:16.893Z" }, + { url = "https://files.pythonhosted.org/packages/85/62/a3892ba945f4e24c78f352e5de3c7620d8479f73f211406a97263d13c7d2/rpds_py-2026.6.3-cp314-cp314-win_amd64.whl", hash = "sha256:0be972be84cfcaf46c8c6edf690ca0f154ac17babf1f6a955a51579b34ad2dc5", size = 220380, upload-time = "2026-06-30T07:16:18.108Z" }, + { url = "https://files.pythonhosted.org/packages/3d/e7/c2bd44dc831931815ad11ebb5f430b5a0a4d3caa9de837107876c30c3432/rpds_py-2026.6.3-cp314-cp314-win_arm64.whl", hash = "sha256:2a9c6f195058cb45335e8cc3802745c603d716eb96bc9625950c1aac71c0c703", size = 215976, upload-time = "2026-06-30T07:16:19.654Z" }, + { url = "https://files.pythonhosted.org/packages/79/9c/fff7b74bce9a091ec9a012a03f9ff5f69364eaf9451060dfc4486da2ffdd/rpds_py-2026.6.3-cp314-cp314t-macosx_10_12_x86_64.whl", hash = "sha256:f90938e92afda60266da758ee7d363447f7f0138c9559f9e1811629580582d90", size = 346840, upload-time = "2026-06-30T07:16:21.268Z" }, + { url = "https://files.pythonhosted.org/packages/e9/44/77bcb1168b33704908295533d27f10eb811e9e3e193e8993dc99572211d3/rpds_py-2026.6.3-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:ec829541c45bca16e61c7ae50c20501f213605beb75d1aba91a6ee37fbbb56a4", size = 340282, upload-time = "2026-06-30T07:16:22.875Z" }, + { url = "https://files.pythonhosted.org/packages/87/3c/7a9081c7c9e645b39efe19e4ffbeccd80add246327cd9b888aecffd72317/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afd70d95892096cdb26f15a00c45907b17817577aa8d1c76b2dcc2788391f9e9", size = 370403, upload-time = "2026-06-30T07:16:24.415Z" }, + { url = "https://files.pythonhosted.org/packages/f7/69/af47021eb7dad6ff3396cb001c08f0f3c4d06c20253f75be6421a59fe6b7/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:29dfa0533a5d4c94d4dfa1b694fcb56c9c63aad8330ffdd816fd225d0a7a162f", size = 376055, upload-time = "2026-06-30T07:16:26.111Z" }, + { url = "https://files.pythonhosted.org/packages/81/fc/a3bcf517084396a6dd258c592567a3c011ba4557f2fde23dceaf26e74f2e/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:af05d726809bff6b141be124d4c7ce998f9c9c7f30edb1f46c07aa103d540b41", size = 494419, upload-time = "2026-06-30T07:16:27.596Z" }, + { url = "https://files.pythonhosted.org/packages/c9/eb/13d529d1788135425c7bf207f8463458ca5d92e43f3f701365b83e9dffc1/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9826217f048f620d9a712672818bf231442c1b35d96b227a07eabd11b4bb6945", size = 384848, upload-time = "2026-06-30T07:16:29.183Z" }, + { url = "https://files.pythonhosted.org/packages/8e/f4/b7ac49f30013aba8f7b9566b1dd07e81de95e708c1374b7bacc5b9bc5c9c/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:536bceea4fa4acf7e1c61da2b5786304367c816c8895be71b8f537c480b0ea1f", size = 371369, upload-time = "2026-06-30T07:16:30.912Z" }, + { url = "https://files.pythonhosted.org/packages/31/86/6260bafa622f788b07ddec0e52d810305c8b9b0b8c27f58a2ab04bf62b4f/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_31_riscv64.whl", hash = "sha256:bc0011654b91cc4fb2ae701bec0a0ba1e552c0714247fa7af6c59e0ccfa3a4e1", size = 379673, upload-time = "2026-06-30T07:16:32.486Z" }, + { url = "https://files.pythonhosted.org/packages/19/c3/03f1ee79a047b48daeca157c89a18509cde22b6b951d642b9b0af1be660a/rpds_py-2026.6.3-cp314-cp314t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:539d75de9e0d536c84ff18dfeb805398e58227001ce09231a26a08b9aed1ee0e", size = 397500, upload-time = "2026-06-30T07:16:34.471Z" }, + { url = "https://files.pythonhosted.org/packages/f0/95/8ed0cd8c377dca12aea498f119fe639fc474d1461545c39d2b5872eb1c0f/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:166cf54d9f44fc6ceb53c7860258dde44a81406646de79f8ed3234fca3b6e538", size = 545978, upload-time = "2026-06-30T07:16:36.45Z" }, + { url = "https://files.pythonhosted.org/packages/d3/f2/0eb57f0eaa83f8fc152a7e03de968ab77e1f00732bebc892b190c6eebde7/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_i686.whl", hash = "sha256:d34c20167764fbcf927194d532dd7e0c56772f0a5f943fa5ef9e9afbba8fb9db", size = 613350, upload-time = "2026-06-30T07:16:38.213Z" }, + { url = "https://files.pythonhosted.org/packages/5b/de/e0674bdbc3ef7634989b3f854c3f34bc1f587d36e5bfdc5c378d57034619/rpds_py-2026.6.3-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:ea7bb13b7c9a29791f87a0387ba7d3ad3a6d783d827e4d3f27b40a0ff44495e2", size = 576486, upload-time = "2026-06-30T07:16:39.797Z" }, + { url = "https://files.pythonhosted.org/packages/f2/f6/21101359743cd136ada781e8210a85769578422ba460672eea0e29739200/rpds_py-2026.6.3-cp314-cp314t-win32.whl", hash = "sha256:6de4744d05bd1aa1be4ed7ea1189e3979196808008113bbbf899a460966b925e", size = 201068, upload-time = "2026-06-30T07:16:41.316Z" }, + { url = "https://files.pythonhosted.org/packages/a6/b2/9574d4d44f7760c2aa32d92a0a4f41698e33f5b204a0bf5c9758f52c79d5/rpds_py-2026.6.3-cp314-cp314t-win_amd64.whl", hash = "sha256:c7b9a2f8f4d8e90af72571d3d495deebdd7e3c75451f5b41719aee166e940fc2", size = 220600, upload-time = "2026-06-30T07:16:43.091Z" }, + { url = "https://files.pythonhosted.org/packages/08/ae/f23a2697e6ee6340a578b0f136be6483657bef0c6f9497b752bb5c0964bb/rpds_py-2026.6.3-cp315-cp315-macosx_10_12_x86_64.whl", hash = "sha256:e059c5dde6452b44424bd1834557556c226b57781dee1227af23518459722b13", size = 344726, upload-time = "2026-06-30T07:16:44.5Z" }, + { url = "https://files.pythonhosted.org/packages/c3/63/e7b3a1a5358dd32c930a1062d8e15b67fd6e8922e81df9e91706d66ee5c8/rpds_py-2026.6.3-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2f7c26fbc5acd2522b95d4177fe4710ffd8e9b20529e703ffbf8db4d93903f05", size = 339587, upload-time = "2026-06-30T07:16:46.255Z" }, + { url = "https://files.pythonhosted.org/packages/ec/64/10a85681916ca55fffb91b0a211f84e34297c109243484dd6394660a8a7c/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a3086b538543802f84c843911242db20447de00d8752dd0efc936dbcf02218ba", size = 369585, upload-time = "2026-06-30T07:16:48.101Z" }, + { url = "https://files.pythonhosted.org/packages/76/c2/baf95c7c38823e12ba34407c5f5767a89e5cf2233895e56f608167ae9493/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8f2e5c5ee828d42cb11760761c0af6507927bec42d0ad5458f97c9203b054617", size = 375479, upload-time = "2026-06-30T07:16:49.93Z" }, + { url = "https://files.pythonhosted.org/packages/6a/94/0aad06c72d65101e11d33528d438cda99a39ce0da99466e156158f2541d3/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ed0c1e5d10cdc7135537988c74a0188da68e2f3c30813ba3744ab1e42e0480f9", size = 492418, upload-time = "2026-06-30T07:16:51.641Z" }, + { url = "https://files.pythonhosted.org/packages/b5/17/de3f5a479a1f056535d7489819639d8cd591ea6281d700390b43b1abd745/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c2642a7603ec0b16ed77da4555db3b4b472341904873788327c0b0d7b95f1bb", size = 384123, upload-time = "2026-06-30T07:16:53.622Z" }, + { url = "https://files.pythonhosted.org/packages/46/7d/bf09bd1b145bb2671c03e1e6d1ab8651858d90d8c7dfeadd85a37a934fd8/rpds_py-2026.6.3-cp315-cp315-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:8e4320744c1ffdd95a603def63344bfab2d33edeab301c5007e7de9f9f5b3885", size = 367351, upload-time = "2026-06-30T07:16:55.241Z" }, + { url = "https://files.pythonhosted.org/packages/a3/ea/1bb734f314b8be319149ddee80b18bd41372bdcfbdf88d28131c0cd37719/rpds_py-2026.6.3-cp315-cp315-manylinux_2_31_riscv64.whl", hash = "sha256:a9f4645593036b81bbdb36b9c8e0ea0d1c3fee968c4d59db0344c14087ef143a", size = 378827, upload-time = "2026-06-30T07:16:56.841Z" }, + { url = "https://files.pythonhosted.org/packages/4b/93/d9611e5b25e26df9a3649813ed66193ace9347a7c7fc4ab7cf70e94851c0/rpds_py-2026.6.3-cp315-cp315-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:e55d236be29255554da47abe5c577637db7c24a02b8b46f0ca9524c855801868", size = 395966, upload-time = "2026-06-30T07:16:58.557Z" }, + { url = "https://files.pythonhosted.org/packages/c3/cb/99d77e16e5534ae1d90629bbe419ba6ee170833a6a85e3aa1cc41726fbbc/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:24e9c5386e16669b674a69c156c8eeefcb578f3b3397b713b08e6d60f3c7b187", size = 545680, upload-time = "2026-06-30T07:17:00.164Z" }, + { url = "https://files.pythonhosted.org/packages/59/15/11a29755f790cef7a2f755e8e14f4f0c33f39489e1893a632a2eee59672b/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_i686.whl", hash = "sha256:c60924535c75f1566b6eb75b5c31a48a43fef04fa2d0d201acbad8a9969c6107", size = 611853, upload-time = "2026-06-30T07:17:01.962Z" }, + { url = "https://files.pythonhosted.org/packages/68/86/0c27547e21644da938fb530f7e1a8148dd24d02db07e7a5f2567a17ce710/rpds_py-2026.6.3-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:38a2fea2787428f811719ceb9114cb78964a3138838320c29ac39526c79c16ba", size = 573715, upload-time = "2026-06-30T07:17:03.693Z" }, + { url = "https://files.pythonhosted.org/packages/29/71/4d8fcf700931815594bce892255bbd973b94efaf0fc1932b0590df18d886/rpds_py-2026.6.3-cp315-cp315-win32.whl", hash = "sha256:d483fe17f01ad64b7bf7cc38fcefff1ca9fb83f8c2b2542b68f97ffe0611b369", size = 202864, upload-time = "2026-06-30T07:17:05.746Z" }, + { url = "https://files.pythonhosted.org/packages/eb/62/b577562de0edbb55b2be85ce5fd09c33e386b9b13eee09833af4240fd5c4/rpds_py-2026.6.3-cp315-cp315-win_amd64.whl", hash = "sha256:67e3a721ffc5d8d2210d3671872298c4a84e4b8035cfe42ffd7cde35d772b146", size = 220430, upload-time = "2026-06-30T07:17:07.471Z" }, + { url = "https://files.pythonhosted.org/packages/c8/95/d6d0b2509825141eef60669a5739eec88dbc6a48053d6c92993a5704defe/rpds_py-2026.6.3-cp315-cp315-win_arm64.whl", hash = "sha256:6e84adbcf4bf841aed8116a8264b9f50b4cb3e7bd89b516122e616ac56ca269e", size = 215877, upload-time = "2026-06-30T07:17:09.008Z" }, + { url = "https://files.pythonhosted.org/packages/b7/bf/f3ea278f0afd615c1d0f19cb69043a41526e2bb600c2b536eb192218eb27/rpds_py-2026.6.3-cp315-cp315t-macosx_10_12_x86_64.whl", hash = "sha256:ae6dd8f10bd17aad820876d24caec9efdafd80a318d16c0a48edb5e136902c6b", size = 346933, upload-time = "2026-06-30T07:17:10.762Z" }, + { url = "https://files.pythonhosted.org/packages/9d/29/9907bdf1c5346763cf10b7f6852aad86652168c259def904cbe0082c5864/rpds_py-2026.6.3-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:bdbd97738551fca3917c1bd7188bec1920bb520104f28e7e1007f9ceb17b7690", size = 340274, upload-time = "2026-06-30T07:17:12.266Z" }, + { url = "https://files.pythonhosted.org/packages/6f/2c/8e03767b5778ef25cebf74a7a91a2c3806f8eced4c92cb7406bbe060756d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b95977e7211527ab0ba576e286d023389fbeeb32a6b7b771665d333c60e5342", size = 370763, upload-time = "2026-06-30T07:17:14.107Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e1/df2a7e1ba2efd796af26194250b8d42c821b46592311595162af9ef0528d/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15fde0e6fb0d88a60d221204873743e5d9f0b7d29165e62cd86d0413ad74ba6", size = 376467, upload-time = "2026-06-30T07:17:15.76Z" }, + { url = "https://files.pythonhosted.org/packages/6b/de/8a0814d1946af29cb068fb259aa8622f856df1d0bab58429448726b537f5/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a136d453475ac0fcbda502ef1e6504bd28d6d904700915d278deeab0d00fe140", size = 496689, upload-time = "2026-06-30T07:17:17.308Z" }, + { url = "https://files.pythonhosted.org/packages/df/f3/f19e0c852ba13694f5a79f3b719331051573cb5693feacf8a88ffffc3a71/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f826877d462181e5eb1c26a0026b8d0cab05d99844ecb6d8bf3627a2ca0c0442", size = 385340, upload-time = "2026-06-30T07:17:18.928Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ae/7ec3a9d2d4351f99e37bcb06b6b6f954512646bfdbf9742e1de727865daf/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79486287de1730dbaff3dbd124d0ca4d2ef7f9d29bf2544f1f93c09b5bcbbd12", size = 372179, upload-time = "2026-06-30T07:17:20.539Z" }, + { url = "https://files.pythonhosted.org/packages/d3/ac/9cee911dff2aaa9a5a8354f6610bf2e6a616de9197c5fff4f54f82585f1e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_31_riscv64.whl", hash = "sha256:808345f53cb952433ca2816f1604ff3515608a81784954f38d4452acfe8e61d5", size = 379993, upload-time = "2026-06-30T07:17:22.212Z" }, + { url = "https://files.pythonhosted.org/packages/83/6b/7c2a07ba88d1e9a936612f7a5d067467ed03d971d5a06f7d309dff044a7e/rpds_py-2026.6.3-cp315-cp315t-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:1967debc37f64f2c4dc90a7f563aec558b471966e12adcac4e1c4240496b6ebf", size = 398909, upload-time = "2026-06-30T07:17:23.66Z" }, + { url = "https://files.pythonhosted.org/packages/97/0b/776ffcb66783637b0031f6d58d6fb55913c8b5abf00aeecd46bf933fb477/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:f0840b5b17057f7fd918b76183a4b5a0635f43e14eb2ce60dce1d4ee4707ea00", size = 546584, upload-time = "2026-06-30T07:17:25.264Z" }, + { url = "https://files.pythonhosted.org/packages/55/33/ba3bc04d7092bd553c9b2b195624992d2cc4f3de1f380b7b93cbee67bd79/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_i686.whl", hash = "sha256:faa679d19a6696fd54259ad321251ad77a13e70e03dd834daa762a44fb6196ef", size = 614357, upload-time = "2026-06-30T07:17:26.888Z" }, + { url = "https://files.pythonhosted.org/packages/8b/71/14edf065f04630b1a8472f7653cad03f6c478bcf95ea0e6aed55451e33ea/rpds_py-2026.6.3-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:23a439f31ccbeff1574e24889128821d1f7917470e830cf6544dced1c662262a", size = 576533, upload-time = "2026-06-30T07:17:28.546Z" }, + { url = "https://files.pythonhosted.org/packages/ba/76/65002b08596c389105720a8c0d22298b8dc25a4baf89b2ce431343c8b1de/rpds_py-2026.6.3-cp315-cp315t-win32.whl", hash = "sha256:913ca42ccad3f8cc6e292b587ae8ae49c8c823e5dce51a736252fc7c7cdfa577", size = 201204, upload-time = "2026-06-30T07:17:30.193Z" }, + { url = "https://files.pythonhosted.org/packages/8c/97/d855d6b3c322d1f27e26f5241c42016b56cf01377ea8ed348285f54652f0/rpds_py-2026.6.3-cp315-cp315t-win_amd64.whl", hash = "sha256:ae3d4fe8c0b9213624fdce7279d70e3b148b682ca20719ebd193a23ebfa47324", size = 220719, upload-time = "2026-06-30T07:17:31.788Z" }, +] + [[package]] name = "ruff" version = "0.15.12"