diff --git a/.cursor/rules/ltx2-patch-reverify.mdc b/.cursor/rules/ltx2-patch-reverify.mdc index eea4f62d6..4ecf9b6bb 100644 --- a/.cursor/rules/ltx2-patch-reverify.mdc +++ b/.cursor/rules/ltx2-patch-reverify.mdc @@ -6,14 +6,25 @@ alwaysApply: false # LTX-2 bump → re-check `services.patches` -If this change updates `ltx-core` or `ltx-pipelines` (version pin, git tag, or `tool.uv.dependency-metadata`), treat every module imported from `backend/services/patches/` in `backend/ltx2_server.py` as suspect. +Delete-first. If this change updates `ltx-core` or `ltx-pipelines` (version pin, git tag, or `tool.uv.dependency-metadata`), treat every module imported from `backend/services/patches/` in `backend/ltx2_server.py` as suspect — plus any out-of-directory swaps such as `distilled_keyframe_guiding`. -Those patches rebind private upstream symbols. A bump can rename the target (import-time assert should fail) or change the contract (assert still passes, behavior is wrong). +Those patches rebind private upstream symbols. A bump can rename the target (import-time assert should fail) or change the contract (assert still passes, behavior is wrong). Default is **delete** the patch; keep only what still fails on the new revision. For each patch: -1. Read the module's "Remove once ..." docstring. If upstream now includes the fix, delete the patch and its `ltx2_server.py` import. -2. Otherwise diff the upstream function against the replacement and keep the contract identical. -3. Run that patch's tests (`backend/tests/test_.py`). +1. Read the module's "Remove once ..." docstring. If upstream now includes the fix, delete the patch, its `ltx2_server.py` import, and its tests. +2. Cautionary example: `diffvae_mps_tiling_budget` asserted `DiffusionVideoDecoder.recommended_tiling_config`, which 1.3.0 removed. Keeping it made the backend unable to boot. `safetensors_metadata_fix` is the opposite kind of patch (Windows 1455 / never-`safe_open` the 46GB distilled-1.1 checkpoint) — keep until that contract is upstream. +3. Otherwise diff the upstream function against the replacement and keep the contract identical. Re-earn; do not copy blindly. +4. Run that patch's tests (`backend/tests/test_.py`) plus the patch import-smoke test. + +Forked pipeline classes copy upstream bodies, and a signature test does not catch body drift. On every bump diff these against the new upstream and re-run their tests: + +- `TiledICLoraPipeline._video_conditionings` (`ic_lora_pipeline/tiled_ic_lora_pipeline.py`) copies upstream `ICLoraPipeline._video_conditionings`; keep the `apply_ic_lora` gate and only change `encode_tiling`. +- `DistilledPipelineWithSkipStage2._call_stage_1_only` mirrors stage 1 of `DistilledPipeline`. +- `DistilledA2VPipeline` and `LTXRetakePipeline` call `DiffusionStage` directly. + +Size latents with `stage.video_scale_factors` (transformer geometry). `tiling_scale_factors_for_vae` is the decoder's tiling scale (2x8x8 on the 2.5 DiffVAE) and is only for `ensure_tiling_config`. + +Unit tests cannot prove a forked pipeline still generates correctly. After the patch review, run the live regression suite on each platform (`backend/performance_runner/README.md`, "Live regression suite"): `sanity.py --tags smoke` at minimum, `--tags smoke full bump` for a release, on both the deterministic (2.3) and ancestral (2.5) models. `safetensors_metadata_fix` is in this set (Windows 1455 / LTX-Desktop#158: do not `safe_open` the 46GB distilled-1.1 checkpoint in `_read_scales` or `_scan_checkpoint_keys`). diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f713ceeca..30d5fa7e9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -16,6 +16,8 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + with: + fetch-depth: 0 - uses: pnpm/action-setup@41ff72655975bd51cab0327fa583b6e92b6d3061 # v4.2.0 @@ -51,43 +53,78 @@ jobs: - name: TypeScript type check run: pnpm run typecheck:ts + - name: ESLint + run: pnpm run lint + - name: Pack helper tests run: pnpm run scripts:test - test-python: - name: Python Tests (${{ matrix.os }}) - runs-on: ${{ matrix.runner }} - strategy: - fail-fast: false - matrix: - include: - - os: macos - runner: macos-latest - - os: windows - runner: windows-latest - - os: linux - runner: ubuntu-latest + - name: File size check + run: bash scripts/check-file-sizes.sh origin/main + + test-python-windows: + name: Python Tests (windows) + runs-on: windows-latest defaults: run: working-directory: backend steps: - - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 + - &checkout + uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4.3.1 - - uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 + - &setup-uv + uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5.4.2 with: version: "latest" enable-cache: true cache-dependency-glob: "backend/uv.lock" - - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 + - &setup-python + uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0 with: python-version: "3.12" - - name: Install dependencies + - &install-backend + name: Install dependencies run: uv sync --frozen --extra test --extra dev + # The full suite runs on Linux. Windows only runs tests that call the + # real Win32 DLL APIs. `--` keeps `-m` from being read as a uv flag. + - name: Run tests + run: uv run -- pytest -v --tb=short -m ci_os + + # One Linux pytest job was the wait. Four shards run together. + # The matrix length and `--splits` below are the same number. + test-python-linux: + name: Python Tests (linux ${{ matrix.shard }}/4) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + shard: [1, 2, 3, 4] + defaults: + run: + working-directory: backend + steps: + - *checkout + - *setup-uv + - *setup-python + - *install-backend + # `--` keeps `--splits` from being read as a uv flag. + # least_duration deals tests round-robin when there is no durations file, + # so a slow module is not collected entirely onto the first shard. - name: Run tests - run: uv run pytest -v --tb=short + run: uv run -- pytest -v --tb=short --splits 4 --group ${{ matrix.shard }} --splitting-algorithm least_duration + + # Branch protection still looks for this name. It passes when every Linux shard passes. + test-python-linux-gate: + name: Python Tests (linux) + needs: test-python-linux + if: always() + runs-on: ubuntu-latest + steps: + - name: Require every Linux shard + run: test "${{ needs.test-python-linux.result }}" = "success" build-check: name: Frontend Build diff --git a/.gitignore b/.gitignore index 4f9ea8e73..cb7bca7cc 100644 --- a/.gitignore +++ b/.gitignore @@ -6,6 +6,7 @@ node_modules/ # Build outputs dist/ dist-electron/ +dist-remote/ .vite/ release/ *.tsbuildinfo @@ -35,6 +36,8 @@ backend/**/__pycache__/ .vscode/* !.vscode/launch.json !.vscode/tasks.json +!.vscode/settings.json +!.vscode/extensions.json *.swp *.swo *~ diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 000000000..b230d3948 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,12 @@ +node_modules +dist +dist-electron +dist-remote +.vite +release +coverage +.vscode +backend +frontend/generated +pnpm-lock.yaml +*.min.js diff --git a/.prettierrc.js b/.prettierrc.js new file mode 100644 index 000000000..43601d065 --- /dev/null +++ b/.prettierrc.js @@ -0,0 +1,24 @@ +/** + * Copied from LTX Studio `infinity-formatter` (vl-web-client). + * + * @type {import("prettier").Config} + */ +export default { + importOrder: [ + // 1. All global packages from node_modules (react, lodash, etc.) + "^(?!@/|\\.).*$", + // 2. All global imports starting with @/ + "^@/", + // 3. Relative imports from parent directories + "^../", + // 4. Relative imports from current directory + "./", + ], + importOrderParserPlugins: ["typescript", "jsx", "decorators-legacy"], + importOrderSeparation: true, + importOrderSortSpecifiers: true, + printWidth: 90, + arrowParens: "always", + objectWrap: "preserve", + plugins: ["@trivago/prettier-plugin-sort-imports"], +}; diff --git a/.vscode/extensions.json b/.vscode/extensions.json new file mode 100644 index 000000000..d7df89c9c --- /dev/null +++ b/.vscode/extensions.json @@ -0,0 +1,3 @@ +{ + "recommendations": ["esbenp.prettier-vscode", "dbaeumer.vscode-eslint"] +} diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 000000000..cb85e2cb9 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,24 @@ +{ + "editor.defaultFormatter": "esbenp.prettier-vscode", + "[javascript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[javascriptreact]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[typescript]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[typescriptreact]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "[json]": { + "editor.defaultFormatter": "esbenp.prettier-vscode" + }, + "editor.formatOnSave": true, + "prettier.requireConfig": true, + "editor.indentSize": 2, + "editor.tabSize": 2, + "editor.insertSpaces": true, + "editor.detectIndentation": false +} diff --git a/AGENTS.md b/AGENTS.md index 609384865..6601a08b6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,7 +38,7 @@ PRs must pass: `pnpm typecheck` + `pnpm backend:test` + frontend Vite build. - **IPC bridge**: All Electron communication through `window.electronAPI` (defined in `electron/preload.ts`) - **Backend calls**: Always use `backendFetch` from `frontend/lib/backend.ts` for app backend HTTP requests (it attaches auth/session details). Do not call `fetch` directly for backend endpoints. - **Styling**: Tailwind with custom semantic color tokens via CSS variables; utilities from `class-variance-authority` + `clsx` + `tailwind-merge` -- **No frontend tests** currently exist +- Frontend, Electron, and shared tests are `node:test` files. `pnpm run scripts:test` runs them. Which ones are worth writing is in [Tests](#tests). ## Backend Architecture @@ -57,8 +57,10 @@ Key patterns: - Integration-first using Starlette `TestClient` against real FastAPI app - **No mocks**: `test_no_mock_usage.py` enforces no `unittest.mock`. Swap services via `ServiceBundle` fakes only. +- Assert the status, the body, the resulting state, or the persisted row. A call assertion on a fake is out. - Fakes live in `tests/fakes/`; `conftest.py` wires fresh `AppHandler` per test -- Pyright strict mode is also enforced as a test (`test_pyright.py`) +- Pyright strict mode runs in the CI typecheck job (`uv run pyright`). Pytest does not run it again. +- Which tests are worth writing is in [Tests](#tests) ### Adding a Backend Feature @@ -89,3 +91,39 @@ Key patterns: - Electron builder config: `electron-builder.yml` - Video editor (largest frontend file): `frontend/views/VideoEditor.tsx` - Project types: `frontend/types/project.ts` + +## Tests + +Before writing tests, list the cases you intend to cover and wait for approval. +Each line names one bug. Do not create or edit a test file until that list is approved. + +Each test must correspond to a specific bug a reasonable developer could +introduce. Put that bug in the test name. Use a one-line comment only when the +name would be unreadable. If you can't name the bug, don't write the test. + +Do NOT write tests that: + +- assert a component renders without throwing +- assert a pure function returns its own obvious output (add(1, 2) === 3). A cap, an alignment grid, or None when over the cap is in scope +- verify that a mock you just configured was called with what you configured +- re-assert types the compiler already guarantees +- re-assert a Pydantic model, dataclass, or TypedDict field type that Pyright or the schema already enforces. A wire alias (currentStep present, current_step absent) and the error envelope (code, message) are in scope +- snapshot entire component trees +- test library behaviour (Zustand's set, React's useState, Radix internals) +- exist to raise coverage +- fail only when the entire module is deleted + +DO write tests for: + +- branch and boundary conditions (empty, single, off-by-one, null vs undefined) +- error paths and failure modes +- state transitions and their ordering +- anything with non-obvious business rules +- regressions: bugs previously fixed + +Prefer fewer tests with real assertions over many shallow ones. +Test observable behaviour through the public interface. + +When you touch a file that already has tests, delete any that break the rules +above. On legacy surfaces (GenSpace and similar), keep the smallest set that +still catches the cases above. Do not grow those suites. diff --git a/README.md b/README.md index 92f2d3f6f..4d27b3790 100644 --- a/README.md +++ b/README.md @@ -33,16 +33,18 @@ LTX Desktop is an open-source desktop app for generating videos with LTX models ## Local vs API mode +See [`docs/local-compat-matrix.md`](docs/local-compat-matrix.md) for the tool × hardware projection of the same generate decisions (not a second Yes table). CUDA **16 GB** cards are local-viable but do not advertise Fast 720p/20s or 1080p/10s. + | Platform / hardware | Generation mode | Notes | | --- | --- | --- | -| Windows + CUDA GPU with **≥16GB VRAM** | Local generation | Downloads model weights locally | -| Windows (no CUDA, <16GB VRAM, or unknown VRAM) | API-only | **LTX API key required** | -| Linux + CUDA GPU with **≥16GB VRAM** | Local generation | Downloads model weights locally | -| Linux (no CUDA, <16GB VRAM, or unknown VRAM) | API-only | **LTX API key required** | -| macOS, Apple Silicon with **≥15GB free RAM** | Local generation | Downloads model weights locally; runs on MPS | -| macOS, Apple Silicon with <15GB free RAM, or Intel Mac | API-only | **LTX API key required** | +| Windows + CUDA GPU with **≥15 GiB VRAM** | Local generation | Integer GiB from `total_memory // 1024**3` | +| Windows (no CUDA, <15 GiB VRAM, or unknown VRAM) | Local unsupported | Cloud API is optional if configured | +| Linux + CUDA GPU with **≥15 GiB VRAM** | Local generation | Integer GiB from `total_memory // 1024**3` | +| Linux (no CUDA, <15 GiB VRAM, or unknown VRAM) | Local unsupported | Cloud API is optional if configured | +| macOS, Apple Silicon with **≥32 GiB total RAM** | Local generation | Downloads model weights locally; runs on MPS | +| macOS, Apple Silicon with <32 GiB total RAM, or Intel Mac | Local unsupported | Cloud API is optional if configured | -In API-only mode, available resolutions/durations may be limited to what the API supports. The API path also offers **LTX 2.5 Fast**, **LTX 2.5 Pro**, and 2.3 Fast/Pro. +When local generation is unsupported, the app does not require an LTX API key. The optional API path still offers **LTX 2.5 Fast**, **LTX 2.5 Pro**, and 2.3 Fast/Pro. ### Local models @@ -59,30 +61,26 @@ Switch the active local checkpoint in **Settings > Models**. Newer weights (incl ### Windows (local generation) - Windows 10/11 (x64) -- NVIDIA GPU with CUDA support and **≥16GB VRAM** (more is better) +- NVIDIA GPU with CUDA support and **≥15 GiB VRAM** (integer GiB from `total_memory // 1024**3`; more is better) - 16GB+ RAM (32GB recommended) -- **160GB+ free disk space** (for model weights, Python environment, and outputs) +- **~72 GB free disk** for the 2.5 Fast core pack (transformer, text encoder, VAEs). Kitchen-sink installs (2.3, image models, processors, prompt enhancer) are larger. ### Linux (local generation) - Ubuntu 22.04+ or similar distro (x64 or arm64) -- NVIDIA GPU with CUDA support and **≥16GB VRAM** (more is better) +- NVIDIA GPU with CUDA support and **≥15 GiB VRAM** (integer GiB from `total_memory // 1024**3`; more is better) - NVIDIA driver installed (PyTorch bundles the CUDA runtime) - 16GB+ RAM (32GB recommended) -- Plenty of free disk space for model weights and outputs +- Plenty of free disk space for model weights and outputs (~72 GB for the 2.5 Fast core pack; kitchen-sink is larger) ### macOS (local generation) -- Apple Silicon (arm64) — Intel Macs have no MPS backend and stay in API-only mode +- Apple Silicon (arm64) — Intel Macs have no MPS backend and cannot run local generation - macOS 13+ (Ventura) -- **≥15GB free RAM** (not total — the OS/Electron/app already use some); more avoids weight streaming from disk -- Plenty of free disk space for model weights and outputs - -Below the free-RAM floor, or on an Intel Mac, the app falls back to API-only mode instead — same as underpowered Windows/Linux hardware (see the table above). API-only mode just needs a stable internet connection. - -**How the RAM check works.** The app checks *free* RAM — not total — and only **once**, at launch (when the Python backend process starts). It is not re-checked while the app is running. If other apps are using memory at that moment, you can land in API-only mode even on a capable Mac. +- **≥32 GiB total RAM** (machine SKU, integer GiB from physical memory; not free RAM at launch) +- Plenty of free disk space for model weights and outputs (~72 GB for the 2.5 Fast core pack; kitchen-sink is larger) -If you have 32GB+ of total RAM but still see API-only mode: close memory-heavy apps (browsers are usually the biggest offender), then **quit and relaunch LTX Desktop** — freeing memory while the app is already open has no effect, since the check doesn't run again until the next launch. +Below the total-RAM floor, or on an Intel Mac, local generation is unsupported — same as underpowered Windows/Linux hardware (see the table above). An LTX API key is not required. ## Install @@ -155,10 +153,10 @@ Open the selector to tick one or more LoRAs and adjust each one's strength. If y The LTX API is used for: - **Cloud text encoding and prompt enhancement** — **FREE**; text encoding is highly recommended to speed up inference and save memory -- API-based video generations (required on unsupported hardware; optional Fast/Pro cloud generations including **LTX 2.5**) — paid +- API-based video generations (optional Fast/Pro cloud generations including **LTX 2.5**) — paid - Retake — paid -An LTX API key is required in API-only mode, but optional for local generation if you enable the Local Text Encoder. +An LTX API key is optional. Local generation does not require one. Cloud text encoding, prompt enhancement, and API video generation use it when configured. Generate a FREE API key at the [LTX Console](https://console.ltx.video/). Text encoding is free; video generation API usage is paid. [Read more](https://ltx.io/model/model-blog/ltx-2-better-control-for-real-workflows). @@ -256,7 +254,7 @@ Building installers: ## Telemetry -LTX Desktop collects minimal, anonymous usage analytics (app version, platform, and a random installation ID) to help prioritize development. No personal information or generated content is collected. Analytics is enabled by default and can be disabled in **Settings > General > Anonymous Analytics**. See [`TELEMETRY.md`](docs/TELEMETRY.md) for details. +LTX Desktop collects minimal, anonymous usage analytics (app version, platform, hardware information, and a random installation ID) to help prioritize development. No personal information or generated content is collected. Analytics is enabled by default and can be disabled in **Settings > General > Anonymous Analytics**. See [`TELEMETRY.md`](docs/TELEMETRY.md) for details. ## Docs diff --git a/backend/_routes/_analytics.py b/backend/_routes/_analytics.py new file mode 100644 index 000000000..7136c1cbd --- /dev/null +++ b/backend/_routes/_analytics.py @@ -0,0 +1,79 @@ +from __future__ import annotations + +import uuid +from collections.abc import Callable +from typing import Protocol, TypeVar + +from services.analytics import AnalyticsService, pixel_resolution + +__all__ = [ + "AnalyticsService", + "desktop_generation_details", + "image_execution", + "pixel_resolution", + "run_tracked_generation", + "video_execution", +] +from services.services_utils import JSONValue +from state.app_settings import ( + AppSettings, + should_image_generate_with_fal_api, + should_video_generate_with_ltx_api, +) + + +class _Cancellable(Protocol): + @property + def status(self) -> str: ... + + +ResponseT = TypeVar("ResponseT", bound=_Cancellable) + + +def video_execution(*, force_api_generations: bool, settings: AppSettings) -> str: + if should_video_generate_with_ltx_api( + force_api_generations=force_api_generations, + settings=settings, + ): + return "ltx_api" + return "local" + + +def image_execution(*, force_api_generations: bool, settings: AppSettings) -> str: + if should_image_generate_with_fal_api( + force_api_generations=force_api_generations, + settings=settings, + ): + return "fal_api" + return "local" + + +def desktop_generation_details( + *, + surface: str, + feature: str, + kind: str, + execution: str, + **metadata: JSONValue, +) -> dict[str, JSONValue]: + return { + "generation_id": str(uuid.uuid4()), + "client": "desktop", + "surface": surface, + "feature": feature, + "kind": kind, + "execution": execution, + **metadata, + } + + +def run_tracked_generation( + analytics: AnalyticsService, + details: dict[str, JSONValue], + operation: Callable[[], ResponseT], +) -> ResponseT: + with analytics.generation(details) as tracker: + response = operation() + if response.status == "cancelled": + tracker.finish("cancelled") + return response diff --git a/backend/_routes/assets.py b/backend/_routes/assets.py new file mode 100644 index 000000000..e3f3556c8 --- /dev/null +++ b/backend/_routes/assets.py @@ -0,0 +1,488 @@ +from __future__ import annotations + +import os +import tempfile +from collections.abc import Callable, Coroutine +from pathlib import Path +from typing import Annotated, Any, BinaryIO + +from fastapi import APIRouter, Depends, File, Query, Request, UploadFile +from fastapi.responses import FileResponse, JSONResponse +from fastapi.routing import APIRoute +from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.responses import Response +from starlette.types import Message, Receive + +from _routes._errors import HTTPError, build_http_error_response +from api_types import ( + Asset, + AssetListQuery, + AssetListResponse, + IngestAssetRequest, + MediaKind, + StatusResponse, + TrimMediaRequest, +) +from app_handler import AppHandler +from remote.deps import RemoteContext, get_remote_context +from remote.dto import ( + RemoteAsset, + RemoteAssetListResponse, + to_remote_list_item, +) +from services.media_probe import ( + ALLOWED_AUDIO_SUFFIXES, + ALLOWED_IMAGE_SUFFIXES, + ALLOWED_VIDEO_SUFFIXES, + MAX_AUDIO_BYTES, + MAX_IMAGE_BYTES, + MAX_VIDEO_BYTES, +) +from state import get_state_service + +router = APIRouter(prefix="/api") + +_UPLOAD_READ_CHUNK_BYTES = 1024 * 1024 +_UPLOAD_TEMP_PREFIX = "ltx-remote-upload-" +# Multipart bodies are larger than the file (boundaries, disposition, MIME). +# This slack is only for the HTTP Content-Length early abort so a file of +# the per-kind max is not rejected. UploadFile.size and the copied-byte cap +# still use that max with no slack. +_MULTIPART_OVERHEAD_BYTES = 64 * 1024 +# Remote-only ASGI body cap: largest permitted file plus multipart framing. +# Enforced on actual receive bytes before Starlette parses/spools multipart. +MAX_REMOTE_UPLOAD_BODY_BYTES = ( + max(MAX_IMAGE_BYTES, MAX_AUDIO_BYTES, MAX_VIDEO_BYTES) + + _MULTIPART_OVERHEAD_BYTES +) + + +class _UploadBodyTooLarge(StarletteHTTPException): + """Raised when ASGI receive bytes exceed MAX_REMOTE_UPLOAD_BODY_BYTES. + + Subclasses Starlette HTTPException so FastAPI's body-parsing wrapper + (which converts generic Exceptions to "There was an error parsing the + body") re-raises it unchanged to the route handler. + """ + + def __init__(self) -> None: + super().__init__(status_code=400, detail="FILE_TOO_LARGE") + + +def _declared_upload_body_too_large(content_length: str | None) -> bool: + if content_length is None: + return False + try: + declared = int(content_length.strip()) + except ValueError: + return False + return declared > MAX_REMOTE_UPLOAD_BODY_BYTES + + +def _upload_too_large_response() -> JSONResponse: + return JSONResponse( + status_code=400, + content=build_http_error_response(400, "FILE_TOO_LARGE").model_dump(), + ) + + +def _bounded_upload_receive(base_receive: Receive) -> Receive: + """Wrap ASGI receive to bound total body bytes and per-event chunks. + + Counts actual receive bytes so chunked/missing/lying Content-Length cannot + spool unbounded temp disk in Starlette's multipart parser. Large ASGI + events are split into _UPLOAD_READ_CHUNK_BYTES pieces; an event that would + push the total over the cap raises before any of it is forwarded. + """ + total = 0 + pending = b"" + pending_more_body = False + + async def bounded_receive() -> Message: + nonlocal total, pending, pending_more_body + if pending: + chunk = pending[:_UPLOAD_READ_CHUNK_BYTES] + pending = pending[_UPLOAD_READ_CHUNK_BYTES:] + if total + len(chunk) > MAX_REMOTE_UPLOAD_BODY_BYTES: + raise _UploadBodyTooLarge() + total += len(chunk) + more_body = bool(pending) or pending_more_body + if not pending: + pending_more_body = False + return {"type": "http.request", "body": chunk, "more_body": more_body} + message = await base_receive() + if message.get("type") != "http.request": + return message + raw_body: Any = message.get("body", b"") + body = raw_body if isinstance(raw_body, bytes) else b"" + more_body = bool(message.get("more_body", False)) + if len(body) == 0: + return {"type": "http.request", "body": b"", "more_body": more_body} + if total + len(body) > MAX_REMOTE_UPLOAD_BODY_BYTES: + raise _UploadBodyTooLarge() + if len(body) <= _UPLOAD_READ_CHUNK_BYTES: + total += len(body) + return {"type": "http.request", "body": body, "more_body": more_body} + chunk = body[:_UPLOAD_READ_CHUNK_BYTES] + pending = body[_UPLOAD_READ_CHUNK_BYTES:] + pending_more_body = more_body + total += len(chunk) + return {"type": "http.request", "body": chunk, "more_body": True} + + return bounded_receive + + +class BoundedRemoteUploadRoute(APIRoute): + """Bound POST /api/assets/upload body before multipart parsing (remote only).""" + + def get_route_handler(self) -> Callable[[Request], Coroutine[Any, Any, Response]]: + original = super().get_route_handler() + if self.path != "/api/assets/upload": + return original + if self.methods is None or "POST" not in self.methods: + return original + + async def bounded_upload_handler(request: Request) -> Response: + if _declared_upload_body_too_large( + request.headers.get("content-length") + ): + return _upload_too_large_response() + bounded_request = Request( + request.scope, _bounded_upload_receive(request.receive) + ) + try: + return await original(bounded_request) + except _UploadBodyTooLarge: + return _upload_too_large_response() + + return bounded_upload_handler + + +phone_assets_router = APIRouter(prefix="/api", route_class=BoundedRemoteUploadRoute) + + +def asset_list_query( + media_kind: MediaKind | None = None, + # Document the allowed values in OpenAPI without FastAPI 422; store/handler map invalid sort to 400. + sort: Annotated[ + str, + Query( + json_schema_extra={"enum": ["created_at-desc", "created_at-asc"]}, + ), + ] = "created_at-desc", + q: str | None = None, + cursor: str | None = None, + limit: Annotated[int, Query(ge=1, le=200)] = 100, +) -> AssetListQuery: + return AssetListQuery( + media_kind=media_kind, + sort=sort, + q=q, + cursor=cursor, + limit=limit, + ) + + +@router.post("/assets", response_model=Asset, tags=["assets"]) +def route_ingest_asset( + req: IngestAssetRequest, handler: AppHandler = Depends(get_state_service) +) -> Asset: + return handler.assets.ingest_asset(req) + + +@router.get( + "/assets", + response_model=AssetListResponse, + tags=["assets"], + operation_id="route_list_assets", +) +def route_list_assets( + query: AssetListQuery = Depends(asset_list_query), + handler: AppHandler = Depends(get_state_service), +) -> AssetListResponse: + return handler.assets.list_assets(query) + + +@router.delete( + "/assets/{asset_id}", + response_model=StatusResponse, + tags=["assets"], + operation_id="route_delete_asset", +) +def route_delete_asset( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> StatusResponse: + handler.assets.delete_asset(asset_id) + return StatusResponse(status="ok") + + +@router.get("/assets/{asset_id}", response_model=Asset, tags=["assets"]) +def route_get_asset( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> Asset: + return handler.assets.get_asset(asset_id) + + +@router.post( + "/assets/{asset_id}/trim-audio", response_model=Asset, tags=["assets"] +) +def route_trim_audio( + asset_id: str, + req: TrimMediaRequest, + handler: AppHandler = Depends(get_state_service), +) -> Asset: + return handler.assets.trim_audio(asset_id, req) + + +@router.post( + "/assets/{asset_id}/trim-video", response_model=Asset, tags=["assets"] +) +def route_trim_video( + asset_id: str, + req: TrimMediaRequest, + handler: AppHandler = Depends(get_state_service), +) -> Asset: + return handler.assets.trim_video(asset_id, req) + + +@router.post( + "/assets/{asset_id}/extract-audio", response_model=Asset, tags=["assets"] +) +def route_extract_audio( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> Asset: + return handler.assets.extract_audio(asset_id) + + +@phone_assets_router.get( + "/assets", + response_model=RemoteAssetListResponse, + tags=["assets"], + operation_id="route_list_phone_assets", +) +def route_list_phone_assets( + query: AssetListQuery = Depends(asset_list_query), + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteAssetListResponse: + page = handler.assets.list_assets(query, tombstone_missing=False) + return RemoteAssetListResponse( + items=[ + to_remote_list_item( + item, + in_use=item.in_use, + signer=remote.signer, + device_id=remote.device.id, + ) + for item in page.items + ], + next_cursor=page.next_cursor, + ) + + +@phone_assets_router.get("/assets/{asset_id}", response_model=RemoteAsset, tags=["assets"]) +def route_get_phone_asset( + asset_id: str, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteAsset: + return remote.asset( + handler.assets.get_asset(asset_id, tombstone_missing=False) + ) + + +@phone_assets_router.post( + "/assets/{asset_id}/trim-audio", + response_model=RemoteAsset, + tags=["assets"], +) +def route_phone_trim_audio( + asset_id: str, + req: TrimMediaRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteAsset: + return remote.asset(handler.assets.trim_audio(asset_id, req)) + + +@phone_assets_router.post( + "/assets/{asset_id}/trim-video", + response_model=RemoteAsset, + tags=["assets"], +) +def route_phone_trim_video( + asset_id: str, + req: TrimMediaRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteAsset: + return remote.asset(handler.assets.trim_video(asset_id, req)) + + +@phone_assets_router.post( + "/assets/{asset_id}/extract-audio", + response_model=RemoteAsset, + tags=["assets"], +) +def route_phone_extract_audio( + asset_id: str, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteAsset: + return remote.asset(handler.assets.extract_audio(asset_id)) + + +def _upload_suffix(filename: str | None) -> str: + suffix = Path(filename or "").suffix.lower() + if suffix not in ( + ALLOWED_IMAGE_SUFFIXES | ALLOWED_AUDIO_SUFFIXES | ALLOWED_VIDEO_SUFFIXES + ): + raise HTTPError(400, "UNSUPPORTED_MEDIA") + return suffix + + +def _upload_max_bytes(suffix: str) -> int: + if suffix in ALLOWED_AUDIO_SUFFIXES: + return MAX_AUDIO_BYTES + if suffix in ALLOWED_VIDEO_SUFFIXES: + return MAX_VIDEO_BYTES + return MAX_IMAGE_BYTES + + +def _upload_body_exceeds_limit( + *, file_size: int | None, content_length: str | None, max_bytes: int +) -> bool: + if file_size is not None and file_size > max_bytes: + return True + if content_length is None: + return False + try: + declared = int(content_length) + except ValueError: + return False + return declared > max_bytes + _MULTIPART_OVERHEAD_BYTES + + +def _reject_declared_oversize( + file: UploadFile, request: Request, *, max_bytes: int +) -> None: + if _upload_body_exceeds_limit( + file_size=file.size, + content_length=request.headers.get("content-length"), + max_bytes=max_bytes, + ): + raise HTTPError(400, "FILE_TOO_LARGE") + + +async def _write_bounded_upload( + file: UploadFile, handle: BinaryIO, max_bytes: int +) -> None: + received = 0 + while True: + chunk = await file.read(_UPLOAD_READ_CHUNK_BYTES) + if not chunk: + return + if received + len(chunk) > max_bytes: + raise HTTPError(400, "FILE_TOO_LARGE") + handle.write(chunk) + received += len(chunk) + + +@phone_assets_router.post( + "/assets/upload", response_model=RemoteAsset, tags=["assets"] +) +async def route_upload_asset( + request: Request, + file: UploadFile = File(), + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteAsset: + suffix = _upload_suffix(file.filename) + max_bytes = _upload_max_bytes(suffix) + _reject_declared_oversize(file, request, max_bytes=max_bytes) + fd, tmp_name = tempfile.mkstemp(prefix=_UPLOAD_TEMP_PREFIX, suffix=suffix) + tmp_path = Path(tmp_name) + try: + with os.fdopen(fd, "wb") as handle: + await _write_bounded_upload(file, handle, max_bytes) + return remote.asset( + handler.assets.ingest_asset(IngestAssetRequest(path=str(tmp_path))), + ) + finally: + tmp_path.unlink(missing_ok=True) + + +def _file_response_for( + path_value: str, *, mime_type: str, filename: str +) -> FileResponse: + path = Path(path_value) + if not path.is_file(): + raise HTTPError(404, "ASSET_NOT_FOUND") + return FileResponse( + path, + media_type=mime_type, + filename=filename, + content_disposition_type="inline", + ) + + +# Also on the Desktop router: the renderer streams asset bytes over HTTP for +# waveform decoding instead of marshalling a base64 copy through IPC. +@router.get( + "/assets/{asset_id}/bytes", + tags=["assets"], + operation_id="route_desktop_asset_bytes", +) +@router.head("/assets/{asset_id}/bytes", tags=["assets"]) +def route_desktop_asset_bytes( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> FileResponse: + asset = handler.assets.get_asset(asset_id, tombstone_missing=False) + return _file_response_for( + asset.path, mime_type=asset.mime_type, filename=asset.name + ) + + +@router.get( + "/assets/{asset_id}/thumbnail/bytes", + tags=["assets"], + operation_id="route_desktop_asset_thumbnail_bytes", +) +@router.head("/assets/{asset_id}/thumbnail/bytes", tags=["assets"]) +def route_desktop_asset_thumbnail_bytes( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> FileResponse: + asset = handler.assets.get_asset(asset_id, tombstone_missing=False) + if asset.thumbnail_path is None: + raise HTTPError(404, "THUMBNAIL_NOT_FOUND") + return _file_response_for( + asset.thumbnail_path, + mime_type="image/jpeg", + filename=f"{asset.id}-thumb.jpg", + ) + + +@phone_assets_router.get("/assets/{asset_id}/bytes", tags=["assets"]) +@phone_assets_router.head("/assets/{asset_id}/bytes", tags=["assets"]) +def route_asset_bytes( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> FileResponse: + asset = handler.assets.get_asset(asset_id, tombstone_missing=False) + return _file_response_for( + asset.path, mime_type=asset.mime_type, filename=asset.name + ) + + +@phone_assets_router.get("/assets/{asset_id}/thumbnail/bytes", tags=["assets"]) +@phone_assets_router.head("/assets/{asset_id}/thumbnail/bytes", tags=["assets"]) +def route_asset_thumbnail_bytes( + asset_id: str, handler: AppHandler = Depends(get_state_service) +) -> FileResponse: + asset = handler.assets.get_asset(asset_id, tombstone_missing=False) + if asset.thumbnail_path is None: + raise HTTPError(404, "THUMBNAIL_NOT_FOUND") + return _file_response_for( + asset.thumbnail_path, + mime_type="image/jpeg", + filename=f"{asset.id}-thumb.jpg", + ) diff --git a/backend/_routes/extend.py b/backend/_routes/extend.py index b16baa67f..82be86fd3 100644 --- a/backend/_routes/extend.py +++ b/backend/_routes/extend.py @@ -4,7 +4,14 @@ from fastapi import APIRouter, Depends +from _routes._analytics import ( + desktop_generation_details, + pixel_resolution, + run_tracked_generation, + video_execution, +) from api_types import ExtendRequest, ExtendResponse +from services.analytics import unenhanced_prompt_provenance from state import get_state_service from app_handler import AppHandler @@ -13,4 +20,25 @@ @router.post("/extend", response_model=ExtendResponse) def route_extend(req: ExtendRequest, handler: AppHandler = Depends(get_state_service)) -> ExtendResponse: - return handler.extend.run(req) + details = desktop_generation_details( + surface="genspace", + feature="extend", + kind="video", + execution=video_execution( + force_api_generations=handler.config.force_api_generations, + settings=handler.state.app_settings, + ), + model=req.model, + duration_sec=req.duration, + prompt_provenance=unenhanced_prompt_provenance(req.prompt_provenance), + **( + {"resolution": pixel_resolution(req.resolution.width, req.resolution.height)} + if req.resolution is not None + else {} + ), + ) + return run_tracked_generation( + handler.analytics, + details, + lambda: handler.extend.run(req), + ) diff --git a/backend/_routes/feature_flags.py b/backend/_routes/feature_flags.py new file mode 100644 index 000000000..980d4fced --- /dev/null +++ b/backend/_routes/feature_flags.py @@ -0,0 +1,24 @@ +"""Route handlers for /api/feature-flags. Mounted on both Desktop and Remote.""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends + +from api_types import FeatureFlags, FeatureFlagsPatch +from app_handler import AppHandler +from state import get_state_service + +router = APIRouter(prefix="/api", tags=["feature-flags"]) + + +@router.get("/feature-flags", response_model=FeatureFlags) +def route_get_feature_flags(handler: AppHandler = Depends(get_state_service)) -> FeatureFlags: + return handler.feature_flags.get_flags() + + +@router.patch("/feature-flags", response_model=FeatureFlags) +def route_update_feature_flags( + req: FeatureFlagsPatch, + handler: AppHandler = Depends(get_state_service), +) -> FeatureFlags: + return handler.feature_flags.update_flags(req) diff --git a/backend/_routes/generation.py b/backend/_routes/generation.py index 42a4e87a0..9aaa6b81d 100644 --- a/backend/_routes/generation.py +++ b/backend/_routes/generation.py @@ -4,6 +4,12 @@ from fastapi import APIRouter, Depends +from _routes._analytics import ( + desktop_generation_details, + run_tracked_generation, + video_execution, +) +from api_model_specs import video_generation_feature from api_types import ( CancelResponse, GenerateVideoModelsSpecsResponse, @@ -12,10 +18,12 @@ GenerationProgressResponse, LtxInsufficientFundsErrorResponse, ) +from services.services_utils import JSONValue from state import get_state_service from app_handler import AppHandler router = APIRouter(prefix="/api", tags=["generation"]) +specs_router = APIRouter(prefix="/api", tags=["generation"]) @router.post( @@ -33,10 +41,51 @@ def route_generate( handler: AppHandler = Depends(get_state_service), ) -> GenerateVideoResponse: """POST /api/generate — video generation from JSON body.""" - return handler.video_generation.generate(req) + feature = video_generation_feature( + audio_path=req.audioPath, + image_path=req.imagePath, + last_image_path=req.lastImagePath, + keyframes=req.keyframes, + ) + catalog_ids: list[JSONValue] = [ + lora.catalogId for lora in req.loras if lora.catalogId is not None + ] + execution = video_execution( + force_api_generations=handler.config.force_api_generations, + settings=handler.state.app_settings, + ) + metadata: dict[str, JSONValue] = { + "model": req.model, + "resolution": req.resolution, + "fps": req.fps, + "prompt_provenance": handler.prompt_enhancement.preview_prompt_provenance( + req.prompt, + provenance=req.promptProvenance, + explore_generation=False, + force_api=execution == "ltx_api", + ), + } + if req.duration is not None: + metadata["duration_sec"] = req.duration + if catalog_ids: + metadata["lora_catalog_ids"] = catalog_ids + if any(lora.catalogId is None for lora in req.loras): + metadata["has_custom_lora"] = True + details = desktop_generation_details( + surface="genspace", + feature=feature, + kind="video", + execution=execution, + **metadata, + ) + return run_tracked_generation( + handler.analytics, + details, + lambda: handler.video_generation.generate(req), + ) -@router.get("/generate/models-specs", response_model=GenerateVideoModelsSpecsResponse) +@specs_router.get("/generate/models-specs", response_model=GenerateVideoModelsSpecsResponse) def route_generate_model_specs( handler: AppHandler = Depends(get_state_service), ) -> GenerateVideoModelsSpecsResponse: diff --git a/backend/_routes/generation_seed.py b/backend/_routes/generation_seed.py new file mode 100644 index 000000000..79f0a523c --- /dev/null +++ b/backend/_routes/generation_seed.py @@ -0,0 +1,43 @@ +"""Route handlers for GET/POST /api/generation-seed. + +The seed and its lock are the app settings `locked_seed` / `seed_locked`. This is the one +surface the remote app can reach for them, since it does not expose /api/settings. +""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends + +from app_handler import AppHandler +from state import get_state_service +from state.app_settings import GenerationSeed, GenerationSeedUpdate, UpdateSettingsRequest + +router = APIRouter(prefix="/api") +phone_generation_seed_router = APIRouter(prefix="/api") + + +def _current(handler: AppHandler) -> GenerationSeed: + settings = handler.settings.get_settings_snapshot() + return GenerationSeed(seed=settings.locked_seed, locked=settings.seed_locked) + + +@router.get("/generation-seed", response_model=GenerationSeed, tags=["generation-seed"]) +@phone_generation_seed_router.get("/generation-seed", response_model=GenerationSeed, tags=["generation-seed"]) +def route_get_generation_seed(handler: AppHandler = Depends(get_state_service)) -> GenerationSeed: + return _current(handler) + + +@router.post("/generation-seed", response_model=GenerationSeed, tags=["generation-seed"]) +@phone_generation_seed_router.post("/generation-seed", response_model=GenerationSeed, tags=["generation-seed"]) +def route_post_generation_seed( + body: GenerationSeedUpdate, + handler: AppHandler = Depends(get_state_service), +) -> GenerationSeed: + patch: dict[str, int | bool] = {} + if body.seed is not None: + patch["locked_seed"] = body.seed + if body.locked is not None: + patch["seed_locked"] = body.locked + if patch: + handler.settings.update_settings(UpdateSettingsRequest.model_validate(patch)) + return _current(handler) diff --git a/backend/_routes/generations.py b/backend/_routes/generations.py new file mode 100644 index 000000000..21f02256c --- /dev/null +++ b/backend/_routes/generations.py @@ -0,0 +1,264 @@ +from __future__ import annotations + +from fastapi import APIRouter, Depends, Path, Query + +from api_types import ( + CreateAudioToVideoRequest, + CreateIcLoraRecipeRequest, + CreateExtendRequest, + CreateImageToVideoRequest, + CreateLoraRecipeRequest, + CreateRetakeRequest, + CreateTextToVideoRequest, + Generation, + QueueSnapshot, + ReorderGenerationQueueRequest, + StatusResponse, +) + +# Recipe ids we actually ship — kept in sync with shared/lora-recipes.json. Fail +# closed on shape here so a malformed id 422s at the route rather than reaching +# create_lora_recipe. +_RECIPE_ID_PATTERN = r"^[a-z0-9-]+$" +from app_handler import AppHandler +from services.features.queued_features import QUEUED_GENERATION_FEATURES +from state import get_state_service + +router = APIRouter(prefix="/api") + + +@router.get( + "/generation-queue", + response_model=QueueSnapshot, + tags=["generations"], +) +def route_get_generation_queue( + handler: AppHandler = Depends(get_state_service), +) -> QueueSnapshot: + return handler.queued_generations.get_queue_snapshot() + + +@router.post( + "/generation-queue/reorder", + response_model=QueueSnapshot, + tags=["generations"], +) +def route_reorder_generation_queue( + req: ReorderGenerationQueueRequest, + handler: AppHandler = Depends(get_state_service), +) -> QueueSnapshot: + return handler.queued_generations.reorder_queue( + req.generation_id, req.before_generation_id + ) + + +@router.post( + "/generation-queue/done/clear", + response_model=QueueSnapshot, + tags=["generations"], +) +def route_clear_generation_queue_done( + handler: AppHandler = Depends(get_state_service), +) -> QueueSnapshot: + return handler.queued_generations.clear_done() + + +@router.post( + "/generation-queue/failed/clear", + response_model=QueueSnapshot, + tags=["generations"], +) +def route_clear_generation_queue_failed( + handler: AppHandler = Depends(get_state_service), +) -> QueueSnapshot: + return handler.queued_generations.clear_failed() + + +@router.post( + "/generation-queue/done/{generation_id}/seen", + response_model=QueueSnapshot, + tags=["generations"], +) +def route_mark_generation_queue_done_seen( + generation_id: str = Path(min_length=1), + handler: AppHandler = Depends(get_state_service), +) -> QueueSnapshot: + return handler.queued_generations.mark_done_seen(generation_id) + + +@router.post( + "/generation-queue/done/{generation_id}/dismiss", + response_model=QueueSnapshot, + tags=["generations"], +) +def route_dismiss_generation_queue_done( + generation_id: str = Path(min_length=1), + handler: AppHandler = Depends(get_state_service), +) -> QueueSnapshot: + return handler.queued_generations.dismiss_done(generation_id) + + +@router.post( + "/generations/text-to-video", + response_model=Generation, + tags=["generations"], +) +def route_create_text_to_video( + req: CreateTextToVideoRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_text_to_video( + req, analytics_client="desktop" + ) + + +@router.post( + "/generations/image-to-video", + response_model=Generation, + tags=["generations"], +) +def route_create_image_to_video( + req: CreateImageToVideoRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_image_to_video( + req, analytics_client="desktop" + ) + + +@router.post( + # Bounded under /recipes/ so the `{recipe_id}` wildcard does not swallow the + # whole `POST /generations/*` namespace (a future static create route would + # otherwise never match, and a typo'd id would 422 instead of 404). + "/generations/recipes/{recipe_id}", + response_model=Generation, + tags=["generations"], +) +def route_create_lora_recipe( + req: CreateLoraRecipeRequest, + recipe_id: str = Path(pattern=_RECIPE_ID_PATTERN, max_length=64), + handler: AppHandler = Depends(get_state_service), +) -> Generation: + return handler.queued_generations.create_lora_recipe( + recipe_id, req, analytics_client="desktop" + ) + + +@router.post( + "/generations/audio-to-video", + response_model=Generation, + tags=["generations"], +) +def route_create_audio_to_video( + req: CreateAudioToVideoRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_audio_to_video( + req, analytics_client="desktop" + ) + + +@router.post( + "/generations/retake", + response_model=Generation, + tags=["generations"], +) +def route_create_retake( + req: CreateRetakeRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_retake( + req, analytics_client="desktop" + ) + + +@router.post( + "/generations/ic-lora-recipes/{recipe_id}", + response_model=Generation, + tags=["generations"], +) +def route_create_ic_lora_recipe( + req: CreateIcLoraRecipeRequest, + recipe_id: str = Path(pattern=_RECIPE_ID_PATTERN), + handler: AppHandler = Depends(get_state_service), +) -> Generation: + return handler.queued_generations.create_ic_lora_recipe( + recipe_id, req, analytics_client="desktop" + ) + + +@router.post( + "/generations/extend", + response_model=Generation, + tags=["generations"], +) +def route_create_extend( + req: CreateExtendRequest, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.create_extend( + req, analytics_client="desktop" + ) + + +@router.get("/generations", response_model=list[Generation], tags=["generations"]) +def route_list_generations( + feature: str, handler: AppHandler = Depends(get_state_service) +) -> list[Generation]: + return handler.queued_generations.list_generations(feature) + + +@router.get( + "/generations/recent-features", + response_model=list[str], + tags=["generations"], +) +def route_list_recent_features( + limit: int = Query(default=4, ge=1, le=20), + handler: AppHandler = Depends(get_state_service), +) -> list[str]: + """Distinct Explore features, newest generation first. Same list as remote.""" + return handler.queued_generations.list_recent_features( + limit=limit, + allowed=QUEUED_GENERATION_FEATURES, + ) + + +@router.get( + "/generations/{generation_id}", + response_model=Generation, + tags=["generations"], +) +def route_get_generation( + generation_id: str, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.get_generation(generation_id) + + +@router.post( + "/generations/{generation_id}/retry", + response_model=Generation, + tags=["generations"], +) +def route_retry_generation( + generation_id: str, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.retry_generation(generation_id) + + +@router.post( + "/generations/{generation_id}/cancel", + response_model=Generation, + tags=["generations"], +) +def route_cancel_generation( + generation_id: str, handler: AppHandler = Depends(get_state_service) +) -> Generation: + return handler.queued_generations.cancel_generation(generation_id) + + +@router.delete( + "/generations/{generation_id}", + response_model=StatusResponse, + tags=["generations"], +) +def route_delete_generation( + generation_id: str, handler: AppHandler = Depends(get_state_service) +) -> StatusResponse: + handler.queued_generations.delete_generation(generation_id) + return StatusResponse(status="ok") diff --git a/backend/_routes/ic_lora.py b/backend/_routes/ic_lora.py index f6ae4904a..a0f27628d 100644 --- a/backend/_routes/ic_lora.py +++ b/backend/_routes/ic_lora.py @@ -4,12 +4,18 @@ from fastapi import APIRouter, Depends +from _routes._analytics import ( + desktop_generation_details, + pixel_resolution, + run_tracked_generation, +) from api_types import ( IcLoraExtractRequest, IcLoraExtractResponse, IcLoraGenerateRequest, IcLoraGenerateResponse, ) +from services.services_utils import JSONValue from state import get_state_service from app_handler import AppHandler @@ -29,4 +35,34 @@ def route_ic_lora_generate( req: IcLoraGenerateRequest, handler: AppHandler = Depends(get_state_service), ) -> IcLoraGenerateResponse: - return handler.ic_lora.generate(req) + metadata: dict[str, JSONValue] = {} + if req.resolution is not None: + metadata["resolution"] = pixel_resolution( + req.resolution.width, req.resolution.height + ) + if req.fps_override is not None: + metadata["fps"] = req.fps_override + duration = req.control_values.get("duration") + if isinstance(duration, int): + metadata["duration_sec"] = duration + metadata["prompt_provenance"] = handler.prompt_enhancement.preview_prompt_provenance( + req.prompt, + provenance=req.prompt_provenance, + explore_generation=False, + ) + if req.ic_lora_id is not None: + metadata["lora_catalog_ids"] = [req.ic_lora_id] + elif req.custom_lora_ref is not None: + metadata["has_custom_lora"] = True + details = desktop_generation_details( + surface="genspace", + feature="ic-lora", + kind="video", + execution="local", + **metadata, + ) + return run_tracked_generation( + handler.analytics, + details, + lambda: handler.ic_lora.generate(req), + ) diff --git a/backend/_routes/image_gen.py b/backend/_routes/image_gen.py index 4536079a3..d5c2deadf 100644 --- a/backend/_routes/image_gen.py +++ b/backend/_routes/image_gen.py @@ -4,6 +4,12 @@ from fastapi import APIRouter, Depends +from _routes._analytics import ( + desktop_generation_details, + image_execution, + pixel_resolution, + run_tracked_generation, +) from api_types import GenerateImageRequest, GenerateImageResponse from state import get_state_service from app_handler import AppHandler @@ -17,5 +23,20 @@ def route_generate_image( handler: AppHandler = Depends(get_state_service), ) -> GenerateImageResponse: """POST /api/generate-image.""" - return handler.image_generation.generate(req) + details = desktop_generation_details( + surface="genspace", + feature="image-to-image" if req.imagePath else "text-to-image", + kind="image", + execution=image_execution( + force_api_generations=handler.config.force_api_generations, + settings=handler.state.app_settings, + ), + resolution=pixel_resolution(req.width, req.height), + output_count=req.numImages, + ) + return run_tracked_generation( + handler.analytics, + details, + lambda: handler.image_generation.generate(req), + ) diff --git a/backend/_routes/lora_catalog.py b/backend/_routes/lora_catalog.py index 9f2cdd64c..5615bfaa9 100644 --- a/backend/_routes/lora_catalog.py +++ b/backend/_routes/lora_catalog.py @@ -3,13 +3,18 @@ from fastapi import APIRouter, Depends, Query from api_types import ( + ActiveIcLoraDownloadResponse, + ActiveLoraDownloadResponse, CatalogDownloadStartResponse, + IcLoraDeleteRequest, IcLoraDownloadProgressResponse, IcLoraDownloadRequest, IcLoraListResponse, + LoraDeleteRequest, LoraDownloadProgressResponse, LoraDownloadRequest, LoraListResponse, + StatusResponse, ) from app_handler import AppHandler from state import get_state_service @@ -23,8 +28,11 @@ # --- Plain LoRAs --- @router.get("/loras", response_model=LoraListResponse, tags=["loras"]) -def route_list_loras(handler: AppHandler = Depends(get_state_service)) -> LoraListResponse: - return handler.catalog.list_loras() +def route_list_loras( + fresh: bool = Query(default=False), + handler: AppHandler = Depends(get_state_service), +) -> LoraListResponse: + return handler.catalog.list_loras(fresh=fresh) @router.post("/loras/download", response_model=CatalogDownloadStartResponse, tags=["loras"]) @@ -45,10 +53,29 @@ def route_lora_download_progress( return handler.catalog.get_lora_download_progress(sessionId) +@router.get("/loras/download/active", response_model=ActiveLoraDownloadResponse, tags=["loras"]) +def route_lora_download_active( + handler: AppHandler = Depends(get_state_service), +) -> ActiveLoraDownloadResponse: + return handler.catalog.get_active_lora_download() + + +@router.delete("/loras/installation", response_model=StatusResponse, tags=["loras"]) +def route_delete_lora_installation( + req: LoraDeleteRequest, + handler: AppHandler = Depends(get_state_service), +) -> StatusResponse: + handler.catalog.delete_lora(req.lora_id, variant_id=req.variant_id) + return StatusResponse(status="ok") + + # --- IC-LoRAs --- @router.get("/ic-loras", response_model=IcLoraListResponse, tags=["ic-loras"]) -def route_list_ic_loras(handler: AppHandler = Depends(get_state_service)) -> IcLoraListResponse: - return handler.catalog.list_ic_loras() +def route_list_ic_loras( + fresh: bool = Query(default=False), + handler: AppHandler = Depends(get_state_service), +) -> IcLoraListResponse: + return handler.catalog.list_ic_loras(fresh=fresh) @router.post("/ic-loras/download", response_model=CatalogDownloadStartResponse, tags=["ic-loras"]) @@ -67,3 +94,21 @@ def route_ic_lora_download_progress( handler: AppHandler = Depends(get_state_service), ) -> IcLoraDownloadProgressResponse: return handler.catalog.get_ic_lora_download_progress(sessionId) + + +@router.get( + "/ic-loras/download/active", response_model=ActiveIcLoraDownloadResponse, tags=["ic-loras"] +) +def route_ic_lora_download_active( + handler: AppHandler = Depends(get_state_service), +) -> ActiveIcLoraDownloadResponse: + return handler.catalog.get_active_ic_lora_download() + + +@router.delete("/ic-loras/installation", response_model=StatusResponse, tags=["ic-loras"]) +def route_delete_ic_lora_installation( + req: IcLoraDeleteRequest, + handler: AppHandler = Depends(get_state_service), +) -> StatusResponse: + handler.catalog.delete_ic_lora(req.ic_lora_id, variant_id=req.variant_id) + return StatusResponse(status="ok") diff --git a/backend/_routes/models.py b/backend/_routes/models.py index 7d74823a1..4725dcbad 100644 --- a/backend/_routes/models.py +++ b/backend/_routes/models.py @@ -41,13 +41,29 @@ def route_list_models( @router.get("/models/ltx-recommendation", response_model=LtxRecommendationResponse) -def route_ltx_recommendation(handler: AppHandler = Depends(get_state_service)) -> LtxRecommendationResponse: - return handler.models.get_ltx_recommendation() +def route_ltx_recommendation( + fresh: bool = Query(default=False), + include_installed: bool = Query( + default=False, + description=( + "Full checkpoint sets for the model the live recommendation would download, " + "including files already on disk. Does not switch to the latest model. " + "Ignored when fresh is set." + ), + ), + handler: AppHandler = Depends(get_state_service), +) -> LtxRecommendationResponse: + return handler.models.get_ltx_recommendation( + fresh=fresh, include_installed=include_installed + ) @router.get("/models/img-gen-recommendation", response_model=ImageGenRecommendationResponse) -def route_img_gen_recommendation(handler: AppHandler = Depends(get_state_service)) -> ImageGenRecommendationResponse: - return handler.models.get_img_gen_recommendation() +def route_img_gen_recommendation( + fresh: bool = Query(default=False), + handler: AppHandler = Depends(get_state_service), +) -> ImageGenRecommendationResponse: + return handler.models.get_img_gen_recommendation(fresh=fresh) @router.get("/models/ltx-ic-lora-recommendation", response_model=LtxIcLoraRecommendationResponse) diff --git a/backend/_routes/prompt_enhancement.py b/backend/_routes/prompt_enhancement.py index d55031a8a..87cb4e930 100644 --- a/backend/_routes/prompt_enhancement.py +++ b/backend/_routes/prompt_enhancement.py @@ -1,20 +1,35 @@ -"""Route handlers for /api/enhance-prompt.""" +"""Route handlers for /api/enhance-prompt and /api/prompt-enhancer.""" from __future__ import annotations from fastapi import APIRouter, Depends -from api_types import EnhancePromptRequest, EnhancePromptResponse -from state import get_state_service +from api_types import ( + EnhancePromptRequest, + EnhancePromptResponse, + PromptEnhancerStatusResponse, +) from app_handler import AppHandler +from services.prompt_enhancement.resolve_enhance_assets import resolve_enhance_image_assets +from state import get_state_service router = APIRouter(prefix="/api", tags=["prompt-enhancement"]) +@router.get("/prompt-enhancer", response_model=PromptEnhancerStatusResponse) +def route_prompt_enhancer( + handler: AppHandler = Depends(get_state_service), +) -> PromptEnhancerStatusResponse: + """GET /api/prompt-enhancer.""" + return handler.prompt_enhancement.status(prefer_gemini=False) + + @router.post("/enhance-prompt", response_model=EnhancePromptResponse) def route_enhance_prompt( req: EnhancePromptRequest, handler: AppHandler = Depends(get_state_service), ) -> EnhancePromptResponse: """POST /api/enhance-prompt.""" - return handler.prompt_enhancement.enhance(req) + return handler.prompt_enhancement.enhance( + resolve_enhance_image_assets(handler.assets, req) + ) diff --git a/backend/_routes/remote.py b/backend/_routes/remote.py new file mode 100644 index 000000000..0b7c85f82 --- /dev/null +++ b/backend/_routes/remote.py @@ -0,0 +1,55 @@ +"""Desktop-only remote exposure status and paired-device control. + +Part of the desktop OpenAPI contract so Settings can share a typed status payload. +Not mounted on the remote phone app. +""" + +from __future__ import annotations + +from fastapi import APIRouter, Request + +from _routes._errors import HTTPError +from api_types import StatusResponse +from remote.controller import remote_controller_from_app +from remote.pairing import PairedDevicePublic +from remote.status import RemoteStatusResponse +from services.records import UnavailableError + +router = APIRouter(prefix="/api", tags=["remote"]) + + +@router.get("/remote/status", response_model=RemoteStatusResponse) +def route_remote_status(request: Request) -> RemoteStatusResponse: + controller = remote_controller_from_app(request.app) + if controller is None: + return RemoteStatusResponse( + permitted=False, + serving=False, + reason="remote controller is not initialized", + ) + return controller.status() + + +@router.get("/remote/devices", response_model=list[PairedDevicePublic]) +def route_list_remote_devices(request: Request) -> list[PairedDevicePublic]: + controller = remote_controller_from_app(request.app) + if controller is None: + return [] + try: + return controller.list_devices() + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + + +@router.post("/remote/devices/{device_id}/revoke", response_model=StatusResponse) +def route_revoke_remote_device(device_id: str, request: Request) -> StatusResponse: + controller = remote_controller_from_app(request.app) + if controller is None: + raise HTTPError(404, "DEVICE_NOT_FOUND") + try: + revoked = controller.revoke_device(device_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + if not revoked: + raise HTTPError(404, "DEVICE_NOT_FOUND") + return StatusResponse(status="ok") diff --git a/backend/_routes/retake.py b/backend/_routes/retake.py index 8618cc074..a9e834032 100644 --- a/backend/_routes/retake.py +++ b/backend/_routes/retake.py @@ -4,7 +4,14 @@ from fastapi import APIRouter, Depends +from _routes._analytics import ( + desktop_generation_details, + pixel_resolution, + run_tracked_generation, + video_execution, +) from api_types import RetakeRequest, RetakeResponse +from services.analytics import unenhanced_prompt_provenance from state import get_state_service from app_handler import AppHandler @@ -13,4 +20,25 @@ @router.post("/retake", response_model=RetakeResponse) def route_retake(req: RetakeRequest, handler: AppHandler = Depends(get_state_service)) -> RetakeResponse: - return handler.retake.run(req) + details = desktop_generation_details( + surface="genspace", + feature="retake", + kind="video", + execution=video_execution( + force_api_generations=handler.config.force_api_generations, + settings=handler.state.app_settings, + ), + model=req.model, + duration_sec=req.duration, + prompt_provenance=unenhanced_prompt_provenance(req.prompt_provenance), + **( + {"resolution": pixel_resolution(req.resolution.width, req.resolution.height)} + if req.resolution is not None + else {} + ), + ) + return run_tracked_generation( + handler.analytics, + details, + lambda: handler.retake.run(req), + ) diff --git a/backend/_routes/settings.py b/backend/_routes/settings.py index fad2bb5bd..12e976fe3 100644 --- a/backend/_routes/settings.py +++ b/backend/_routes/settings.py @@ -9,6 +9,7 @@ from _routes._admin_guard import guard_admin_permission from state.app_settings import SettingsResponse, UpdateSettingsRequest, to_settings_response from api_types import GeminiModelsResponsePayload, StatusResponse +from remote.controller import remote_controller_from_app from state import get_state_service from app_handler import AppHandler @@ -45,6 +46,11 @@ def route_post_settings( if "use_conv_vae" in changed_roots: handler.pipelines.unload_gpu_pipeline() + if "remote_exposure" in changed_roots: + controller = remote_controller_from_app(request.app) + if controller is not None: + controller.sync() + return StatusResponse(status="ok") diff --git a/backend/_routes/stats.py b/backend/_routes/stats.py new file mode 100644 index 000000000..339b7078e --- /dev/null +++ b/backend/_routes/stats.py @@ -0,0 +1,48 @@ +from __future__ import annotations + +from typing import Literal + +from fastapi import APIRouter, Depends, Query + +from app_handler import AppHandler +from handlers.dashboard_handler import DashboardHandler +from services.dashboard_stats import DashboardSnapshot +from state import get_state_service +from state.app_settings import DashboardSelection, UpdateSettingsRequest + +router = APIRouter(prefix="/api") +phone_stats_router = APIRouter(prefix="/api") + + +def _dashboard(handler: AppHandler) -> DashboardHandler: + return handler.dashboard + + +@router.get("/stats/dashboard", response_model=DashboardSnapshot, tags=["stats"]) +@phone_stats_router.get("/stats/dashboard", response_model=DashboardSnapshot, tags=["stats"]) +def route_dashboard( + tz: str = Query(min_length=1), + window: Literal["7d", "30d", "all"] = Query(alias="range"), + handler: AppHandler = Depends(get_state_service), +) -> DashboardSnapshot: + return _dashboard(handler).get(window=window, tz=tz) + + +@router.get("/stats/activity-dashboard-selections", response_model=DashboardSelection, tags=["stats"]) +@phone_stats_router.get("/stats/activity-dashboard-selections", response_model=DashboardSelection, tags=["stats"]) +def route_get_dashboard_selection( + handler: AppHandler = Depends(get_state_service), +) -> DashboardSelection: + return handler.settings.get_settings_snapshot().activity_dashboard_selections + + +@router.post("/stats/activity-dashboard-selections", response_model=DashboardSelection, tags=["stats"]) +@phone_stats_router.post("/stats/activity-dashboard-selections", response_model=DashboardSelection, tags=["stats"]) +def route_post_dashboard_selection( + body: DashboardSelection, + handler: AppHandler = Depends(get_state_service), +) -> DashboardSelection: + handler.settings.update_settings( + UpdateSettingsRequest.model_validate({"activity_dashboard_selections": body.model_dump()}) + ) + return handler.settings.get_settings_snapshot().activity_dashboard_selections diff --git a/backend/api_model_specs.py b/backend/api_model_specs.py index 537d8eaa7..a3d7e0104 100644 --- a/backend/api_model_specs.py +++ b/backend/api_model_specs.py @@ -2,7 +2,11 @@ from __future__ import annotations +from pathlib import Path +from typing import Literal, cast + from api_types import ( + DownloadedLocalVideoGenerationModelSpecItem, GenerateVideoModelsSpecsResponse, GenerateVideoRequest, LTXLocalModelId, @@ -10,14 +14,34 @@ LTXVideoGenerationModelSpecItem, LTXVideoGenerationResolutionSpec, LTXVideoGenerationSpec, + LTXVideoGenAspectRatio, LTXVideoGenDuration, LTXVideoGenFps, LTXVideoGenPipeline, LTXVideoGenResolution, ) from keyframe_request import validate_keyframe_inputs -from runtime_config.ltx_capabilities import LtxOfferingCapabilities, api_caps, effective_local_caps -from runtime_config.model_download_specs import get_latest_ltx_model_id, get_ltx_model_spec +from runtime_config.ltx_capabilities import ( + CanvasMode, + LtxOfferingCapabilities, + api_caps, + budget_size, + effective_local_caps, + local_canvas, + pixels_for, +) +from runtime_config.offerings import ( + OFFERING_IDS, + offering_id_for_local_model_id, + resolve_offering_local_model_id, +) +from runtime_config.model_download_specs import ( + get_latest_ltx_model_id, + get_ltx_model_spec, + is_duration_head_ready, +) +from runtime_config.runtime_policy import LocalGenerationMode +from runtime_config.video_job_budget import advertised_fast_durations from server_utils.media_validation import normalize_optional_path # The concrete ltxv-api model id each Desktop-facing pipeline maps to when forced onto @@ -61,46 +85,62 @@ } -def _resolution_spec(fps_to_durations: _ApiFpsDurationMap) -> LTXVideoGenerationResolutionSpec: +# 2.3 generate is 16:9/9:16. 2.5 adds 1:1 and 3:2. 21:9, 4:3, and 4:5 are local-only. +_API_ASPECT_RATIOS_2_3: tuple[LTXVideoGenAspectRatio, ...] = ("16:9", "9:16") +_API_ASPECT_RATIOS_2_5: tuple[LTXVideoGenAspectRatio, ...] = ("16:9", "3:2", "1:1", "9:16") + + +def _resolution_spec( + fps_to_durations: _ApiFpsDurationMap, + aspect_ratios: tuple[LTXVideoGenAspectRatio, ...], +) -> LTXVideoGenerationResolutionSpec: return LTXVideoGenerationResolutionSpec( fps_to_durations={ fps: list(durations) for fps, durations in fps_to_durations.items() }, + aspect_ratios=list(aspect_ratios), ) -_API_STANDARD_RESOLUTION = _resolution_spec(_API_FPS_STANDARD) -_API_EXTENDED_RESOLUTION = _resolution_spec(_API_FPS_EXTENDED) -_API_PRO_2_5_RESOLUTION = _resolution_spec(_API_FPS_PRO_2_5) +def _resolution_map( + cells: dict[LTXVideoGenResolution, _ApiFpsDurationMap], + aspect_ratios: tuple[LTXVideoGenAspectRatio, ...], +) -> _ApiResolutionMap: + return { + resolution: _resolution_spec(fps_to_durations, aspect_ratios) + for resolution, fps_to_durations in cells.items() + } + # Fast t2v/i2v: 720p/1080p get 20s at 24/25; 1440p/4K stay at 10s. -_API_FAST_RESOLUTIONS: _ApiResolutionMap = { - "720p": _API_EXTENDED_RESOLUTION, - "1080p": _API_EXTENDED_RESOLUTION, - "1440p": _API_STANDARD_RESOLUTION, - "2160p": _API_STANDARD_RESOLUTION, +_API_FAST_CELLS: dict[LTXVideoGenResolution, _ApiFpsDurationMap] = { + "720p": _API_FPS_EXTENDED, + "1080p": _API_FPS_EXTENDED, + "1440p": _API_FPS_STANDARD, + "2160p": _API_FPS_STANDARD, } # Pro 2.3 t2v/i2v: 10s at every fps and resolution, including 720p. -_API_PRO_RESOLUTIONS: _ApiResolutionMap = { - "720p": _API_STANDARD_RESOLUTION, - "1080p": _API_STANDARD_RESOLUTION, - "1440p": _API_STANDARD_RESOLUTION, - "2160p": _API_STANDARD_RESOLUTION, +_API_PRO_CELLS: dict[LTXVideoGenResolution, _ApiFpsDurationMap] = { + "720p": _API_FPS_STANDARD, + "1080p": _API_FPS_STANDARD, + "1440p": _API_FPS_STANDARD, + "2160p": _API_FPS_STANDARD, } -# Pro 2.5 t2v/i2v/a2v: 720p+1080p, 24/25/50, 10s. No 48 fps, no 1440p/4K. -_API_PRO_2_5_RESOLUTIONS: _ApiResolutionMap = { - "720p": _API_PRO_2_5_RESOLUTION, - "1080p": _API_PRO_2_5_RESOLUTION, -} -# A2V for Pro 2.3 / Fast 2.5: 20s audio at 720p/1080p, 10s at 1440p/4K. -_API_A2V_RESOLUTIONS: _ApiResolutionMap = { - "720p": _API_EXTENDED_RESOLUTION, - "1080p": _API_EXTENDED_RESOLUTION, - "1440p": _API_STANDARD_RESOLUTION, - "2160p": _API_STANDARD_RESOLUTION, +# Pro 2.5 t2v/i2v: 720p+1080p, 24/25/50, 10s. No 48 fps, no 1440p/4K. +_API_PRO_2_5_CELLS: dict[LTXVideoGenResolution, _ApiFpsDurationMap] = { + "720p": _API_FPS_PRO_2_5, + "1080p": _API_FPS_PRO_2_5, } +_API_FAST_RESOLUTIONS = _resolution_map(_API_FAST_CELLS, _API_ASPECT_RATIOS_2_3) +_API_FAST_25_RESOLUTIONS = _resolution_map(_API_FAST_CELLS, _API_ASPECT_RATIOS_2_5) +_API_PRO_RESOLUTIONS = _resolution_map(_API_PRO_CELLS, _API_ASPECT_RATIOS_2_3) +_API_PRO_2_5_RESOLUTIONS = _resolution_map(_API_PRO_2_5_CELLS, _API_ASPECT_RATIOS_2_5) +# A2V stays 16:9/9:16 even on 2.5. 20s audio at 720p/1080p, 10s at 1440p/4K. +_API_A2V_RESOLUTIONS = _resolution_map(_API_FAST_CELLS, _API_ASPECT_RATIOS_2_3) +_API_PRO_2_5_A2V_RESOLUTIONS = _resolution_map(_API_PRO_2_5_CELLS, _API_ASPECT_RATIOS_2_3) + ltx_api_model_specs: tuple[tuple[LTXVideoGenPipeline, LTXVideoGenerationSpec], ...] = ( ( @@ -123,7 +163,7 @@ def _resolution_spec(fps_to_durations: _ApiFpsDurationMap) -> LTXVideoGeneration "fast-2.5", LTXVideoGenerationSpec( display_name="LTX-2.5 Fast (API)", - supported_resolutions_durations=_API_FAST_RESOLUTIONS, + supported_resolutions_durations=_API_FAST_25_RESOLUTIONS, a2v_supported_resolutions_durations=_API_A2V_RESOLUTIONS, ), ), @@ -132,12 +172,28 @@ def _resolution_spec(fps_to_durations: _ApiFpsDurationMap) -> LTXVideoGeneration LTXVideoGenerationSpec( display_name="LTX-2.5 Pro (API)", supported_resolutions_durations=_API_PRO_2_5_RESOLUTIONS, - a2v_supported_resolutions_durations=_API_PRO_2_5_RESOLUTIONS, + a2v_supported_resolutions_durations=_API_PRO_2_5_A2V_RESOLUTIONS, ), ), ) +def forced_api_resolution_map() -> dict[str, dict[str, dict[str, str]]]: + """Pipeline → resolution label → aspect → WxH, taken from each API spec cell.""" + mapped: dict[str, dict[str, dict[str, str]]] = {} + for pipeline, spec in ltx_api_model_specs: + caps = api_caps(pipeline) + by_resolution: dict[str, dict[str, str]] = {} + for resolution, cell in spec.supported_resolutions_durations.items(): + by_resolution[resolution] = { + aspect: f"{width}x{height}" + for aspect in cell.aspect_ratios + for width, height in (pixels_for(caps, resolution, aspect),) + } + mapped[pipeline] = by_resolution + return mapped + + def _capabilities_spec(caps: LtxOfferingCapabilities) -> LTXOfferingCapabilitiesSpec: return LTXOfferingCapabilitiesSpec( t2v=caps.t2v, @@ -172,18 +228,106 @@ def _item_with_caps( ) +def _filter_local_fast_resolution_map( + specs: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None, + caps: LtxOfferingCapabilities, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool, + mode: CanvasMode = "video", +) -> dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None: + if specs is None: + return None + if process_mode == "unsupported": + return {} + filtered: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] = {} + for resolution, spec in specs.items(): + if resolution not in caps.resolution_pixels_16_9: + raise KeyError(resolution) + width, height = budget_size(local_canvas(resolution, mode=mode)) + fps_to_durations: dict[LTXVideoGenFps, list[LTXVideoGenDuration]] = {} + for fps, durations in spec.fps_to_durations.items(): + kept = advertised_fast_durations( + width, + height, + int(fps), + durations, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + if kept: + fps_to_durations[fps] = cast(list[LTXVideoGenDuration], kept) + if fps_to_durations: + filtered[resolution] = LTXVideoGenerationResolutionSpec( + fps_to_durations=fps_to_durations, + aspect_ratios=list(spec.aspect_ratios), + ) + return filtered + + +def _filter_local_fast_item( + item: LTXVideoGenerationModelSpecItem, + caps: LtxOfferingCapabilities, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool, +) -> LTXVideoGenerationModelSpecItem: + spec = item.spec + return item.model_copy( + update={ + "spec": spec.model_copy( + update={ + "supported_resolutions_durations": _filter_local_fast_resolution_map( + spec.supported_resolutions_durations, + caps, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ), + "a2v_supported_resolutions_durations": _filter_local_fast_resolution_map( + spec.a2v_supported_resolutions_durations, + caps, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + mode="a2v", + ), + } + ) + } + ) + + def get_local_video_generation_model_specs( model_id: LTXLocalModelId | None = None, *, duration_head_ready: bool = False, + memory_gb: float | None = None, + process_mode: LocalGenerationMode | None = None, + darwin: bool = False, ) -> list[LTXVideoGenerationModelSpecItem]: resolved_id = model_id or get_latest_ltx_model_id() local_model_spec = get_ltx_model_spec(resolved_id) caps = effective_local_caps(resolved_id, duration_head_ready=duration_head_ready) - return [ + items = [ _item_with_caps(pipeline, spec, caps) for pipeline, spec in local_model_spec.supported_pipelines ] + if process_mode is None: + return items + return [ + _filter_local_fast_item( + item, + caps, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + for item in items + ] def get_api_video_generation_model_specs() -> list[LTXVideoGenerationModelSpecItem]: @@ -194,16 +338,71 @@ def get_api_video_generation_model_specs() -> list[LTXVideoGenerationModelSpecIt ] +def get_downloaded_local_video_generation_model_specs( + models_dir: Path, + *, + memory_gb: float | None = None, + process_mode: LocalGenerationMode | None = None, + darwin: bool = False, +) -> list[DownloadedLocalVideoGenerationModelSpecItem]: + items: list[DownloadedLocalVideoGenerationModelSpecItem] = [] + for offering in OFFERING_IDS: + model_id = resolve_offering_local_model_id(models_dir, offering) + if model_id is None: + continue + for local_item in get_local_video_generation_model_specs( + model_id, + duration_head_ready=is_duration_head_ready(models_dir, model_id), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ): + items.append( + DownloadedLocalVideoGenerationModelSpecItem( + model=offering, + pipeline=local_item.pipeline, + spec=local_item.spec, + ) + ) + return items + + def build_generate_video_model_specs_response( local_model_id: LTXLocalModelId | None = None, *, + models_dir: Path | None = None, duration_head_ready: bool = False, + memory_gb: float | None = None, + process_mode: LocalGenerationMode | None = None, + darwin: bool = False, + low_performance_machine: bool = False, ) -> GenerateVideoModelsSpecsResponse: + downloaded = ( + get_downloaded_local_video_generation_model_specs( + models_dir, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + if models_dir is not None + else [] + ) return GenerateVideoModelsSpecsResponse( local_models=get_local_video_generation_model_specs( - local_model_id, duration_head_ready=duration_head_ready + local_model_id, + duration_head_ready=duration_head_ready, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, ), api_models=get_api_video_generation_model_specs(), + downloaded_local_models=downloaded, + active_offering=( + offering_id_for_local_model_id(local_model_id) + if local_model_id is not None + else None + ), + low_performance_machine=low_performance_machine, ) @@ -249,6 +448,36 @@ def supported_duration_range( return min(durations), max(durations) +VideoGenerationFeature = Literal[ + "multi-keyframe", + "audio-to-video", + "image-to-video", + "text-to-video", +] + + +def video_generation_feature( + *, + audio_path: str | None, + image_path: str | None, + last_image_path: str | None = None, + keyframes: object = None, +) -> VideoGenerationFeature: + """User-facing mode. Keyframes win, then audio, then a still. + + Same order as ``videoGenerationModeFromInputs`` in the frontend. Validation + error text and analytics feature names both use this so a keyframe job is + not recorded as image-to-video. + """ + if keyframes: + return "multi-keyframe" + if audio_path: + return "audio-to-video" + if image_path or last_image_path: + return "image-to-video" + return "text-to-video" + + def validate_generate_video_request( req: GenerateVideoRequest, *, @@ -268,10 +497,11 @@ def validate_generate_video_request( image_path = normalize_optional_path(req.imagePath) last_image_path = normalize_optional_path(req.lastImagePath) audio_path = normalize_optional_path(req.audioPath) - generation_mode = ( - "audio-to-video" if audio_path is not None - else "image-to-video" if image_path is not None or req.keyframes - else "text-to-video" + generation_mode = video_generation_feature( + audio_path=audio_path, + image_path=image_path, + last_image_path=last_image_path, + keyframes=req.keyframes, ) keyframe_error = validate_keyframe_inputs( @@ -303,6 +533,12 @@ def validate_generate_video_request( f"for pipeline '{req.model}'" ) + if req.aspectRatio not in resolution_spec.aspect_ratios: + return ( + f"Unsupported {generation_backend} {generation_mode} aspect ratio '{req.aspectRatio}' " + f"for pipeline '{req.model}' at resolution '{req.resolution}'" + ) + if req.fps not in resolution_spec.fps_to_durations: return ( f"Unsupported {generation_backend} {generation_mode} fps '{req.fps}' " diff --git a/backend/api_types.py b/backend/api_types.py index 8f004fff1..e634ec545 100644 --- a/backend/api_types.py +++ b/backend/api_types.py @@ -3,12 +3,23 @@ from __future__ import annotations import re -from typing import Annotated -from typing import Literal, NamedTuple, TypeAlias - -from pydantic import BaseModel, ConfigDict, Field, JsonValue, StringConstraints, field_validator, model_validator +from typing import Annotated, Literal, NamedTuple, Self, TypeAlias, cast + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + JsonValue, + StringConstraints, + field_validator, + model_serializer, + model_validator, + SerializerFunctionWrapHandler, +) from frame_math import compute_num_frames +from runtime_config.ic_lora_stage_mode import IcLoraStageMode, ic_lora_stage_mode +from runtime_config.ic_lora_tiling import IcLoraTiling NonEmptyPrompt = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1)] ModelCheckpointID = Literal[ @@ -36,6 +47,9 @@ "ltx-2.3-22b-distilled-1.1", "ltx-2.3-22b-distilled", ] +# T2V/I2V/A2V/LoRA create-body `params.model`. Not a GenSpace pipeline (`fast`) +# and not a checkpoint id. Future API rows (`ltx-2.5-pro`, …) join this union. +OfferingId = Literal["ltx-2.3-fast", "ltx-2.5-fast"] class ImageConditioningInput(NamedTuple): @@ -98,6 +112,7 @@ class GpuInfoResponse(BaseModel): class MpsMemoryResponse(BaseModel): """Read-only Apple Silicon MPS memory snapshot, MiB. Fields are None off MPS.""" + available: bool allocated_mib: int | None = None driver_mib: int | None = None @@ -106,6 +121,23 @@ class MpsMemoryResponse(BaseModel): class RuntimePolicyResponse(BaseModel): force_api_generations: bool + local_viable: bool + + +class FeatureFlags(BaseModel): + """Dev feature flags, persisted in feature_flags.json. Adding a flag = one field here.""" + + customIcLora: bool = False + advancedIcLoraControls: bool = False + + +class FeatureFlagsPatch(BaseModel): + """Partial update: only the fields present in the body are applied.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + customIcLora: bool | None = None + advancedIcLoraControls: bool | None = None class GenerationProgressResponse(BaseModel): @@ -149,7 +181,9 @@ class DownloadProgressErrorResponse(BaseModel): DownloadProgressResponse: TypeAlias = ( - DownloadProgressRunningResponse | DownloadProgressCompleteResponse | DownloadProgressErrorResponse + DownloadProgressRunningResponse + | DownloadProgressCompleteResponse + | DownloadProgressErrorResponse ) @@ -167,7 +201,9 @@ class GenerateVideoCancelledResponse(BaseModel): status: Literal["cancelled"] -GenerateVideoResponse: TypeAlias = GenerateVideoCompleteResponse | GenerateVideoCancelledResponse +GenerateVideoResponse: TypeAlias = ( + GenerateVideoCompleteResponse | GenerateVideoCancelledResponse +) class GenerateImageCompleteResponse(BaseModel): @@ -179,7 +215,9 @@ class GenerateImageCancelledResponse(BaseModel): status: Literal["cancelled"] -GenerateImageResponse: TypeAlias = GenerateImageCompleteResponse | GenerateImageCancelledResponse +GenerateImageResponse: TypeAlias = ( + GenerateImageCompleteResponse | GenerateImageCancelledResponse +) class CancelCancellingResponse(BaseModel): @@ -208,7 +246,9 @@ class RetakeCancelledResponse(BaseModel): status: Literal["cancelled"] -RetakeResponse: TypeAlias = RetakeVideoResponse | RetakePayloadResponse | RetakeCancelledResponse +RetakeResponse: TypeAlias = ( + RetakeVideoResponse | RetakePayloadResponse | RetakeCancelledResponse +) class IcLoraExtractResponse(BaseModel): @@ -227,7 +267,9 @@ class IcLoraGenerateCancelledResponse(BaseModel): status: Literal["cancelled"] -IcLoraGenerateResponse: TypeAlias = IcLoraGenerateCompleteResponse | IcLoraGenerateCancelledResponse +IcLoraGenerateResponse: TypeAlias = ( + IcLoraGenerateCompleteResponse | IcLoraGenerateCancelledResponse +) # ============================================================ @@ -273,6 +315,10 @@ class LtxDownloadRecommendationResponse(BaseModel): # Offered as an opt-in so a user who wants to generate offline can take the download now # instead of discovering later that the key is the only thing making generation work. optional_cp_ids: list[ModelCheckpointID] = [] + # Quality extras recommended for the bundle being installed (currently 2.5's preferred + # Gemma 4 E2B enhancer). Distinct from required and from API-excused optional_cp_ids. + # Missing or skipped items must not block app entry or generation. + recommended_quality_cp_ids: list[ModelCheckpointID] = [] class LtxUpgradeRecommendationResponse(BaseModel): @@ -282,9 +328,10 @@ class LtxUpgradeRecommendationResponse(BaseModel): cps_to_download: list[ModelCheckpointID] cps_to_delete: list[ModelCheckpointID] # True when deleting the old bundle would also remove built-in Union Control IC-LoRA - # (2.3 → 2.5). The upgrade UI defaults "delete old" off in that case so users don't - # silently lose the easy path back to depth/canny/pose control. + # that the target model does not share. The upgrade UI defaults "delete old" off so + # users don't silently lose the easy path back to depth/canny/pose control. loses_built_in_control: bool = False + recommended_quality_cp_ids: list[ModelCheckpointID] = [] class LtxOkRecommendationResponse(BaseModel): @@ -292,7 +339,9 @@ class LtxOkRecommendationResponse(BaseModel): LtxRecommendationResponse: TypeAlias = ( - LtxDownloadRecommendationResponse | LtxUpgradeRecommendationResponse | LtxOkRecommendationResponse + LtxDownloadRecommendationResponse + | LtxUpgradeRecommendationResponse + | LtxOkRecommendationResponse ) @@ -302,7 +351,7 @@ class ImageGenRecommendationResponse(BaseModel): class LtxIcLoraRecommendationResponse(BaseModel): cps_to_download: list[ModelCheckpointID] - # False when the active model has no built-in Union Control IC-LoRA (LTX 2.5): distinct from + # False when the active model has no built-in Union Control IC-LoRA: distinct from # "supported but already downloaded" (both have empty cps_to_download). supported: bool = True @@ -325,6 +374,13 @@ class TextEncoderRecommendationResponse(BaseModel): # The checkpoint Enhance will actually load, after E2B-then-Gemma-3 fallback. None if local # Enhance cannot run. Equal to local_enhancer_cp when the preferred extra model is present. active_local_enhancer_cp: ModelCheckpointID | None + # Installed local text encoder for the active LTX model (for delete in Settings). None if missing. + active_local_text_encoder_cp: ModelCheckpointID | None = None + # Whether that encoder may actually be deleted right now. False while local encoding is the + # only way to encode for this model (no API encoding support, no API key, or the user chose + # the local encoder), in which case /api/models/delete protects it and Settings disables the + # action instead of offering a request that is guaranteed to 409. + local_text_encoder_removable: bool = False class LtxModelVersionItem(BaseModel): @@ -346,7 +402,7 @@ class SetActiveLtxModelRequest(BaseModel): model_id: LTXLocalModelId -CheckpointRole = Literal["base", "upscaler", "text_encoder", "vae", "image", "support"] +CheckpointRole = Literal["base", "upscaler", "text_encoder", "vae", "image", "support", "prompt_enhancer"] class CheckpointDescriptor(BaseModel): @@ -382,14 +438,21 @@ class LtxInsufficientFundsErrorResponse(BaseModel): # ============================================================ -LTXVideoGenResolution: TypeAlias = Literal["540p", "720p", "1080p", "1440p", "2160p"] +LTXVideoGenResolution: TypeAlias = Literal[ + "270p", "360p", "540p", "720p", "1080p", "1440p", "2160p" +] +LTXLocalA2VResolution: TypeAlias = Literal["270p", "360p", "540p", "720p", "1080p"] LTXVideoGenDuration: TypeAlias = Literal[2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 18, 20] LTXVideoGenFps: TypeAlias = Literal[24, 25, 48, 50] LTXVideoGenPipeline: TypeAlias = Literal["fast", "pro", "fast-2.5", "pro-2.5"] +# Widest to tallest. A cell advertises a subset of this; 2:3 is intentionally absent. +LTXVideoGenAspectRatio: TypeAlias = Literal["21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16"] +LTXQueuedAspectRatio: TypeAlias = Literal["auto", "21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16"] class LTXVideoGenerationResolutionSpec(BaseModel): fps_to_durations: dict[LTXVideoGenFps, list[LTXVideoGenDuration]] + aspect_ratios: list[LTXVideoGenAspectRatio] class LTXOfferingCapabilitiesSpec(BaseModel): @@ -410,8 +473,12 @@ class LTXOfferingCapabilitiesSpec(BaseModel): class LTXVideoGenerationSpec(BaseModel): display_name: str - supported_resolutions_durations: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] - a2v_supported_resolutions_durations: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None = None + supported_resolutions_durations: dict[ + LTXVideoGenResolution, LTXVideoGenerationResolutionSpec + ] + a2v_supported_resolutions_durations: ( + dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None + ) = None capabilities: LTXOfferingCapabilitiesSpec | None = None @@ -420,9 +487,26 @@ class LTXVideoGenerationModelSpecItem(BaseModel): spec: LTXVideoGenerationSpec +class DownloadedLocalVideoGenerationModelSpecItem(BaseModel): + """One downloaded offering. `local_models` stays active-pipeline-shaped.""" + + model: OfferingId + pipeline: LTXVideoGenPipeline + spec: LTXVideoGenerationSpec + + class GenerateVideoModelsSpecsResponse(BaseModel): local_models: list[LTXVideoGenerationModelSpecItem] api_models: list[LTXVideoGenerationModelSpecItem] + downloaded_local_models: list[DownloadedLocalVideoGenerationModelSpecItem] = Field( + default_factory=list[DownloadedLocalVideoGenerationModelSpecItem] + ) + # Settings-active checkpoint mapped to an offering id. Home prefers this over + # joining local_models[0].display_name to downloaded rows (both share pipeline fast). + active_offering: OfferingId | None = None + # The backend machine is slow for heavy local runs. The backend decides, so the + # desktop app and the Remote app show the same warnings. + low_performance_machine: bool = False class InstalledModelResponse(BaseModel): @@ -443,6 +527,24 @@ class LoraEntry(BaseModel): ref: str scale: float = Field(default=1.0, ge=0.0, le=4.0) + # Catalog id when this LoRA was picked from the library, so automatic enhancement can look + # up its trigger/instructions. Absent for a custom LoRA the user supplied themselves, which + # stays weights-only — the weights' filename is never matched against the catalog. + catalogId: str | None = None + # Catalog name at enqueue time. Kept after the LoRA leaves the catalog so + # the dashboard can still label the run. + displayName: str | None = None + # Checkpoint chosen at enqueue, next to scale, so a later variant can be told apart. + variantId: str | None = None + + @model_serializer(mode="wrap") + def _omit_unset_variant( + self, handler: SerializerFunctionWrapHandler + ) -> dict[str, JsonValue]: + data = cast("dict[str, JsonValue]", handler(self)) + if data.get("variantId") is None: + data.pop("variantId", None) + return data # Local Distilled offering cap. API pipelines stay at 0 via multi_keyframe=False. @@ -459,10 +561,18 @@ class KeyframeInput(BaseModel): strength: float = Field(default=1.0, ge=0.0, le=1.0) +# Where the submitted prompt came from. "typed" (the default for any client that omits it) is +# eligible for automatic enhancement; "enhanced" is the exact text a successful manual Enhance +# produced and the user chose to keep, so generation must submit it untouched rather than +# rewrite a rewrite. Editing the prompt returns it to "typed". +PromptProvenance: TypeAlias = Literal["typed", "enhanced"] + + class GenerateVideoRequest(BaseModel): model_config = ConfigDict(strict=True) - prompt: NonEmptyPrompt + prompt: Annotated[str, StringConstraints(strip_whitespace=True)] + promptProvenance: PromptProvenance = "typed" resolution: LTXVideoGenResolution = "1080p" model: LTXVideoGenPipeline = "fast" cameraMotion: VideoCameraMotion = "none" @@ -475,10 +585,16 @@ class GenerateVideoRequest(BaseModel): lastImagePath: str | None = None keyframes: list[KeyframeInput] = Field(default_factory=list[KeyframeInput]) audioPath: str | None = None - aspectRatio: Literal["16:9", "9:16"] = "16:9" + aspectRatio: LTXVideoGenAspectRatio = "16:9" seed: int | None = None loras: list[LoraEntry] = Field(default_factory=list[LoraEntry]) + @model_validator(mode="after") + def _require_prompt_or_start_image(self) -> "GenerateVideoRequest": + if not self.prompt.strip() and not (self.imagePath or "").strip(): + raise ValueError("Prompt is required unless an image is provided") + return self + class GenerateImageRequest(BaseModel): model_config = ConfigDict(strict=True) @@ -541,9 +657,11 @@ def _validate_input_image_mode(self) -> "SuggestGapPromptRequest": return self -RetakeMode: TypeAlias = Literal["replace_audio_and_video", "replace_video", "replace_audio"] +RetakeMode: TypeAlias = Literal[ + "replace_audio_and_video", "replace_video", "replace_audio" +] -# ltxv-api /v1/retake and /v2/extend accept ltx-2-pro / ltx-2-3-pro. Desktop maps +# ltxv-api /v2/retake and /v2/extend accept ltx-2-pro / ltx-2-3-pro. Desktop maps # those to pipeline "pro" — narrower than LTXVideoGenPipeline on purpose. RetakeExtendModel: TypeAlias = Literal["pro"] @@ -565,6 +683,7 @@ class RetakeRequest(BaseModel): start_time: float duration: float prompt: str = "" + prompt_provenance: PromptProvenance = "typed" mode: RetakeMode = "replace_audio_and_video" resolution: TargetResolution | None = None # API-mode only; ignored for local generation (there is no local model choice). @@ -582,6 +701,7 @@ class ExtendRequest(BaseModel): # slipping past the handler's min/max guards and blowing up in frame-count math. duration: float = Field(gt=0, allow_inf_nan=False) prompt: str = "" + prompt_provenance: PromptProvenance = "typed" mode: ExtendMode = "end" resolution: TargetResolution | None = None # API-mode only; ignored for local generation (there is no local model choice). @@ -608,11 +728,18 @@ class IcLoraExtractRequest(BaseModel): frame_time: float = 0 +# The frame index of a reference still (the look still of Layout To Render). Upstream +# rejects a negative index, so the pipeline keeps the still apart from the clip frames. +# Only a catalog entry can pin it (``reference_image_frame``). A request cannot send it. +REFERENCE_STILL_FRAME_IDX = -1 + + class IcLoraImageInput(BaseModel): model_config = ConfigDict(strict=True) path: str - frame: int = 0 + # A clip frame. A negative index is a reference still, which only the catalog pins. + frame: int = Field(default=0, ge=0) strength: float = 1.0 @@ -642,6 +769,7 @@ class IcLoraGenerateRequest(BaseModel): # May be empty for catalog IC-LoRAs whose entry sets allows_empty_prompt (e.g. outpainting). # Non-emptiness is enforced in the handler per path, not at the DTO level. prompt: str + prompt_provenance: PromptProvenance = "typed" # These five are overlay settings: None means "use the default" — the IC-LoRA's # default_settings in IC-LoRA mode, or the built-in default otherwise. The UI sends # an explicit value only when the user edits it (advanced controls). @@ -650,13 +778,12 @@ class IcLoraGenerateRequest(BaseModel): # Transformation IC-LoRAs (cross-eye, etc.) need this True or Stage 2 repaints # from the prompt and erases the effect. skip_stage_2: bool | None = None - # Keep the IC-LoRA active during Stage 2 refinement (only meaningful when Stage 2 - # runs, i.e. skip_stage_2=False). Default False = canonical behavior (Stage 2 drops - # the LoRA and refines from the prompt). True preserves the transformation through - # refinement. EXPERIMENTAL — honoured by services.patches.ic_lora_stage2_lora. + # Deprecated (LTXP-514): accepted for API compatibility, always ignored. + # Stage 2 never keeps the IC-LoRA; catalog never set this. use_lora_in_stage_2: bool | None = None - # Target output resolution, used only on the use_lora_in_stage_2 two-stage path - # (mirrors t2v: snapped down to a valid size, never above source). None = source. + # Target output resolution. Two-stage snaps down to a valid size, never above + # source. skip_stage_2 with a resolution renders that size (canvas 2×, factor 1). + # skip_stage_2 without a resolution keeps the 768-wide catalog bucket. resolution: TargetResolution | None = None # Stage-1-only canvas multiplier (only affects skip_stage_2). Stage 1 runs at # half the passed canvas, so 2.0 = native target resolution, 1.0 = half (faster). @@ -703,7 +830,9 @@ class IcLoraGenerateRequest(BaseModel): # Shared base `LoraCatalogItem` (used as-is for plain LoRAs); `IcLoraCatalogItem` extends it # with the IC-specific preprocessing / controls / default settings. InputKind: TypeAlias = Literal["image", "video"] -InstructionTitle: TypeAlias = Literal["What it does", "Input", "Prompt", "Tips", "Notes"] +InstructionTitle: TypeAlias = Literal[ + "What it does", "Input", "Prompt", "Tips", "Notes" +] # Machine-readable counterpart to `title`, so consumers (e.g. a prompt enhancer) can select # instruction blocks by purpose without string-matching display titles. "tips" also covers # the "Notes" title; "summary" covers "What it does". @@ -712,6 +841,11 @@ class IcLoraGenerateRequest(BaseModel): # trained on). 2.3 adapters often run on 2.5; that is recorded here after validation, not # inferred from the training tag. LtxCatalogModelFamily: TypeAlias = Literal["LTX-2.3", "LTX-2.5"] +# What a checkpoint was trained on. Wider than the runnable families: some camera +# LoRAs are LTX-2 weights that still run on 2.3 and 2.5. +LtxVariantBaseModel: TypeAlias = Literal["LTX-2", "LTX-2.3", "LTX-2.5"] +# Variant id stored on runs created before ids carried the base model and LoRA name. +LEGACY_DEFAULT_VARIANT_ID = "default" # Where a trigger word/phrase must appear in the prompt. Not set (and not applicable) when # `prompt_template` is present, since the template's placeholder position already encodes it. TriggerPlacement: TypeAlias = Literal["first_token", "anywhere"] @@ -740,6 +874,7 @@ class PromptTemplateSpec(BaseModel): entry in `placeholders`. A degenerate template with no placeholders (e.g. "upscale") is a fixed, non-generated prompt. """ + model_config = ConfigDict(strict=True) template: str placeholders: dict[str, PromptTemplatePlaceholder] = Field(default_factory=dict) @@ -758,11 +893,20 @@ def _check_placeholders_match_template(self) -> "PromptTemplateSpec": class DownloadVariant(BaseModel): """One downloadable weights file under a catalog item (e.g. strong vs light).""" + model_config = ConfigDict(strict=True) id: str label: str filename: str size_bytes: int + # Training family for the mismatch notice. Required so a catalog entry that + # forgets it is not treated as LTX-2.3. + base_model: LtxVariantBaseModel + # Set when this file lives in a different Hugging Face repo than DownloadSpec.repo_id. + repo_id: str | None = None + + def resolved_repo_id(self, parent_repo_id: str) -> str: + return self.repo_id if self.repo_id is not None else parent_repo_id class DownloadSpec(BaseModel): @@ -772,6 +916,7 @@ class DownloadSpec(BaseModel): (preferred for generation / omit-``variant_id`` downloads). See the comment on ``LoraCatalogHandler`` listing helpers. """ + model_config = ConfigDict(strict=True) repo_id: str variants: list[DownloadVariant] @@ -779,7 +924,9 @@ class DownloadSpec(BaseModel): @model_validator(mode="after") def _check_variants(self) -> "DownloadSpec": if not self.variants: - raise ValueError("download.variants must contain at least one entry (first = default)") + raise ValueError( + "download.variants must contain at least one entry (first = default)" + ) filenames = [v.filename for v in self.variants] if len(filenames) != len(set(filenames)): raise ValueError("download.variants filenames must be unique") @@ -791,11 +938,44 @@ def _check_variants(self) -> "DownloadSpec": def default_variant(self) -> DownloadVariant: return self.variants[0] + def legacy_variant(self) -> DownloadVariant: + """The checkpoint stored runs meant before variant ids were unique. + + New checkpoints are added at index 0, so the original one is last. + """ + return self.variants[-1] + def resolve_variant(self, variant_id: str | None) -> DownloadVariant | None: - """Resolve by id; ``None`` → first variant (the default).""" + """Resolve by id; ``None`` → first variant (the default). + + A stored ``"default"`` id (written before ids were renamed) resolves to + the original checkpoint when no variant carries that id. + """ if variant_id is None: return self.variants[0] - return next((v for v in self.variants if v.id == variant_id), None) + match = next((v for v in self.variants if v.id == variant_id), None) + if match is None and variant_id == LEGACY_DEFAULT_VARIANT_ID: + return self.legacy_variant() + return match + + def variant_for_run( + self, variant_id: str | None, installed_ids: list[str] + ) -> DownloadVariant | None: + """Checkpoint a generate should use. + + An explicit id must exist (``None`` when it does not). An omitted id is + the only checkpoint when the entry has one, otherwise index 0 only when + nothing is installed; once one of several files is on disk the caller + sends its id. + """ + if variant_id is not None: + return self.resolve_variant(variant_id) + if len(self.variants) == 1: + return self.variants[0] + installed = set(installed_ids) + if any(variant.id in installed for variant in self.variants): + return None + return self.variants[0] def candidate_filenames(self) -> list[str]: """Filenames in preference order (default first).""" @@ -851,6 +1031,7 @@ def _default_supported_models() -> list[LtxCatalogModelFamily]: class LoraCatalogItem(BaseModel): """Base catalog entry — used as-is for a plain LoRA.""" + model_config = ConfigDict(strict=True) id: str name: str @@ -869,7 +1050,9 @@ class LoraCatalogItem(BaseModel): base_model: str | None = None # Families this adapter is known to run on. Currently both, so 2.5 testing can # use the full catalog; trim after validation. - supported_models: list[LtxCatalogModelFamily] = Field(default_factory=_default_supported_models) + supported_models: list[LtxCatalogModelFamily] = Field( + default_factory=_default_supported_models + ) tags: list[str] = Field(default_factory=_empty_tags) # Trigger phrase to include in the prompt if the LoRA needs one (e.g. "ADD WATER"). trigger: str | None = None @@ -896,7 +1079,9 @@ def supports_family(self, family: LtxCatalogModelFamily) -> bool: @field_validator("supported_models") @classmethod - def _check_supported_models(cls, value: list[LtxCatalogModelFamily]) -> list[LtxCatalogModelFamily]: + def _check_supported_models( + cls, value: list[LtxCatalogModelFamily] + ) -> list[LtxCatalogModelFamily]: if not value: raise ValueError("supported_models must not be empty") if len(value) != len(set(value)): @@ -911,21 +1096,34 @@ def _check_trigger_placement(self) -> "LoraCatalogItem": f"'{self.id}': trigger_placement is redundant when prompt_template is set" ) elif (self.trigger is None) != (self.trigger_placement is None): - raise ValueError(f"'{self.id}': trigger and trigger_placement must be set together") + raise ValueError( + f"'{self.id}': trigger and trigger_placement must be set together" + ) return self class IcLoraSettings(BaseModel): model_config = ConfigDict(strict=True) skip_stage_2: bool = False - # Keep the IC-LoRA active in Stage 2 (only when skip_stage_2=False). EXPERIMENTAL. + # Deprecated (LTXP-514): accepted for API compatibility, always ignored. use_lora_in_stage_2: bool = False + # Keep the IC-LoRA and its reference (video and stills) on stage 2 (Layout To Render). + # Ignored when skip_stage_2 is true. Unlike the deprecated flag above, this one is honoured. + stage_2_ic_lora: bool = False + # Tile size of a LoRA trained on one tile (Restore, Refine Details). Catalog only: a + # request cannot set it. Needs skip_stage_2 (see IcLoraCatalogItem). + tiling: IcLoraTiling | None = None # 2.0 = native, 1.0 = half; sentinel 0 = source dimensions (see ic_lora_handler). resolution_factor: float = Field(default=2.0, ge=0.0, le=2.0) audio_mode: IcLoraAudioMode = "generated" lora_strength: float = Field(default=1.0, ge=0.0, le=2.0) conditioning_strength: float = 1.0 + @property + def stage_mode(self) -> IcLoraStageMode: + """The stage layout of these settings. The job budget and the chunk rule read it.""" + return ic_lora_stage_mode(skip_stage_2=self.skip_stage_2, stage_2_ic_lora=self.stage_2_ic_lora) + IcLoraControlKind: TypeAlias = Literal["int", "select", "position_canvas"] @@ -955,18 +1153,26 @@ class IcLoraControl(BaseModel): def _check_value_type(self) -> "IcLoraControl": if self.kind == "position_canvas": if self.default is not None or self.options is not None: - raise ValueError("position_canvas control takes no default/options (value is structured)") + raise ValueError( + "position_canvas control takes no default/options (value is structured)" + ) return self if self.default is None or self.options is None: raise ValueError(f"{self.kind} control requires a default and options") if self.kind == "int": - ok = isinstance(self.default, int) and all(isinstance(o, int) for o in self.options) + ok = isinstance(self.default, int) and all( + isinstance(o, int) for o in self.options + ) if not ok: raise ValueError("int control requires an int default and int options") else: - ok = isinstance(self.default, str) and all(isinstance(o, str) for o in self.options) + ok = isinstance(self.default, str) and all( + isinstance(o, str) for o in self.options + ) if not ok: - raise ValueError("select control requires a str default and str options") + raise ValueError( + "select control requires a str default and str options" + ) return self @@ -984,6 +1190,39 @@ def _empty_controls() -> list[IcLoraControl]: return [] +# Every field is_home_recipe has classified. A field added to IcLoraCatalogItem +# is absent from this set, so is_home_recipe fails closed until it is classified +# here and in the method. +_HOME_RECIPE_FIELDS = frozenset({ + "allows_empty_prompt", + "allows_reference_image", + "author", + "base_model", + "controls", + "created_at", + "default_settings", + "description", + "download", + "enhancement_examples", + "id", + "input", + "instructions", + "license", + "media", + "name", + "preprocessing", + "prompt_template", + "recommended_strength", + "reference_image_frame", + "reference_image_required", + "requires_hf_login", + "supported_models", + "tags", + "trigger", + "trigger_placement", +}) + + class IcLoraCatalogItem(LoraCatalogItem): """IC-LoRA — base plus IC-specific preprocessing / controls / default settings. @@ -991,12 +1230,42 @@ class IcLoraCatalogItem(LoraCatalogItem): field is optional for plain LoRAs). Enforced by the validator below, so handlers can rely on it being present. """ + preprocessing: list[PreprocessingStep] = Field(default_factory=_empty_preprocessing) controls: list[IcLoraControl] = Field(default_factory=_empty_controls) default_settings: IcLoraSettings = Field(default_factory=IcLoraSettings) # When true, the UI offers an optional reference image that seeds the first frame # (image conditioning at frame 0, strength 1.0) — e.g. a photoreal seed for 3D-render. allows_reference_image: bool = False + # Pins the reference image to this pixel frame and ignores the request frame. + # REFERENCE_STILL_FRAME_IDX is the look still of Layout To Render. None keeps the + # request frame (0). + reference_image_frame: int | None = None + # The Home form refuses a create without the reference image. + reference_image_required: bool = False + + def is_home_recipe(self) -> bool: + """True when the Home recipe path can run this entry. + + A Home recipe has a video input, no controls and no preprocessing. It + takes an optional or required reference image, pinned to the catalog + ``reference_image_frame``. Stage 2 is skipped, or it keeps the IC-LoRA + (``stage_2_ic_lora``). Home sizes an explicit resolution and ignores + ``resolution_factor``, which is only correct for those two cases. + The model default for ``skip_stage_2`` is false, so an entry that omits + ``default_settings`` is not a Home recipe. + """ + if frozenset(type(self).model_fields) != _HOME_RECIPE_FIELDS: + return False + return ( + self.input is not None + and self.input.kind == "video" + and not self.controls + and not self.preprocessing + # A reference image is pinned to a catalog frame, never a request frame. + and (not self.allows_reference_image or self.reference_image_frame is not None) + and (self.default_settings.skip_stage_2 or self.default_settings.stage_2_ic_lora) + ) @model_validator(mode="after") def _require_input(self) -> "IcLoraCatalogItem": @@ -1004,6 +1273,21 @@ def _require_input(self) -> "IcLoraCatalogItem": # at parse time rather than letting it trip the handler's assert at generate time. if self.input is None: raise ValueError(f"IC-LoRA '{self.id}' must declare an input spec") + if self.reference_image_required and not self.allows_reference_image: + raise ValueError(f"IC-LoRA '{self.id}' requires a reference image it does not allow") + if self.reference_image_frame not in (None, 0, REFERENCE_STILL_FRAME_IDX): + # Another frame would reach the pipeline as a negative still or an unknown index. + raise ValueError( + f"IC-LoRA '{self.id}' reference_image_frame must be 0 or {REFERENCE_STILL_FRAME_IDX}, " + f"got {self.reference_image_frame}" + ) + if self.default_settings.tiling is not None: + if not self.default_settings.skip_stage_2: + raise ValueError(f"IC-LoRA '{self.id}' tiling needs skip_stage_2") + if self.reference_image_frame is not None and self.reference_image_frame < 0: + # ltx-pipelines keeps a negative-time token whole in every tile. It does not + # crop the still to each tile, as the LoRA cards do. + raise ValueError(f"IC-LoRA '{self.id}' tiling cannot take a reference still") return self @@ -1039,6 +1323,7 @@ class EnhancePromptRequest(BaseModel): """Regular-LoRA, IC-LoRA, and built-in conditioning-type selection are mutually exclusive UI surfaces — a request never carries more than one of loraCatalogIds/icLoraId/conditioningType. """ + model_config = ConfigDict(strict=True) # Empty is allowed when imagePath or keyframes are set — the rewrite is then captioned # from the attached frame(s), plus any extra text the user did type. @@ -1052,6 +1337,10 @@ class EnhancePromptRequest(BaseModel): conditioningType: Literal["canny", "depth"] | None = None imagePath: str | None = None lastImagePath: str | None = None + # Explore sends asset ids (Remote has no filesystem paths). Mutually exclusive with + # imagePath / lastImagePath. + imageAssetId: str | None = None + lastImageAssetId: str | None = None # Same shape as GenerateVideoRequest.keyframes. Mutually exclusive with imagePath/ # lastImagePath — middle markers have nowhere to go on the two-slot i2v path. keyframes: list[KeyframeInput] = Field(default_factory=list[KeyframeInput]) @@ -1072,13 +1361,29 @@ class EnhancePromptRequest(BaseModel): @model_validator(mode="after") def _check_selection_is_mutually_exclusive(self) -> "EnhancePromptRequest": - selected = [bool(self.loraCatalogIds), self.icLoraId is not None, self.conditioningType is not None] + selected = [ + bool(self.loraCatalogIds), + self.icLoraId is not None, + self.conditioningType is not None, + ] if sum(selected) > 1: - raise ValueError("loraCatalogIds, icLoraId, and conditioningType are mutually exclusive") + raise ValueError( + "loraCatalogIds, icLoraId, and conditioningType are mutually exclusive" + ) if self.mediaType == "image" and sum(selected) > 0: - raise ValueError("loraCatalogIds, icLoraId, and conditioningType only apply to mediaType='video'") - has_first = bool((self.imagePath or "").strip()) - has_last = bool((self.lastImagePath or "").strip()) + raise ValueError( + "loraCatalogIds, icLoraId, and conditioningType only apply to mediaType='video'" + ) + has_first_path = bool((self.imagePath or "").strip()) + has_last_path = bool((self.lastImagePath or "").strip()) + has_first_asset = bool((self.imageAssetId or "").strip()) + has_last_asset = bool((self.lastImageAssetId or "").strip()) + if has_first_path and has_first_asset: + raise ValueError("Use imagePath or imageAssetId, not both") + if has_last_path and has_last_asset: + raise ValueError("Use lastImagePath or lastImageAssetId, not both") + has_first = has_first_path or has_first_asset + has_last = has_last_path or has_last_asset has_keyframes = bool(self.keyframes) if self.mediaType == "image" and has_keyframes: raise ValueError("keyframes only apply to mediaType='video'") @@ -1111,6 +1416,18 @@ class EnhancePromptResponse(BaseModel): enhancedPrompt: str +class PromptEnhancerStatusResponse(BaseModel): + """Availability for the Explore Enhance control. Does not expose API keys or paths.""" + + model_config = ConfigDict(strict=True) + exploreAutoEnhancePrompts: bool + hasGeminiApiKey: bool + localEnhancementSupported: bool + defaultProvider: Literal["local", "api"] + canToggleProvider: bool + showManualEnhance: bool + + class IcLoraListItem(BaseModel): model_config = ConfigDict(strict=True) ic_lora: IcLoraCatalogItem @@ -1134,6 +1451,12 @@ class IcLoraDownloadRequest(BaseModel): use_hf_auth: bool = False +class IcLoraDeleteRequest(BaseModel): + model_config = ConfigDict(strict=True) + ic_lora_id: str + variant_id: str | None = None + + # Shared start-response for both catalog download kinds (IC-LoRA + plain LoRA). class CatalogDownloadStartResponse(BaseModel): model_config = ConfigDict(strict=True) @@ -1178,6 +1501,12 @@ class LoraDownloadRequest(BaseModel): use_hf_auth: bool = False +class LoraDeleteRequest(BaseModel): + model_config = ConfigDict(strict=True) + lora_id: str + variant_id: str | None = None + + class LoraDownloadProgressResponse(BaseModel): model_config = ConfigDict(strict=True) status: CatalogDownloadStatus @@ -1189,6 +1518,23 @@ class LoraDownloadProgressResponse(BaseModel): error: str | None = None +class ActiveLoraDownloadResponse(BaseModel): + model_config = ConfigDict(strict=True) + # The currently-running plain-LoRA download session. Nulls when idle. + session_id: str | None + lora_id: str | None + # 0–99 while downloading so a remount can seed the progress label instead of flashing 0%. + progress: float | None = None + + +class ActiveIcLoraDownloadResponse(BaseModel): + model_config = ConfigDict(strict=True) + # The currently-running IC-LoRA download session. Nulls when idle. + session_id: str | None + ic_lora_id: str | None + progress: float | None = None + + class GeminiModelOptionPayload(BaseModel): model_config = ConfigDict(strict=True) id: str @@ -1200,3 +1546,507 @@ class GeminiModelsResponsePayload(BaseModel): model_config = ConfigDict(strict=True) models: list[GeminiModelOptionPayload] resolvedModel: str + + +MediaKind = Literal["image", "video", "audio"] +Origin = Literal["uploaded", "generated"] +GenerationStatus = Literal[ + "queued", "running", "cancelling", "succeeded", "failed", "cancelled" +] +GenerationErrorCode = Literal[ + "INTERRUPTED", + "INPUT_MISSING", + "OUTPUT_MISSING", + "OUTPUT_UNREADABLE", + "EXECUTOR_FAILED", + "CAPABILITY_FAILED", + # A queued job's LTX key was rejected, or prompt embedding failed. + # Other capability failures stay CAPABILITY_FAILED. + "LTX_INVALID_API_KEY", + "LTX_API_PROMPT_EMBEDDING_FAILED", +] + + +class ImageMeta(BaseModel): + model_config = ConfigDict(frozen=True, extra="allow", strict=True) + width: int = Field(gt=0) + height: int = Field(gt=0) + + +class VideoMeta(BaseModel): + model_config = ConfigDict(frozen=True, extra="allow", strict=True) + width: int = Field(gt=0) + height: int = Field(gt=0) + durationMs: int = Field(ge=1) + sizeBytes: int = Field(ge=0) + audioStreamCount: int = Field(ge=0) + # Written at ingest. Older rows omit it; create probes the file then. + fps: float | None = Field(default=None, gt=0) + + +class AudioMeta(BaseModel): + model_config = ConfigDict(frozen=True, extra="allow", strict=True) + durationMs: int = Field(ge=1) + bitrate: int | None = Field(default=None, ge=1) + + +class ImageAssetMetadata(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + mediaType: Literal["image"] + metadata: ImageMeta + + +class VideoAssetMetadata(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + mediaType: Literal["video"] + metadata: VideoMeta + + +class AudioAssetMetadata(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + mediaType: Literal["audio"] + metadata: AudioMeta + + +AssetMetadata = Annotated[ + ImageAssetMetadata | VideoAssetMetadata | AudioAssetMetadata, + Field(discriminator="mediaType"), +] + + +def require_media_kind_matches_metadata( + media_kind: MediaKind, metadata: AssetMetadata +) -> None: + if metadata.mediaType != media_kind: + raise ValueError( + f"media_kind {media_kind!r} does not match metadata.mediaType {metadata.mediaType!r}" + ) + + +def require_failed_has_error_code( + status: GenerationStatus, error_code: GenerationErrorCode | None +) -> None: + if status == "failed" and error_code is None: + raise ValueError("failed generation requires error_code") + if status != "failed" and error_code is not None: + raise ValueError("error_code is only valid when status is failed") + + +class AssetCore(BaseModel): + """Identity, media kind, and metadata shared by Desktop and Remote assets. + + Filesystem paths stay on Desktop `Asset` only. Remote `RemoteAsset` must not + inherit those fields. + """ + + model_config = ConfigDict(strict=True) + id: str = Field(min_length=1) + media_kind: MediaKind + origin: Origin + mime_type: str = Field(min_length=1) + name: str = Field(min_length=1) + metadata: AssetMetadata + created_at: int = Field(ge=0) + + @model_validator(mode="after") + def _media_kind_matches_metadata(self) -> Self: + require_media_kind_matches_metadata(self.media_kind, self.metadata) + return self + + +class Asset(AssetCore): + model_config = ConfigDict(strict=True) + path: str = Field(min_length=1) + thumbnail_path: str | None = None + + +class AssetListItem(Asset): + in_use: bool + + +class AssetListQuery(BaseModel): + model_config = ConfigDict(strict=True) + media_kind: MediaKind | None = None + sort: str = "created_at-desc" + q: str | None = None + cursor: str | None = None + limit: int = Field(default=100, ge=1, le=200) + + +class AssetListResponse(BaseModel): + items: list[AssetListItem] + next_cursor: str | None = None + + +class GenerationCore(BaseModel): + """Lifecycle fields shared by Desktop and Remote generations. + + `spec` and `outputs` stay on the concrete models: Desktop keeps generic JSON + plus `Asset` outputs; Remote keeps the allowlisted spec plus `RemoteAsset` + outputs. + """ + + model_config = ConfigDict(strict=True) + id: str = Field(min_length=1) + feature: str = Field(min_length=1) + contract_version: int = Field(ge=1) + status: GenerationStatus + error_code: GenerationErrorCode | None = None + created_at: int = Field(ge=0) + queued_at: int = Field(ge=0) + attempt_count: int = Field(ge=0) + started_at: int | None = None + finished_at: int | None = None + + @model_validator(mode="after") + def _failed_has_error_code(self) -> Self: + require_failed_has_error_code(self.status, self.error_code) + return self + + +class Generation(GenerationCore): + model_config = ConfigDict(strict=True) + spec: dict[str, JsonValue] + outputs: list[Asset] + + +class QueueProgress(BaseModel): + """Live progress for the persisted active queue entry.""" + + model_config = ConfigDict(strict=True) + phase: str + progress: int + currentStep: int | None + totalSteps: int | None + + +class QueueEntry(BaseModel): + model_config = ConfigDict(strict=True) + generation: Generation + input_assets: list[Asset] + progress: QueueProgress | None = None + + +class QueueSnapshot(BaseModel): + model_config = ConfigDict(strict=True) + active: QueueEntry | None + queued: list[QueueEntry] + done: list[QueueEntry] = Field(default_factory=list[QueueEntry]) + failed: list[QueueEntry] = Field(default_factory=list[QueueEntry]) + unseen_ids: list[str] = Field(default_factory=list[str]) + + +class IngestAssetRequest(BaseModel): + model_config = ConfigDict(strict=True) + path: str = Field(min_length=1) + + +class ReorderGenerationQueueRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + generation_id: str = Field(min_length=1) + before_generation_id: str | None = Field(default=None, min_length=1) + + +class TrimMediaRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + startSec: float = Field(ge=0, allow_inf_nan=False) + endSec: float = Field(gt=0, allow_inf_nan=False) + + +class _QueuedVideoParams(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + resolution: LTXVideoGenResolution = "1080p" + model: OfferingId + cameraMotion: VideoCameraMotion = "none" + negativePrompt: str = "" + duration: LTXVideoGenDuration | None = 5 + fps: LTXVideoGenFps = 24 + seed: int | None = None + promptProvenance: PromptProvenance = "typed" + + +class TextToVideoParams(_QueuedVideoParams): + """Non-media text-to-video params stored on a generation row.""" + + prompt: NonEmptyPrompt + aspectRatio: LTXVideoGenAspectRatio = "16:9" + loras: list[LoraEntry] = Field(default_factory=list[LoraEntry]) + + +class ImageToVideoParams(_QueuedVideoParams): + """Non-media image-to-video params stored on a generation row.""" + + prompt: str + aspectRatio: LTXQueuedAspectRatio = "auto" + + +class ImageToVideoRecipeParams(ImageToVideoParams): + """Stored params for an i2v LoRA recipe. + + Public ``CreateImageToVideoRequest`` stays loras-free. Recipe rows carry the + catalog id + scale (empty ``ref``) the same way t2v recipes do; execute + hydrates ``ref`` via ``lora_resolver``. + """ + + loras: list[LoraEntry] = Field(default_factory=list[LoraEntry]) + + +class LoraRecipeParams(_QueuedVideoParams): + """Create-body params for a LoRA recipe. + + The client sends the catalog id + scale of the recipe's adapter, never a + filesystem ``ref``. Create stores ``loras: [{ ref: "", scale, catalogId }]``; + execute hydrates the installed path (see ``make_recipe_lora_resolver``). + ``prompt`` is the raw user scene; the recipe's prompt scaffold is applied at + execution time. ``aspectRatio`` includes ``auto`` for i2v recipes (resolved + from the start frame at execute); t2v recipes reject ``auto``. + """ + + prompt: NonEmptyPrompt + aspectRatio: LTXQueuedAspectRatio = "16:9" + catalogId: str = Field(pattern=r"^[a-z0-9-]+$", max_length=64) + scale: float = Field(default=1.0, ge=0.0, le=4.0) + # Omitted resolves to the only checkpoint, or to index 0 when nothing is installed. + variantId: str | None = None + + +class InputAssetRef(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + assetId: str = Field(min_length=1) + + +class ImageToVideoInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + startFrame: InputAssetRef + endFrame: InputAssetRef | None = None + + +class LoraRecipeInputs(BaseModel): + """Start frame for an i2v LoRA recipe. t2v recipes omit this object. + + ``endFrame`` is only valid for recipes that require it (Transition). + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + startFrame: InputAssetRef + endFrame: InputAssetRef | None = None + + +class CreateLoraRecipeRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + params: LoraRecipeParams + inputs: LoraRecipeInputs | None = None + contract_version: int = Field(default=1, ge=1) + + +class CreateTextToVideoRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + params: TextToVideoParams + contract_version: int = Field(default=1, ge=1) + + +class CreateImageToVideoRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + params: ImageToVideoParams + inputs: ImageToVideoInputs + contract_version: int = Field(default=1, ge=1) + + +class CreateAudioToVideoParams(BaseModel): + """Public non-media A2V inputs; the server derives inference frames from audio.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + prompt: str + aspectRatio: LTXQueuedAspectRatio = "16:9" + resolution: LTXLocalA2VResolution = "540p" + model: OfferingId + fps: LTXVideoGenFps = 24 + cameraMotion: VideoCameraMotion = "none" + negativePrompt: str = "" + seed: int | None = None + promptProvenance: PromptProvenance = "typed" + + +class AudioToVideoParams(CreateAudioToVideoParams): + """Authoritative A2V parameters persisted on the queued generation.""" + + numFrames: int = Field(ge=9) + + @model_validator(mode="after") + def _require_a2v_frame_grid(self) -> "AudioToVideoParams": + if (self.numFrames - 1) % 8 != 0: + raise ValueError("numFrames must be on the 8k+1 frame grid") + return self + + +class AudioToVideoInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + audio: InputAssetRef + startFrame: InputAssetRef | None = None + + +class CreateAudioToVideoRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + params: CreateAudioToVideoParams + inputs: AudioToVideoInputs + contract_version: int = Field(default=1, ge=1) + + +# Longest selection one Home/Remote retake regenerates, at every resolution. +# Product limit on new requests (`RetakeRequestParams`); the legacy editor +# endpoint (`RetakeRequest`) is not capped. +RETAKE_MAX_DURATION_SECONDS = 10.0 + + +class RetakeParams(BaseModel): + """Queued Home/Remote retake. + + ``resolution`` omitted keeps the source size. Either way the picture is + capped at the local 1080p cell. The model encodes a black-bar letterbox + up to the next multiple of 32, and the stitch crops back to this picture. + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + prompt: str = "" + model: OfferingId + startTime: float = Field(ge=0, allow_inf_nan=False) + duration: float = Field(ge=2, allow_inf_nan=False) + mode: RetakeMode = "replace_audio_and_video" + resolution: TargetResolution | None = None + seed: int | None = None + # Accepted so the shared Home form can submit provenance like every other + # queued video feature. Execution always submits the prompt as-is + # (enhance_prompt=False), so this is recorded, never acted on. + promptProvenance: PromptProvenance = "typed" + + +class RetakeInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + video: InputAssetRef + + +class RetakeRequestParams(RetakeParams): + """New retakes only: specs queued before the cap still parse as ``RetakeParams``.""" + + duration: float = Field( + ge=2, le=RETAKE_MAX_DURATION_SECONDS, allow_inf_nan=False + ) + + +class CreateRetakeRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + params: RetakeRequestParams + inputs: RetakeInputs + contract_version: int = Field(default=1, ge=1) + + +class ExtendParams(BaseModel): + """Queued Home/Remote extend. + + ``resolution`` omitted keeps the source size. Either way the picture is + capped at the local 1080p cell. The model encodes a black-bar letterbox + up to the next multiple of 32, and the stitch crops back to this picture. + """ + + model_config = ConfigDict(strict=True, extra="forbid") + + prompt: str = "" + model: OfferingId + duration: float = Field(ge=2, le=20, allow_inf_nan=False) + mode: ExtendMode = "end" + resolution: TargetResolution | None = None + seed: int | None = None + # Accepted so the shared Home form can submit provenance like every other + # queued video feature. Execution always submits the prompt as-is + # (enhance_prompt=False), so this is recorded, never acted on. + promptProvenance: PromptProvenance = "typed" + + +class ExtendInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + video: InputAssetRef + + +class CreateExtendRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + params: ExtendParams + inputs: ExtendInputs + contract_version: int = Field(default=1, ge=1) + + +IcLoraRecipeResolution: TypeAlias = Literal["270p", "360p", "540p", "720p", "1080p"] + + +class _IcLoraRecipeCore(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + prompt: str = "" + model: OfferingId + resolution: IcLoraRecipeResolution = "720p" + seed: int | None = None + promptProvenance: PromptProvenance = "typed" + + +class IcLoraRecipeParams(_IcLoraRecipeCore): + """Create-body params. Strength is ``scale``; the stored spec uses ``loras``. + + A ``loras`` array on the create body is rejected. The path id is the recipe, + so the body does not carry a catalog id. The server writes the checkpoint + it actually ran. Omitted audio and strength are filled from the catalog. + """ + + audioMode: IcLoraAudioMode | None = None + scale: float | None = Field(default=None, ge=0.0, le=2.0) + # Omitted fps is the supported rate closest to the source, never above it. + fps: float | None = Field(default=None, gt=0) + # Omitted resolves to the only checkpoint, or to index 0 when nothing is installed. + variantId: str | None = None + + +class IcLoraRecipeStoredParams(_IcLoraRecipeCore): + """Stored IC-LoRA recipe spec. + + The executor picks the closest local aspect from the source video. Resolution + stays inside the local 1080p IC-LoRA envelope. ``fps`` is the output rate: + the crop filter decimates when it is below the source. + ``loras`` is the one checkpoint this run used. ``audioMode`` is required + because create resolves it from the catalog when the request omits it. + """ + + audioMode: IcLoraAudioMode + fps: float = Field(gt=0) + loras: list[LoraEntry] = Field(default_factory=list[LoraEntry]) + + @model_validator(mode="after") + def _require_one_catalog_lora(self) -> "IcLoraRecipeStoredParams": + if len(self.loras) != 1 or not self.loras[0].catalogId: + raise ValueError("an IC-LoRA recipe spec requires one catalog LoRA") + return self + + +class IcLoraRecipeInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + video: InputAssetRef + # Reference image for a catalog entry with allows_reference_image. + image: InputAssetRef | None = None + + +class CreateIcLoraRecipeRequest(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + params: IcLoraRecipeParams + inputs: IcLoraRecipeInputs + contract_version: int = Field(default=1, ge=1) diff --git a/backend/app_factory.py b/backend/app_factory.py index 5073c3c0f..dd1be1cfa 100644 --- a/backend/app_factory.py +++ b/backend/app_factory.py @@ -4,18 +4,18 @@ import base64 import hmac -from collections.abc import Awaitable, Callable +from collections.abc import AsyncGenerator, Awaitable, Callable +from contextlib import asynccontextmanager from typing import TYPE_CHECKING, Any from fastapi import FastAPI, Request -from fastapi.exceptions import RequestValidationError from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import JSONResponse -from starlette.exceptions import HTTPException as StarletteHTTPException from starlette.responses import Response as StarletteResponse -from _routes._errors import HTTPError, build_http_error_response +from _routes._errors import build_http_error_response from _routes.generation import router as generation_router +from _routes.generation import specs_router as generate_specs_router from _routes.hf_auth import router as hf_auth_router from _routes.health import router as health_router from _routes.ic_lora import router as ic_lora_router @@ -26,11 +26,18 @@ from _routes.suggest_gap_prompt import router as suggest_gap_prompt_router from _routes.retake import router as retake_router from _routes.extend import router as extend_router +from _routes.assets import router as assets_router +from _routes.generations import router as generations_router +from _routes.stats import router as stats_router +from _routes.generation_seed import router as generation_seed_router from _routes.runtime_policy import router as runtime_policy_router +from _routes.feature_flags import router as feature_flags_router from _routes.settings import router as settings_router +from _routes.remote import router as remote_status_router from api_types import HTTPErrorResponse -from logging_policy import log_http_error, log_unhandled_exception -from state import init_state_service +from http_exception_handlers import install_http_exception_handlers +from remote.controller import RemoteExposureController, remote_controller_from_app +from state import get_state_service, init_state_service if TYPE_CHECKING: from app_handler import AppHandler @@ -61,10 +68,25 @@ def create_app( admin_token: str = "", ) -> FastAPI: """Create a configured FastAPI app bound to the provided handler.""" - init_state_service(handler) - app = FastAPI(title=title, responses=DEFAULT_ERROR_RESPONSES) + @asynccontextmanager + async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + handler.generation_queue.start() + controller = remote_controller_from_app(app) + if controller is None: + raise RuntimeError("Desktop app is missing RemoteExposureController") + controller.sync() + try: + yield + finally: + controller.stop() + handler.generation_queue.stop() + + app = FastAPI(title=title, responses=DEFAULT_ERROR_RESPONSES, lifespan=lifespan) app.state.admin_token = admin_token # type: ignore[attr-defined] + app.state.remote_controller = RemoteExposureController(handler) # type: ignore[attr-defined] + app.dependency_overrides[get_state_service] = lambda: handler + init_state_service(handler) app.add_middleware( CORSMiddleware, allow_origins=allowed_origins or DEFAULT_ALLOWED_ORIGINS, @@ -111,61 +133,27 @@ def _token_matches(candidate: str) -> bool: content=build_http_error_response(401, "Unauthorized").model_dump(), ) - async def _route_http_error_handler(request: Request, exc: Exception) -> JSONResponse: - if isinstance(exc, HTTPError): - log_http_error(request, exc) - return JSONResponse(status_code=exc.status_code, content=exc.response.model_dump()) - return JSONResponse( - status_code=500, - content=build_http_error_response(500, str(exc)).model_dump(), - ) - - async def _starlette_http_error_handler(request: Request, exc: Exception) -> JSONResponse: - if isinstance(exc, StarletteHTTPException): - return JSONResponse( - status_code=exc.status_code, - content=build_http_error_response(exc.status_code, exc.detail).model_dump(), - ) - return JSONResponse( - status_code=500, - content=build_http_error_response(500, str(exc)).model_dump(), - ) - - async def _validation_error_handler(request: Request, exc: Exception) -> JSONResponse: - if isinstance(exc, RequestValidationError): - return JSONResponse( - status_code=422, - content=build_http_error_response(422, str(exc)).model_dump(), - ) - return JSONResponse( - status_code=422, - content=build_http_error_response(422, str(exc)).model_dump(), - ) - - async def _route_generic_error_handler(request: Request, exc: Exception) -> JSONResponse: - log_unhandled_exception(request, exc) - return JSONResponse( - status_code=500, - content=build_http_error_response(500, str(exc)).model_dump(), - ) - - app.add_exception_handler(RequestValidationError, _validation_error_handler) - app.add_exception_handler(HTTPError, _route_http_error_handler) - app.add_exception_handler(StarletteHTTPException, _starlette_http_error_handler) - app.add_exception_handler(Exception, _route_generic_error_handler) + install_http_exception_handlers(app) app.include_router(health_router) app.include_router(generation_router) + app.include_router(generate_specs_router) app.include_router(models_router) app.include_router(settings_router) app.include_router(image_gen_router) app.include_router(suggest_gap_prompt_router) app.include_router(retake_router) app.include_router(extend_router) + app.include_router(assets_router) + app.include_router(generations_router) + app.include_router(stats_router) + app.include_router(generation_seed_router) app.include_router(ic_lora_router) app.include_router(lora_catalog_router) app.include_router(prompt_enhancement_router) app.include_router(runtime_policy_router) + app.include_router(feature_flags_router) app.include_router(hf_auth_router) + app.include_router(remote_status_router) return app diff --git a/backend/app_handler.py b/backend/app_handler.py index 5cfca0764..9bde39c41 100644 --- a/backend/app_handler.py +++ b/backend/app_handler.py @@ -2,11 +2,17 @@ from __future__ import annotations +import logging +import os import threading +from collections.abc import Mapping from dataclasses import dataclass +from pathlib import Path +from api_types import LTXLocalModelId from state.app_settings import AppSettings from handlers import ( + AssetHandler, DownloadHandler, GenerationHandler, HealthHandler, @@ -20,11 +26,15 @@ SuggestGapPromptHandler, RetakeHandler, ExtendHandler, + FeatureFlagsHandler, RuntimePolicyHandler, SettingsHandler, TextHandler, VideoGenerationHandler, ) +from handlers.dashboard_handler import DashboardHandler +from handlers.queued_generation_handler import QueuedGenerationHandler +from runtime_config.offerings import OFFERING_IDS, resolve_offering_local_model_id from runtime_config.runtime_config import RuntimeConfig from services.interfaces import ( A2VPipeline, @@ -45,10 +55,40 @@ TextEncoder, VideoProcessor, ) +from services.analytics import AnalyticsService, QueuedEnhancement from services.lora_catalog import LoraCatalogProvider +from services.store import Store +from services.records import GenerationRecord, UnavailableError +from services.unavailable_store import UnavailableStore +from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.runner import QueueRunner +from services.features.video import ( + AUDIO_TO_VIDEO_FEATURE, + EXTEND_FEATURE, + FEATURE as TEXT_TO_VIDEO_FEATURE, + IMAGE_TO_VIDEO_FEATURE, + RETAKE_FEATURE, + AudioToVideoExecutor, + IcLoraRecipeExecutor, + ExtendExecutor, + ImageToVideoExecutor, + RebindableAssetResolver, + RetakeExecutor, + TextToVideoExecutor, +) +from services.features.ic_lora_recipes import queued_ic_lora_recipes +from services.features.lora_recipes import ( + i2v_lora_recipes, + make_recipe_lora_resolver, + make_recipe_prompt_wrap, + t2v_lora_recipes, +) +from services.generation_queue.types import GenerationExecutor from services.prompt_enhancer_pipeline.gemini_prompt_enhancer_pipeline import GeminiPromptEnhancerPipeline from state.app_state_types import AppState, TextEncoderState +logger = logging.getLogger(__name__) + class AppHandler: """Composition-only state service exposing typed domain handlers.""" @@ -75,6 +115,8 @@ def __init__( a2v_pipeline_class: type[A2VPipeline], retake_pipeline_class: type[RetakePipeline], prompt_enhancer_pipeline_class: type[PromptEnhancerPipeline], + store: Store, + generation_executors: Mapping[str, GenerationExecutor] | None = None, ) -> None: self.config = config @@ -97,6 +139,12 @@ def __init__( self.prompt_enhancer_pipeline_class = prompt_enhancer_pipeline_class self._lock = threading.RLock() + self.analytics = AnalyticsService( + http=http, + task_runner=task_runner, + sink_url=os.environ.get("LTX_ANALYTICS_SINK_URL", ""), + token=os.environ.get("LTX_ANALYTICS_TOKEN", ""), + ) self.state = AppState( downloading_session=None, @@ -197,6 +245,83 @@ def __init__( config=config, ) + self._lora_catalog_provider = lora_catalog_provider + self.ic_lora = IcLoraHandler( + state=self.state, + lock=self._lock, + generation_handler=self.generation, + pipelines_handler=self.pipelines, + text_handler=self.text, + prompt_enhancement_handler=self.prompt_enhancement, + video_processor=video_processor, + lora_catalog=lora_catalog_provider, + config=config, + ) + self._queued_asset_resolver: RebindableAssetResolver | None = None + if generation_executors is None: + self._queued_asset_resolver = RebindableAssetResolver(store) + executors: dict[str, GenerationExecutor] = { + TEXT_TO_VIDEO_FEATURE: TextToVideoExecutor(self.video_generation), + IMAGE_TO_VIDEO_FEATURE: ImageToVideoExecutor( + self.video_generation, self._queued_asset_resolver + ), + } + # Each t2v LoRA recipe reuses the text-to-video executor, keyed on its + # Explore id, with its scaffold applied post-enhance. i2v recipes reuse + # the image-to-video executor the same way (start frame + LoRA). + for recipe in t2v_lora_recipes(): + executors[recipe.recipe_id] = TextToVideoExecutor( + self.video_generation, + prompt_wrap=make_recipe_prompt_wrap(recipe), + lora_resolver=make_recipe_lora_resolver( + recipe, + catalog=self._lora_catalog_provider, + models_dir=lambda: self.video_generation.models_dir, + ), + ) + for recipe in i2v_lora_recipes(): + executors[recipe.recipe_id] = ImageToVideoExecutor( + self.video_generation, + self._queued_asset_resolver, + prompt_wrap=make_recipe_prompt_wrap(recipe), + lora_resolver=make_recipe_lora_resolver( + recipe, + catalog=self._lora_catalog_provider, + models_dir=lambda: self.video_generation.models_dir, + ), + ) + executors[AUDIO_TO_VIDEO_FEATURE] = AudioToVideoExecutor( + self.video_generation, self._queued_asset_resolver + ) + executors[RETAKE_FEATURE] = RetakeExecutor( + self.pipelines, + self._queued_asset_resolver, + self.text, + lambda: self.video_generation.models_dir, + config.default_negative_prompt, + self.generation, + ) + executors[EXTEND_FEATURE] = ExtendExecutor( + self.pipelines, + self._queued_asset_resolver, + self.text, + lambda: self.video_generation.models_dir, + config.default_negative_prompt, + self.generation, + ) + for recipe in queued_ic_lora_recipes(): + executors[recipe.recipe_id] = IcLoraRecipeExecutor( + self.ic_lora, + self._queued_asset_resolver, + lambda: self.video_generation.models_dir, + catalog_id=recipe.catalog_id, + cutout=recipe.cutout, + ) + self.executor_registry = ExecutorRegistry(executors) + else: + self.executor_registry = ExecutorRegistry(generation_executors) + self._bind_store(store) + self.image_generation = ImageGenerationHandler( state=self.state, lock=self._lock, @@ -215,6 +340,7 @@ def __init__( ) self.runtime_policy = RuntimePolicyHandler(config=config) + self.feature_flags = FeatureFlagsHandler(lock=self._lock, config=config) self.suggest_gap_prompt = SuggestGapPromptHandler( state=self.state, @@ -243,17 +369,6 @@ def __init__( text_handler=self.text, ) - self.ic_lora = IcLoraHandler( - state=self.state, - lock=self._lock, - generation_handler=self.generation, - pipelines_handler=self.pipelines, - text_handler=self.text, - video_processor=video_processor, - lora_catalog=lora_catalog_provider, - config=config, - ) - self.downloads.cleanup_downloading_dir() self.load_persistent_state(default_settings) @@ -262,6 +377,66 @@ def load_persistent_state(self, default_settings: AppSettings) -> None: """Load persisted state from disk (settings, HF auth token, etc.).""" self.settings.load_settings(default_settings) self.hf_auth.load_token() + try: + self.queued_generations.recover_on_boot() + except UnavailableError: + logger.warning( + "Store boot recovery failed; store unavailable at %s", + self.config.app_data_dir / "store.sqlite3", + exc_info=True, + ) + self._bind_store(UnavailableStore()) + + def _queued_local_model_id(self, generation: GenerationRecord) -> LTXLocalModelId | None: + """The checkpoint this queued job will encode with, not the active model.""" + params = generation.spec.get("params") + if not isinstance(params, dict): + return None + model = params.get("model") + if not isinstance(model, str) or model not in OFFERING_IDS: + return None + return resolve_offering_local_model_id(self.video_generation.models_dir, model) + + def _queued_enhancement_policy(self, generation: GenerationRecord) -> QueuedEnhancement: + settings = self.state.app_settings + model_id = self._queued_local_model_id(generation) + return QueuedEnhancement( + explore_auto_enhance_prompts=settings.explore_auto_enhance_prompts, + prompt_enhancer_enabled=settings.prompt_enhancer_enabled, + use_local_encoding=self.text.should_use_local_encoding(model_id), + local_enhancer_available=( + self.text.resolve_prompt_enhancer_root_if_downloaded(model_id) is not None + ), + ) + + def _bind_store(self, store: Store) -> None: + if self._queued_asset_resolver is not None: + self._queued_asset_resolver.bind(store) + self.generation_queue = QueueRunner( + db=store, + generation=self.generation, + executors=self.executor_registry, + analytics=self.analytics, + enhancement_policy=self._queued_enhancement_policy, + ) + self.assets = AssetHandler( + store=store, + ) + self.queued_generations = QueuedGenerationHandler( + store=store, + executor_registry=self.executor_registry, + derive_local_a2v=self.video_generation.derive_local_a2v_params, + queue_control=self.generation_queue, + progress_reader=self.generation.get_generation_progress, + config=self.config, + lora_catalog_provider=self._lora_catalog_provider, + state=self.state, + lock=self._lock, + ) + self.generation_queue.set_finished_listener( + self.queued_generations.remember_finished + ) + self.dashboard = DashboardHandler(store, self._lora_catalog_provider) @dataclass @@ -284,6 +459,8 @@ class ServiceBundle: a2v_pipeline_class: type[A2VPipeline] retake_pipeline_class: type[RetakePipeline] prompt_enhancer_pipeline_class: type[PromptEnhancerPipeline] + store: Store + generation_executors: Mapping[str, GenerationExecutor] | None = None def build_default_service_bundle(config: RuntimeConfig) -> ServiceBundle: @@ -334,9 +511,22 @@ def build_default_service_bundle(config: RuntimeConfig) -> ServiceBundle: a2v_pipeline_class=LTXa2vPipeline, retake_pipeline_class=LTXRetakePipeline, prompt_enhancer_pipeline_class=LtxPromptEnhancerPipeline, + store=open_store(config.app_data_dir), ) +def open_store(app_data_dir: Path) -> Store: + from services.sqlite_store import SqliteStore + + try: + return SqliteStore(app_data_dir) + except UnavailableError: + logger.warning( + "Store unavailable at %s", app_data_dir / "store.sqlite3", exc_info=True + ) + return UnavailableStore() + + def build_initial_state( config: RuntimeConfig, default_settings: AppSettings, @@ -365,4 +555,6 @@ def build_initial_state( a2v_pipeline_class=bundle.a2v_pipeline_class, retake_pipeline_class=bundle.retake_pipeline_class, prompt_enhancer_pipeline_class=bundle.prompt_enhancer_pipeline_class, + store=bundle.store, + generation_executors=bundle.generation_executors, ) diff --git a/backend/export_openapi_schema.py b/backend/export_openapi_schema.py index 3cadbc2ad..2e467e753 100644 --- a/backend/export_openapi_schema.py +++ b/backend/export_openapi_schema.py @@ -20,6 +20,7 @@ from state.app_settings import AppSettings from tests.fake_camera_motion_prompts import FAKE_CAMERA_MOTION_PROMPTS from tests.fakes.services import FakeServices +from services.sqlite_store import SqliteStore import torch DEFAULT_NEGATIVE_PROMPT = "openapi-export" @@ -71,6 +72,7 @@ def _build_schema() -> dict[str, object]: a2v_pipeline_class=cast(Any, type(fake.a2v_pipeline)), retake_pipeline_class=cast(Any, type(fake.retake_pipeline)), prompt_enhancer_pipeline_class=cast(Any, type(fake.prompt_enhancer_pipeline)), + store=SqliteStore(config.app_data_dir), ) handler = build_initial_state(config, AppSettings(), service_bundle=bundle) diff --git a/backend/frame_math.py b/backend/frame_math.py index 94f7071d7..788ab9b83 100644 --- a/backend/frame_math.py +++ b/backend/frame_math.py @@ -3,6 +3,7 @@ from __future__ import annotations from dataclasses import dataclass +from math import floor @dataclass(frozen=True) @@ -36,3 +37,35 @@ def compute_num_frames(duration_seconds: int, fps: int) -> int: """Frame count for a duration, snapped to the pipeline's (n - 1) % 8 == 0 grid.""" n = ((duration_seconds * fps) // 8) * 8 + 1 return max(n, 9) + + +def effective_a2v_audio_seconds( + audio_duration_seconds: float, + *, + cell_max_seconds: float, + longest_cell_seconds: float, + tolerance_seconds: float = 0.1, +) -> float | None: + """Seconds of the clip generation should hear. + + Inside this resolution's cell, the whole clip. Past this cell but inside a + longer one, only the opening cell max. Past every cell, None. Returning the + original length there would look like the whole clip is acceptable. + """ + if audio_duration_seconds < cell_max_seconds + tolerance_seconds: + return audio_duration_seconds + if ( + longest_cell_seconds <= cell_max_seconds + or audio_duration_seconds >= longest_cell_seconds + tolerance_seconds + ): + return None + return float(cell_max_seconds) + + +def num_frames_for_audio_duration( + duration_seconds: float, fps: float, *, max_frames: int +) -> int | None: + """Floor audio duration to the 8k+1 video grid, or report that it exceeds the cap.""" + latent_steps = max(1, floor((duration_seconds * fps - 1) / 8)) + num_frames = latent_steps * 8 + 1 + return None if num_frames > max_frames else num_frames diff --git a/backend/handlers/__init__.py b/backend/handlers/__init__.py index 3f598943f..053aebafe 100644 --- a/backend/handlers/__init__.py +++ b/backend/handlers/__init__.py @@ -1,6 +1,7 @@ """State handler exports.""" from handlers.download_handler import DownloadHandler +from handlers.feature_flags_handler import FeatureFlagsHandler from handlers.hf_auth_handler import HuggingFaceAuthHandler from handlers.generation_handler import GenerationHandler from handlers.health_handler import HealthHandler @@ -17,6 +18,8 @@ from handlers.settings_handler import SettingsHandler from handlers.text_handler import TextHandler from handlers.video_generation_handler import VideoGenerationHandler +from handlers.asset_handler import AssetHandler +from handlers.queued_generation_handler import QueuedGenerationHandler __all__ = [ "SettingsHandler", @@ -32,8 +35,11 @@ "RetakeHandler", "ExtendHandler", "RuntimePolicyHandler", + "FeatureFlagsHandler", "IcLoraHandler", "HuggingFaceAuthHandler", "LoraCatalogHandler", "PromptEnhancementHandler", + "AssetHandler", + "QueuedGenerationHandler", ] diff --git a/backend/handlers/_settings_utils.py b/backend/handlers/_settings_utils.py index 95a8cf932..57c6046c2 100644 --- a/backend/handlers/_settings_utils.py +++ b/backend/handlers/_settings_utils.py @@ -75,14 +75,16 @@ def collect_changed_paths(before: JSONValue, after: JSONValue, prefix: str = "") def migrate_legacy_settings(raw: Mapping[str, JSONValue]) -> JSONObject: + """Fold the per-conditioning API enhance gates back into one flag. + + The setting was split into T2V/I2V and is now a single control again. A saved file can + hold either shape, and the split pair can disagree: OR keeps enhancement on for anyone + who had it on for at least one conditioning, so nobody silently loses it on upgrade. + """ migrated: JSONObject = dict(raw) - if ( - "prompt_enhancer_enabled" in migrated - and "prompt_enhancer_enabled_t2v" not in migrated - ): - legacy_value = bool(migrated["prompt_enhancer_enabled"]) - migrated.setdefault("prompt_enhancer_enabled_t2v", legacy_value) - migrated.setdefault("prompt_enhancer_enabled_i2v", legacy_value) - - migrated.pop("prompt_enhancer_enabled", None) + t2v = migrated.pop("prompt_enhancer_enabled_t2v", None) + i2v = migrated.pop("prompt_enhancer_enabled_i2v", None) + if (t2v is not None or i2v is not None) and "prompt_enhancer_enabled" not in migrated: + migrated["prompt_enhancer_enabled"] = bool(t2v) or bool(i2v) + return migrated diff --git a/backend/handlers/asset_handler.py b/backend/handlers/asset_handler.py new file mode 100644 index 000000000..2e87ca8a0 --- /dev/null +++ b/backend/handlers/asset_handler.py @@ -0,0 +1,134 @@ +from __future__ import annotations + +from collections.abc import Callable + +from api_types import ( + Asset, + AssetListItem, + AssetListQuery, + AssetListResponse, + IngestAssetRequest, + TrimMediaRequest, +) +from _routes._errors import HTTPError +from services.audio_trim import extract_audio_asset, trim_audio_asset +from services.video_trim import trim_video_asset +from services.store import Store +from services.records import ( + AssetInUseError, + AssetRecord, + ListedAsset, + MediaError, + StatusError, + UnavailableError, +) + + +def _asset_to_api(record: AssetRecord) -> Asset: + return Asset.model_validate(record.model_dump(mode="json")) + + +def _listed_asset_to_api(item: ListedAsset) -> AssetListItem: + return AssetListItem.model_validate( + {**_asset_to_api(item.asset).model_dump(), "in_use": item.in_use} + ) + + +_MEDIA_ERROR_STATUS = { + "UNSUPPORTED_MEDIA": 422, + "INVALID_TRIM_RANGE": 422, + "TRIM_BUSY": 503, +} + + +class AssetHandler: + def __init__(self, store: Store) -> None: + self._db = store + + def ingest_asset(self, req: IngestAssetRequest) -> Asset: + try: + record = self._db.ingest_upload(req.path) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except FileNotFoundError as exc: + raise HTTPError( + 400, f"file not found: {req.path}", code="FILE_NOT_FOUND" + ) from exc + except MediaError as exc: + raise HTTPError(400, str(exc), code=exc.code) from exc + return _asset_to_api(record) + + def get_asset( + self, asset_id: str, *, tombstone_missing: bool = True + ) -> Asset: + try: + record = self._db.get_asset( + asset_id, tombstone_missing=tombstone_missing + ) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + if record is None: + raise HTTPError(404, "ASSET_NOT_FOUND") + return _asset_to_api(record) + + def list_assets( + self, query: AssetListQuery, *, tombstone_missing: bool = True + ) -> AssetListResponse: + try: + page = self._db.list_assets( + media_kind=query.media_kind, + sort=query.sort, + q=query.q, + cursor=query.cursor, + limit=query.limit, + tombstone_missing=tombstone_missing, + ) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except ValueError as exc: + raise HTTPError(400, str(exc)) from exc + return AssetListResponse( + items=[_listed_asset_to_api(item) for item in page.items], + next_cursor=page.next_cursor, + ) + + def delete_asset(self, asset_id: str) -> None: + try: + deleted = self._db.delete_asset(asset_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except AssetInUseError as exc: + raise HTTPError(409, "ASSET_IN_USE") from exc + except StatusError as exc: + raise HTTPError(409, "INVALID_GENERATION_STATUS") from exc + if not deleted: + raise HTTPError(404, "ASSET_NOT_FOUND") + + def trim_audio(self, asset_id: str, req: TrimMediaRequest) -> Asset: + if req.endSec <= req.startSec: + raise HTTPError(422, "INVALID_TRIM_RANGE") + return self._media_transform( + lambda: trim_audio_asset(self._db, asset_id, req.startSec, req.endSec) + ) + + def trim_video(self, asset_id: str, req: TrimMediaRequest) -> Asset: + if req.endSec <= req.startSec: + raise HTTPError(422, "INVALID_TRIM_RANGE") + return self._media_transform( + lambda: trim_video_asset(self._db, asset_id, req.startSec, req.endSec) + ) + + def extract_audio(self, asset_id: str) -> Asset: + return self._media_transform(lambda: extract_audio_asset(self._db, asset_id)) + + def _media_transform(self, produce: Callable[[], AssetRecord]) -> Asset: + try: + record = produce() + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except FileNotFoundError as exc: + raise HTTPError(404, "ASSET_NOT_FOUND") from exc + except MediaError as exc: + status = _MEDIA_ERROR_STATUS.get(exc.code, 400) + raise HTTPError(status, str(exc), code=exc.code) from exc + return _asset_to_api(record) diff --git a/backend/handlers/base.py b/backend/handlers/base.py index 470f4e3b9..08a0dfa5a 100644 --- a/backend/handlers/base.py +++ b/backend/handlers/base.py @@ -3,13 +3,19 @@ from __future__ import annotations import logging -import time +import random from collections.abc import Callable from functools import wraps from pathlib import Path from threading import RLock from typing import TYPE_CHECKING, Concatenate, ParamSpec, TypeVar +from _routes._errors import HTTPError +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, +) +from state.app_settings import MAX_GENERATION_SEED from state.app_state_types import AppState if TYPE_CHECKING: @@ -21,8 +27,15 @@ _R = TypeVar("_R") _S = TypeVar("_S", bound="StateHandlerBase") -# Largest 32-bit signed int; seeds are taken modulo this to stay in the pipeline's range. -_MAX_SEED = 2147483647 +def resolve_models_dir(state: AppState | None, config: RuntimeConfig) -> Path: + """Effective models dir: custom from settings, or the startup default. + + Shared by ``StateHandlerBase.models_dir`` and the queued-generation handler so + the custom-vs-default rule lives in one place. ``state`` may be ``None`` for + callers that only hold a config. + """ + custom = state.app_settings.models_dir if state is not None else None + return Path(custom) if custom else config.default_models_dir class StateHandlerBase: @@ -48,18 +61,32 @@ def config(self) -> RuntimeConfig: @property def models_dir(self) -> Path: """Effective models dir: custom from settings, or startup default.""" - custom = self._state.app_settings.models_dir - return Path(custom) if custom else self._config.default_models_dir + return resolve_models_dir(self._state, self._config) + + def _require_local_generation_possible(self, *, api_key: str | None = None) -> None: + """422 when this machine cannot generate locally and no API route is left. + + Pass the relevant key for entry points that can fall back to the API; omit it + for local-only entry points (the Explore queue, IC-LoRA), which can never + succeed on unsupported hardware no matter what keys are configured. + """ + if self.config.local_generations_mode != "unsupported": + return + if api_key is not None and api_key.strip(): + return + raise HTTPError( + 422, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + code=LOCAL_GENERATION_UNSUPPORTED, + ) def _resolve_seed(self) -> int: - """Resolve the generation seed: locked seed, dev-mode constant, or time-based.""" + """Resolve the generation seed from the lock or a fresh random draw.""" settings = self.state.app_settings if settings.seed_locked: logger.info("Using locked seed: %s", settings.locked_seed) return settings.locked_seed - if self.config.dev_mode: - return 1000 - return int(time.time()) % _MAX_SEED + return random.randint(0, MAX_GENERATION_SEED) def with_state_lock( diff --git a/backend/handlers/dashboard_handler.py b/backend/handlers/dashboard_handler.py new file mode 100644 index 000000000..e36cf9c53 --- /dev/null +++ b/backend/handlers/dashboard_handler.py @@ -0,0 +1,55 @@ +from __future__ import annotations + +from datetime import datetime + +from _routes._errors import HTTPError +from services.dashboard_stats import ( + DashboardSnapshot, + DashboardWindow, + InvalidTimezone, + LoraUsage, +) +from services.features.lora_recipes import LORA_RECIPES +from services.lora_catalog import LoraCatalogProvider +from services.records import UnavailableError +from services.store import Store + + +class DashboardHandler: + def __init__(self, store: Store, catalog: LoraCatalogProvider) -> None: + self._store = store + self._catalog = catalog + + def get( + self, + *, + window: DashboardWindow, + tz: str, + now: datetime | None = None, + ) -> DashboardSnapshot: + try: + snapshot = self._store.dashboard( + window=window, + tz=tz, + now=now, + ) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except InvalidTimezone as exc: + raise HTTPError(422, "Invalid timezone", code="INVALID_TIMEZONE") from exc + + return snapshot.model_copy( + update={ + "loras": snapshot.loras.model_copy( + update={"top": [self._named(usage) for usage in snapshot.loras.top]} + ) + } + ) + + def _named(self, usage: LoraUsage) -> LoraUsage: + """Runs made before names were stored carry the recipe id. The catalog still knows the name.""" + recipe = LORA_RECIPES.get(usage.feature) + if recipe is None or usage.name != usage.feature: + return usage + item = self._catalog.get_lora(recipe.catalog_id) + return usage if item is None else usage.model_copy(update={"name": item.name}) diff --git a/backend/handlers/extend_handler.py b/backend/handlers/extend_handler.py index a922e0f4d..2b51105d2 100644 --- a/backend/handlers/extend_handler.py +++ b/backend/handlers/extend_handler.py @@ -2,11 +2,12 @@ Mirrors ``RetakeHandler``'s dual API/local dispatch. Extend appends (``mode="end"``) or prepends (``mode="start"``) freshly generated frames to a source video. The cloud -``/v1/extend`` endpoint and the local PyTorch wrapper share this entry point. +``/v2/extend`` endpoint and the local PyTorch wrapper share this entry point. """ from __future__ import annotations +import logging import uuid from datetime import datetime from pathlib import Path @@ -25,6 +26,7 @@ from _routes._errors import HTTPError from api_model_specs import FORCED_API_MODEL_MAP from handlers.base import StateHandlerBase +from server_utils.heartbeat import log_heartbeat from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler from handlers.text_handler import TextHandler @@ -40,6 +42,7 @@ from runtime_config.runtime_config import RuntimeConfig from services.generation_interrupt import GenerationCancelledError, is_cancel_exception from services.ltx_api_client.ltx_api_client import LTXAPIClientError +from services.ltx_api_client.ltx_api_errors import map_ltx_api_client_error, missing_ltx_api_key_error from services.interfaces import LTXAPIClient from state.app_state_types import AppState from state.app_settings import should_video_generate_with_ltx_api @@ -48,6 +51,8 @@ _MIN_DURATION = 2.0 _MAX_DURATION = 20.0 +logger = logging.getLogger(__name__) + class ExtendHandler(StateHandlerBase): def __init__( @@ -79,6 +84,7 @@ def run(self, req: ExtendRequest) -> ExtendResponse: video_file = validate_source_video_path(video_path) + self._require_local_generation_possible(api_key=self.state.app_settings.ltx_api_key) if should_video_generate_with_ltx_api( force_api_generations=self.config.force_api_generations, settings=self.state.app_settings, @@ -116,7 +122,7 @@ def _run_api_extend( ) -> ExtendResponse: api_key = self.state.app_settings.ltx_api_key if not api_key: - raise HTTPError(400, "LTX API key not configured. Set it in Settings.") + raise missing_ltx_api_key_error() with self._generation.reserved_generation_start(): @@ -160,8 +166,9 @@ def _run_api_extend( raise HTTPError(500, "Extend API returned no result") except LTXAPIClientError as exc: - self._generation.fail_generation(exc.detail) - raise HTTPError(exc.status_code, exc.detail) from exc + mapped = map_ltx_api_client_error(exc) + self._generation.fail_generation(mapped.detail) + raise mapped from exc except HTTPError as exc: self._generation.fail_generation(exc.detail) raise @@ -193,28 +200,44 @@ def _run_local_extend( generation_id = uuid.uuid4().hex[:8] seed = self._resolve_seed() output_path = self.config.outputs_dir / f"extend_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{generation_id}.mp4" + logger.info( + "Extend %s started (%dx%d, %d source frames @ %g fps, %s +%d)", + generation_id, + target_width, + target_height, + target_frames, + fps, + mode, + extend_frames, + ) try: - pipeline_state = self._pipelines.load_retake_pipeline(distilled=True) + pipeline_state = self._pipelines.load_retake_pipeline( + distilled=True, + width=target_width, + height=target_height, + frames=target_frames + extend_frames, + ) self._generation.start_generation(generation_id) self._generation.update_progress("loading_model", 5, 0, 1) self._generation.update_progress("inference", 15, 0, 1) - pipeline_state.pipeline.extend( - video_path=str(video_file), - prompt=prompt, - extend_frames=extend_frames, - mode=mode, - seed=seed, - output_path=str(output_path), - negative_prompt=self.config.default_negative_prompt, - regenerate_audio=True, - enhance_prompt=False, - distilled=True, - target_width=target_width, - target_height=target_height, - target_frames=target_frames, - ) + with log_heartbeat("extend inference"): + pipeline_state.pipeline.extend( + video_path=str(video_file), + prompt=prompt, + extend_frames=extend_frames, + mode=mode, + seed=seed, + output_path=str(output_path), + negative_prompt=self.config.default_negative_prompt, + regenerate_audio=True, + enhance_prompt=False, + distilled=True, + target_width=target_width, + target_height=target_height, + target_frames=target_frames, + ) # Denoiser interrupt cannot abort VAE decode / ffmpeg; a Stop after the last # denoise step still finishes encode, then this check drops the file. diff --git a/backend/handlers/feature_flags_handler.py b/backend/handlers/feature_flags_handler.py new file mode 100644 index 000000000..1dd6baa8d --- /dev/null +++ b/backend/handlers/feature_flags_handler.py @@ -0,0 +1,45 @@ +"""Dev feature flags persisted in feature_flags.json next to settings.json.""" + +from __future__ import annotations + +import json +import logging +import os +from threading import RLock + +from api_types import FeatureFlags, FeatureFlagsPatch +from runtime_config.runtime_config import RuntimeConfig + +logger = logging.getLogger(__name__) + +FEATURE_FLAGS_FILENAME = "feature_flags.json" + + +class FeatureFlagsHandler: + def __init__(self, lock: RLock, config: RuntimeConfig) -> None: + self._lock = lock + self._path = config.app_data_dir / FEATURE_FLAGS_FILENAME + + def get_flags(self) -> FeatureFlags: + with self._lock: + return self._read() + + def update_flags(self, patch: FeatureFlagsPatch) -> FeatureFlags: + with self._lock: + # None means "leave unchanged" (omitted or explicit null). + merged = FeatureFlags.model_validate( + {**self._read().model_dump(), **patch.model_dump(exclude_none=True)} + ) + tmp_path = self._path.with_suffix(".json.tmp") + tmp_path.write_text(json.dumps(merged.model_dump(), indent=2), encoding="utf-8") + os.replace(tmp_path, self._path) + return merged + + def _read(self) -> FeatureFlags: + try: + return FeatureFlags.model_validate_json(self._path.read_text(encoding="utf-8")) + except FileNotFoundError: + return FeatureFlags() + except (OSError, ValueError) as exc: + logger.warning("Could not read %s, using defaults: %s", self._path, exc) + return FeatureFlags() diff --git a/backend/handlers/generation_handler.py b/backend/handlers/generation_handler.py index 499f9c81a..421ccada1 100644 --- a/backend/handlers/generation_handler.py +++ b/backend/handlers/generation_handler.py @@ -6,7 +6,7 @@ import time from collections.abc import Iterator from contextlib import contextmanager -from threading import RLock +from threading import Condition, Event, RLock from typing import TYPE_CHECKING, Literal from _routes._errors import HTTPError @@ -19,6 +19,7 @@ from handlers.base import StateHandlerBase, with_state_lock from services import generation_interrupt from services.generation_interrupt import GenerationCancelledError +from services.generation_queue.control import GenerationSlotWaitAborted from services.patches import diffusion_stage_cache from state.app_state_types import ( ApiGeneration, @@ -40,11 +41,41 @@ # Generous vs. any realistic pipeline load, but bounds how long a reservation can block future # generations if some path raises before ever reaching start_generation()/fail_generation(). _RESERVATION_TIMEOUT_S = 180 +# shutdown is an Event, not the Condition; waiters must re-check it after a bounded wait. +_SLOT_WAIT_POLL_S = 0.05 class GenerationHandler(StateHandlerBase): def __init__(self, state: AppState, lock: RLock, config: RuntimeConfig) -> None: super().__init__(state, lock, config) + self._generation_slot = Condition(self._lock) + from services.denoising_progress import configure_sink + + configure_sink(self._on_denoise_step) + + def _on_denoise_step(self, current: int, total: int) -> None: + from services.denoising_progress import inference_percent + + self.update_progress("inference", inference_percent(current, total), current, total) + + def _generation_start_block_reason(self) -> str | None: + """Return why the shared slot cannot be claimed, or None if it is free. + + Caller must hold the state lock. Same rules as try_reserve_generation_start(). + """ + since = self.state.generation_starting_since + if self.is_generation_running(): + return "a generation is already running" + if self.state.generation_in_flight: + # After start_generation(), starting_since is None and in_flight stays True through + # generate() unwind — do not expire that. Only a pre-start reservation whose + # timestamp aged out (no finally) is reclaimable. + if since is None or time.monotonic() - since < _RESERVATION_TIMEOUT_S: + return "a generation is still in flight" + return None + if since is not None and time.monotonic() - since < _RESERVATION_TIMEOUT_S: + return "another reservation is still active" + return None @with_state_lock def try_reserve_generation_start(self) -> bool: @@ -58,19 +89,9 @@ def try_reserve_generation_start(self) -> bool: is a backstop for a reservation that never got a context finally (legacy try_reserve without the context manager). """ - since = self.state.generation_starting_since - if self.is_generation_running(): - logger.info("Generation start reservation denied: a generation is already running") - return False - if self.state.generation_in_flight: - # After start_generation(), starting_since is None and in_flight stays True through - # generate() unwind — do not expire that. Only a pre-start reservation whose - # timestamp aged out (no finally) is reclaimable. - if since is None or time.monotonic() - since < _RESERVATION_TIMEOUT_S: - logger.info("Generation start reservation denied: a generation is still in flight") - return False - elif since is not None and time.monotonic() - since < _RESERVATION_TIMEOUT_S: - logger.info("Generation start reservation denied: another reservation is still active") + reason = self._generation_start_block_reason() + if reason is not None: + logger.info("Generation start reservation denied: %s", reason) return False self.state.generation_in_flight = True self.state.generation_starting_since = time.monotonic() @@ -81,6 +102,36 @@ def release_generation_start_reservation(self) -> None: self.state.generation_in_flight = False self.state.generation_starting_since = None generation_interrupt.clear() + self._generation_slot.notify_all() + + @contextmanager + def wait_for_generation_slot(self, shutdown: Event) -> Iterator[None]: + """Block until the shared generation reservation is free, then hold it. + + Unlike reserved_generation_start(), this waits instead of raising 409. + shutdown aborts the wait without claiming the slot (the with-body is + skipped) by raising GenerationSlotWaitAborted. Waiters are notified + from release_generation_start_reservation(). + """ + reserved = False + try: + with self._generation_slot: + while True: + if shutdown.is_set(): + break + if ( + self._generation_start_block_reason() is None + and self.try_reserve_generation_start() + ): + reserved = True + break + self._generation_slot.wait(timeout=_SLOT_WAIT_POLL_S) + if not reserved: + raise GenerationSlotWaitAborted() + yield + finally: + if reserved: + self.release_generation_start_reservation() @contextmanager def reserved_generation_start(self) -> Iterator[None]: @@ -126,6 +177,9 @@ def start_generation(self, generation_id: str) -> None: diffusion_stage_cache.set_enabled(self.state.app_settings.diffusion_stage_cache_enabled) diffusion_stage_cache.evict() generation_interrupt.clear() + from services.denoising_progress import configure_sink + + configure_sink(self._on_denoise_step) self.state.active_generation = GpuGeneration( state=GenerationRunning( diff --git a/backend/handlers/ic_lora_handler.py b/backend/handlers/ic_lora_handler.py index d9446188a..58ce4cb5b 100644 --- a/backend/handlers/ic_lora_handler.py +++ b/backend/handlers/ic_lora_handler.py @@ -9,52 +9,76 @@ from datetime import datetime from pathlib import Path from threading import RLock -from typing import TYPE_CHECKING + +from PIL import UnidentifiedImageError from api_types import ( ConditioningType, + IcLoraCatalogItem, IcLoraExtractRequest, IcLoraExtractResponse, IcLoraGenerateCancelledResponse, IcLoraGenerateCompleteResponse, IcLoraGenerateRequest, IcLoraGenerateResponse, - ImageConditioningInput, - IcLoraCatalogItem, + IcLoraImageInput, IcLoraSettings, + ImageConditioningInput, + LTXLocalModelId, ) from _routes._errors import HTTPError from frame_math import compute_num_frames, snap_to_frame_grid from handlers.base import StateHandlerBase from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler +from handlers.prompt_enhancement_handler import PromptEnhancementHandler from handlers.text_handler import TextHandler from ic_lora_preprocessing import MediaArtifact, OutpaintParams, PreprocessingContext, run_preprocessing +from runtime_config.ic_lora_job_budget import ( + IcLoraJobLoad, + IcLoraJobReject, + catalog_output_fps, + decide_ic_lora_job, +) +from runtime_config.ic_lora_local_envelope import ( + IC_LORA_SOURCE_TOO_LARGE, + IC_LORA_V1_ENVELOPE_MESSAGE, + effective_denoise_stage1, + ic_lora_output_canvas, +) +from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.ic_lora_tiling import IcLoraTiling +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + VIDEO_JOB_TOO_LARGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, +) from runtime_config.ltx_capabilities import local_caps, supports from runtime_config.model_download_specs import ( DEPTH_PROCESSOR_CP_ID, + catalog_item_visible_for_installed_ltx, find_installed_ic_lora_path, get_existing_cp_path, get_ltx_model_spec, + ltx_catalog_family_for_model, resolve_active_ltx_model_id, resolve_ic_lora_path, ) from runtime_config.models_scanner import is_ic_lora_file, resolve_lora_ref from runtime_config.runtime_config import RuntimeConfig +from runtime_config.video_job_budget import memory_gb_for_job from state.conditioning_cache import ConditioningCacheEntry, ConditioningCacheKey from services.interfaces import VideoProcessor from services.lora_catalog import LoraCatalogProvider from services.services_utils import FrameArray from server_utils.heartbeat import log_heartbeat +from server_utils.oriented_image import open_oriented_image from services.generation_interrupt import GenerationCancelledError, is_cancel_exception from state.app_state_types import AppState, ICLoraState -if TYPE_CHECKING: - from runtime_config.runtime_config import RuntimeConfig - logger = logging.getLogger(__name__) -_DEFAULT_IC_LORA_FPS = 24 _IMAGE_SUFFIXES = frozenset({".png", ".jpg", ".jpeg", ".webp", ".bmp"}) _VIDEO_SUFFIXES = frozenset({".mp4", ".mov", ".avi", ".webm", ".mkv"}) @@ -73,13 +97,38 @@ def _validate_input_kind(input_path: str, expected_kind: str) -> None: raise HTTPError(400, f"This IC-LoRA expects {expected_kind} input, but got '{suffix or 'a file with no extension'}'") +def _reference_frame_idx(ic_lora: IcLoraCatalogItem, img: IcLoraImageInput) -> int: + """The frame a reference image conditions. + + A catalog pin always wins. Every Home recipe is pinned (``is_home_recipe``), + so it never reads the request frame. Only an unpinned entry, from the Studio + form, uses the request frame. + """ + pinned = ic_lora.reference_image_frame + return pinned if pinned is not None else int(img.frame) + + def _resolve_settings(req: IcLoraGenerateRequest, base: IcLoraSettings) -> IcLoraSettings: """Overlay the request's explicit settings onto a base; None means 'keep the base'.""" + requested_stage2_lora = ( + base.use_lora_in_stage_2 if req.use_lora_in_stage_2 is None else req.use_lora_in_stage_2 + ) + if requested_stage2_lora: + logger.warning("[ic-lora] use_lora_in_stage_2 is deprecated and ignored (LTXP-514)") + # A tiled entry runs one stage only. The catalog sets it, so a request override + # (GenSpace advanced controls send one) cannot turn stage 2 back on. + skip_stage_2 = ( + True + if base.tiling is not None + else base.skip_stage_2 if req.skip_stage_2 is None else req.skip_stage_2 + ) return IcLoraSettings( - skip_stage_2=base.skip_stage_2 if req.skip_stage_2 is None else req.skip_stage_2, - use_lora_in_stage_2=( - base.use_lora_in_stage_2 if req.use_lora_in_stage_2 is None else req.use_lora_in_stage_2 - ), + skip_stage_2=skip_stage_2, + use_lora_in_stage_2=False, + # Stage 2 does not run when skipped, so the flag would only change the cache key. + stage_2_ic_lora=base.stage_2_ic_lora and not skip_stage_2, + # Catalog only. A request cannot change the tile size. + tiling=base.tiling, resolution_factor=base.resolution_factor if req.resolution_factor is None else req.resolution_factor, audio_mode=base.audio_mode if req.audio_mode is None else req.audio_mode, lora_strength=base.lora_strength if req.lora_strength is None else req.lora_strength, @@ -91,10 +140,7 @@ def _resolve_settings(req: IcLoraGenerateRequest, base: IcLoraSettings) -> IcLor def _ic_lora_output_fps(ic_lora: IcLoraCatalogItem) -> int: """The fps the IC-LoRA's control video runs at — the image_to_frames step's fps param.""" - for step in ic_lora.preprocessing: - if step.utility == "image_to_frames": - return int(step.params.get("fps", _DEFAULT_IC_LORA_FPS)) # type: ignore[arg-type] - return _DEFAULT_IC_LORA_FPS + return catalog_output_fps(ic_lora) class IcLoraHandler(StateHandlerBase): @@ -105,6 +151,7 @@ def __init__( generation_handler: GenerationHandler, pipelines_handler: PipelinesHandler, text_handler: TextHandler, + prompt_enhancement_handler: PromptEnhancementHandler, video_processor: VideoProcessor, lora_catalog: LoraCatalogProvider, config: RuntimeConfig, @@ -113,9 +160,100 @@ def __init__( self._generation = generation_handler self._pipelines = pipelines_handler self._text = text_handler + self._prompt_enhancement = prompt_enhancement_handler self._video_processor = video_processor self._catalog = lora_catalog + def _ic_lora_job( + self, + canvas_width: int, + canvas_height: int, + *, + frame_count: int, + stage_mode: IcLoraStageMode, + resolution_factor: float, + stills: int = 0, + tiling: IcLoraTiling | None = None, + ) -> IcLoraJobLoad: + """422, or pick full vs stream and the chunk window for this job. + + Does not change process mode. The pipeline runs the window this returns.""" + stage1_w, stage1_h = effective_denoise_stage1( + canvas_width, + canvas_height, + skip_stage_2=stage_mode is IcLoraStageMode.SINGLE_STAGE, + resolution_factor=resolution_factor, + ) + darwin = self.config.darwin_unified_memory + memory_gb = memory_gb_for_job( + vram_gb=self.config.vram_gb, + available_ram_gb=self.config.available_ram_gb, + darwin=darwin, + ) + decision = decide_ic_lora_job( + stage1_w, + stage1_h, + frame_count, + memory_gb=memory_gb, + process_mode=self.config.local_generations_mode, + stage_mode=stage_mode, + darwin=darwin, + stills=stills, + tiling=tiling, + ) + outcome = "reject" if isinstance(decision, IcLoraJobReject) else decision.mode + logger.info( + "[ic-lora] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s", + decision.seq, + decision.full_gib, + decision.stream_gib, + outcome, + ) + if isinstance(decision, IcLoraJobReject): + if decision.reason == "spatial": + raise HTTPError(422, IC_LORA_V1_ENVELOPE_MESSAGE, code=IC_LORA_SOURCE_TOO_LARGE) + if decision.reason == "unsupported": + raise HTTPError( + 422, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + code=LOCAL_GENERATION_UNSUPPORTED, + ) + raise HTTPError(422, VIDEO_JOB_TOO_LARGE_MESSAGE, code=VIDEO_JOB_TOO_LARGE) + return decision + + def _probe_ic_lora_source( + self, path: str, kind: str, requested_frames: int + ) -> tuple[int, int, int]: + """Width, height, and snapped frame count from the user file — before preprocess.""" + if kind == "image": + try: + width, height = open_oriented_image(path).size + except (UnidentifiedImageError, OSError) as exc: + raise HTTPError(400, "Could not read the input image.") from exc + return width, height, requested_frames + cap = self._video_processor.open_video(path) + try: + if not cap.isOpened(): + raise HTTPError(400, "Could not read the input video.") + info = self._video_processor.get_video_info(cap) + finally: + self._video_processor.release(cap) + width, height = int(info["width"]), int(info["height"]) + if width <= 0 or height <= 0: + raise HTTPError(400, "Could not read the input video.") + src_frames = int(info["frame_count"]) or requested_frames + return width, height, snap_to_frame_grid(src_frames, floor=9) + + def _drop_preprocess_artifact(self, artifact_path: str | None, source_path: str) -> None: + if not artifact_path or artifact_path == source_path: + return + path = Path(artifact_path).resolve() + try: + path.relative_to(self.config.outputs_dir.resolve()) + except ValueError: + return + path.unlink(missing_ok=True) + def _build_conditioning_frame( self, frame: FrameArray, @@ -141,16 +279,14 @@ def _require_ic_lora_model_paths(self, conditioning_type: ConditioningType) -> t if not supports(local_caps(model_id), "ic_lora"): raise HTTPError( 409, - "Built-in control IC-LoRA is not available for the active LTX model. " - "Switch to an LTX 2.3 local model to use depth/canny control.", + "Built-in control IC-LoRA is not available for the active LTX model.", code="UNSUPPORTED_IC_LORA", ) ic_loras_spec = get_ltx_model_spec(model_id).ic_loras_spec if ic_loras_spec is None: raise HTTPError( 409, - "Built-in control IC-LoRA is not available for the active LTX model. " - "Switch to an LTX 2.3 local model to use depth/canny control.", + "Built-in control IC-LoRA is not available for the active LTX model.", code="UNSUPPORTED_IC_LORA", ) depth_model_path: Path | None = None @@ -183,9 +319,12 @@ def extract_conditioning(self, req: IcLoraExtractRequest) -> IcLoraExtractRespon ic_state: ICLoraState | None = None if req.conditioning_type == "depth": lora_path, depth_model_path = self._require_ic_lora_model_paths(req.conditioning_type) + # One-frame preview. Streaming matches Darwin and 8s+ generate on 32 GB so + # extract does not warm a full-resident slot that generate then evicts. ic_state = self._pipelines.load_ic_lora( str(lora_path), str(depth_model_path), + mode="streaming_models_loading", ) result = self._build_conditioning_frame(frame, req.conditioning_type, ic_state) @@ -200,6 +339,11 @@ def extract_conditioning(self, req: IcLoraExtractRequest) -> IcLoraExtractRespon frame_time=req.frame_time, ) + @staticmethod + def _frame_count_after_fps_override(frame_count: int, src_fps: float, target_fps: float) -> int: + duration = frame_count / src_fps + return snap_to_frame_grid(round(duration * target_fps), floor=1) + def _resample_control_fps( self, control_video_path: str, frame_count: int, src_fps: float, target_fps: float ) -> tuple[str, int, float]: @@ -209,8 +353,7 @@ def _resample_control_fps( at the cost of choppier motion. Keeps the output duration ~constant and the frame count valid for the pipeline ((n-1) % 8 == 0). """ - duration = frame_count / src_fps - new_count = snap_to_frame_grid(round(duration * target_fps), floor=1) + new_count = self._frame_count_after_fps_override(frame_count, src_fps, target_fps) cap = self._video_processor.open_video(control_video_path) info = self._video_processor.get_video_info(cap) size = (int(info["width"]), int(info["height"])) @@ -266,175 +409,298 @@ def _complete_or_drop_cancelled(self, output_path: Path) -> None: self._generation.update_progress("complete", 100, 1, 1) self._generation.complete_generation(str(output_path)) - def _generate_ic_lora(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: - assert req.ic_lora_id is not None # branch guard in generate() - with self._generation.reserved_generation_start(): - ic_lora = self._catalog.get_ic_lora(req.ic_lora_id) - if ic_lora is None: - raise HTTPError(404, "UNKNOWN_IC_LORA") - # IC-LoRA catalog entries always define a driving input (base field is optional for plain LoRAs). - assert ic_lora.input is not None, "IC-LoRA ic_lora is missing its input spec" - has_prompt = bool(req.prompt.strip()) - # A prompt is required unless this catalog entry opts into promptless runs (e.g. outpainting). - if not has_prompt and not ic_lora.allows_empty_prompt: - raise HTTPError(400, "Prompt is required for this IC-LoRA") - if not req.input_path or not Path(req.input_path).exists(): - raise HTTPError(400, f"Input not found: {req.input_path}") - # The input file must match the kind this IC-LoRA drives on (image vs video) — fail fast - # with a clean 400 instead of a deep pipeline 500 when e.g. an image is fed to a video entry. - _validate_input_kind(req.input_path, ic_lora.input.kind) - # Reference images (when the entry allows them) must exist — fail fast with a clean 400 - # rather than surfacing a deep pipeline error later. - if ic_lora.allows_reference_image: - for img in req.images: - if not Path(img.path).exists(): - raise HTTPError(400, f"Reference image not found: {img.path}") - if req.variant_id is not None: - variant = ic_lora.download.resolve_variant(req.variant_id) - if variant is None: - raise HTTPError(404, "UNKNOWN_DOWNLOAD_VARIANT") - lora_path = resolve_ic_lora_path(self.models_dir, ic_lora.id, variant.filename) - if not lora_path.exists(): - raise HTTPError(409, "IC_LORA_NOT_DOWNLOADED") - else: - lora_path = find_installed_ic_lora_path( - self.models_dir, ic_lora.id, ic_lora.download.candidate_filenames() - ) - if lora_path is None: - raise HTTPError(409, "IC_LORA_NOT_DOWNLOADED") - - control_values = self._resolve_control_values(req, ic_lora) - duration = int(control_values.get("duration", 5)) - requested_frames = compute_num_frames(duration, _ic_lora_output_fps(ic_lora)) - - # IC-LoRA defaults, with any explicit UI override (e.g. skip_stage_2) applied on top. - s = _resolve_settings(req, ic_lora.default_settings) - generation_id = uuid.uuid4().hex[:8] - logger.info("[ic-lora] IC-LoRA generation started (ic_lora=%s)", ic_lora.id) - try: - # IC-LoRA preprocessing builds the control video itself; no depth processor needed. - ic_state = self._pipelines.load_ic_lora(str(lora_path), None, s.lora_strength) - self._generation.start_generation(generation_id) - self._generation.update_progress("loading_model", 5, 0, 1) - - use_api = not self._text.should_use_local_encoding() - # Never enhance an empty prompt — there's nothing to expand and the enhancer would hallucinate. - enhance_prompt = use_api and self.state.app_settings.prompt_enhancer_enabled_t2v and has_prompt - self._text.prepare_text_encoding(req.prompt, enhance_prompt=enhance_prompt) - self._generation.raise_if_cancelled() + def generate_local_reserved( + self, + req: IcLoraGenerateRequest, + *, + generation_id: str, + output_path: Path, + local_model_id: LTXLocalModelId, + seed: int, + explore_generation: bool = True, + explicit_generation_seed: bool = False, + ) -> IcLoraGenerateResponse: + """Local-only Home/Remote entry. The checkpoint id is required. + + The caller already holds the GPU slot and allocated ``output_path``. + GenSpace ``generate()`` still reaches ``_generate_ic_lora`` under + ``reserved_generation_start()``, where ``local_model_id`` may be unset. + """ + self._require_local_generation_possible() + assert req.ic_lora_id is not None + return self._generate_ic_lora( + req, + generation_id=generation_id, + output_path=output_path, + local_model_id=local_model_id, + seed=seed, + explore_generation=explore_generation, + explicit_generation_seed=explicit_generation_seed, + ) - input_artifact = MediaArtifact(path=req.input_path, kind=ic_lora.input.kind) - ctx = PreprocessingContext( - num_frames=requested_frames, - outputs_dir=self.config.outputs_dir, - video_processor=self._video_processor, - outpaint=self._outpaint_from_request(req), + def _generate_ic_lora( + self, + req: IcLoraGenerateRequest, + *, + generation_id: str, + output_path: Path, + local_model_id: LTXLocalModelId | None, + seed: int, + explore_generation: bool, + explicit_generation_seed: bool = False, + ) -> IcLoraGenerateResponse: + assert req.ic_lora_id is not None + ic_lora = self._catalog.get_ic_lora(req.ic_lora_id) + if ic_lora is None: + raise HTTPError(404, "UNKNOWN_IC_LORA") + if not catalog_item_visible_for_installed_ltx(ic_lora.supported_models, self.models_dir): + raise HTTPError(422, "IC_LORA_UNSUPPORTED_MODEL") + if ( + local_model_id is not None + and not ic_lora.supports_family(ltx_catalog_family_for_model(local_model_id)) + ): + raise HTTPError(422, "IC_LORA_UNSUPPORTED_MODEL") + # IC-LoRA catalog entries always define a driving input (base field is optional for plain LoRAs). + assert ic_lora.input is not None, "IC-LoRA ic_lora is missing its input spec" + has_prompt = bool(req.prompt.strip()) + # A prompt is required unless this catalog entry opts into promptless runs (e.g. outpainting). + if not has_prompt and not ic_lora.allows_empty_prompt: + raise HTTPError(400, "Prompt is required for this IC-LoRA") + if not req.input_path or not Path(req.input_path).exists(): + raise HTTPError(400, f"Input not found: {req.input_path}") + # The input file must match the kind this IC-LoRA drives on (image vs video) — fail fast + # with a clean 400 instead of a deep pipeline 500 when e.g. an image is fed to a video entry. + _validate_input_kind(req.input_path, ic_lora.input.kind) + # Reference images (when the entry allows them) must exist — fail fast with a clean 400 + # rather than surfacing a deep pipeline error later. + if ic_lora.reference_image_required and not req.images: + raise HTTPError(400, "A reference image is required for this IC-LoRA") + if ic_lora.allows_reference_image: + for img in req.images: + if not Path(img.path).exists(): + raise HTTPError(400, f"Reference image not found: {img.path}") + if req.variant_id is not None: + variant = ic_lora.download.resolve_variant(req.variant_id) + if variant is None: + raise HTTPError(404, "UNKNOWN_DOWNLOAD_VARIANT") + lora_path = resolve_ic_lora_path(self.models_dir, ic_lora.id, variant.filename) + if not lora_path.exists(): + raise HTTPError(409, "IC_LORA_NOT_DOWNLOADED") + else: + lora_path = find_installed_ic_lora_path( + self.models_dir, ic_lora.id, ic_lora.download.candidate_filenames() + ) + if lora_path is None: + raise HTTPError(409, "IC_LORA_NOT_DOWNLOADED") + + control_values = self._resolve_control_values(req, ic_lora) + duration = int(control_values.get("duration", 5)) + requested_frames = compute_num_frames(duration, _ic_lora_output_fps(ic_lora)) + + # IC-LoRA defaults, with any explicit UI override (e.g. skip_stage_2) applied on top. + s = _resolve_settings(req, ic_lora.default_settings) + stage_mode = s.stage_mode + # Optional reference image (e.g. a photoreal seed for 3D-render): conditions the + # first frame. Only honoured when the catalog entry opts in; ignored otherwise. + reference_images: list[ImageConditioningInput] = ( + [ + ImageConditioningInput( + path=img.path, + frame_idx=_reference_frame_idx(ic_lora, img), + strength=float(img.strength), ) - control = run_preprocessing(ic_lora.preprocessing, input_artifact, ctx) - control_video_path = control.path - - cap = self._video_processor.open_video(control_video_path) - info = self._video_processor.get_video_info(cap) - self._video_processor.release(cap) - input_width, input_height = int(info["width"]), int(info["height"]) - - if control.frame_count: - # Preprocessed control video (image_to_frames at the chosen duration, or an - # outpaint canvas). Snap to the pipeline's grid: image_to_frames already coerces, - # but _outpaint_canvas returns its raw written count, which can be off-grid. - frame_count, fps = snap_to_frame_grid(control.frame_count, floor=9), control.fps or 24.0 - else: - # Video IC-LoRAs: transform the whole input clip — match its length and fps, - # snapped to the pipeline's (n - 1) % 8 == 0 grid (not the duration control). - src_frames = int(info["frame_count"]) or requested_frames - frame_count = snap_to_frame_grid(src_frames, floor=9) - fps = float(info["fps"]) or 24.0 + for img in req.images + ] + if ic_lora.allows_reference_image + else [] + ) + stills = sum(1 for img in reference_images if img.frame_idx < 0) + logger.info("[ic-lora] IC-LoRA generation started (ic_lora=%s)", ic_lora.id) + try: + probe_w, probe_h, probe_frames = self._probe_ic_lora_source( + req.input_path, ic_lora.input.kind, requested_frames + ) + width, height, resolution_factor = ic_lora_output_canvas( + skip_stage_2=s.skip_stage_2, + resolution_factor=s.resolution_factor, + input_width=probe_w, + input_height=probe_h, + resolution=req.resolution, + stage_2_ic_lora=s.stage_2_ic_lora, + ) + job = self._ic_lora_job( + width, + height, + frame_count=probe_frames, + stage_mode=stage_mode, + resolution_factor=resolution_factor, + stills=stills, + tiling=s.tiling, + ) + resolved_prompt = self._prompt_enhancement.resolve_for_generation( + req.prompt, + provenance=req.prompt_provenance, + generation_seed=seed, + explicit_generation_seed=explicit_generation_seed, + ic_lora=ic_lora, + local_model_id=local_model_id, + explore_generation=explore_generation, + ) + prompt = resolved_prompt.prompt + enhance_via_api = resolved_prompt.enhance_via_api - self._generation.update_progress("inference", 15, 0, 1) - if s.resolution_factor == 0 and s.skip_stage_2: - # "Source dimensions" (resolution_factor sentinel 0): land the output at the - # source resolution instead of the 768 bucket. skip_stage_2 renders at - # canvas//2, so pass 2*source and render at factor 1.0; the pipeline snaps to - # /128, so final dims are multiples of 64 (source dims that aren't are snapped - # to the nearest, e.g. 540 -> 512). - width = max(128, 2 * input_width) - height = max(128, 2 * input_height) - resolution_factor = 1.0 - elif s.use_lora_in_stage_2 and not s.skip_stage_2: - # IC-LoRA kept in Stage 2 → mirror the t2v two-stage flow: land the output at - # the chosen resolution (or source if unset). Snap each edge down to a multiple - # of 128 (Stage 1 runs at canvas//2 and its latent must be even for the 2x - # patchify) and never upscale above source. - target_w = req.resolution.width if req.resolution else input_width - target_h = req.resolution.height if req.resolution else input_height - width = max(128, (min(target_w, input_width) // 128) * 128) - height = max(128, (min(target_h, input_height) // 128) * 128) - # The pipeline only consumes resolution_factor on the skip_stage_2 path, so it - # has no effect here (two-stage lands at the width/height above). Pass 1.0. - resolution_factor = 1.0 - else: - width = 768 - height = max(round(width * input_height / input_width / 128) * 128, 128) - resolution_factor = s.resolution_factor - output_path = ( - self.config.outputs_dir - / f"ic_lora_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}.mp4" - ) - # Optional reference image (e.g. a photoreal seed for 3D-render): conditions the - # first frame. Only honoured when the catalog entry opts in; ignored otherwise. - reference_images: list[ImageConditioningInput] = ( - [ - ImageConditioningInput(path=img.path, frame_idx=int(img.frame), strength=float(img.strength)) - for img in req.images - ] - if ic_lora.allows_reference_image - else [] + # start_generation requires gpu_slot. Load first so preprocess is not stuck + # on phase=starting (Stop only takes effect once the job is Running). + ic_state = self._pipelines.load_ic_lora( + str(lora_path), + None, + s.lora_strength, + mode=job.mode, + ltx_model_id=local_model_id, + stage_2_ic_lora=s.stage_2_ic_lora, + tiling=s.tiling, + ) + self._generation.start_generation(generation_id) + self._generation.update_progress("loading_model", 5, 0, 1) + + input_artifact = MediaArtifact(path=req.input_path, kind=ic_lora.input.kind) + ctx = PreprocessingContext( + num_frames=requested_frames, + outputs_dir=self.config.outputs_dir, + video_processor=self._video_processor, + outpaint=self._outpaint_from_request(req), + on_frame=self._generation.raise_if_cancelled, + ) + control = run_preprocessing(ic_lora.preprocessing, input_artifact, ctx) + control_video_path = control.path + + cap = self._video_processor.open_video(control_video_path) + info = self._video_processor.get_video_info(cap) + self._video_processor.release(cap) + input_width, input_height = int(info["width"]), int(info["height"]) + + if control.frame_count: + # Preprocessed control video (image_to_frames at the chosen duration, or an + # outpaint canvas). Snap to the pipeline's grid: image_to_frames already coerces, + # but _outpaint_canvas returns its raw written count, which can be off-grid. + frame_count, fps = snap_to_frame_grid(control.frame_count, floor=9), control.fps or 24.0 + else: + # Video IC-LoRAs: transform the whole input clip — match its length and fps, + # snapped to the pipeline's (n - 1) % 8 == 0 grid (not the duration control). + src_frames = int(info["frame_count"]) or requested_frames + frame_count = snap_to_frame_grid(src_frames, floor=9) + fps = float(info["fps"]) or 24.0 + + if (input_width, input_height, frame_count) != (probe_w, probe_h, probe_frames): + width, height, resolution_factor = ic_lora_output_canvas( + skip_stage_2=s.skip_stage_2, + resolution_factor=s.resolution_factor, + input_width=input_width, + input_height=input_height, + resolution=req.resolution, + stage_2_ic_lora=s.stage_2_ic_lora, ) - seed = self._resolve_seed() - with log_heartbeat("ic-lora inference"): - ic_state.pipeline.generate( - prompt=req.prompt, - seed=seed, - height=height, - width=width, - num_frames=frame_count, - frame_rate=fps, - images=reference_images, - video_conditioning=[(control_video_path, s.conditioning_strength)], - output_path=str(output_path), - skip_stage_2=s.skip_stage_2, - use_lora_in_stage_2=s.use_lora_in_stage_2, + try: + new_job = self._ic_lora_job( + width, + height, + frame_count=frame_count, + stage_mode=stage_mode, resolution_factor=resolution_factor, - source_audio_path=( - req.input_path - if s.audio_mode == "source" and ic_lora.input.kind == "video" - else None - ), - mute_audio=s.audio_mode == "off", - conditioning_mask_path=control.mask_path, + stills=stills, + tiling=s.tiling, + ) + except HTTPError: + self._drop_preprocess_artifact(control_video_path, req.input_path) + self._drop_preprocess_artifact(control.mask_path, req.input_path) + raise + reload = new_job.mode != job.mode + job = new_job + if reload: + ic_state = self._pipelines.load_ic_lora( + str(lora_path), + None, + s.lora_strength, + mode=job.mode, + ltx_model_id=local_model_id, + stage_2_ic_lora=s.stage_2_ic_lora, + tiling=s.tiling, ) - self._complete_or_drop_cancelled(output_path) - return IcLoraGenerateCompleteResponse(status="complete", video_path=str(output_path)) - except HTTPError: - self._generation.fail_generation("IC-LoRA generation failed") - raise - except ValueError as exc: - # run_preprocessing raises ValueError for user-fixable input (bad pads, unreadable - # media, >+100% outpaint) — surface it as a 400 so the user sees what to fix. - self._generation.fail_generation(str(exc)) - raise HTTPError(400, str(exc)) from exc - except Exception as exc: - self._generation.fail_generation(str(exc)) - if is_cancel_exception(exc): - logger.info("Generation cancelled by user") - return IcLoraGenerateCancelledResponse(status="cancelled") - raise HTTPError(500, f"Generation error: {exc}") from exc - finally: - self._text.clear_api_embeddings() + + self._text.prepare_text_encoding( + prompt, + enhance_prompt=enhance_via_api, + model_id=local_model_id, + ) + self._generation.raise_if_cancelled() + + self._generation.update_progress("inference", 15, 0, 1) + with log_heartbeat("ic-lora inference"): + ic_state.pipeline.generate( + prompt=prompt, + seed=seed, + height=height, + width=width, + num_frames=frame_count, + frame_rate=fps, + images=reference_images, + video_conditioning=[(control_video_path, s.conditioning_strength)], + output_path=str(output_path), + skip_stage_2=s.skip_stage_2, + use_lora_in_stage_2=s.use_lora_in_stage_2, + resolution_factor=resolution_factor, + chunk_pixel_frames=job.chunk_pixel_frames, + source_audio_path=( + req.input_path + if s.audio_mode == "source" and ic_lora.input.kind == "video" + else None + ), + mute_audio=s.audio_mode == "off", + conditioning_mask_path=control.mask_path, + ) + self._complete_or_drop_cancelled(output_path) + return IcLoraGenerateCompleteResponse(status="complete", video_path=str(output_path)) + except HTTPError: + self._generation.fail_generation("IC-LoRA generation failed") + raise + except ValueError as exc: + # run_preprocessing raises ValueError for user-fixable input (bad pads, unreadable + # media, >+100% outpaint) — surface it as a 400 so the user sees what to fix. + self._generation.fail_generation(str(exc)) + raise HTTPError(400, str(exc)) from exc + except Exception as exc: + if is_cancel_exception(exc): + logger.info("Generation cancelled by user") + return IcLoraGenerateCancelledResponse(status="cancelled") + self._generation.fail_generation(str(exc)) + raise HTTPError(500, f"Generation error: {exc}") from exc + finally: + self._text.clear_api_embeddings() def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: + # Hardware viability first: local downloads are disabled on an unsupported + # runtime, so a later weights check would report IC_LORA_NOT_DOWNLOADED and + # hide the real reason. The per-job budget still 422s unsupported on its own. + self._require_local_generation_possible() if req.ic_lora_id is not None: - return self._generate_ic_lora(req) + # Queued Home passes an explicit size with stage 2 skipped. GenSpace + # does not. Reject it here so a later GenSpace caller cannot inherit + # that canvas without opting in on the queued entry. + if req.resolution is not None and req.skip_stage_2 is not False: + raise HTTPError( + 400, + "Explicit resolution with skip_stage_2 is only supported on the queued catalog path", + ) + with self._generation.reserved_generation_start(): + return self._generate_ic_lora( + req, + generation_id=uuid.uuid4().hex[:8], + seed=self._resolve_seed(), + output_path=self.config.outputs_dir + / f"ic_lora_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}.mp4", + local_model_id=None, + explore_generation=False, + ) # The canny/depth/custom paths have no catalog entry to opt into promptless runs. if not req.prompt.strip(): @@ -471,13 +737,72 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: t_total_start = time.perf_counter() logger.info("[ic-lora] Generation started (conditioning=%s)", req.conditioning_type) + seed = self._resolve_seed() + try: + preprocess_time = 0.0 + if req.conditioning_type == "custom": + # Pre-rendered control video supplied; derive shape/timing from it. + assert req.control_video_path is not None # validated above + control_video_path = req.control_video_path + cap = self._video_processor.open_video(control_video_path) + if not cap.isOpened(): + raise HTTPError(400, f"Cannot open control video: {control_video_path}") + info = self._video_processor.get_video_info(cap) + self._video_processor.release(cap) + input_width = int(info["width"]) + input_height = int(info["height"]) + frame_count = int(info["frame_count"]) + fps = float(info["fps"]) + logger.info("[ic-lora] custom: using provided control video (%d frames)", frame_count) + else: + video_path = Path(req.video_path) + cap = self._video_processor.open_video(str(video_path)) + if not cap.isOpened(): + raise HTTPError(400, f"Cannot open video: {video_path}") + info = self._video_processor.get_video_info(cap) + self._video_processor.release(cap) + input_width = int(info["width"]) + input_height = int(info["height"]) + frame_count = int(info["frame_count"]) + fps = float(info["fps"]) + control_video_path = "" + + width, height, resolution_factor = ic_lora_output_canvas( + skip_stage_2=settings.skip_stage_2, + resolution_factor=settings.resolution_factor, + input_width=input_width, + input_height=input_height, + resolution=req.resolution, + ) + budget_frames = frame_count + if req.fps_override is not None and fps > 0 and req.fps_override < fps: + budget_frames = self._frame_count_after_fps_override( + frame_count, fps, req.fps_override + ) + job = self._ic_lora_job( + width, + height, + frame_count=snap_to_frame_grid(budget_frames, floor=9), + stage_mode=settings.stage_mode, + resolution_factor=resolution_factor, + ) + # Before the pipeline claims the GPU. canny/depth get a conditioning system + # prompt; a fully custom IC-LoRA falls back to the generic rewrite. + resolved_prompt = self._prompt_enhancement.resolve_for_generation( + req.prompt, + provenance=req.prompt_provenance, + generation_seed=seed, + conditioning_type=None if req.conditioning_type == "custom" else req.conditioning_type, + ) + prompt = resolved_prompt.prompt t_load_start = time.perf_counter() with log_heartbeat("ic-lora model load"): ic_state = self._pipelines.load_ic_lora( str(lora_path), str(depth_model_path) if depth_model_path is not None else None, settings.lora_strength, + mode=job.mode, ) t_load_end = time.perf_counter() logger.info("[ic-lora] Pipeline load: %.2fs", t_load_end - t_load_start) @@ -485,42 +810,20 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: self._generation.start_generation(generation_id) self._generation.update_progress("loading_model", 5, 0, 1) - s = self.state.app_settings - use_api = not self._text.should_use_local_encoding() - encoding_method = "api" if use_api else "local" + encoding_method = "local" if self._text.should_use_local_encoding() else "api" t_text_start = time.perf_counter() - # The prompt is guaranteed non-empty here (guarded at the top of generate()). - enhance_prompt = use_api and s.prompt_enhancer_enabled_t2v - self._text.prepare_text_encoding(req.prompt, enhance_prompt=enhance_prompt) + self._text.prepare_text_encoding(prompt, enhance_prompt=resolved_prompt.enhance_via_api) t_text_end = time.perf_counter() logger.info("[ic-lora] Text encoding (%s): %.2fs", encoding_method, t_text_end - t_text_start) self._generation.raise_if_cancelled() - preprocess_time = 0.0 - - if req.conditioning_type == "custom": - # Pre-rendered control video supplied; derive shape/timing from it. - assert req.control_video_path is not None # validated above - control_video_path = req.control_video_path - cap = self._video_processor.open_video(control_video_path) - if not cap.isOpened(): - raise HTTPError(400, f"Cannot open control video: {control_video_path}") - info = self._video_processor.get_video_info(cap) - self._video_processor.release(cap) - input_width = int(info["width"]) - input_height = int(info["height"]) - frame_count = int(info["frame_count"]) - fps = float(info["fps"]) - logger.info("[ic-lora] custom: using provided control video (%d frames)", frame_count) - else: + if req.conditioning_type != "custom": cond = req.conditioning_type # narrowed to Literal["canny", "depth"] video_path = Path(req.video_path) cap = self._video_processor.open_video(str(video_path)) if not cap.isOpened(): raise HTTPError(400, f"Cannot open video: {video_path}") info = self._video_processor.get_video_info(cap) - input_width = int(info["width"]) - input_height = int(info["height"]) cache_key = ConditioningCacheKey(str(video_path), cond) cached = ic_state.conditioning_cache.get(cache_key) @@ -581,38 +884,22 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: self._generation.update_progress("inference", 15, 0, 1) - if settings.use_lora_in_stage_2 and not settings.skip_stage_2: - # IC-LoRA kept in Stage 2 → mirror the t2v two-stage flow: output at the chosen - # resolution (or source if unset), snapped down to a multiple of 128 (Stage 1 - # runs at canvas//2; its latent must be even for the 2x patchify), never upscaling. - target_w = req.resolution.width if req.resolution else input_width - target_h = req.resolution.height if req.resolution else input_height - width = max(128, (min(target_w, input_width) // 128) * 128) - height = max(128, (min(target_h, input_height) // 128) * 128) - else: - width = 768 - height = max(round(width * input_height / input_width / 128) * 128, 128) - output_path = ( self.config.outputs_dir / f"ic_lora_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{uuid.uuid4().hex[:8]}.mp4" ) - if (frame_count - 1) % 8 != 0: - logger.warning( - "[ic-lora] %d frames: (frames-1) %% 8 != 0 — pipeline may pad/trim and output could glitch.", - frame_count, - ) - seed = self._resolve_seed() + # The budget priced the snapped count. The control video can be longer. + frame_count = snap_to_frame_grid(frame_count, floor=9) logger.info( "[ic-lora] run: lora=%s strength=%.2f skip_stage_2=%s res_factor=%.2f audio=%s enhance=%s " "seed=%d -> target %dx%d x %d frames @%gfps | prompt_len=%d", - lora_path.name, settings.lora_strength, settings.skip_stage_2, settings.resolution_factor, - settings.audio_mode, enhance_prompt, seed, width, height, frame_count, fps, len(req.prompt), + lora_path.name, settings.lora_strength, settings.skip_stage_2, resolution_factor, + settings.audio_mode, resolved_prompt.enhancement, seed, width, height, frame_count, fps, len(prompt), ) t_inference_start = time.perf_counter() with log_heartbeat("ic-lora inference"): ic_state.pipeline.generate( - prompt=req.prompt, + prompt=prompt, seed=seed, height=height, width=width, @@ -623,7 +910,8 @@ def generate(self, req: IcLoraGenerateRequest) -> IcLoraGenerateResponse: output_path=str(output_path), skip_stage_2=settings.skip_stage_2, use_lora_in_stage_2=settings.use_lora_in_stage_2, - resolution_factor=settings.resolution_factor, + resolution_factor=resolution_factor, + chunk_pixel_frames=job.chunk_pixel_frames, # "source" mode muxes the input clip's soundtrack (None if it has none); # "off" mutes; "generated" keeps the model audio. source_audio_path=( diff --git a/backend/handlers/image_generation_handler.py b/backend/handlers/image_generation_handler.py index be543a438..c0294ad37 100644 --- a/backend/handlers/image_generation_handler.py +++ b/backend/handlers/image_generation_handler.py @@ -27,6 +27,7 @@ from services.interfaces import ZitAPIClient from server_utils.heartbeat import log_heartbeat from server_utils.media_validation import validate_image_file +from server_utils.oriented_image import open_oriented_rgb from services.services_utils import clamp_strength, compute_edit_dimensions, effective_edit_steps from state.app_settings import should_image_generate_with_fal_api from state.app_state_types import AppState @@ -60,6 +61,7 @@ def generate(self, req: GenerateImageRequest) -> GenerateImageResponse: num_images = max(1, min(12, req.numImages)) seed = self._resolve_seed() + self._require_local_generation_possible(api_key=self.state.app_settings.fal_api_key) use_fal_api = should_image_generate_with_fal_api( force_api_generations=self.config.force_api_generations, settings=self.state.app_settings, @@ -248,8 +250,7 @@ def _run_local_batch( def _load_edit_source(self, image_path: str) -> PILImage.Image: # Downscale to the same /16 target the local edit path uses before the pipeline # runs — keeps the base64 upload on the FAL path from inflating with source size. - with PILImage.open(image_path) as raw: - source = raw.convert("RGB") + source = open_oriented_rgb(image_path) target_w, target_h = compute_edit_dimensions(source.width, source.height) return source.resize((target_w, target_h), PILImage.Resampling.LANCZOS) diff --git a/backend/handlers/lora_catalog_handler.py b/backend/handlers/lora_catalog_handler.py index 621595fe8..113b6e576 100644 --- a/backend/handlers/lora_catalog_handler.py +++ b/backend/handlers/lora_catalog_handler.py @@ -13,6 +13,8 @@ from _routes._errors import HTTPError from api_types import ( + ActiveIcLoraDownloadResponse, + ActiveLoraDownloadResponse, CatalogDownloadStartResponse, CatalogDownloadStatus, IcLoraDownloadProgressResponse, @@ -25,12 +27,15 @@ ) from handlers.base import StateHandlerBase, with_state_lock from handlers.hf_auth_utils import optional_hf_token, require_hf_token +from runtime_config.ic_lora_job_budget import with_budgeted_duration_controls from runtime_config.model_download_specs import ( + catalog_item_visible_for_installed_ltx, downloaded_ic_lora_variant_ids, downloaded_lora_variant_ids, resolve_lora_path, resolve_ic_lora_path, ) +from runtime_config.video_job_budget import memory_gb_for_job from services.interfaces import ModelDownloader, TaskRunner from services.lora_catalog import LoraCatalogProvider from services.lora_catalog.media_urls import with_resolved_media @@ -73,6 +78,12 @@ def _lookup_lora(catalog: LoraCatalogProvider, item_id: str) -> LoraCatalogItem return catalog.get_lora(item_id) +def _session_progress_pct(session: CatalogDownloadSession) -> float: + if not session.expected_bytes: + return 0.0 + return min(99.0, session.downloaded_bytes / session.expected_bytes * 100) + + def _ic_lora_progress( status: CatalogDownloadStatus, *, @@ -172,26 +183,42 @@ def __init__( # Catalog download.variants is always non-empty; the first variant is the default # checkpoint (preferred when listing "downloaded", when generation omits variant_id, # and when a download request omits variant_id). - def list_ic_loras(self) -> IcLoraListResponse: + def list_ic_loras(self, fresh: bool = False) -> IcLoraListResponse: catalog = self._catalog.get_catalog() + darwin = self.config.darwin_unified_memory + memory_gb = memory_gb_for_job( + vram_gb=self.config.vram_gb, + available_ram_gb=self.config.available_ram_gb, + darwin=darwin, + ) items: list[IcLoraListItem] = [] for r in catalog.ic_loras: + if not fresh and not catalog_item_visible_for_installed_ltx(r.supported_models, self.models_dir): + continue variant_ids = downloaded_ic_lora_variant_ids( self.models_dir, r.id, [(v.id, v.filename) for v in r.download.variants] ) + item = with_budgeted_duration_controls( + with_resolved_media(r), + memory_gb=memory_gb, + process_mode=self.config.local_generations_mode, + darwin=darwin, + ) items.append( IcLoraListItem( - ic_lora=with_resolved_media(r), + ic_lora=item, downloaded=bool(variant_ids), downloaded_variant_ids=variant_ids, ) ) return IcLoraListResponse(ic_loras=items) - def list_loras(self) -> LoraListResponse: + def list_loras(self, fresh: bool = False) -> LoraListResponse: catalog = self._catalog.get_catalog() items: list[LoraListItem] = [] for item in catalog.loras: + if not fresh and not catalog_item_visible_for_installed_ltx(item.supported_models, self.models_dir): + continue variant_ids = downloaded_lora_variant_ids( self.models_dir, item.id, [(v.id, v.filename) for v in item.download.variants] ) @@ -263,7 +290,7 @@ def _work() -> None: staging_dir.mkdir(parents=True, exist_ok=True) try: staged = self._model_downloader.download_file( - repo_id=item.download.repo_id, + repo_id=variant.resolved_repo_id(item.download.repo_id), filename=variant.filename, local_dir=str(staging_dir), token=hf_token, @@ -308,13 +335,12 @@ def _get_progress(self, kind: _CatalogKind[ProgressResponseT], session_id: str) sid = DownloadSessionId(session_id) s: CatalogDownloadSession | None = getattr(self.state, kind.session_attr) if s is not None and s.id == sid: - pct = min(99.0, s.downloaded_bytes / s.expected_bytes * 100) if s.expected_bytes else 0.0 return kind.build_progress( "downloading", item_id=s.item_id, downloaded_bytes=s.downloaded_bytes, expected_bytes=s.expected_bytes, - progress=pct, + progress=_session_progress_pct(s), speed_bytes_per_sec=s.speed_bytes_per_sec, ) result = self._completed(kind).get(sid) @@ -340,3 +366,69 @@ def start_lora_download( def get_lora_download_progress(self, session_id: str) -> LoraDownloadProgressResponse: return self._get_progress(_PLAIN_LORA, session_id) + + def _delete_installation( + self, + kind: _CatalogKind[ProgressResponseT], + item_id: str, + variant_id: str | None = None, + ) -> None: + if self.config.force_api_generations: + raise HTTPError(409, "LOCAL_MODEL_DOWNLOADS_DISABLED_IN_FORCE_API_MODE") + item = kind.lookup(self._catalog, item_id) + if item is None: + raise HTTPError(404, kind.not_found) + variant = item.download.resolve_variant(variant_id) + if variant is None: + raise HTTPError(404, "UNKNOWN_DOWNLOAD_VARIANT") + with self._lock: + session: CatalogDownloadSession | None = getattr(self.state, kind.session_attr) + if session is not None and session.item_id == item_id: + raise HTTPError(409, "DOWNLOAD_ALREADY_RUNNING") + path = kind.resolve_path(self.models_dir, item.id, variant.filename) + if not path.is_file(): + raise HTTPError(404, "LORA_NOT_INSTALLED") + path.unlink() + parent = path.parent + if parent.is_dir() and not any(parent.iterdir()): + parent.rmdir() + + def delete_lora(self, lora_id: str, variant_id: str | None = None) -> None: + self._delete_installation(_PLAIN_LORA, lora_id, variant_id) + + def delete_ic_lora(self, ic_lora_id: str, variant_id: str | None = None) -> None: + self._delete_installation(_IC_LORA, ic_lora_id, variant_id) + + @with_state_lock + def get_active_lora_download(self) -> ActiveLoraDownloadResponse: + """The in-flight plain-LoRA download, if any, so a remounting screen can reattach. + + Returns nulls when idle; otherwise the session id (to resume polling + ``get_lora_download_progress``) and the lora id being fetched. + """ + session = self.state.lora_download_session + if session is None: + return ActiveLoraDownloadResponse(session_id=None, lora_id=None, progress=None) + return ActiveLoraDownloadResponse( + session_id=str(session.id), + lora_id=session.item_id, + progress=_session_progress_pct(session), + ) + + @with_state_lock + def get_active_ic_lora_download(self) -> ActiveIcLoraDownloadResponse: + """The in-flight IC-LoRA download, if any. Mirrors ``get_active_lora_download``. + + IC-LoRA downloads keep their own state slot, so both kinds can run at once and each + needs its own reattach point after a remount or a renderer reload. + """ + session = self.state.ic_lora_download_session + if session is None: + return ActiveIcLoraDownloadResponse( + session_id=None, ic_lora_id=None, progress=None + ) + return ActiveIcLoraDownloadResponse( + session_id=str(session.id), + ic_lora_id=session.item_id, + progress=_session_progress_pct(session), + ) diff --git a/backend/handlers/models_handler.py b/backend/handlers/models_handler.py index 4eaa25bee..02e6cb4b8 100644 --- a/backend/handlers/models_handler.py +++ b/backend/handlers/models_handler.py @@ -36,6 +36,7 @@ DEPTH_PROCESSOR_CP_ID, IMG_GEN_MODEL_CP_ID, LTXLocalModelRelevant, + LTXLocalModelSpec, get_downloaded_ltx_model_id, get_ic_loras_cp_ids, get_latest_ltx_model_id, @@ -66,6 +67,62 @@ class ResolvedUpgradeDownload: cp_ids: tuple[ModelCheckpointID, ...] +def _required_ltx_cp_ids( + spec: LTXLocalModelSpec, *, use_conv_vae: bool, has_api_key: bool +) -> set[ModelCheckpointID]: + """Full required checkpoint set for `spec`. Pure spec computation: no disk, no state.""" + required: set[ModelCheckpointID] = {spec.model_cp, spec.upscale_cp} + selected_vae = selected_video_vae_cp(spec, use_conv_vae=use_conv_vae) + if selected_vae is not None: + required.add(selected_vae) + # Conv VAE is always part of the 2.5 download set so Fast decode can be turned on + # later without a hidden extra fetch. DiffVAE stays selected-only (Mac default). + if spec.video_vae_conv_cp is not None: + required.add(spec.video_vae_conv_cp) + if spec.audio_vae_cp is not None: + required.add(spec.audio_vae_cp) + if spec.duration_head_cp is not None: + required.add(spec.duration_head_cp) + if not has_api_key or not spec.supports_api_text_encoding: + required.add(spec.text_encoder_cp) + return required + + +def _optional_ltx_cp_ids( + spec: LTXLocalModelSpec, *, use_conv_vae: bool, has_api_key: bool +) -> set[ModelCheckpointID]: + """Full optional set the user can still choose to download. Pure: no disk, no state. + + Includes the unused 2.5 DiffVAE when Fast decode is on, and any text encoder an + LTX API key excused. Never overlaps the required set. + """ + optional: set[ModelCheckpointID] = set() + unused_vae = unused_video_vae_cp(spec, use_conv_vae=use_conv_vae) + if unused_vae is not None: + optional.add(unused_vae) + if has_api_key and spec.supports_api_text_encoding: + optional.add(spec.text_encoder_cp) + optional -= _required_ltx_cp_ids(spec, use_conv_vae=use_conv_vae, has_api_key=has_api_key) + return optional + + +def _recommended_quality_ltx_cp_ids( + spec: LTXLocalModelSpec, *, required: set[ModelCheckpointID] +) -> set[ModelCheckpointID]: + """Full recommended-quality set: extras recommended but never required to run. Pure. + + LTX 2.5's preferred Gemma 4 E2B enhancer is the only current member. 2.3's + encoder already enhances, so it contributes nothing. + + Takes the already-computed `required` set instead of key flags so the caller + cannot consult a different API-key state than the rest of the bundle. + """ + if spec.prompt_enhancer_cp is None: + return set() + recommended: set[ModelCheckpointID] = {spec.prompt_enhancer_cp} + return recommended - required + + class ModelsHandler(StateHandlerBase): def __init__( self, @@ -94,6 +151,20 @@ def _current_active_ltx_model_id(self) -> LTXLocalModelId | None: self.models_dir, self.state.app_settings.active_ltx_model_id ) + def _active_ltx_model_id_for_versions_list(self) -> LTXLocalModelId | None: + """Which row to mark Active in Settings — honour the saved choice when runnable. + + ``resolve_active_ltx_model_id`` can fall back to another installed version when its + bundle check disagrees with the live required-cp rules (API key, conv VAE). That made + set-active appear to do nothing while the preference was persisted correctly. + """ + preferred = self.state.app_settings.active_ltx_model_id + if preferred is not None and not self._get_missing_cp_ids( + self._get_required_ltx_cp_ids(preferred) + ): + return preferred + return resolve_active_ltx_model_id(self.models_dir, preferred) + def _has_api_key(self) -> bool: return bool(self.state.app_settings.ltx_api_key.strip()) @@ -118,6 +189,8 @@ def _cp_role(self, cp_id: ModelCheckpointID) -> CheckpointRole: return "vae" if cp_id == spec.duration_head_cp: return "support" + if spec.prompt_enhancer_cp is not None and cp_id == spec.prompt_enhancer_cp: + return "prompt_enhancer" if cp_id == IMG_GEN_MODEL_CP_ID: return "image" return "support" @@ -147,38 +220,47 @@ def _use_conv_vae(self) -> bool: return resolved_use_conv_vae(self.state.app_settings) def _get_required_ltx_cp_ids(self, model_id: LTXLocalModelId) -> set[ModelCheckpointID]: + """Full required set under live settings (conv toggle + API key). No disk check.""" spec = get_ltx_model_spec(model_id) - required: set[ModelCheckpointID] = {spec.model_cp, spec.upscale_cp} - selected_vae = selected_video_vae_cp(spec, use_conv_vae=self._use_conv_vae()) - if selected_vae is not None: - required.add(selected_vae) - # Conv VAE is always part of the 2.5 download set so Fast decode can be turned on - # later without a hidden extra fetch. DiffVAE stays selected-only (Mac default). - if spec.video_vae_conv_cp is not None: - required.add(spec.video_vae_conv_cp) - if spec.audio_vae_cp is not None: - required.add(spec.audio_vae_cp) - if spec.duration_head_cp is not None: - required.add(spec.duration_head_cp) - if not self._has_api_key() or not spec.supports_api_text_encoding: - required.add(spec.text_encoder_cp) - return required - - def _get_optional_ltx_cp_ids(self, model_id: LTXLocalModelId) -> set[ModelCheckpointID]: - """Missing checkpoints the user can still choose to download. - - Includes the unused 2.5 DiffVAE when Fast decode is on, and any text encoder an - LTX API key excused. Never overlaps the required set. + return _required_ltx_cp_ids( + spec, use_conv_vae=self._use_conv_vae(), has_api_key=self._has_api_key() + ) + + def _get_recommended_quality_ltx_cp_ids(self, model_id: LTXLocalModelId) -> set[ModelCheckpointID]: + """Missing quality extras under live settings. Always missing-filtered.""" + spec = get_ltx_model_spec(model_id) + use_conv_vae = self._use_conv_vae() + has_api_key = self._has_api_key() + required = _required_ltx_cp_ids(spec, use_conv_vae=use_conv_vae, has_api_key=has_api_key) + return self._get_missing_cp_ids( + _recommended_quality_ltx_cp_ids(spec, required=required) + ) + + def _ltx_download_bundle( + self, model_id: LTXLocalModelId, *, has_api_key: bool, only_missing: bool + ) -> LtxDownloadRecommendationResponse: + """Single construction site for download recommendations. + + All three sets derive from the same `has_api_key` + one conv-toggle read, so the + recommended set can never consult a different key state than required/optional. + `only_missing=False` returns the full spec sets (fresh/empty-machine bundle); + `only_missing=True` filters each set to checkpoints not on disk. """ spec = get_ltx_model_spec(model_id) - optional: set[ModelCheckpointID] = set() - unused_vae = unused_video_vae_cp(spec, use_conv_vae=self._use_conv_vae()) - if unused_vae is not None: - optional.add(unused_vae) - if self._has_api_key() and spec.supports_api_text_encoding: - optional.add(spec.text_encoder_cp) - optional -= self._get_required_ltx_cp_ids(model_id) - return self._get_missing_cp_ids(optional) + use_conv_vae = self._use_conv_vae() + required = _required_ltx_cp_ids(spec, use_conv_vae=use_conv_vae, has_api_key=has_api_key) + optional = _optional_ltx_cp_ids(spec, use_conv_vae=use_conv_vae, has_api_key=has_api_key) + recommended = _recommended_quality_ltx_cp_ids(spec, required=required) + if only_missing: + required = self._get_missing_cp_ids(required) + optional = self._get_missing_cp_ids(optional) + recommended = self._get_missing_cp_ids(recommended) + return LtxDownloadRecommendationResponse( + status="download", + cps_to_download=self._ordered_cp_ids(required), + optional_cp_ids=self._ordered_cp_ids(optional), + recommended_quality_cp_ids=self._ordered_cp_ids(recommended), + ) def _get_missing_cp_ids(self, cp_ids: set[ModelCheckpointID]) -> set[ModelCheckpointID]: return {cp_id for cp_id in cp_ids if not self.is_cp_downloaded(cp_id)} @@ -261,20 +343,28 @@ def _get_upgrade_delete_cp_ids( if self.is_cp_downloaded(cp_id) } - def get_ltx_recommendation(self) -> LtxRecommendationResponse: + def get_ltx_recommendation( + self, fresh: bool = False, include_installed: bool = False + ) -> LtxRecommendationResponse: self._ensure_local_model_mode() + if fresh: + # Empty-machine bundle: full no-key spec sets of the latest model, no disk + # filtering. Still honors the Fast-decode conv toggle. `include_installed` + # does not apply here — fresh always means latest, even if an older bundle + # is what Setup would repair. + return self._ltx_download_bundle( + get_latest_ltx_model_id(), has_api_key=False, only_missing=False + ) current_model_id = self._current_downloaded_ltx_model_id() latest_model_id = get_latest_ltx_model_id() + has_api_key = self._has_api_key() if current_model_id is None: - cps_to_download = self._ordered_cp_ids( - self._get_missing_cp_ids(self._get_required_ltx_cp_ids(latest_model_id)) - ) - return LtxDownloadRecommendationResponse( - status="download", - cps_to_download=cps_to_download, - optional_cp_ids=self._ordered_cp_ids(self._get_optional_ltx_cp_ids(latest_model_id)), + return self._ltx_download_bundle( + latest_model_id, + has_api_key=has_api_key, + only_missing=not include_installed, ) # A required checkpoint for the current model can be missing even when its base @@ -282,15 +372,17 @@ def get_ltx_recommendation(self) -> LtxRecommendationResponse: # superseded the version already on disk. Surface that download before offering any # base upgrade: the current setup needs it regardless of whether the user upgrades, # and routing it through the 'download' status lets the missing-models gate prompt it. - missing_current = self._ordered_cp_ids( - self._get_missing_cp_ids(self._get_required_ltx_cp_ids(current_model_id)) + # `include_installed` returns that same model's full sets so Setup can show files + # already on disk. It must not swap in the latest model. + current_bundle = self._ltx_download_bundle( + current_model_id, has_api_key=has_api_key, only_missing=True ) - if missing_current: - return LtxDownloadRecommendationResponse( - status="download", - cps_to_download=missing_current, - optional_cp_ids=self._ordered_cp_ids(self._get_optional_ltx_cp_ids(current_model_id)), - ) + if current_bundle.cps_to_download: + if include_installed: + return self._ltx_download_bundle( + current_model_id, has_api_key=has_api_key, only_missing=False + ) + return current_bundle if current_model_id == latest_model_id: return LtxOkRecommendationResponse(status="ok") @@ -315,12 +407,16 @@ def get_ltx_recommendation(self) -> LtxRecommendationResponse: cps_to_download=cps_to_download, cps_to_delete=cps_to_delete, loses_built_in_control=loses_control, + recommended_quality_cp_ids=self._ordered_cp_ids( + self._get_recommended_quality_ltx_cp_ids(latest_model_id) + ), ) - def get_img_gen_recommendation(self) -> ImageGenRecommendationResponse: + def get_img_gen_recommendation(self, fresh: bool = False) -> ImageGenRecommendationResponse: self._ensure_local_model_mode() - cp_to_download = None if self.is_cp_downloaded(IMG_GEN_MODEL_CP_ID) else IMG_GEN_MODEL_CP_ID - return ImageGenRecommendationResponse(cp_to_download=cp_to_download) + if fresh or not self.is_cp_downloaded(IMG_GEN_MODEL_CP_ID): + return ImageGenRecommendationResponse(cp_to_download=IMG_GEN_MODEL_CP_ID) + return ImageGenRecommendationResponse(cp_to_download=None) def list_installed_models(self, model_type: str | None) -> InstalledModelsResponse: # "lora" -> regular LoRAs only (IC-LoRAs excluded; they need a reference video), @@ -381,8 +477,10 @@ def get_text_encoder_recommendation(self) -> TextEncoderRecommendationResponse: spec = get_model_cp_spec(cp_id) enhancer_cp = ltx_spec.prompt_enhancer_cp active_enhancer_cp = resolve_downloaded_prompt_enhancer_cp(self.models_dir, ltx_spec) + encoder_downloaded = self.is_cp_downloaded(cp_id) + removable = encoder_downloaded and self._local_text_encoder_is_removable(ltx_spec) return TextEncoderRecommendationResponse( - cp_to_download=None if self.is_cp_downloaded(cp_id) else cp_id, + cp_to_download=None if encoder_downloaded else cp_id, expected_size_bytes=spec.expected_size_bytes, expected_size_gb=round(spec.expected_size_bytes / (1024**3), 1), api_encoding_supported=ltx_spec.supports_api_text_encoding, @@ -394,6 +492,8 @@ def get_text_encoder_recommendation(self) -> TextEncoderRecommendationResponse: else round(get_model_cp_spec(enhancer_cp).expected_size_bytes / (1024**3), 1) ), active_local_enhancer_cp=active_enhancer_cp, + active_local_text_encoder_cp=cp_id if encoder_downloaded else None, + local_text_encoder_removable=removable, ) def resolve_upgrade_download(self, requested_cp_ids: set[ModelCheckpointID]) -> ResolvedUpgradeDownload: @@ -436,13 +536,31 @@ def resolve_upgrade_download(self, requested_cp_ids: set[ModelCheckpointID]) -> cp_ids=tuple(self._ordered_cp_ids(expected_cp_ids)), ) + def _local_text_encoder_is_removable(self, ltx_spec: LTXLocalModelSpec) -> bool: + """Whether the active model's local text encoder is safe to delete right now. + + The encoder is only expendable when prompts can be encoded another way: the model + supports API encoding, a key is configured, and the user has not chosen local + encoding. Otherwise deleting it would leave the app unable to encode at all, so it + stays protected and Settings disables the action. + """ + if not ltx_spec.supports_api_text_encoding: + return False + if self.state.app_settings.use_local_text_encoder: + return False + return self._has_api_key() + def get_protected_cp_ids(self) -> set[ModelCheckpointID]: active_model_id = resolve_active_ltx_model_id( self.models_dir, self.state.app_settings.active_ltx_model_id ) if active_model_id is None: return set() - return set(get_ltx_model_cp_ids(active_model_id)) + protected = set(get_ltx_model_cp_ids(active_model_id)) + ltx_spec = get_ltx_model_spec(active_model_id) + if self._local_text_encoder_is_removable(ltx_spec): + protected.discard(ltx_spec.text_encoder_cp) + return protected def delete_checkpoints(self, cp_ids: set[ModelCheckpointID]) -> None: protected = self.get_protected_cp_ids() @@ -455,7 +573,7 @@ def delete_checkpoints(self, cp_ids: set[ModelCheckpointID]) -> None: def list_ltx_versions(self) -> LtxModelVersionsResponse: self._ensure_local_model_mode() latest = get_latest_ltx_model_id() - active = resolve_active_ltx_model_id(self.models_dir, self.state.app_settings.active_ltx_model_id) + active = self._active_ltx_model_id_for_versions_list() items: list[LtxModelVersionItem] = [] for model_id in ALL_LTX_LOCAL_MODEL_IDS: spec = get_ltx_model_spec(model_id) diff --git a/backend/handlers/pipelines_handler.py b/backend/handlers/pipelines_handler.py index aff78e8ad..aa4077f69 100644 --- a/backend/handlers/pipelines_handler.py +++ b/backend/handlers/pipelines_handler.py @@ -10,12 +10,26 @@ from api_types import LTXLocalModelId from handlers.base import StateHandlerBase from handlers.text_handler import TextHandler +from runtime_config.ic_lora_tiling import IcLoraTiling from runtime_config.model_download_specs import ( IMG_GEN_MODEL_CP_ID, + ltx_generation_bundle_on_disk, get_existing_cp_path, resolve_active_ltx_model_id, ) -from runtime_config.runtime_policy import streaming_prefetch_count_for_mode +from runtime_config.runtime_policy import LocalGenerationMode, streaming_prefetch_count_for_mode +from runtime_config.video_job_budget import ( + EDIT_JOB_TOO_LARGE_MESSAGE, + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + VIDEO_JOB_TOO_LARGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, + VideoJobReject, + decide_edit_job, + max_edit_frames_that_load, + memory_gb_for_job, +) +from services.retake_pipeline.window import MAX_INPUT_FRAMES from services.interfaces import ( A2VPipeline, DepthProcessorPipeline, @@ -116,13 +130,19 @@ def _install_text_patches_if_needed(self) -> None: return te.service.install_patches(lambda: self.state) - def _require_downloaded_ltx_model_id(self) -> LTXLocalModelId: - model_id = resolve_active_ltx_model_id( + def _require_downloaded_ltx_model_id( + self, model_id: LTXLocalModelId | None = None + ) -> LTXLocalModelId: + if model_id is not None: + if not ltx_generation_bundle_on_disk(self.models_dir, model_id): + raise HTTPError(409, "LTX_MODEL_NOT_INSTALLED") + return model_id + resolved = resolve_active_ltx_model_id( self.models_dir, self.state.app_settings.active_ltx_model_id ) - if model_id is None: + if resolved is None: raise HTTPError(409, "NO_DOWNLOADED_LTX_MODEL") - return model_id + return resolved def _compile_if_enabled(self, state: VideoPipelineState) -> VideoPipelineState: if not self.state.app_settings.use_torch_compile: @@ -155,10 +175,15 @@ def _compile_if_enabled(self, state: VideoPipelineState) -> VideoPipelineState: return state def _create_video_pipeline( - self, model_type: VideoPipelineModelType, loras: list[tuple[str, float]] | None = None + self, + model_type: VideoPipelineModelType, + loras: list[tuple[str, float]] | None = None, + *, + load_mode: LocalGenerationMode, + ltx_model_id: LTXLocalModelId | None = None, ) -> VideoPipelineState: - gemma_root = self._text_handler.resolve_gemma_root() - model_id = self._require_downloaded_ltx_model_id() + model_id = self._require_downloaded_ltx_model_id(ltx_model_id) + gemma_root = self._text_handler.resolve_gemma_root(model_id=model_id) paths = self._resolve_ltx_paths(model_id, gemma_root) pipeline = self._fast_video_pipeline_class.create( @@ -166,7 +191,7 @@ def _create_video_pipeline( paths.gemma_root, paths.upsampler_path, self.config.device, - streaming_prefetch_count_for_mode(self.config.local_generations_mode), + streaming_prefetch_count_for_mode(load_mode), loras=loras or [], video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, @@ -177,6 +202,7 @@ def _create_video_pipeline( pipeline=pipeline, is_compiled=False, ltx_model_id=model_id, + loading_mode=load_mode, loras=tuple(loras) if loras else (), gemma_root=gemma_root, video_vae_path=paths.video_vae_path, @@ -284,12 +310,16 @@ def load_gpu_pipeline( self, model_type: VideoPipelineModelType, loras: list[tuple[str, float]] | None = None, + mode: LocalGenerationMode | None = None, + *, + ltx_model_id: LTXLocalModelId | None = None, ) -> VideoPipelineState: self._install_text_patches_if_needed() + load_mode = mode or self.config.local_generations_mode requested_loras = tuple(loras) if loras else () - requested_gemma_root = self._text_handler.resolve_gemma_root() - requested_model_id = self._require_downloaded_ltx_model_id() + requested_model_id = self._require_downloaded_ltx_model_id(ltx_model_id) + requested_gemma_root = self._text_handler.resolve_gemma_root(model_id=requested_model_id) requested_video_vae_path = self._resolve_ltx_paths( requested_model_id, requested_gemma_root ).video_vae_path @@ -301,6 +331,7 @@ def load_gpu_pipeline( active_pipeline=VideoPipelineState() as existing_state ) if ( existing_state.ltx_model_id == requested_model_id + and existing_state.loading_mode == load_mode and existing_state.loras == requested_loras and existing_state.gemma_root == requested_gemma_root and existing_state.video_vae_path == requested_video_vae_path @@ -311,7 +342,9 @@ def load_gpu_pipeline( if state is None: self._evict_gpu_pipeline_for_swap() - state = self._create_video_pipeline(model_type, loras=loras) + state = self._create_video_pipeline( + model_type, loras=loras, load_mode=load_mode, ltx_model_id=requested_model_id + ) with self._lock: self.state.gpu_slot = GpuSlot(active_pipeline=state) self._assert_invariants() @@ -323,11 +356,21 @@ def load_ic_lora( lora_path: str, depth_model_path: str | None = None, lora_strength: float = 1.0, + mode: LocalGenerationMode | None = None, + *, + ltx_model_id: LTXLocalModelId | None = None, + stage_2_ic_lora: bool = False, + tiling: IcLoraTiling | None = None, ) -> ICLoraState: self._install_text_patches_if_needed() - gemma_root = self._text_handler.resolve_gemma_root() - model_id = self._require_downloaded_ltx_model_id() + load_mode = mode or self.config.local_generations_mode + prefetch = streaming_prefetch_count_for_mode(load_mode) + # GenSpace omits ltx_model_id and follows Settings. A queued Home job passes + # the offering's local checkpoint so Settings stays put. The text encoder + # follows that same checkpoint: 2.3 and 2.5 do not share one. + model_id = self._require_downloaded_ltx_model_id(ltx_model_id) + gemma_root = self._text_handler.resolve_gemma_root(model_id=model_id) paths = self._resolve_ltx_paths(model_id, gemma_root) with self._lock: match self.state.gpu_slot: @@ -336,14 +379,20 @@ def load_ic_lora( lora_path=current_lora_path, depth_model_path=current_depth_model_path, lora_strength=current_lora_strength, + loading_mode=current_loading_mode, gemma_root=current_gemma_root, ltx_model_id=current_model_id, video_vae_path=current_video_vae_path, + stage_2_ic_lora=current_stage_2_ic_lora, + tiling=current_tiling, ) as state ) if ( current_lora_path == lora_path + and current_stage_2_ic_lora == stage_2_ic_lora + and current_tiling == tiling and current_depth_model_path == depth_model_path and current_lora_strength == lora_strength + and current_loading_mode == load_mode and current_gemma_root == gemma_root and current_model_id == model_id and current_video_vae_path == paths.video_vae_path @@ -360,11 +409,13 @@ def load_ic_lora( paths.upsampler_path, lora_path, self.config.device, - streaming_prefetch_count_for_mode(self.config.local_generations_mode), + prefetch, lora_strength, video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, duration_head_path=paths.duration_head_path, + stage_2_ic_lora=stage_2_ic_lora, + tiling=tiling, ) depth_pipeline = ( self._depth_processor_pipeline_class.create(depth_model_path, self.config.device) @@ -377,9 +428,12 @@ def load_ic_lora( depth_pipeline=depth_pipeline, depth_model_path=depth_model_path, ltx_model_id=model_id, + loading_mode=load_mode, lora_strength=lora_strength, gemma_root=gemma_root, video_vae_path=paths.video_vae_path, + stage_2_ic_lora=stage_2_ic_lora, + tiling=tiling, ) with self._lock: @@ -387,17 +441,25 @@ def load_ic_lora( self._assert_invariants() return state - def load_a2v_pipeline(self, loras: list[tuple[str, float]] | None = None) -> A2VPipelineState: + def load_a2v_pipeline( + self, + loras: list[tuple[str, float]] | None = None, + mode: LocalGenerationMode | None = None, + *, + ltx_model_id: LTXLocalModelId | None = None, + ) -> A2VPipelineState: self._install_text_patches_if_needed() + load_mode = mode or self.config.local_generations_mode requested_loras = tuple(loras) if loras else () - gemma_root = self._text_handler.resolve_gemma_root() - model_id = self._require_downloaded_ltx_model_id() + model_id = self._require_downloaded_ltx_model_id(ltx_model_id) + gemma_root = self._text_handler.resolve_gemma_root(model_id=model_id) paths = self._resolve_ltx_paths(model_id, gemma_root) with self._lock: match self.state.gpu_slot: case GpuSlot(active_pipeline=A2VPipelineState() as state) if ( state.ltx_model_id == model_id + and state.loading_mode == load_mode and state.loras == requested_loras and state.gemma_root == gemma_root and state.video_vae_path == paths.video_vae_path @@ -413,7 +475,7 @@ def load_a2v_pipeline(self, loras: list[tuple[str, float]] | None = None) -> A2V paths.gemma_root, paths.upsampler_path, self.config.device, - streaming_prefetch_count_for_mode(self.config.local_generations_mode), + streaming_prefetch_count_for_mode(load_mode), loras=loras or [], video_vae_path=paths.video_vae_path, audio_vae_path=paths.audio_vae_path, @@ -422,6 +484,7 @@ def load_a2v_pipeline(self, loras: list[tuple[str, float]] | None = None) -> A2V state = A2VPipelineState( pipeline=pipeline, ltx_model_id=model_id, + loading_mode=load_mode, loras=requested_loras, gemma_root=gemma_root, video_vae_path=paths.video_vae_path, @@ -432,13 +495,100 @@ def load_a2v_pipeline(self, loras: list[tuple[str, float]] | None = None) -> A2V self._assert_invariants() return state - def load_retake_pipeline(self, *, distilled: bool = True) -> RetakePipelineState: + def _edit_load_mode( + self, + width: int | None, + height: int | None, + frames: int | None, + *, + queued_home: bool = False, + ) -> LocalGenerationMode: + """Per-job full vs stream. Missing shape keeps the process mode. + + Does not change ``local_generations_mode``. Uses the edit headroom, so a + 31 GB card streams a long 720p retake/extend as well as 1080p. + """ + if width is None or height is None or frames is None: + return self.config.local_generations_mode + darwin = self.config.darwin_unified_memory + memory_gb = memory_gb_for_job( + vram_gb=self.config.vram_gb, + available_ram_gb=self.config.available_ram_gb, + darwin=darwin, + ) + decision = decide_edit_job( + width, + height, + frames, + memory_gb=memory_gb, + process_mode=self.config.local_generations_mode, + darwin=darwin, + ) + outcome = "reject" if isinstance(decision, VideoJobReject) else decision.mode + logger.info( + "[video-edit] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s", + decision.seq, + decision.full_gib, + decision.stream_gib, + outcome, + ) + if isinstance(decision, VideoJobReject): + if decision.reason == "unsupported": + raise HTTPError( + 422, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + code=LOCAL_GENERATION_UNSUPPORTED, + ) + # GenSpace still encodes the whole source, so a shorter duration + # shrinks that job. Queued Home pads context back up to the cap. + message = ( + EDIT_JOB_TOO_LARGE_MESSAGE + if queued_home + else VIDEO_JOB_TOO_LARGE_MESSAGE + ) + raise HTTPError(422, message, code=VIDEO_JOB_TOO_LARGE) + return decision.mode + + def edit_encode_frame_cap(self, width: int, height: int) -> int: + """Longest Home encode window this machine will load at ``width``×``height``. + + Does not change GenSpace, which never asks for this cap. A 31 GB card + keeps a long 720p window and shortens 1080p below 505 frames. + """ + darwin = self.config.darwin_unified_memory + memory_gb = memory_gb_for_job( + vram_gb=self.config.vram_gb, + available_ram_gb=self.config.available_ram_gb, + darwin=darwin, + ) + return max_edit_frames_that_load( + width, + height, + frame_cap=MAX_INPUT_FRAMES, + memory_gb=memory_gb, + process_mode=self.config.local_generations_mode, + darwin=darwin, + ) + + def load_retake_pipeline( + self, + *, + distilled: bool = True, + ltx_model_id: LTXLocalModelId | None = None, + width: int | None = None, + height: int | None = None, + frames: int | None = None, + queued_home: bool = False, + ) -> RetakePipelineState: self._install_text_patches_if_needed() quantized = device_supports_fp8(self.config.device) gemma_root = self._text_handler.resolve_gemma_root() - model_id = self._require_downloaded_ltx_model_id() + model_id = self._require_downloaded_ltx_model_id(ltx_model_id) paths = self._resolve_ltx_paths(model_id, gemma_root) + load_mode = self._edit_load_mode( + width, height, frames, queued_home=queued_home + ) with self._lock: match self.state.gpu_slot: @@ -449,6 +599,7 @@ def load_retake_pipeline(self, *, distilled: bool = True) -> RetakePipelineState gemma_root=current_gemma_root, ltx_model_id=current_model_id, video_vae_path=current_video_vae_path, + loading_mode=current_loading_mode, ) as state ) if ( current_distilled == distilled @@ -456,6 +607,7 @@ def load_retake_pipeline(self, *, distilled: bool = True) -> RetakePipelineState and current_gemma_root == gemma_root and current_model_id == model_id and current_video_vae_path == paths.video_vae_path + and current_loading_mode == load_mode ): return state case _: @@ -470,7 +622,7 @@ def load_retake_pipeline(self, *, distilled: bool = True) -> RetakePipelineState checkpoint_path=paths.checkpoint_path, gemma_root=paths.gemma_root, device=self.config.device, - streaming_prefetch_count=streaming_prefetch_count_for_mode(self.config.local_generations_mode), + streaming_prefetch_count=streaming_prefetch_count_for_mode(load_mode), loras=[], quantization=quantization, video_vae_path=paths.video_vae_path, @@ -482,6 +634,7 @@ def load_retake_pipeline(self, *, distilled: bool = True) -> RetakePipelineState distilled=distilled, quantized=quantized, ltx_model_id=model_id, + loading_mode=load_mode, gemma_root=gemma_root, video_vae_path=paths.video_vae_path, ) diff --git a/backend/handlers/prompt_enhancement_handler.py b/backend/handlers/prompt_enhancement_handler.py index c2db642f3..357b70be1 100644 --- a/backend/handlers/prompt_enhancement_handler.py +++ b/backend/handlers/prompt_enhancement_handler.py @@ -6,16 +6,28 @@ import random import uuid from threading import RLock -from typing import TYPE_CHECKING +from typing import TYPE_CHECKING, Literal, NamedTuple from _routes._errors import HTTPError -from api_types import EnhancePromptRequest, EnhancePromptResponse, IcLoraCatalogItem, LoraCatalogItem +from api_types import ( + ConditioningType, + EnhancePromptRequest, + EnhancePromptResponse, + IcLoraCatalogItem, + LoraCatalogItem, + LTXLocalModelId, + PromptEnhancerStatusResponse, + PromptProvenance, +) from handlers.base import StateHandlerBase from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler from handlers.text_handler import TextHandler from server_utils.media_validation import normalize_optional_path, validate_image_file +from services.analytics import resolution_for_provenance as shared_resolution_for_provenance +from services.analytics import prompt_provenance_label as shared_prompt_provenance_label from services.gemini_text_client import resolve_gemini_model +from services.generation_interrupt import is_cancel_exception from services.interfaces import PromptEnhancerPipeline from services.lora_catalog import LoraCatalogProvider from services.prompt_enhancement import ( @@ -41,13 +53,44 @@ if TYPE_CHECKING: from runtime_config.runtime_config import RuntimeConfig -# Deliberately independent of StateHandlerBase._resolve_seed(): that helper honors the app's -# reproducibility seed lock (and a fixed constant in dev mode), which would make every enhance -# call — including a redo — produce the exact same output. Enhancement is a quick, exploratory -# action where a fresh draw each call is the whole point. +# Manual Enhance is exploratory — a redo should offer a different rewrite even when generation +# seeds are locked — so it always draws fresh here rather than going through +# StateHandlerBase._resolve_seed(). Automatic enhancement is the opposite case; see +# _automatic_enhancement_seed(). _MAX_ENHANCE_SEED = 2147483647 +class ResolvedGenerationPrompt(NamedTuple): + """The prompt a local generation should submit, and how it got (or will get) enhanced.""" + + prompt: str + enhance_via_api: bool + enhanced_locally: bool + skip_recipe_wrap: bool = False + + @property + def enhancement(self) -> str: + """Where the rewrite happens, for run logs: local, server-side, or nowhere.""" + if self.enhanced_locally: + return "local" + return "api" if self.enhance_via_api else "none" + + +PromptProvenanceLabel = Literal["raw", "manually-enhanced", "auto-enhanced"] + + +def prompt_provenance_label( + provenance: PromptProvenance, + resolved: ResolvedGenerationPrompt, +) -> PromptProvenanceLabel: + """How this run asked for the prompt to be passed. Not the prompt text.""" + return shared_prompt_provenance_label( + provenance, + enhanced_locally=resolved.enhanced_locally, + enhance_via_api=resolved.enhance_via_api, + ) + + class PromptEnhancementHandler(StateHandlerBase): def __init__( self, @@ -72,6 +115,57 @@ def __init__( def _random_seed(self) -> int: return random.randint(0, _MAX_ENHANCE_SEED) + def status(self, *, prefer_gemini: bool) -> PromptEnhancerStatusResponse: + """Flags for the Home Enhance control. ``prefer_gemini`` is Remote's default.""" + settings = self.state.app_settings + has_gemini = bool(settings.gemini_api_key.strip()) + local_downloaded = ( + self._text_handler.resolve_prompt_enhancer_root_if_downloaded() is not None + ) + has_local = local_downloaded and not self.config.force_api_generations + if prefer_gemini: + default_provider: Literal["local", "api"] = ( + "api" if has_gemini else "local" if has_local else "api" + ) + else: + preference = settings.prompt_enhancer_provider_preference + if preference == "api": + preferred: Literal["local", "api"] = "api" + elif preference == "local" and has_local: + preferred = "local" + elif has_local: + preferred = "local" + else: + preferred = "api" + default_provider = ( + "local" + if preferred == "api" and not has_gemini and has_local + else preferred + ) + return PromptEnhancerStatusResponse( + exploreAutoEnhancePrompts=settings.explore_auto_enhance_prompts, + hasGeminiApiKey=has_gemini, + localEnhancementSupported=has_local, + defaultProvider=default_provider, + canToggleProvider=has_local and has_gemini, + showManualEnhance=not settings.explore_auto_enhance_prompts, + ) + + def _automatic_enhancement_seed( + self, generation_seed: int, *, explicit_generation_seed: bool + ) -> int: + """The seed an automatic rewrite runs on, given the seed the generation resolved to. + + Automatic enhancement is part of what produces the video: the model never sees the + prompt as typed, only the rewrite. Drawing that rewrite independently would leave a + pinned local generation irreproducible — same seed, different prompt, different clip — + so an explicit request seed or seed lock makes the rewrite ride the generation's seed. + An unlocked request without an explicit seed draws fresh like manual Enhance does. + """ + if explicit_generation_seed or self.state.app_settings.seed_locked: + return generation_seed + return self._random_seed() + def enhance(self, req: EnhancePromptRequest) -> EnhancePromptResponse: # Enhance never occupies the GPU slot (see PipelinesHandler. # evict_gpu_pipeline_for_prompt_enhancement) but still needs to mutually exclude with @@ -87,7 +181,7 @@ def enhance(self, req: EnhancePromptRequest) -> EnhancePromptResponse: gemma_root = self._text_handler.resolve_prompt_enhancer_root_if_downloaded() if gemma_root is None: raise HTTPError(409, "LOCAL_TEXT_ENCODER_NOT_AVAILABLE") - elif not self.state.app_settings.gemini_api_key: + elif not self.state.app_settings.gemini_api_key.strip(): raise HTTPError(400, "GEMINI_API_KEY_MISSING") generation_id = uuid.uuid4().hex[:8] @@ -140,85 +234,357 @@ def _default_video_system_prompt(self, req: EnhancePromptRequest) -> str | None: return self._keyframe_system_prompt() return self._video_system_prompt(t2v=req.imagePath is None) - def _keyframe_system_prompt(self) -> str: - spec = self._text_handler.active_ltx_model_spec() + def _keyframe_system_prompt(self, model_id: LTXLocalModelId | None = None) -> str: + spec = self._text_handler.ltx_model_spec(model_id) audio_visual = spec is not None and spec.wants_audio_visual_captions return build_keyframe_enhancement_system_prompt(audio_visual=audio_visual) - def _video_system_prompt(self, *, t2v: bool) -> str | None: - """The active model's own caption style, or None to keep each provider's default. + def _video_system_prompt( + self, *, t2v: bool, model_id: LTXLocalModelId | None = None + ) -> str | None: + """The model's own caption style, or None to keep each provider's default. Only the audio-visual generations (2.5) need this: their captions cover the soundscape, which neither the generic Gemini fallback nor a 2.3-era prompt asks for. """ - spec = self._text_handler.active_ltx_model_spec() + spec = self._text_handler.ltx_model_spec(model_id) if spec is None or not spec.wants_audio_visual_captions: return None return build_audio_visual_caption_system_prompt(t2v=t2v) - def enhance_for_generation( + def resolve_for_generation( self, prompt: str, *, - image_path: str | None, + provenance: PromptProvenance, + generation_seed: int, + explicit_generation_seed: bool = False, + image_path: str | None = None, last_image_path: str | None = None, keyframes: list[KeyframeStill] | None = None, duration: int | None = None, fps: int | None = None, - ) -> str: - """Rewrite ``prompt`` on the local enhancer for a generation that's already started. + ic_lora: IcLoraCatalogItem | None = None, + lora_catalog_ids: list[str] | None = None, + conditioning_type: ConditioningType | None = None, + local_model_id: LTXLocalModelId | None = None, + explore_generation: bool = False, + audio_path: str | None = None, + ) -> ResolvedGenerationPrompt: + """The single enhancement policy for prompt-bearing local generation. + + Local encoding attempts a rewrite unless this is an Explore generation with + auto-enhance off. API encoding forwards ``enhance_prompt`` according to the T2V/I2V + settings (I2V and keyframe jobs use the I2V toggle; T2V, IC-LoRA, and A2V — + including A2V with an optional start frame — use T2V). Three things still suppress + both paths: an "enhanced" provenance, meaning the + user already ran Enhance by hand and kept the result (rewriting a rewrite drifts the + prompt away from what they approved); an empty prompt, which has nothing to expand; and + Explore auto-enhance off, which sends the prompt as typed (Gen Space is unchanged). + + The two text-encoding paths enhance in different places: API encoding rewrites + server-side inside the same /prompt-embedding call, so it only needs the flag forwarded. + Local encoding has no such step, so the rewrite happens here — without it the model sees + the prompt as typed, which for a version captioned in 150-220 word audio-visual + paragraphs (2.5) lands far outside its training distribution and it invents the rest. + + ``lora_catalog_ids`` are the catalog ids of the plain LoRAs the request selected. They + get the same catalog-aware treatment manual Enhance gives them, because the generic + rewrite would paraphrase a required trigger phrase away and leave the adapter inert. + + ``generation_seed`` is the seed the caller already resolved for this run (an explicit + request seed, the lock, or a fresh draw). It reaches the rewrite when + ``explicit_generation_seed`` is true or seed locking is enabled — see + _automatic_enhancement_seed() — and never reaches the API path, whose ``enhance_prompt`` + flag takes no seed. + + Must be called before the pipeline is loaded and before start_generation: the enhancer + needs the VRAM a resident pipeline holds, and PipelinesHandler refuses to evict one + while a generation is running. + """ + preview = self._preview_resolution( + prompt, + provenance=provenance, + explore_generation=explore_generation, + local_model_id=local_model_id, + ) + if preview is not None: + if preview.skip_recipe_wrap and provenance != "enhanced" and prompt.strip(): + logger.info( + "Explore auto-enhance off: sending prompt as typed (%d chars)", + len(prompt), + ) + return preview + enhanced, rewritten = self.enhance_for_generation( + prompt, + generation_seed=generation_seed, + explicit_generation_seed=explicit_generation_seed, + image_path=image_path, + last_image_path=last_image_path, + keyframes=keyframes, + duration=duration, + fps=fps, + ic_lora=ic_lora, + loras=self._resolve_generation_loras(lora_catalog_ids), + conditioning_type=conditioning_type, + local_model_id=local_model_id, + ) + return ResolvedGenerationPrompt(enhanced, False, rewritten, False) + + def preview_prompt_provenance( + self, + prompt: str, + *, + provenance: PromptProvenance, + explore_generation: bool = False, + local_model_id: LTXLocalModelId | None = None, + force_api: bool = False, + ) -> PromptProvenanceLabel: + """The analytics label for this request, without rewriting the prompt. + + A local rewrite that has not run yet counts as auto-enhanced. That is the + mode this run requested; a later Gemma fallback still used that mode. + """ + preview = self._preview_resolution( + prompt, + provenance=provenance, + explore_generation=explore_generation, + local_model_id=local_model_id, + force_api=force_api, + ) + if preview is None: + preview = ResolvedGenerationPrompt(prompt, False, True) + return shared_prompt_provenance_label( + provenance, + enhanced_locally=preview.enhanced_locally, + enhance_via_api=preview.enhance_via_api, + ) + + def _preview_resolution( + self, + prompt: str, + *, + provenance: PromptProvenance, + explore_generation: bool, + local_model_id: LTXLocalModelId | None, + force_api: bool = False, + ) -> ResolvedGenerationPrompt | None: + """Resolution when no local rewrite is required. + + None means a local rewrite will be attempted. + """ + decided = shared_resolution_for_provenance( + provenance, + prompt=prompt, + explore_generation=explore_generation, + explore_auto_enhance_prompts=self.state.app_settings.explore_auto_enhance_prompts, + use_local_encoding=self._text_handler.should_use_local_encoding(local_model_id), + prompt_enhancer_enabled=self.state.app_settings.prompt_enhancer_enabled, + local_enhancer_available=( + self._text_handler.resolve_prompt_enhancer_root_if_downloaded(local_model_id) + is not None + ), + force_api=force_api, + ) + if decided is None: + return None + enhance_via_api, enhanced_locally, skip_recipe_wrap = decided + return ResolvedGenerationPrompt(prompt, enhance_via_api, enhanced_locally, skip_recipe_wrap) + + def api_enhance_prompt( + self, + prompt: str, + *, + provenance: PromptProvenance, + image_path: str | None = None, + keyframes: list[KeyframeStill] | None = None, + audio_path: str | None = None, + ) -> bool: + """Whether the LTX API should rewrite this prompt on the server. + + Used for API text encoding (``enhance_prompt`` on /prompt-embedding) and for + fully-remote video (``enhance_prompt`` on /v2/text-to-video and siblings). The + LTX gateway defaults that flag to true when omitted, so callers must send it. + + One setting covers every conditioning: the conditioning arguments stay in the + signature because callers pass them, but they no longer select between gates. + """ + if provenance == "enhanced" or not prompt.strip(): + return False + return self.state.app_settings.prompt_enhancer_enabled + + def _resolve_generation_loras(self, catalog_ids: list[str] | None) -> list[LoraCatalogItem]: + """The catalog entries behind a generation's selected plain LoRAs, by id alone. - Only for the local text-encoding path: API encoding enhances server-side inside the - same call, so it never gets here. Deliberately not `enhance()` — the caller already - holds the generation slot, and there's no provider choice to make, only "is the - enhancer on disk". + Unlike manual Enhance, an unresolvable id doesn't 404: automatic enhancement is a + quality step layered onto a generation the user already started, so a stale id costs + the catalog treatment rather than the run. + """ + items: list[LoraCatalogItem] = [] + for catalog_id in catalog_ids or []: + lora = self._lora_catalog_provider.get_lora(catalog_id) + if lora is None: + logger.info("Skipping unknown LoRA catalog id for enhancement: %s", catalog_id) + continue + # A templated entry needs the template-fill path, which the multi-select free + # rewrite has no shape for. No plain catalog LoRA has one today. + if lora.prompt_template is not None: + continue + items.append(lora) + return items - Never raises: enhancement is a quality step, so a missing checkpoint or a failed - rewrite degrades to the prompt as typed rather than failing the generation. + def enhance_for_generation( + self, + prompt: str, + *, + generation_seed: int, + explicit_generation_seed: bool, + image_path: str | None, + last_image_path: str | None = None, + keyframes: list[KeyframeStill] | None = None, + duration: int | None = None, + fps: int | None = None, + ic_lora: IcLoraCatalogItem | None = None, + loras: list[LoraCatalogItem] | None = None, + conditioning_type: ConditioningType | None = None, + local_model_id: LTXLocalModelId | None = None, + ) -> tuple[str, bool]: + """Rewrite ``prompt`` on the local enhancer: ``(prompt, rewritten)``. + + ``rewritten`` is False on every fallback below, which is what lets a caller's run log + distinguish "the enhancer rewrote this" from "the enhancer never ran". + + Home auto-enhance calls this whenever the enhancer checkpoint is on disk, including + when text embeddings come from the API. A plain API-encoding run with no local + checkpoint still enhances server-side and never gets here. Deliberately not + `enhance()` — the caller already holds the generation slot, and there's no provider + choice to make, only "is the enhancer on disk". + + Only cancellation is re-raised. Enhancement is otherwise a quality step, so a missing + checkpoint or failed rewrite degrades to a deterministic fallback rather than failing + the generation. """ + loras = loras or [] if not prompt.strip(): - return prompt - gemma_root = self._text_handler.resolve_prompt_enhancer_root_if_downloaded() + return prompt, False + gemma_root = self._text_handler.resolve_prompt_enhancer_root_if_downloaded( + model_id=local_model_id + ) if gemma_root is None: logger.info("Skipping automatic enhancement: no local prompt enhancer downloaded") - return prompt + return self._generation_fallback_prompt(prompt, ic_lora, loras), False try: pipeline = self._load_prompt_enhancer_pipeline(gemma_root) - system_prompt = ( - self._keyframe_system_prompt() - if keyframes - else self._video_system_prompt(t2v=image_path is None) + seed = self._automatic_enhancement_seed( + generation_seed, explicit_generation_seed=explicit_generation_seed ) - seed = self._random_seed() - if image_path is not None or keyframes: - first_path = image_path or (keyframes[0][0] if keyframes else None) - assert first_path is not None - enhanced = pipeline.enhance_i2v( - prompt, - first_path, - system_prompt=system_prompt, - seed=seed, - last_image_path=None if keyframes else last_image_path, + if ic_lora is not None: + enhanced = self._enhance_ic_lora_for_generation(pipeline, prompt, ic_lora, seed) + else: + system_prompt = self._generation_system_prompt( + loras=loras, + image_path=image_path, keyframes=keyframes, - duration=duration, - fps=fps, + conditioning_type=conditioning_type, + local_model_id=local_model_id, ) - else: - enhanced = pipeline.enhance_t2v(prompt, system_prompt=system_prompt, seed=seed) - except Exception: - logger.warning("Automatic local enhancement failed; using the prompt as typed", exc_info=True) - return prompt + if image_path is not None or keyframes: + first_path = image_path or (keyframes[0][0] if keyframes else None) + assert first_path is not None + enhanced = pipeline.enhance_i2v( + prompt, + first_path, + system_prompt=system_prompt, + seed=seed, + last_image_path=None if keyframes else last_image_path, + keyframes=keyframes, + duration=duration, + fps=fps, + ) + else: + enhanced = pipeline.enhance_t2v(prompt, system_prompt=system_prompt, seed=seed) + if enhanced.strip(): + # Deterministic, same as manual Enhance: the rewrite is asked for the + # trigger phrases, never trusted to have kept them. + enhanced = enforce_trigger_placements(enhanced, loras) + except Exception as exc: + if is_cancel_exception(exc): + raise + logger.warning("Automatic local enhancement failed; using the fallback prompt", exc_info=True) + return self._generation_fallback_prompt(prompt, ic_lora, loras), False if not enhanced.strip(): - return prompt + return self._generation_fallback_prompt(prompt, ic_lora, loras), False logger.info( - "Enhanced prompt locally for generation (%d -> %d chars): %s", + "Enhanced prompt locally for generation (%d -> %d chars)", len(prompt), len(enhanced), - enhanced, ) - return enhanced + return enhanced, True + + def _generation_fallback_prompt( + self, + prompt: str, + ic_lora: IcLoraCatalogItem | None, + loras: list[LoraCatalogItem], + ) -> str: + """Preserve every non-template catalog adapter's trigger when no rewrite is available.""" + items: list[LoraCatalogItem] = list(loras) + if ic_lora is not None and ic_lora.prompt_template is None: + items.append(ic_lora) + return prompt if not items else enforce_trigger_placements(prompt, items) + + def _generation_system_prompt( + self, + *, + loras: list[LoraCatalogItem], + image_path: str | None, + keyframes: list[KeyframeStill] | None, + conditioning_type: ConditioningType | None, + local_model_id: LTXLocalModelId | None = None, + ) -> str | None: + if loras: + # Same treatment manual Enhance's multi-select path applies. It replaces the + # model's own caption style rather than layering onto it: what the adapters need + # from the prompt is the more specific constraint, and the LoRA block already + # carries its own output-format instruction. + return build_lora_enhancement_system_prompt(loras) + if conditioning_type is not None: + # Built-in canny/depth IC-LoRA: no catalog entry to draw from, but the same + # "describe the reference scene faithfully" discipline manual Enhance applies. + return build_conditioning_system_prompt(conditioning_type) + if keyframes: + return self._keyframe_system_prompt(model_id=local_model_id) + return self._video_system_prompt(t2v=image_path is None, model_id=local_model_id) + + def _enhance_ic_lora_for_generation( + self, + pipeline: PromptEnhancerPipeline, + prompt: str, + ic_lora: IcLoraCatalogItem, + seed: int, + ) -> str: + """The catalog-aware treatment manual Enhance gives an IC-LoRA, minus the error surface. + + Text-only on purpose, exactly like the manual IC-LoRA path: an IC-LoRA's reference is + its driving clip (or the control video built from it), not an i2v conditioning still. + A template that can't be filled raises out to the caller's typed-prompt fallback rather + than failing the generation. + """ + if ic_lora.prompt_template is not None: + raw = pipeline.enhance_t2v( + prompt, system_prompt=build_template_fill_system_prompt(ic_lora), seed=seed + ) + values = parse_template_fill_response(raw, set(ic_lora.prompt_template.placeholders)) + return fill_prompt_template(ic_lora.prompt_template, values) + enhanced = pipeline.enhance_t2v( + prompt, system_prompt=build_ic_lora_enhancement_system_prompt(ic_lora), seed=seed + ) + # Trigger enforcement on an empty rewrite would generate from a bare trigger word. + if not enhanced.strip(): + return enhanced + return enforce_trigger_placements(enhanced, [ic_lora]) def _enhance_loras( self, loras: list[LoraCatalogItem], req: EnhancePromptRequest, gemma_root: str | None @@ -263,7 +629,7 @@ def _run_free_rewrite( if req.provider == "api": resolved_model = resolve_gemini_model(self.state.app_settings.gemini_model) logger.info("Enhancing prompt via Gemini API (%s)", resolved_model) - api_key = self.state.app_settings.gemini_api_key + api_key = self.state.app_settings.gemini_api_key.strip() if first_path is not None: return self._gemini_pipeline.enhance_i2v( req.prompt, @@ -331,7 +697,7 @@ def _run_template_fill( req.prompt, system_prompt=system_prompt, seed=seed, - api_key=self.state.app_settings.gemini_api_key, + api_key=self.state.app_settings.gemini_api_key.strip(), model=resolved_model, ) else: diff --git a/backend/handlers/queued_generation_handler.py b/backend/handlers/queued_generation_handler.py new file mode 100644 index 000000000..1ae04a4c5 --- /dev/null +++ b/backend/handlers/queued_generation_handler.py @@ -0,0 +1,718 @@ +from __future__ import annotations + +import sqlite3 +from collections.abc import Callable, Collection +from pathlib import Path +from threading import RLock +from typing import TYPE_CHECKING, Literal + +from pydantic import JsonValue, ValidationError + +from api_types import ( + CreateIcLoraRecipeRequest, + AudioToVideoParams, + Asset, + CreateAudioToVideoParams, + CreateAudioToVideoRequest, + CreateImageToVideoRequest, + CreateLoraRecipeRequest, + CreateExtendRequest, + CreateRetakeRequest, + CreateTextToVideoRequest, + Generation, + GenerationProgressResponse, + OfferingId, + QueueEntry, + QueueProgress, + QueueSnapshot, +) +from _routes._errors import HTTPError +from handlers.base import resolve_models_dir +from handlers.hf_auth_utils import optional_hf_token +from runtime_config.accelerator import accelerator_backend +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, +) +from runtime_config.ltx_capabilities import LtxCapabilityFeature +from services.features.video.job_common import require_capable_local_model +from services.media_probe import MAX_VIDEO_BYTES, video_fps +from services.features.ic_lora_recipes import ( + ic_lora_input_cap_message, + resolve_ic_lora_recipe_create, +) +from services.features.lora_recipes import RecipeCreateError, resolve_recipe_create +from services.lora_catalog import LoraCatalogProvider +from services.store import Store +from services.sqlite_store import collect_asset_ids +from services.records import ( + AttemptError, + AssetRecord, + CapabilityFailedError, + GenerationRecord, + MediaError, + QueueGenerationRecord, + StatusError, + UnavailableError, +) +from services.generation_queue.control import ( + QueueControl, + NoOpQueueControl, + cancel_queued_generation, +) +from services.generation_queue.finished_tray import FinishedTray +from services.generation_queue.registry import ExecutorRegistry +from services.features.video import ( + AUDIO_TO_VIDEO_FEATURE, + EXTEND_FEATURE, + FEATURE as TEXT_TO_VIDEO_FEATURE, + IMAGE_TO_VIDEO_FEATURE, + RETAKE_FEATURE, +) +from state.app_state_types import AppState + +if TYPE_CHECKING: + from runtime_config.runtime_config import RuntimeConfig + + +AnalyticsClient = Literal["desktop", "remote"] + + +def _generation_to_api(record: GenerationRecord) -> Generation: + payload = record.model_dump(mode="json") + spec = dict(record.spec) + spec.pop("_analytics", None) + payload["spec"] = spec + return Generation.model_validate(payload) + + +class QueuedGenerationHandler: + def __init__( + self, + store: Store, + executor_registry: ExecutorRegistry, + derive_local_a2v: Callable[[CreateAudioToVideoParams, int], AudioToVideoParams], + queue_control: QueueControl | None = None, + *, + progress_reader: Callable[[], GenerationProgressResponse] | None = None, + config: "RuntimeConfig | None" = None, + lora_catalog_provider: LoraCatalogProvider | None = None, + state: AppState | None = None, + lock: RLock | None = None, + ) -> None: + self._db = store + self._executor_registry = executor_registry + self._derive_local_a2v = derive_local_a2v + self._queue_control = ( + NoOpQueueControl() if queue_control is None else queue_control + ) + self._progress_reader = progress_reader + # LoRA-recipe create needs the models dir, the catalog, and HF-auth state to + # resolve a catalog id to an installed path and to gate typed misses before + # enqueue. Optional so tests that only exercise the plain t2v/i2v create paths + # (or construct the handler directly) don't have to wire them. + self._config = config + self._lora_catalog_provider = lora_catalog_provider + self._state = state + self._lock = lock + self._finished = FinishedTray() + + def recover_on_boot(self) -> None: + self._db.fail_running_on_boot() + + def create_text_to_video( + self, + req: CreateTextToVideoRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + spec: dict[str, JsonValue] = { + "params": req.params.model_dump(mode="json"), + "inputs": {}, + } + return self._enqueue_generation( + TEXT_TO_VIDEO_FEATURE, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + ) + + def create_image_to_video( + self, + req: CreateImageToVideoRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + self._require_image_asset(req.inputs.startFrame.assetId, slot="startFrame") + if req.inputs.endFrame is not None: + self._require_image_asset(req.inputs.endFrame.assetId, slot="endFrame") + spec: dict[str, JsonValue] = { + "params": req.params.model_dump(mode="json"), + "inputs": req.inputs.model_dump(mode="json", exclude_none=True), + } + return self._enqueue_generation( + IMAGE_TO_VIDEO_FEATURE, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + ) + + def create_lora_recipe( + self, + recipe_id: str, + req: CreateLoraRecipeRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + """Create a queued generation for a LoRA recipe. + + The client sends the catalog id + scale, never a filesystem path. + :func:`resolve_recipe_create` validates the recipe (unknown / mode / device / + HF / visibility / not-downloaded / missing start frame) and stores + ``loras: [{ ref: "", scale, catalogId }]``. Execute hydrates ``ref`` via + ``make_recipe_lora_resolver``. Anything invalid raises a typed miss *before* + this handler enqueues — no row, no GPU slot. The row is stored under + ``feature == recipe_id`` (the web Explore id). i2v recipes also persist + ``inputs.startFrame``. + """ + self._require_local_generation_possible() + try: + feature, params, inputs = resolve_recipe_create( + recipe_id, + req, + catalog=self._require_catalog(), + models_dir=self._models_dir(), + device=self._recipe_device(), + hf_authenticated=self._hf_authenticated(), + ) + except RecipeCreateError as exc: + raise HTTPError(422, str(exc), code=exc.code) from exc + + if inputs is not None: + self._require_image_asset(inputs.startFrame.assetId, slot="startFrame") + if inputs.endFrame is not None: + self._require_image_asset(inputs.endFrame.assetId, slot="endFrame") + + spec: dict[str, JsonValue] = { + "params": params.model_dump(mode="json"), + "inputs": ( + inputs.model_dump(mode="json", exclude_none=True) if inputs is not None else {} + ), + } + return self._enqueue_generation( + feature, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + ) + + def _require_local_generation_possible(self) -> None: + # The Explore queue is local-only (no API fallback), so a machine that can't + # generate locally must fail the create rather than enqueue a job that can + # never run. Mirrors StateHandlerBase._require_local_generation_possible. + if ( + self._config is not None + and self._config.local_generations_mode == "unsupported" + ): + raise HTTPError( + 422, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + code=LOCAL_GENERATION_UNSUPPORTED, + ) + + def _recipe_device(self) -> str | None: + # The real accelerator backend (cuda / rocm / mps / cpu), not the Darwin flag: + # an Intel Mac is not MPS and a CPU/ROCm Linux box is not CUDA. None when there + # is no config to gate against (tests that construct the handler directly). + if self._config is None: + return None + return accelerator_backend() + + def _hf_authenticated(self) -> bool: + if self._state is None or self._lock is None: + return False + return optional_hf_token(self._state, self._lock) is not None + + def _require_catalog(self) -> LoraCatalogProvider: + if self._lora_catalog_provider is None: + raise HTTPError(500, "LoRA catalog is not configured") + return self._lora_catalog_provider + + def _models_dir(self) -> Path: + if self._config is None: + raise HTTPError(500, "Runtime config is not configured") + return resolve_models_dir(self._state, self._config) + + def create_audio_to_video( + self, + req: CreateAudioToVideoRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + if req.params.prompt.strip() == "" and req.inputs.startFrame is None: + raise HTTPError( + 422, + "Connect a prompt or a start image before running this node.", + code="INVALID_GENERATION_SPEC", + ) + audio = self._require_audio_asset(req.inputs.audio.assetId, slot="audio") + if audio.metadata.mediaType != "audio": + raise HTTPError(422, "INVALID_AUDIO_ASSET", code="INVALID_GENERATION_SPEC") + params = self._derive_local_a2v( + req.params, + audio.metadata.metadata.durationMs, + ) + if req.inputs.startFrame is not None: + self._require_image_asset(req.inputs.startFrame.assetId, slot="startFrame") + spec: dict[str, JsonValue] = { + "params": params.model_dump(mode="json"), + "inputs": req.inputs.model_dump(mode="json", exclude_none=True), + } + return self._enqueue_generation( + AUDIO_TO_VIDEO_FEATURE, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + ) + + def create_retake( + self, + req: CreateRetakeRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + return self._enqueue_video_edit( + RETAKE_FEATURE, + req, + "retake", + code="UNSUPPORTED_RETAKE", + message="Retake is not supported for the selected LTX model.", + analytics_client=analytics_client, + extra=lambda duration_ms: self._validate_retake_selection( + req.params.startTime, + req.params.duration, + duration_ms, + ), + ) + + def create_ic_lora_recipe( + self, + recipe_id: str, + req: CreateIcLoraRecipeRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + self._require_local_generation_possible() + video = self._require_asset( + req.inputs.video.assetId, + slot="video", + kind="video", + max_bytes=MAX_VIDEO_BYTES, + ) + if video.metadata.mediaType != "video": + raise HTTPError(422, "INVALID_VIDEO_ASSET", code="INVALID_GENERATION_SPEC") + if req.inputs.image is not None: + self._require_image_asset(req.inputs.image.assetId, slot="image") + source_fps = video.metadata.metadata.fps + if source_fps is None: + try: + source_fps = video_fps(Path(video.path)) + except MediaError as exc: + raise HTTPError( + 422, "INVALID_VIDEO_ASSET", code="INVALID_GENERATION_SPEC" + ) from exc + try: + recipe, item, stored = resolve_ic_lora_recipe_create( + recipe_id, + req, + catalog=self._require_catalog(), + models_dir=self._models_dir(), + hf_authenticated=self._hf_authenticated(), + source_fps=source_fps, + ) + except RecipeCreateError as exc: + if exc.code == "IC_LORA_NOT_DOWNLOADED": + status = 409 + elif exc.code == "UNKNOWN_DOWNLOAD_VARIANT": + status = 404 + else: + status = 422 + raise HTTPError(status, str(exc), code=exc.code) from exc + too_long = ic_lora_input_cap_message( + video.metadata.metadata.durationMs, stored.fps + ) + if too_long is not None: + raise HTTPError(422, too_long, code="IC_LORA_INPUT_TOO_LONG") + self._require_offering_capability( + req.params.model, + "ic_lora", + code="UNSUPPORTED_IC_LORA", + message=f"{item.name} is not supported for the selected LTX model.", + ) + spec: dict[str, JsonValue] = { + "params": stored.model_dump(mode="json", exclude={"scale", "variantId"}), + "inputs": req.inputs.model_dump(mode="json", exclude_none=True), + } + return self._enqueue_generation( + recipe.recipe_id, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + ) + + def create_extend( + self, + req: CreateExtendRequest, + *, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + return self._enqueue_video_edit( + EXTEND_FEATURE, + req, + "extend", + code="UNSUPPORTED_EXTEND", + message="Extend is not supported for the selected LTX model.", + analytics_client=analytics_client, + ) + + def _enqueue_video_edit( + self, + feature: str, + req: CreateRetakeRequest | CreateExtendRequest, + capability: LtxCapabilityFeature, + *, + code: str, + message: str, + analytics_client: AnalyticsClient | None, + extra: Callable[[int], None] | None = None, + ) -> Generation: + video = self._require_asset( + req.inputs.video.assetId, + slot="video", + kind="video", + max_bytes=MAX_VIDEO_BYTES, + ) + if video.metadata.mediaType != "video": + raise HTTPError(422, "INVALID_VIDEO_ASSET", code="INVALID_GENERATION_SPEC") + if extra is not None: + extra(video.metadata.metadata.durationMs) + self._require_offering_capability( + req.params.model, capability, code=code, message=message + ) + params_payload = req.params.model_dump(mode="json") + spec: dict[str, JsonValue] = { + "params": params_payload, + "inputs": req.inputs.model_dump(mode="json", exclude_none=True), + } + return self._enqueue_generation( + feature, + spec, + contract_version=req.contract_version, + analytics_client=analytics_client, + ) + + def _require_asset( + self, + asset_id: str, + *, + slot: str, + kind: Literal["image", "audio", "video"], + max_bytes: int | None = None, + ) -> AssetRecord: + try: + asset = self._db.get_asset(asset_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + missing = ( + f"{slot} image is no longer available" + if kind == "image" + else f"{slot} is no longer available" + ) + if asset is None: + raise HTTPError( + 422, + missing, + code="INPUT_ASSET_NOT_FOUND", + ) + if asset.media_kind != kind: + article = "an" if kind[0] in "aeiou" else "a" + raise HTTPError( + 422, + f"{slot} must reference {article} {kind} asset", + code="INVALID_GENERATION_SPEC", + ) + if max_bytes is not None: + try: + if Path(asset.path).stat().st_size > max_bytes: + raise HTTPError(400, "FILE_TOO_LARGE", code="FILE_TOO_LARGE") + except OSError as exc: + raise HTTPError( + 422, + missing, + code="INPUT_ASSET_NOT_FOUND", + ) from exc + return asset + + def _require_image_asset(self, asset_id: str, *, slot: str) -> AssetRecord: + return self._require_asset(asset_id, slot=slot, kind="image") + + def _require_audio_asset(self, asset_id: str, *, slot: str) -> AssetRecord: + return self._require_asset(asset_id, slot=slot, kind="audio") + + def _validate_retake_selection( + self, start_time: float, duration: float, duration_ms: int + ) -> None: + source_seconds = duration_ms / 1000 + if source_seconds + 0.1 < 2.0: + raise HTTPError( + 422, + "This video is shorter than 2s. Replace it to continue.", + code="INVALID_GENERATION_SPEC", + ) + if start_time + duration > source_seconds + 0.1: + raise HTTPError( + 422, + "Selection is outside the usable video range", + code="INVALID_GENERATION_SPEC", + ) + + def _require_offering_capability( + self, + offering: OfferingId, + capability: LtxCapabilityFeature, + *, + code: str, + message: str, + ) -> None: + try: + require_capable_local_model( + self._models_dir(), + offering, + capability, + unsupported_code=code, + unsupported_message=message, + ) + except CapabilityFailedError as exc: + raise HTTPError(409, exc.detail, code=exc.code) from exc + + def _enqueue_generation( + self, + feature: str, + spec: dict[str, JsonValue], + *, + contract_version: int, + analytics_client: AnalyticsClient | None = None, + ) -> Generation: + try: + self._executor_registry.validate_params( + feature, spec, contract_version=contract_version + ) + except (ValidationError, ValueError, CapabilityFailedError) as exc: + if isinstance(exc, CapabilityFailedError): + raise HTTPError( + 422, + exc.detail, + code=exc.code or "INVALID_GENERATION_SPEC", + ) from exc + raise HTTPError( + 422, + str(exc), + code="INVALID_GENERATION_SPEC", + ) from exc + if analytics_client is not None: + spec = { + **spec, + "_analytics": {"client": analytics_client}, + } + try: + record = self._db.insert_generation( + feature, + spec, + contract_version=contract_version, + ) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except ValueError as exc: + raise HTTPError(400, str(exc)) from exc + except sqlite3.IntegrityError as exc: + raise HTTPError(400, str(exc)) from exc + self._queue_control.wake() + return _generation_to_api(record) + + def retry_generation(self, generation_id: str) -> Generation: + try: + record = self._db.retry_generation(generation_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except KeyError as exc: + raise HTTPError(404, "GENERATION_NOT_FOUND") from exc + except StatusError as exc: + raise HTTPError(409, "INVALID_GENERATION_STATUS") from exc + self._finished.release(generation_id) + self._queue_control.wake() + return _generation_to_api(record) + + def cancel_generation(self, generation_id: str) -> Generation: + try: + record = cancel_queued_generation( + self._db, + generation_id, + self._queue_control.interrupt, + ) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except KeyError as exc: + raise HTTPError(404, "GENERATION_NOT_FOUND") from exc + except (AttemptError, StatusError) as exc: + raise HTTPError(409, "INVALID_GENERATION_STATUS") from exc + self._queue_control.wake() + return _generation_to_api(record) + + def get_queue_snapshot(self) -> QueueSnapshot: + try: + entries = self._db.list_queue_generations() + self._finished.observe(entries, self._db.get_generation) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + + active_record = next( + ( + entry + for entry in entries + if entry.generation.status in {"running", "cancelling"} + ), + None, + ) + active = ( + self._queue_entry(active_record, self._active_progress(active_record)) + if active_record is not None + else None + ) + queued = [ + self._queue_entry(entry, None) + for entry in entries + if entry.generation.status == "queued" + ] + done, failed, unseen_ids = self._finished.lists() + return QueueSnapshot( + active=active, + queued=queued, + done=[self._queue_entry(entry, None) for entry in done], + failed=[self._queue_entry(entry, None) for entry in failed], + unseen_ids=unseen_ids, + ) + + def remember_finished(self, generation_id: str) -> None: + try: + record = self._db.get_generation(generation_id) + if record is None: + return + assets = tuple( + asset + for asset_id in collect_asset_ids(record.spec) + if (asset := self._db.get_asset(asset_id)) is not None + ) + except UnavailableError: + return + self._finished.remember( + QueueGenerationRecord(generation=record, input_assets=assets) + ) + + def mark_done_seen(self, generation_id: str) -> QueueSnapshot: + if not self._finished.mark_seen(generation_id): + raise HTTPError(404, "GENERATION_NOT_FOUND") + return self.get_queue_snapshot() + + def dismiss_done(self, generation_id: str) -> QueueSnapshot: + if not self._finished.dismiss_done(generation_id): + raise HTTPError(404, "GENERATION_NOT_FOUND") + return self.get_queue_snapshot() + + def clear_done( + self, *, feature_is_allowed: Callable[[str], bool] | None = None + ) -> QueueSnapshot: + self._finished.clear_done(feature_is_allowed) + return self.get_queue_snapshot() + + def clear_failed( + self, *, feature_is_allowed: Callable[[str], bool] | None = None + ) -> QueueSnapshot: + self._finished.clear_failed(feature_is_allowed) + return self.get_queue_snapshot() + + def reorder_queue( + self, generation_id: str, before_generation_id: str | None + ) -> QueueSnapshot: + try: + self._db.reorder_queued_generation(generation_id, before_generation_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except KeyError as exc: + raise HTTPError(404, "GENERATION_NOT_FOUND") from exc + except StatusError as exc: + raise HTTPError(409, "INVALID_GENERATION_STATUS") from exc + self._queue_control.wake() + return self.get_queue_snapshot() + + def _active_progress( + self, active: QueueGenerationRecord + ) -> QueueProgress | None: + if self._progress_reader is None: + return None + progress = self._progress_reader() + if progress.id != active.generation.id: + return None + return QueueProgress( + phase=progress.phase, + progress=progress.progress, + currentStep=progress.currentStep, + totalSteps=progress.totalSteps, + ) + + @staticmethod + def _queue_entry( + entry: QueueGenerationRecord, progress: QueueProgress | None + ) -> QueueEntry: + return QueueEntry( + generation=_generation_to_api(entry.generation), + input_assets=[ + Asset.model_validate(asset.model_dump(mode="json")) + for asset in entry.input_assets + ], + progress=progress, + ) + + def list_generations(self, feature: str) -> list[Generation]: + try: + records = self._db.list_generations(feature) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + return [_generation_to_api(record) for record in records] + + def list_recent_features( + self, *, limit: int, allowed: Collection[str] | None = None + ) -> list[str]: + try: + return self._db.list_recent_features(limit=limit, allowed=allowed) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + + def get_generation(self, generation_id: str) -> Generation: + try: + record = self._db.get_generation(generation_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + if record is None: + raise HTTPError(404, "GENERATION_NOT_FOUND") + return _generation_to_api(record) + + def delete_generation(self, generation_id: str) -> None: + try: + deleted = self._db.delete_generation(generation_id) + except UnavailableError as exc: + raise HTTPError(503, "STORE_UNAVAILABLE") from exc + except StatusError as exc: + raise HTTPError(409, "INVALID_GENERATION_STATUS") from exc + if not deleted: + raise HTTPError(404, "GENERATION_NOT_FOUND") + self._finished.forget(generation_id) diff --git a/backend/handlers/retake_handler.py b/backend/handlers/retake_handler.py index 57756ca36..835f65295 100644 --- a/backend/handlers/retake_handler.py +++ b/backend/handlers/retake_handler.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import uuid from datetime import datetime from pathlib import Path @@ -20,6 +21,7 @@ from _routes._errors import HTTPError from api_model_specs import FORCED_API_MODEL_MAP from handlers.base import StateHandlerBase +from server_utils.heartbeat import log_heartbeat from handlers.generation_handler import GenerationHandler from handlers.pipelines_handler import PipelinesHandler from handlers.text_handler import TextHandler @@ -33,11 +35,18 @@ from runtime_config.model_download_specs import resolve_active_ltx_model_id from runtime_config.runtime_config import RuntimeConfig from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.retake_pipeline.retake_mode import ( + InvalidRetakeModeError, + resolve_retake_mode, +) from services.ltx_api_client.ltx_api_client import LTXAPIClientError +from services.ltx_api_client.ltx_api_errors import map_ltx_api_client_error, missing_ltx_api_key_error from services.interfaces import LTXAPIClient from state.app_state_types import AppState from state.app_settings import should_video_generate_with_ltx_api +logger = logging.getLogger(__name__) + class RetakeHandler(StateHandlerBase): def __init__( @@ -68,6 +77,7 @@ def run(self, req: RetakeRequest) -> RetakeResponse: video_file = validate_source_video_path(video_path) + self._require_local_generation_possible(api_key=self.state.app_settings.ltx_api_key) if should_video_generate_with_ltx_api( force_api_generations=self.config.force_api_generations, settings=self.state.app_settings, @@ -114,7 +124,7 @@ def _run_api_retake( ) -> RetakeResponse: api_key = self.state.app_settings.ltx_api_key if not api_key: - raise HTTPError(400, "LTX API key not configured. Set it in Settings.") + raise missing_ltx_api_key_error() with self._generation.reserved_generation_start(): @@ -160,8 +170,9 @@ def _run_api_retake( raise HTTPError(500, "Retake API returned no result") except LTXAPIClientError as exc: - self._generation.fail_generation(exc.detail) - raise HTTPError(exc.status_code, exc.detail) from exc + mapped = map_ltx_api_client_error(exc) + self._generation.fail_generation(mapped.detail) + raise mapped from exc except HTTPError as exc: self._generation.fail_generation(exc.detail) raise @@ -200,33 +211,52 @@ def _run_local_retake( generation_id = uuid.uuid4().hex[:8] seed = self._resolve_seed() output_path = self.config.outputs_dir / f"retake_{datetime.now().strftime('%Y%m%d_%H%M%S')}_{generation_id}.mp4" - regenerate_video, regenerate_audio = self._resolve_retake_mode(mode) + try: + regenerate_video, regenerate_audio = resolve_retake_mode(mode) + except InvalidRetakeModeError as exc: + raise HTTPError(400, "INVALID_RETAKE_MODE") from exc + logger.info( + "Retake %s started (%dx%d, %d frames @ %g fps, %.2fs–%.2fs)", + generation_id, + target_width, + target_height, + target_frames, + fps, + start_time, + end_time, + ) try: - pipeline_state = self._pipelines.load_retake_pipeline(distilled=True) + pipeline_state = self._pipelines.load_retake_pipeline( + distilled=True, + width=target_width, + height=target_height, + frames=target_frames, + ) self._generation.start_generation(generation_id) self._generation.update_progress("loading_model", 5, 0, 1) self._generation.update_progress("inference", 15, 0, 1) - pipeline_state.pipeline.generate( - video_path=str(video_file), - prompt=prompt, - start_time=start_time, - end_time=end_time, - seed=seed, - output_path=str(output_path), - negative_prompt=self.config.default_negative_prompt, - num_inference_steps=40, - video_guider_params=None, - audio_guider_params=None, - regenerate_video=regenerate_video, - regenerate_audio=regenerate_audio, - enhance_prompt=False, - distilled=True, - target_width=target_width, - target_height=target_height, - target_frames=target_frames, - ) + with log_heartbeat("retake inference"): + pipeline_state.pipeline.generate( + video_path=str(video_file), + prompt=prompt, + start_time=start_time, + end_time=end_time, + seed=seed, + output_path=str(output_path), + negative_prompt=self.config.default_negative_prompt, + num_inference_steps=40, + video_guider_params=None, + audio_guider_params=None, + regenerate_video=regenerate_video, + regenerate_audio=regenerate_audio, + enhance_prompt=False, + distilled=True, + target_width=target_width, + target_height=target_height, + target_frames=target_frames, + ) # Denoiser interrupt cannot abort VAE decode / ffmpeg; a Stop after the last # denoise step still finishes encode, then this check drops the file. @@ -248,12 +278,3 @@ def _run_local_retake( finally: self._text.clear_api_embeddings() - @staticmethod - def _resolve_retake_mode(mode: RetakeMode) -> tuple[bool, bool]: - if mode == "replace_audio_and_video": - return True, True - if mode == "replace_video": - return True, False - if mode == "replace_audio": - return False, True - raise HTTPError(400, "INVALID_RETAKE_MODE") diff --git a/backend/handlers/runtime_policy_handler.py b/backend/handlers/runtime_policy_handler.py index e86e56f9e..156d82932 100644 --- a/backend/handlers/runtime_policy_handler.py +++ b/backend/handlers/runtime_policy_handler.py @@ -2,6 +2,8 @@ from __future__ import annotations +import os + from api_types import RuntimePolicyResponse from runtime_config.runtime_config import RuntimeConfig @@ -11,5 +13,15 @@ def __init__(self, config: RuntimeConfig) -> None: self._config = config def get_runtime_policy(self) -> RuntimePolicyResponse: - # Server-side single source of truth for forced API mode. - return RuntimePolicyResponse(force_api_generations=self._config.force_api_generations) + # force_api_generations stays for leftover API fallback. local_viable is the + # Explore gate: unsupported machines must not be sent to an LTX API key. + local_viable = self._config.local_generations_mode != "unsupported" + if ( + self._config.dev_mode + and os.environ.get("LTX_DEV_FORCE_LOCAL_VIABLE") == "1" + ): + local_viable = True + return RuntimePolicyResponse( + force_api_generations=self._config.force_api_generations, + local_viable=local_viable, + ) diff --git a/backend/handlers/settings_handler.py b/backend/handlers/settings_handler.py index 0d68f21d6..40dc7a5e8 100644 --- a/backend/handlers/settings_handler.py +++ b/backend/handlers/settings_handler.py @@ -24,6 +24,7 @@ normalize_gemini_model_id, resolve_gemini_model, ) +from services.api_key_validation import validate_fal_api_key, validate_gemini_api_key from services.interfaces import HTTPClient from state.app_state_types import AppState @@ -77,13 +78,38 @@ def set_active_ltx_model_id(self, model_id: LTXLocalModelId) -> None: self.state.app_settings.active_ltx_model_id = model_id self.save_settings() - @with_state_lock def update_settings(self, patch: UpdateSettingsRequest) -> tuple[AppSettings, AppSettings, set[str]]: - patch_payload = strip_none_values(ensure_json_object(patch.model_dump(by_alias=False, exclude_unset=True))) + # Probe Fal and Gemini outside the lock — these are network calls. + # LTX is stored without a probe: no LTX route checks a key without a side effect. + self._validate_incoming_api_keys(patch) + return self._apply_settings_patch(patch) + + def _validate_incoming_api_keys(self, patch: UpdateSettingsRequest) -> None: + gemini_key = _nonempty_key(patch, "gemini_api_key") + fal_key = _nonempty_key(patch, "fal_api_key") + if gemini_key is not None: + validate_gemini_api_key(self._http, api_key=gemini_key) + if fal_key is not None: + validate_fal_api_key(self._http, api_key=fal_key) + + @with_state_lock + def _apply_settings_patch( + self, patch: UpdateSettingsRequest + ) -> tuple[AppSettings, AppSettings, set[str]]: + raw_patch = patch.model_dump(by_alias=False, exclude_unset=True) + patch_payload = strip_none_values(ensure_json_object(raw_patch)) for key_field in ("ltx_api_key", "gemini_api_key", "fal_api_key"): - if key_field in patch_payload and patch_payload[key_field] == "": - del patch_payload[key_field] + explicitly_set = key_field in patch.model_fields_set + if not explicitly_set: + continue + value = getattr(patch, key_field) + # null or blank = user removed the key. (Omitted fields stay unchanged.) + # Non-empty keys are stored trimmed, matching the value Fal/Gemini were probed with. + if isinstance(value, str) and value.strip(): + patch_payload[key_field] = value.strip() + else: + patch_payload[key_field] = "" # Empty gemini_model is kept: it means "use DEFAULT_GEMINI_MODEL", not "leave unchanged". # Image/audio/video generators cannot enhance a prompt — persist them as "use default" # so a leftover Nano Banana setting cannot round-trip back into the picker. @@ -136,3 +162,13 @@ def _trim_prompt_cache(self) -> None: while len(te.prompt_cache) > max_size: oldest = next(iter(te.prompt_cache)) del te.prompt_cache[oldest] + + +def _nonempty_key(patch: UpdateSettingsRequest, field: str) -> str | None: + if field not in patch.model_fields_set: + return None + value = getattr(patch, field) + if not isinstance(value, str): + return None + trimmed = value.strip() + return trimmed or None diff --git a/backend/handlers/suggest_gap_prompt_handler.py b/backend/handlers/suggest_gap_prompt_handler.py index d500c8cdc..6d2094362 100644 --- a/backend/handlers/suggest_gap_prompt_handler.py +++ b/backend/handlers/suggest_gap_prompt_handler.py @@ -13,7 +13,8 @@ ) from _routes._errors import HTTPError from handlers.base import StateHandlerBase -from server_utils.media_validation import image_mime_type, normalize_optional_path, validate_image_file +from server_utils.media_validation import normalize_optional_path, validate_image_file +from server_utils.oriented_image import oriented_image_payload from services.gemini_text_client import ( apply_gemini_thinking_config, call_gemini_generate_content, @@ -41,8 +42,8 @@ def _read_image_file_as_base64(file_path: str | None) -> tuple[str, str] | None: logger.warning("Ignoring invalid image file for gap prompt: %s (%s)", normalized, exc.detail) return None try: - data = base64.b64encode(validated_path.read_bytes()).decode() - return data, image_mime_type(str(validated_path)) + raw, mime = oriented_image_payload(validated_path) + return base64.b64encode(raw).decode(), mime except Exception: logger.warning("Failed to read image file for gap prompt: %s", normalized, exc_info=True) return None diff --git a/backend/handlers/text_handler.py b/backend/handlers/text_handler.py index b18deee85..c1a5542a7 100644 --- a/backend/handlers/text_handler.py +++ b/backend/handlers/text_handler.py @@ -6,6 +6,11 @@ from typing import TYPE_CHECKING from _routes._errors import HTTPError +from services.ltx_api_client.ltx_api_errors import ( + LTX_API_KEY_MISSING, + LTX_API_PROMPT_EMBEDDING_FAILED, + LTX_API_PROMPT_EMBEDDING_FAILED_MESSAGE, +) from api_types import LTXLocalModelId from handlers.base import StateHandlerBase, with_state_lock from runtime_config.model_download_specs import ( @@ -32,19 +37,36 @@ def _active_ltx_model_id(self) -> LTXLocalModelId | None: self.models_dir, self.state.app_settings.active_ltx_model_id ) + def ltx_model_spec(self, model_id: LTXLocalModelId | None = None) -> LTXLocalModelSpec | None: + resolved = model_id if model_id is not None else self._active_ltx_model_id() + return None if resolved is None else get_ltx_model_spec(resolved) + def active_ltx_model_spec(self) -> LTXLocalModelSpec | None: - model_id = self._active_ltx_model_id() - return None if model_id is None else get_ltx_model_spec(model_id) + return self.ltx_model_spec() + + def _prompt_cache_key( + self, prompt: str, enhance_prompt: bool, model_id: LTXLocalModelId | None + ) -> tuple[str, bool, str]: + resolved = model_id if model_id is not None else self._active_ltx_model_id() + return (prompt.strip(), enhance_prompt, resolved or "") @with_state_lock - def _get_cached_prompt(self, prompt: str, enhance_prompt: bool) -> TextEncodingResult | None: + def _get_cached_prompt( + self, prompt: str, enhance_prompt: bool, model_id: LTXLocalModelId | None + ) -> TextEncodingResult | None: te = self.state.text_encoder if te is None: return None - return te.prompt_cache.get((prompt.strip(), enhance_prompt)) + return te.prompt_cache.get(self._prompt_cache_key(prompt, enhance_prompt, model_id)) @with_state_lock - def _cache_prompt(self, prompt: str, enhance_prompt: bool, result: TextEncodingResult) -> None: + def _cache_prompt( + self, + prompt: str, + enhance_prompt: bool, + result: TextEncodingResult, + model_id: LTXLocalModelId | None, + ) -> None: te = self.state.text_encoder if te is None: return @@ -53,7 +75,7 @@ def _cache_prompt(self, prompt: str, enhance_prompt: bool, result: TextEncodingR if max_size <= 0: return - key = (prompt.strip(), enhance_prompt) + key = self._prompt_cache_key(prompt, enhance_prompt, model_id) if key in te.prompt_cache: del te.prompt_cache[key] elif len(te.prompt_cache) >= max_size: @@ -69,7 +91,7 @@ def _set_api_embeddings(self, result: TextEncodingResult | None) -> None: def clear_api_embeddings(self) -> None: self._set_api_embeddings(None) - def should_use_local_encoding(self) -> bool: + def should_use_local_encoding(self, model_id: LTXLocalModelId | None = None) -> bool: """Decide whether to use local text encoding based on availability. The user's ``use_local_text_encoder`` setting acts as a tiebreaker only @@ -78,7 +100,7 @@ def should_use_local_encoding(self) -> bool: """ settings = self.state.app_settings.model_copy(deep=True) api_available = bool(settings.ltx_api_key) - spec = self.active_ltx_model_spec() + spec = self.ltx_model_spec(model_id) local_available = spec is not None and is_cp_downloaded(self.models_dir, spec.text_encoder_cp) api_usable = api_available and (spec is None or spec.supports_api_text_encoding) @@ -86,50 +108,59 @@ def should_use_local_encoding(self) -> bool: return settings.use_local_text_encoder # setting is tiebreaker return local_available # use whichever is available - def prepare_text_encoding(self, prompt: str, enhance_prompt: bool) -> None: + def prepare_text_encoding( + self, + prompt: str, + enhance_prompt: bool, + model_id: LTXLocalModelId | None = None, + ) -> None: """Validate settings and prepare text embeddings for a generation run. - Raises RuntimeError with a prefixed message if text encoding is - misconfigured, the local encoder is missing, or API encoding fails - with no local fallback. + Raises HTTPError when an LTX API key is missing or API encoding fails + with no local fallback. Raises RuntimeError when the selected model + requires a local encoder that is not downloaded. """ settings = self.state.app_settings.model_copy(deep=True) api_available = bool(settings.ltx_api_key) - spec = self.active_ltx_model_spec() + spec = self.ltx_model_spec(model_id) local_available = spec is not None and is_cp_downloaded(self.models_dir, spec.text_encoder_cp) if spec is not None and not spec.supports_api_text_encoding and not local_available: raise RuntimeError( - f"TEXT_ENCODING_NOT_CONFIGURED: LTX {spec.version_label} requires the local text " + f"TEXT_ENCODING_NOT_CONFIGURED: {spec.version_label} requires the local text " f"encoder ({get_model_cp_spec(spec.text_encoder_cp).description}); an LTX API key " "cannot encode prompts for this version. Download it in Settings." ) if not api_available and not local_available: - raise RuntimeError( - "TEXT_ENCODING_NOT_CONFIGURED: To generate videos, you need to configure text encoding. " - "Either enter an LTX API Key in Settings, or enable the Local Text Encoder." + raise HTTPError( + 400, + "Add an LTX API key, or turn on the local text encoder.", + code=LTX_API_KEY_MISSING, ) - use_local = self.should_use_local_encoding() - gemma_root = self.resolve_gemma_root() - embeddings = self._prepare_api_embeddings(prompt, enhance_prompt) + use_local = self.should_use_local_encoding(model_id) + gemma_root = self.resolve_gemma_root(model_id=model_id) + embeddings = self._prepare_api_embeddings(prompt, enhance_prompt, model_id=model_id) if not use_local and embeddings is None and gemma_root is None: - raise RuntimeError( - "LTX API text encoding failed and local text encoder is not available. " - "Please download the text encoder from Settings or check your API key." + raise HTTPError( + 502, + LTX_API_PROMPT_EMBEDDING_FAILED_MESSAGE, + code=LTX_API_PROMPT_EMBEDDING_FAILED, ) - def resolve_gemma_root(self) -> str | None: - if not self.should_use_local_encoding(): + def resolve_gemma_root(self, model_id: LTXLocalModelId | None = None) -> str | None: + if not self.should_use_local_encoding(model_id): return None - model_id = self._active_ltx_model_id() - if model_id is None: + resolved_id = model_id if model_id is not None else self._active_ltx_model_id() + if resolved_id is None: return None - return str(get_existing_cp_path(self.models_dir, get_ltx_model_spec(model_id).text_encoder_cp)) + return str(get_existing_cp_path(self.models_dir, get_ltx_model_spec(resolved_id).text_encoder_cp)) - def resolve_prompt_enhancer_root_if_downloaded(self) -> str | None: + def resolve_prompt_enhancer_root_if_downloaded( + self, model_id: LTXLocalModelId | None = None + ) -> str | None: """Like `resolve_gemma_root`, but answers "is the checkpoint present" rather than "should generation prefer local text encoding" — `should_use_local_encoding()`'s API-key tiebreaker (which defaults to API when both are available) answers a different @@ -140,7 +171,7 @@ def resolve_prompt_enhancer_root_if_downloaded(self) -> str | None: Resolves the enhancer rather than the encoder, which differ on 2.5. Prefers Gemma 4 E2B when downloaded, then Gemma 3 from a 2.3 install. """ - spec = self.active_ltx_model_spec() + spec = self.ltx_model_spec(model_id) if spec is None: return None cp_id = resolve_downloaded_prompt_enhancer_cp(self.models_dir, spec) @@ -148,8 +179,13 @@ def resolve_prompt_enhancer_root_if_downloaded(self) -> str | None: return None return str(get_existing_cp_path(self.models_dir, cp_id)) - def _prepare_api_embeddings(self, prompt: str, enhance_prompt: bool) -> TextEncodingResult | None: - if self.should_use_local_encoding(): + def _prepare_api_embeddings( + self, + prompt: str, + enhance_prompt: bool, + model_id: LTXLocalModelId | None = None, + ) -> TextEncodingResult | None: + if self.should_use_local_encoding(model_id): self.clear_api_embeddings() return None @@ -166,7 +202,7 @@ def _prepare_api_embeddings(self, prompt: str, enhance_prompt: bool) -> TextEnco prompt = " " enhance_prompt = False - cached = self._get_cached_prompt(prompt, enhance_prompt) + cached = self._get_cached_prompt(prompt, enhance_prompt, model_id) if cached is not None: self._set_api_embeddings(cached) return cached @@ -175,10 +211,10 @@ def _prepare_api_embeddings(self, prompt: str, enhance_prompt: bool) -> TextEnco if te is None: return None - model_id = self._active_ltx_model_id() - if model_id is None: + resolved_id = model_id if model_id is not None else self._active_ltx_model_id() + if resolved_id is None: raise HTTPError(409, "NO_DOWNLOADED_LTX_MODEL") - model_spec = get_ltx_model_spec(model_id) + model_spec = get_ltx_model_spec(resolved_id) encoded = te.service.encode_via_api( prompt=prompt, @@ -188,6 +224,6 @@ def _prepare_api_embeddings(self, prompt: str, enhance_prompt: bool) -> TextEnco api_model=model_spec.api_prompt_embedding_model, ) if encoded is not None: - self._cache_prompt(prompt, enhance_prompt, encoded) + self._cache_prompt(prompt, enhance_prompt, encoded, model_id) self._set_api_embeddings(encoded) return encoded diff --git a/backend/handlers/video_generation_handler.py b/backend/handlers/video_generation_handler.py index 58634eb47..16ea7de98 100644 --- a/backend/handlers/video_generation_handler.py +++ b/backend/handlers/video_generation_handler.py @@ -5,7 +5,7 @@ import logging import os -from frame_math import AutoDurationSpec, compute_num_frames, snap_up_to_multiple +from collections.abc import Callable import tempfile import time import uuid @@ -16,7 +16,17 @@ from PIL import Image +from frame_math import ( + AutoDurationSpec, + compute_num_frames, + effective_a2v_audio_seconds, + num_frames_for_audio_duration, + snap_up_to_multiple, +) from api_types import ( + AudioToVideoParams, + CreateAudioToVideoParams, + OfferingId, GenerateVideoCancelledResponse, GenerateVideoCompleteResponse, GenerateVideoModelsSpecsResponse, @@ -25,15 +35,39 @@ ImageConditioningInput, LoraEntry, LTXLocalModelId, + LTXLocalA2VResolution, + LTXVideoGenFps, LTXVideoGenResolution, VideoCameraMotion, ) -from runtime_config.ltx_capabilities import LtxAspectRatio, api_caps, local_caps, pixels_for, supports +from runtime_config.ltx_capabilities import ( + CanvasMode, + LtxAspectRatio, + a2v_pixels_for, + budget_pixels, + budget_size, + local_canvas, + local_caps, + pixels_for, + supports, +) +from runtime_config.low_performance_machine import detect_low_performance_machine from runtime_config.models_scanner import resolve_lora_ref +from runtime_config.runtime_policy import LocalGenerationMode +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + VIDEO_JOB_TOO_LARGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, + VideoJobReject, + decide_video_job, + memory_gb_for_job, +) from _routes._errors import HTTPError from api_model_specs import ( FORCED_API_MODEL_MAP, build_generate_video_model_specs_response, + forced_api_resolution_map, get_local_video_generation_model_specs, supported_duration_range, validate_generate_video_request, @@ -44,16 +78,19 @@ from handlers.pipelines_handler import PipelinesHandler from handlers.prompt_enhancement_handler import PromptEnhancementHandler from handlers.text_handler import TextHandler +from runtime_config.offerings import resolve_offering_local_model_id from runtime_config.model_download_specs import is_duration_head_ready, resolve_active_ltx_model_id from server_utils.media_validation import ( normalize_optional_path, validate_audio_file, validate_image_file, ) +from server_utils.oriented_image import open_oriented_rgb, oriented_image_file +from services.denoising_progress import distilled_total_steps from services.generation_interrupt import GenerationCancelledError, is_cancel_exception from services.interfaces import LTXAPIClient from services.ltx_api_client.ltx_api_client import LTXAPIClientError -from services.prompt_enhancement.i2v_frames import KeyframeStill +from services.ltx_api_client.ltx_api_errors import map_ltx_api_client_error, missing_ltx_api_key_error from state.app_state_types import AppState from state.app_settings import should_video_generate_with_ltx_api @@ -63,24 +100,21 @@ logger = logging.getLogger(__name__) -def _wxh(size: tuple[int, int]) -> str: - return f"{size[0]}x{size[1]}" +def _upload_oriented_image(client: LTXAPIClient, *, api_key: str, path: Path) -> str: + with oriented_image_file(path) as upload_path: + return client.upload_file(api_key=api_key, file_path=str(upload_path)) + +def _lora_catalog_ids(loras: list[LoraEntry]) -> list[str]: + """The catalog ids among the selected LoRAs, for catalog-aware prompt enhancement. -def _forced_api_resolution_map() -> dict[str, dict[str, str]]: - caps = api_caps("fast") - return { - resolution: { - "16:9": _wxh(pixels_for(caps, resolution, "16:9")), - "9:16": _wxh(pixels_for(caps, resolution, "9:16")), - } - for resolution in caps.resolution_pixels_16_9 - } + A custom LoRA carries none and stays weights-only: its filename is deliberately not + matched against the catalog, which would attach a stranger's trigger phrase to it. + """ + return [entry.catalogId for entry in loras if entry.catalogId is not None] -FORCED_API_RESOLUTION_MAP: dict[str, dict[str, str]] = _forced_api_resolution_map() -FORCED_API_ALLOWED_ASPECT_RATIOS = {"16:9", "9:16"} -_LTX_INSUFFICIENT_FUNDS_MESSAGE = "Your LTX API credits are insufficient for this generation. Buy more credits and try again." +FORCED_API_RESOLUTION_MAP: dict[str, dict[str, dict[str, str]]] = forced_api_resolution_map() class VideoGenerationHandler(StateHandlerBase): @@ -102,228 +136,507 @@ def __init__( self._prompt_enhancement = prompt_enhancement_handler self._ltx_api_client = ltx_api_client - def _resolve_prompt_enhancement( - self, - prompt: str, - *, - image_path: str | None, - last_image_path: str | None = None, - keyframes: list[KeyframeStill] | None = None, - duration: int | None = None, - fps: int | None = None, - ) -> tuple[str, bool]: - """Apply the enhancer setting, returning ``(prompt, enhance_via_api)``. - - The two encoding paths enhance in different places: API encoding rewrites server-side - inside the same /prompt-embedding call, so it only needs the flag forwarded. Local - encoding has no such step, so the rewrite happens here — without it the model sees the - prompt as typed, which for a version captioned in 150-220 word audio-visual paragraphs - (2.5) lands far outside its training distribution and it invents the rest. - - Must be called before the pipeline is loaded and before start_generation: the enhancer - needs the VRAM a resident pipeline holds, and PipelinesHandler refuses to evict one - while a generation is running. - """ - settings = self.state.app_settings - enabled = ( - settings.prompt_enhancer_enabled_i2v if image_path is not None or keyframes - else settings.prompt_enhancer_enabled_t2v - ) - if not enabled: - return prompt, False - if not self._text.should_use_local_encoding(): - return prompt, True - return self._prompt_enhancement.enhance_for_generation( - prompt, - image_path=image_path, - last_image_path=last_image_path, - keyframes=keyframes, - duration=duration, - fps=fps, - ), False - def _active_ltx_model_id(self) -> LTXLocalModelId | None: return resolve_active_ltx_model_id( self.models_dir, self.state.app_settings.active_ltx_model_id ) - def _duration_head_ready(self) -> bool: - model_id = self._active_ltx_model_id() + def _duration_head_ready_for(self, model_id: LTXLocalModelId | None) -> bool: return model_id is not None and is_duration_head_ready(self.models_dir, model_id) + def _duration_head_ready(self) -> bool: + return self._duration_head_ready_for(self._active_ltx_model_id()) + def _local_pixels( self, resolution: LTXVideoGenResolution, aspect: LtxAspectRatio, *, invalid_code: str, + local_model_id: LTXLocalModelId | None = None, + mode: CanvasMode = "video", ) -> tuple[int, int]: - model_id = self._active_ltx_model_id() + model_id = local_model_id or self._active_ltx_model_id() if model_id is None: raise HTTPError(409, "NO_DOWNLOADED_LTX_MODEL") + lookup = a2v_pixels_for if mode == "a2v" else pixels_for try: - return pixels_for(local_caps(model_id), resolution, aspect) + return lookup(local_caps(model_id), resolution, aspect) except KeyError as exc: raise HTTPError(400, invalid_code) from exc + def _local_job_filter(self) -> tuple[float | None, LocalGenerationMode, bool]: + darwin = self.config.darwin_unified_memory + return ( + memory_gb_for_job( + vram_gb=self.config.vram_gb, + available_ram_gb=self.config.available_ram_gb, + darwin=darwin, + ), + self.config.local_generations_mode, + darwin, + ) + def get_model_specs(self) -> GenerateVideoModelsSpecsResponse: + memory_gb, process_mode, darwin = self._local_job_filter() return build_generate_video_model_specs_response( local_model_id=self._active_ltx_model_id(), + models_dir=self.models_dir, duration_head_ready=self._duration_head_ready(), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + low_performance_machine=detect_low_performance_machine(self.config), ) + def derive_local_a2v_params( + self, params: CreateAudioToVideoParams, audio_duration_ms: int + ) -> AudioToVideoParams: + num_frames = self._local_a2v_num_frames( + resolution=params.resolution, + model=params.model, + fps=params.fps, + audio_duration_ms=audio_duration_ms, + ) + return AudioToVideoParams( + **params.model_dump(mode="python"), + numFrames=num_frames, + ) + + def validate_local_a2v_request( + self, params: AudioToVideoParams, audio_duration_ms: int + ) -> None: + num_frames = self._local_a2v_num_frames( + resolution=params.resolution, + model=params.model, + fps=params.fps, + audio_duration_ms=audio_duration_ms, + ) + if params.numFrames != num_frames: + raise HTTPError( + 422, + "Audio-to-video frame count no longer matches the selected audio.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + + def _prefix_a2v_audio_seconds( + self, + *, + model_id: LTXLocalModelId, + resolution: LTXVideoGenResolution, + fps: LTXVideoGenFps, + audio_duration_seconds: float, + ) -> float | None: + """Opening slice this resolution will hear. + + A clip past this cell but inside a longer one is cut to the cell max. + A clip past every cell is None, so a caller cannot treat it as the + whole clip. Missing specs leave the length unchanged. + """ + memory_gb, process_mode, darwin = self._local_job_filter() + item = next( + ( + candidate + for candidate in get_local_video_generation_model_specs( + model_id, + duration_head_ready=self._duration_head_ready_for(model_id), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + if candidate.pipeline == "fast" + ), + None, + ) + duration_map = None if item is None else item.spec.a2v_supported_resolutions_durations + if duration_map is None: + return audio_duration_seconds + resolution_spec = duration_map.get(resolution) + if resolution_spec is None: + return audio_duration_seconds + durations = resolution_spec.fps_to_durations.get(fps, []) + if not durations: + return audio_duration_seconds + longest = 0 + for cell in duration_map.values(): + cell_durations = cell.fps_to_durations.get(fps, []) + if cell_durations: + longest = max(longest, max(cell_durations)) + return effective_a2v_audio_seconds( + audio_duration_seconds, + cell_max_seconds=float(max(durations)), + longest_cell_seconds=float(longest), + ) + + def _local_a2v_num_frames( + self, + *, + resolution: LTXLocalA2VResolution, + model: OfferingId, + fps: LTXVideoGenFps, + audio_duration_ms: int, + ) -> int: + # Envelope of the checkpoint that will actually run, not the catalog + # preferred row (2.3 1.1 while only 1.0 is on disk). + a2v_model_id = resolve_offering_local_model_id(self.models_dir, model) + if a2v_model_id is None: + raise HTTPError(409, "LTX_MODEL_NOT_INSTALLED") + memory_gb, process_mode, darwin = self._local_job_filter() + item = next( + ( + candidate + for candidate in get_local_video_generation_model_specs( + a2v_model_id, + duration_head_ready=self._duration_head_ready_for(a2v_model_id), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + if candidate.pipeline == "fast" + ), + None, + ) + if item is None or item.spec.a2v_supported_resolutions_durations is None: + raise HTTPError( + 422, + "Audio-to-video is not available for the selected offering.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + resolution_spec = item.spec.a2v_supported_resolutions_durations.get(resolution) + if resolution_spec is None: + raise HTTPError( + 422, + "Audio-to-video is not available at the selected resolution.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + durations = resolution_spec.fps_to_durations.get(fps, []) + if not durations: + raise HTTPError( + 422, + "Audio-to-video is not available at the selected frame rate and duration.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + audio_duration_seconds = audio_duration_ms / 1000 + if audio_duration_seconds < 2.0: + raise HTTPError( + 422, + "Audio is too short for audio-to-video.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + max_duration = max(durations) + heard = self._prefix_a2v_audio_seconds( + model_id=a2v_model_id, + resolution=resolution, + fps=fps, + audio_duration_seconds=audio_duration_seconds, + ) + if heard is None or heard >= max_duration + 0.1: + raise HTTPError( + 422, + "Audio is too long for audio-to-video.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + audio_duration_seconds = heard + max_frames = compute_num_frames(max_duration, fps) + num_frames = num_frames_for_audio_duration( + audio_duration_seconds, + fps, + max_frames=max_frames, + ) + if num_frames is None: + raise HTTPError( + 422, + "Audio is too long for audio-to-video.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + return num_frames + def generate(self, req: GenerateVideoRequest) -> GenerateVideoResponse: + self._require_local_generation_possible(api_key=self.state.app_settings.ltx_api_key) use_api_specs = should_video_generate_with_ltx_api( force_api_generations=self.config.force_api_generations, settings=self.state.app_settings, ) - validation_error = validate_generate_video_request( - req, - use_api_specs=use_api_specs, - local_model_id=None if use_api_specs else self._active_ltx_model_id(), - duration_head_ready=False if use_api_specs else self._duration_head_ready(), - ) - if validation_error is not None: - raise HTTPError(422, validation_error, code="INVALID_VIDEO_GENERATION_SPEC") + self._validate_generate_video_request(req, use_api_specs=use_api_specs) if use_api_specs: return self._generate_forced_api(req) with self._generation.reserved_generation_start(): + return self._generate_local_reserved_validated( + req, generation_id=self._make_generation_id() + ) - resolution = req.resolution - duration = req.duration - fps = req.fps - - audio_path = normalize_optional_path(req.audioPath) - if audio_path: - if duration is None: - raise HTTPError( - 422, - "Automatic duration cannot be combined with audio-to-video", - code="INVALID_VIDEO_GENERATION_SPEC", - ) - return self._generate_a2v(req, duration, fps, audio_path=audio_path) + def generate_local_reserved( + self, + req: GenerateVideoRequest, + *, + generation_id: str, + output_path: Path | None = None, + prompt_wrap: Callable[[str], str] | None = None, + a2v_num_frames: int | None = None, + a2v_audio_duration_seconds: float | None = None, + local_model_id: LTXLocalModelId, + explore_generation: bool = True, + ) -> GenerateVideoResponse: + # Local-only Home/Remote entry: checkpoint is required. GenSpace + # ``generate()`` still uses Settings via ``_generate_local_reserved_validated``. + self._require_local_generation_possible() + self._validate_generate_video_request( + req, use_api_specs=False, local_model_id=local_model_id + ) + return self._generate_local_reserved_validated( + req, + generation_id=generation_id, + output_path=output_path, + prompt_wrap=prompt_wrap, + a2v_num_frames=a2v_num_frames, + a2v_audio_duration_seconds=a2v_audio_duration_seconds, + local_model_id=local_model_id, + explore_generation=explore_generation, + ) - logger.info("Resolution %s - using fast pipeline", resolution) + def _validate_generate_video_request( + self, + req: GenerateVideoRequest, + *, + use_api_specs: bool, + local_model_id: LTXLocalModelId | None = None, + ) -> None: + job_model_id = None if use_api_specs else (local_model_id or self._active_ltx_model_id()) + validation_error = validate_generate_video_request( + req, + use_api_specs=use_api_specs, + local_model_id=job_model_id, + duration_head_ready=False if use_api_specs else self._duration_head_ready_for(job_model_id), + ) + if validation_error is not None: + raise HTTPError(422, validation_error, code="INVALID_VIDEO_GENERATION_SPEC") - width, height = self._local_pixels( - resolution, req.aspectRatio, invalid_code="INVALID_LOCAL_RESOLUTION" - ) + def _generate_local_reserved_validated( + self, + req: GenerateVideoRequest, + *, + generation_id: str, + output_path: Path | None = None, + prompt_wrap: Callable[[str], str] | None = None, + a2v_num_frames: int | None = None, + a2v_audio_duration_seconds: float | None = None, + local_model_id: LTXLocalModelId | None = None, + explore_generation: bool = False, + ) -> GenerateVideoResponse: + resolution = req.resolution + duration = req.duration + fps = req.fps + job_model_id = local_model_id or self._active_ltx_model_id() + audio_path = normalize_optional_path(req.audioPath) + if audio_path: if duration is None: - item = next( - candidate - for candidate in get_local_video_generation_model_specs( - self._active_ltx_model_id(), - duration_head_ready=self._duration_head_ready(), - ) - if candidate.pipeline == req.model - ) - min_seconds, max_seconds = supported_duration_range( - item, resolution=resolution, fps=fps + raise HTTPError( + 422, + "Automatic duration cannot be combined with audio-to-video", + code="INVALID_VIDEO_GENERATION_SPEC", ) - num_frames: int | AutoDurationSpec = AutoDurationSpec( - min_seconds=float(min_seconds), - max_seconds=float(max_seconds), + return self._generate_a2v( + req, + duration, + fps, + audio_path=audio_path, + generation_id=generation_id, + output_path=output_path, + num_frames=a2v_num_frames, + audio_duration_seconds=a2v_audio_duration_seconds, + local_model_id=job_model_id, + explore_generation=explore_generation, + ) + + logger.info("Resolution %s - using fast pipeline", resolution) + + width, height = self._local_pixels( + resolution, + req.aspectRatio, + invalid_code="INVALID_LOCAL_RESOLUTION", + local_model_id=job_model_id, + ) + width = snap_up_to_multiple(width, 64) + height = snap_up_to_multiple(height, 64) + + if duration is None: + memory_gb, process_mode, darwin = self._local_job_filter() + item = next( + candidate + for candidate in get_local_video_generation_model_specs( + job_model_id, + duration_head_ready=self._duration_head_ready_for(job_model_id), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, ) - else: - num_frames = self._compute_num_frames(duration, fps) + if candidate.pipeline == req.model + ) + min_seconds, max_seconds = supported_duration_range( + item, resolution=resolution, fps=fps + ) + num_frames: int | AutoDurationSpec = AutoDurationSpec( + min_seconds=float(min_seconds), + max_seconds=float(max_seconds), + ) + else: + num_frames = self._compute_num_frames(duration, fps) - image = None - last_image = None - keyframe_images: list[tuple[Image.Image, int, float]] | None = None - image_path = normalize_optional_path(req.imagePath) - last_image_path = normalize_optional_path(req.lastImagePath) - if req.keyframes: - keyframe_images = [ - (self._prepare_image(keyframe.imagePath, width, height), keyframe.frameIndex, keyframe.strength) - for keyframe in req.keyframes - ] - logger.info("Keyframes: %s", [(keyframe.imagePath, keyframe.frameIndex) for keyframe in req.keyframes]) - opening = min(req.keyframes, key=lambda keyframe: keyframe.frameIndex) - image_path = normalize_optional_path(opening.imagePath) - last_image_path = None - enhance_keyframes = sorted( + image = None + last_image = None + keyframe_images: list[tuple[Image.Image, int, float]] | None = None + image_path = normalize_optional_path(req.imagePath) + last_image_path = normalize_optional_path(req.lastImagePath) + if req.keyframes: + keyframe_images = [ + (self._prepare_image(keyframe.imagePath, width, height), keyframe.frameIndex, keyframe.strength) + for keyframe in req.keyframes + ] + logger.info("Keyframes: %s", [(keyframe.imagePath, keyframe.frameIndex) for keyframe in req.keyframes]) + opening = min(req.keyframes, key=lambda keyframe: keyframe.frameIndex) + image_path = normalize_optional_path(opening.imagePath) + last_image_path = None + enhance_keyframes = sorted( + ( ( - ( - normalize_optional_path(keyframe.imagePath) or keyframe.imagePath, - keyframe.frameIndex, - keyframe.strength, - ) - for keyframe in req.keyframes - ), - key=lambda item: item[1], - ) - else: - enhance_keyframes = None - if image_path: - image = self._prepare_image(image_path, width, height) - logger.info("Image: %s -> %sx%s", image_path, width, height) - if last_image_path: - last_image = self._prepare_image(last_image_path, width, height) - logger.info("Last image: %s -> %sx%s", last_image_path, width, height) + normalize_optional_path(keyframe.imagePath) or keyframe.imagePath, + keyframe.frameIndex, + keyframe.strength, + ) + for keyframe in req.keyframes + ), + key=lambda item: item[1], + ) + else: + enhance_keyframes = None + if image_path: + image = self._prepare_image(image_path, width, height) + logger.info("Image: %s -> %sx%s", image_path, width, height) + if last_image_path: + last_image = self._prepare_image(last_image_path, width, height) + logger.info("Last image: %s -> %sx%s", last_image_path, width, height) - generation_id = self._make_generation_id() - seed = req.seed if req.seed is not None else self._resolve_seed() - loras = self._resolve_loras(req.loras) + seed = req.seed if req.seed is not None else self._resolve_seed() + loras = self._resolve_loras(req.loras, local_model_id=job_model_id) + + canvas = local_canvas(resolution, mode="video") + budget_width, budget_height = budget_size(canvas) + # The shared duration list is the 16:9 anchor. Only a wider frame can exceed it. + if job_model_id is None: + raise HTTPError(409, "NO_DOWNLOADED_LTX_MODEL") + selected_width, selected_height = budget_pixels( + local_caps(job_model_id), resolution, req.aspectRatio, mode="video" + ) + if selected_width * selected_height > budget_width * budget_height: + budget_width, budget_height = selected_width, selected_height + load_mode = self._video_job_load_mode( + budget_width, budget_height, self._budget_frame_count(num_frames, fps) + ) + try: # Before the pipeline loads and before the generation is marked running: local # enhancement needs the VRAM a resident pipeline holds, and evicting a pipeline is - # refused once a generation is running. - prompt, enhance_via_api = self._resolve_prompt_enhancement( + # refused once a generation is running. Budget 422 already happened so Gemma is + # not loaded for a job this machine cannot run. + resolved_prompt = self._prompt_enhancement.resolve_for_generation( req.prompt, + provenance=req.promptProvenance, + generation_seed=seed, + explicit_generation_seed=req.seed is not None, image_path=image_path, last_image_path=last_image_path, keyframes=enhance_keyframes, duration=req.duration, fps=req.fps, + lora_catalog_ids=_lora_catalog_ids(req.loras), + local_model_id=job_model_id, + explore_generation=explore_generation, + ) + # Recipe-scoped: applied after enhancement so the LLM rewrites the user + # scene, then the fixed scaffold wraps the result. None (and thus + # a no-op) for the plain text-to-video feature. + # + # skip_recipe_wrap is owned by resolve_for_generation: auto-off + a typed + # prompt skips the wrap so Generate sends the scene as typed. A manual + # Enhance (provenance "enhanced") still wraps so the style lock lands on + # the rewrite the user approved. + generation_prompt = resolved_prompt.prompt + enhance_via_api = resolved_prompt.enhance_via_api + if prompt_wrap is not None and not resolved_prompt.skip_recipe_wrap: + generation_prompt = prompt_wrap(generation_prompt) + # The wrap must be the last text mutation: on the API-encoding path + # resolved_prompt.prompt is the *raw* user scene with + # enhance_via_api=True, which would let /prompt-embedding rewrite the + # scaffold we just prepended. Encode the wrapped prompt as-is instead + # so the style lock survives. Home auto-enhance rewrites locally + # before this wrap when the enhancer checkpoint is installed. + if ( + resolved_prompt.enhance_via_api + and not resolved_prompt.enhanced_locally + and req.promptProvenance != "enhanced" + ): + logger.info( + "Style recipe sent the typed scene: no local prompt enhancer " + "is installed, and API enhance would rewrite the scaffold" + ) + enhance_via_api = False + self._generation.raise_if_cancelled() + self._pipelines.load_gpu_pipeline( + "fast", loras=loras, mode=load_mode, ltx_model_id=job_model_id ) + self._generation.start_generation(generation_id) - try: - self._generation.raise_if_cancelled() - self._pipelines.load_gpu_pipeline("fast", loras=loras) - self._generation.start_generation(generation_id) - - output_path = self.generate_video( - prompt=prompt, - enhance_via_api=enhance_via_api, - image=image, - last_image=last_image, - keyframe_images=keyframe_images, - height=height, - width=width, - num_frames=num_frames, - fps=fps, - seed=seed, - camera_motion=req.cameraMotion, - negative_prompt=req.negativePrompt, - loras=loras, - ) + written_path = self.generate_video( + prompt=generation_prompt, + enhance_via_api=enhance_via_api, + image=image, + last_image=last_image, + keyframe_images=keyframe_images, + height=height, + width=width, + num_frames=num_frames, + fps=fps, + seed=seed, + camera_motion=req.cameraMotion, + negative_prompt=req.negativePrompt, + loras=loras, + output_path=output_path, + load_mode=load_mode, + ltx_model_id=job_model_id, + skip_stage_2=canvas.skip_stage_2, + ) - self._generation.complete_generation(output_path) - return GenerateVideoCompleteResponse(status="complete", video_path=output_path) + self._generation.complete_generation(written_path) + return GenerateVideoCompleteResponse(status="complete", video_path=written_path) - except HTTPError as e: - self._generation.fail_generation(e.detail) - raise - except Exception as e: - self._generation.fail_generation(str(e)) - if is_cancel_exception(e): - logger.info("Generation cancelled by user") - return GenerateVideoCancelledResponse(status="cancelled") + except HTTPError as e: + self._generation.fail_generation(e.detail) + raise + except Exception as e: + self._generation.fail_generation(str(e)) + if is_cancel_exception(e): + logger.info("Generation cancelled by user") + return GenerateVideoCancelledResponse(status="cancelled") - raise HTTPError(500, str(e)) from e + raise HTTPError(500, str(e)) from e - def _resolve_loras(self, loras: list[LoraEntry]) -> list[tuple[str, float]]: + def _resolve_loras( + self, + loras: list[LoraEntry], + *, + local_model_id: LTXLocalModelId | None = None, + ) -> list[tuple[str, float]]: if loras: - model_id = self._active_ltx_model_id() + model_id = local_model_id or self._active_ltx_model_id() if model_id is None: raise HTTPError(409, "NO_DOWNLOADED_LTX_MODEL") if not supports(local_caps(model_id), "user_loras"): raise HTTPError( 409, - "User LoRAs are not supported for the active LTX model.", + "User LoRAs are not supported for the selected offering.", code="UNSUPPORTED_USER_LORAS", ) try: @@ -346,6 +659,11 @@ def generate_video( loras: list[tuple[str, float]] | None = None, last_image: Image.Image | None = None, keyframe_images: list[tuple[Image.Image, int, float]] | None = None, + output_path: Path | None = None, + *, + load_mode: LocalGenerationMode, + ltx_model_id: LTXLocalModelId | None = None, + skip_stage_2: bool = False, ) -> str: t_total_start = time.perf_counter() gen_mode = "keyframes" if keyframe_images else "i2v" if image is not None else "t2v" @@ -358,8 +676,6 @@ def generate_video( self._generation.raise_if_cancelled() - total_steps = 8 - if keyframe_images: images, temp_image_paths = self._keyframe_conditionings(keyframe_images) else: @@ -367,28 +683,35 @@ def generate_video( first=image, last=last_image, num_frames=num_frames ) - output_path = self._make_output_path() + if output_path is None: + output_path = self._make_output_path() # Appended after any rewrite the caller already applied, so the enhancer can't # paraphrase the camera directive away. enhanced_prompt = prompt + self.config.camera_motion_prompts.get(camera_motion, "") try: - self._generation.update_progress("loading_model", 5, 0, total_steps) + self._generation.update_progress("loading_model", 5) t_load_start = time.perf_counter() - pipeline_state = self._pipelines.load_gpu_pipeline("fast", loras=loras) + pipeline_state = self._pipelines.load_gpu_pipeline( + "fast", loras=loras, mode=load_mode, ltx_model_id=ltx_model_id + ) t_load_end = time.perf_counter() logger.info("[%s] Pipeline load: %.2fs", gen_mode, t_load_end - t_load_start) - self._generation.update_progress("encoding_text", 10, 0, total_steps) - encoding_method = "api" if not self._text.should_use_local_encoding() else "local" + self._generation.update_progress("encoding_text", 10) + encoding_method = ( + "api" if not self._text.should_use_local_encoding(ltx_model_id) else "local" + ) t_text_start = time.perf_counter() - self._text.prepare_text_encoding(enhanced_prompt, enhance_prompt=enhance_via_api) + self._text.prepare_text_encoding( + enhanced_prompt, enhance_prompt=enhance_via_api, model_id=ltx_model_id + ) t_text_end = time.perf_counter() logger.info("[%s] Text encoding (%s): %.2fs", gen_mode, encoding_method, t_text_end - t_text_start) self._generation.raise_if_cancelled() - self._generation.update_progress("inference", 15, 0, total_steps) + self._generation.update_progress("inference", 15) # Guard for the /64 two-stage grid. Half-way values round up: Python's round() is # half-to-even, which turned a 544 height into 512 and silently shipped a frame 32px @@ -408,6 +731,7 @@ def generate_video( images=images, output_path=str(output_path), guide_all_images=bool(keyframe_images), + skip_stage_2=skip_stage_2, ) t_inference_end = time.perf_counter() logger.info("[%s] Inference: %.2fs", gen_mode, t_inference_end - t_inference_start) @@ -424,32 +748,64 @@ def generate_video( gen_mode, t_total_end - t_total_start, t_load_end - t_load_start, t_text_end - t_text_start, t_inference_end - t_inference_start) - self._generation.update_progress("complete", 100, total_steps, total_steps) + self._generation.update_progress("complete", 100) return str(output_path) finally: self._text.clear_api_embeddings() self._unlink_temp_paths(temp_image_paths) def _generate_a2v( - self, req: GenerateVideoRequest, duration: int, fps: int, *, audio_path: str + self, + req: GenerateVideoRequest, + duration: int, + fps: int, + *, + audio_path: str, + generation_id: str, + output_path: Path | None = None, + num_frames: int | None = None, + audio_duration_seconds: float | None = None, + local_model_id: LTXLocalModelId | None = None, + explore_generation: bool = False, ) -> GenerateVideoResponse: - model_id = self._active_ltx_model_id() + model_id = local_model_id if model_id is None: raise HTTPError(409, "NO_DOWNLOADED_LTX_MODEL") if not supports(local_caps(model_id), "a2v"): raise HTTPError( 409, - "Audio-to-video is not supported for the active LTX model.", + "Audio-to-video is not supported for the selected offering.", code="UNSUPPORTED_A2V", ) validated_audio_path = validate_audio_file(audio_path) audio_path_str = str(validated_audio_path) width, height = self._local_pixels( - req.resolution, req.aspectRatio, invalid_code="INVALID_LOCAL_A2V_RESOLUTION" + req.resolution, + req.aspectRatio, + invalid_code="INVALID_LOCAL_A2V_RESOLUTION", + local_model_id=model_id, + mode="a2v", ) - - num_frames = self._compute_num_frames(duration, fps) + width = snap_up_to_multiple(width, 64) + height = snap_up_to_multiple(height, 64) + + if num_frames is None: + num_frames = self._compute_num_frames(duration, fps) + if audio_duration_seconds is not None: + heard = self._prefix_a2v_audio_seconds( + model_id=model_id, + resolution=req.resolution, + fps=req.fps, + audio_duration_seconds=audio_duration_seconds, + ) + if heard is None: + raise HTTPError( + 422, + "Audio is too long for audio-to-video.", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + audio_duration_seconds = heard image = None image_path = normalize_optional_path(req.imagePath) @@ -462,9 +818,8 @@ def _generate_a2v( last_image = self._prepare_image(last_image_path, width, height) seed = req.seed if req.seed is not None else self._resolve_seed() - loras = self._resolve_loras(req.loras) + loras = self._resolve_loras(req.loras, local_model_id=model_id) - generation_id = self._make_generation_id() temp_image_paths: list[str] = [] try: @@ -474,42 +829,62 @@ def _generate_a2v( first=image, last=last_image, num_frames=num_frames ) - # Same ordering rule as the fast path: enhance before the pipeline takes the GPU - # (and so before start_generation, which requires a pipeline to already be loaded). - a2v_base_prompt, a2v_enhance = self._resolve_prompt_enhancement( - req.prompt, image_path=image_path, last_image_path=last_image_path + load_mode = self._video_job_load_mode(width, height, num_frames) + # Same ordering as Fast: budget 422 before Gemma so an over-size cell + # does not evict a warmed pipeline for a rewrite that will not run. + resolved_prompt = self._prompt_enhancement.resolve_for_generation( + req.prompt, + provenance=req.promptProvenance, + generation_seed=seed, + explicit_generation_seed=req.seed is not None, + image_path=image_path, + last_image_path=last_image_path, + lora_catalog_ids=_lora_catalog_ids(req.loras), + local_model_id=model_id, + explore_generation=explore_generation, + audio_path=audio_path_str, ) - enhanced_prompt = a2v_base_prompt + self.config.camera_motion_prompts.get(req.cameraMotion, "") + enhanced_prompt = resolved_prompt.prompt + self.config.camera_motion_prompts.get(req.cameraMotion, "") self._generation.raise_if_cancelled() - a2v_state = self._pipelines.load_a2v_pipeline(loras=loras) + a2v_state = self._pipelines.load_a2v_pipeline( + loras=loras, mode=load_mode, ltx_model_id=model_id + ) self._generation.start_generation(generation_id) - output_path = self._make_output_path() - - total_steps = 11 # distilled: 8 steps (stage 1) + 3 steps (stage 2) + if output_path is None: + output_path = self._make_output_path() - self._generation.update_progress("loading_model", 5, 0, total_steps) - self._generation.update_progress("encoding_text", 10, 0, total_steps) - self._text.prepare_text_encoding(enhanced_prompt, enhance_prompt=a2v_enhance) + self._generation.update_progress("loading_model", 5) + self._generation.update_progress("encoding_text", 10) + self._text.prepare_text_encoding( + enhanced_prompt, + enhance_prompt=resolved_prompt.enhance_via_api, + model_id=model_id, + ) self._generation.raise_if_cancelled() - self._generation.update_progress("inference", 15, 0, total_steps) + self._generation.update_progress("inference", 15) - a2v_state.pipeline.generate( - prompt=enhanced_prompt, - negative_prompt=neg, - seed=seed, - height=height, - width=width, - num_frames=num_frames, - frame_rate=fps, - num_inference_steps=total_steps, - images=images, - audio_path=audio_path_str, - audio_start_time=0.0, - audio_max_duration=None, - output_path=str(output_path), - ) + with log_heartbeat("a2v inference"): + a2v_state.pipeline.generate( + prompt=enhanced_prompt, + negative_prompt=neg, + seed=seed, + height=height, + width=width, + num_frames=num_frames, + frame_rate=fps, + num_inference_steps=distilled_total_steps(), + images=images, + audio_path=audio_path_str, + audio_start_time=0.0, + audio_max_duration=( + None + if audio_duration_seconds is None + else max(num_frames / fps, audio_duration_seconds) + ), + output_path=str(output_path), + ) # Denoiser interrupt cannot abort VAE decode / ffmpeg; a Stop after the last # denoise step still finishes encode, then this check drops the file. @@ -518,7 +893,7 @@ def _generate_a2v( output_path.unlink() raise GenerationCancelledError() - self._generation.update_progress("complete", 100, total_steps, total_steps) + self._generation.update_progress("complete", 100) self._generation.complete_generation(str(output_path)) return GenerateVideoCompleteResponse(status="complete", video_path=str(output_path)) @@ -590,7 +965,7 @@ def _unlink_temp_paths(paths: list[str]) -> None: def _prepare_image(self, image_path: str, width: int, height: int) -> Image.Image: validated_path = validate_image_file(image_path) try: - img = Image.open(validated_path).convert("RGB") + img = open_oriented_rgb(validated_path) except Exception: raise HTTPError(400, f"Invalid image file: {image_path}") from None img_w, img_h = img.size @@ -611,6 +986,47 @@ def _prepare_image(self, image_path: str, width: int, height: int) -> Image.Imag def _make_generation_id() -> str: return uuid.uuid4().hex[:8] + def _budget_frame_count(self, num_frames: int | AutoDurationSpec, fps: int) -> int: + if isinstance(num_frames, AutoDurationSpec): + return compute_num_frames(int(num_frames.max_seconds), fps) + return num_frames + + def _video_job_load_mode( + self, width: int, height: int, frames: int + ) -> LocalGenerationMode: + """422 or pick full vs stream for this job. Does not change process mode.""" + darwin = self.config.darwin_unified_memory + memory_gb = memory_gb_for_job( + vram_gb=self.config.vram_gb, + available_ram_gb=self.config.available_ram_gb, + darwin=darwin, + ) + decision = decide_video_job( + width, + height, + frames, + memory_gb=memory_gb, + process_mode=self.config.local_generations_mode, + darwin=darwin, + ) + outcome = "reject" if isinstance(decision, VideoJobReject) else decision.mode + logger.info( + "[video] job budget seq=%.0f full=%.1fGiB stream=%.1fGiB -> %s", + decision.seq, + decision.full_gib, + decision.stream_gib, + outcome, + ) + if isinstance(decision, VideoJobReject): + if decision.reason == "unsupported": + raise HTTPError( + 422, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + code=LOCAL_GENERATION_UNSUPPORTED, + ) + raise HTTPError(422, VIDEO_JOB_TOO_LARGE_MESSAGE, code=VIDEO_JOB_TOO_LARGE) + return decision.mode + @staticmethod def _compute_num_frames(duration: int, fps: int) -> int: return compute_num_frames(duration, fps) @@ -637,7 +1053,7 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon api_key = self.state.app_settings.ltx_api_key.strip() logger.info("Forced API generation route selected (key_present=%s)", bool(api_key)) if not api_key: - raise HTTPError(400, "PRO_API_KEY_REQUIRED") + raise missing_ltx_api_key_error() requested_model = req.model api_model_id = FORCED_API_MODEL_MAP.get(requested_model) @@ -645,17 +1061,22 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon raise HTTPError(500, "INVALID_FORCED_API_MODEL_CONFIG") resolution_label = req.resolution - resolution_by_aspect = FORCED_API_RESOLUTION_MAP.get(resolution_label) + resolution_by_aspect = FORCED_API_RESOLUTION_MAP.get(requested_model, {}).get(resolution_label) if resolution_by_aspect is None: raise HTTPError(500, "INVALID_FORCED_API_RESOLUTION_CONFIG") aspect_ratio = req.aspectRatio - if aspect_ratio not in FORCED_API_ALLOWED_ASPECT_RATIOS: + api_resolution = resolution_by_aspect.get(aspect_ratio) + if api_resolution is None: raise HTTPError(400, "INVALID_FORCED_API_ASPECT_RATIO") - api_resolution = resolution_by_aspect[aspect_ratio] - prompt = req.prompt + enhance_prompt = self._prompt_enhancement.api_enhance_prompt( + prompt, + provenance=req.promptProvenance, + image_path=image_path, + audio_path=audio_path, + ) self._generation.raise_if_cancelled() @@ -674,15 +1095,17 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon last_frame_uri: str | None = None if validated_image_path is not None: self._generation.update_progress("uploading_image", 35, None, None) - image_uri = self._ltx_api_client.upload_file( + image_uri = _upload_oriented_image( + self._ltx_api_client, api_key=api_key, - file_path=str(validated_image_path), + path=validated_image_path, ) if last_image_path is not None: self._generation.update_progress("uploading_image", 45, None, None) - last_frame_uri = self._ltx_api_client.upload_file( + last_frame_uri = _upload_oriented_image( + self._ltx_api_client, api_key=api_key, - file_path=str(validate_image_file(last_image_path)), + path=validate_image_file(last_image_path), ) self._generation.update_progress("inference", 55, None, None) video_bytes = self._ltx_api_client.generate_audio_to_video( @@ -693,6 +1116,7 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon last_frame_uri=last_frame_uri, model=api_model_id, resolution=api_resolution, + enhance_prompt=enhance_prompt, ) self._generation.update_progress("downloading_output", 85, None, None) elif has_input_image: @@ -703,16 +1127,18 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon generate_audio = req.audio self._generation.update_progress("uploading_image", 20, None, None) - image_uri = self._ltx_api_client.upload_file( + image_uri = _upload_oriented_image( + self._ltx_api_client, api_key=api_key, - file_path=str(validated_image_path), + path=validated_image_path, ) last_frame_uri: str | None = None if last_image_path is not None: self._generation.update_progress("uploading_image", 35, None, None) - last_frame_uri = self._ltx_api_client.upload_file( + last_frame_uri = _upload_oriented_image( + self._ltx_api_client, api_key=api_key, - file_path=str(validate_image_file(last_image_path)), + path=validate_image_file(last_image_path), ) self._generation.update_progress("inference", 55, None, None) video_bytes = self._ltx_api_client.generate_image_to_video( @@ -726,6 +1152,7 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon fps=float(fps), generate_audio=generate_audio, camera_motion=req.cameraMotion, + enhance_prompt=enhance_prompt, ) self._generation.update_progress("downloading_output", 85, None, None) else: @@ -743,6 +1170,7 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon fps=float(fps), generate_audio=generate_audio, camera_motion=req.cameraMotion, + enhance_prompt=enhance_prompt, ) self._generation.update_progress("downloading_output", 85, None, None) @@ -760,7 +1188,7 @@ def _generate_forced_api(self, req: GenerateVideoRequest) -> GenerateVideoRespon self._generation.fail_generation(e.detail) raise except LTXAPIClientError as e: - mapped_error = self._map_ltx_api_generation_error(e) + mapped_error = map_ltx_api_client_error(e) self._generation.fail_generation(mapped_error.detail) raise mapped_error from e except Exception as e: @@ -774,9 +1202,3 @@ def _write_forced_api_video(self, video_bytes: bytes) -> Path: output_path = self._make_output_path() output_path.write_bytes(video_bytes) return output_path - - @staticmethod - def _map_ltx_api_generation_error(exc: LTXAPIClientError) -> HTTPError: - if exc.status_code == 402 and exc.provider_error_type == "insufficient_funds_error": - return HTTPError(402, _LTX_INSUFFICIENT_FUNDS_MESSAGE, code="LTX_INSUFFICIENT_FUNDS") - return HTTPError(exc.status_code, exc.detail) diff --git a/backend/handlers/video_resolution.py b/backend/handlers/video_resolution.py index 3a5bf24e2..d16fc0d89 100644 --- a/backend/handlers/video_resolution.py +++ b/backend/handlers/video_resolution.py @@ -1,13 +1,14 @@ """Local source-video prep shared by the retake and extend local paths. The local pipeline needs width/height divisible by 32 and a frame count of the form -``8k+1``. Rather than rejecting inputs that don't comply (standard 1080p isn't ÷32 in -height; arbitrary clips rarely land on 8k+1), we correct both: snap resolution down to a -÷32 size (never above source) and trim the frame count down to the nearest ``8k+1``. +``8k+1``. GenSpace snaps a requested size down to that grid. Home retake and extend +keep the picture size and letterbox up to the next multiple of 32, then crop the +bars off after generation. Frame count is always trimmed down to the nearest ``8k+1``. """ from __future__ import annotations +from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING @@ -76,15 +77,100 @@ def correct_resolution( return width, height +# Home/queued Retake and Extend fit inside the local 1080p cell (1920×1088). +# 1088 (not 1080) is the box so a clip that is already on the ÷32 grid is not shrunk. +# A 1920×1080 picture is letterboxed up to 1920×1088, then cropped back. +_1080P_LONG_EDGE = 1920 +_1080P_SHORT_EDGE = 1088 + + +@dataclass(frozen=True) +class SpatialLetterbox: + """Picture rect centered on the ÷32 canvas the model actually encodes.""" + + content_width: int + content_height: int + canvas_width: int + canvas_height: int + left: int + top: int + + @property + def right(self) -> int: + return self.canvas_width - self.content_width - self.left + + @property + def bottom(self) -> int: + return self.canvas_height - self.content_height - self.top + + +def generation_letterbox(width: int, height: int) -> SpatialLetterbox: + """Pad ``width``×``height`` up to the next multiple of 32, split evenly. + + An odd remainder gives the extra pixel to the right or the bottom. + """ + canvas_width = ((width + _SPATIAL_FACTOR - 1) // _SPATIAL_FACTOR) * _SPATIAL_FACTOR + canvas_height = ((height + _SPATIAL_FACTOR - 1) // _SPATIAL_FACTOR) * _SPATIAL_FACTOR + pad_x = canvas_width - width + pad_y = canvas_height - height + return SpatialLetterbox( + content_width=width, + content_height=height, + canvas_width=canvas_width, + canvas_height=canvas_height, + left=pad_x // 2, + top=pad_y // 2, + ) + + +def cap_to_1080p(width: int, height: int) -> tuple[int, int]: + """Fit inside local 1080p without upscaling or changing aspect. + + Home/queued Retake and Extend opt into this. GenSpace ``resolve_target_resolution`` + does not — it keeps the requested (or source) size after the ÷32 snap. + """ + max_w, max_h = ( + (_1080P_LONG_EDGE, _1080P_SHORT_EDGE) + if width >= height + else (_1080P_SHORT_EDGE, _1080P_LONG_EDGE) + ) + scale = min(max_w / width, max_h / height, 1.0) + if scale >= 1.0: + return width, height + return max(1, round(width * scale)), max(1, round(height * scale)) + + +def resolve_home_edit_size( + requested_width: int | None, + requested_height: int | None, + source_width: int, + source_height: int, +) -> tuple[int, int]: + """Home Retake/Extend picture size, before the ÷32 letterbox. + + A missing request keeps the source. The 1080p cap still applies, and the + result is never larger than the source. Callers pad this with + ``generation_letterbox`` for the model and crop back to this size. + """ + width = source_width if requested_width is None or requested_height is None else requested_width + height = source_height if requested_width is None or requested_height is None else requested_height + width, height = cap_to_1080p(width, height) + return min(width, source_width), min(height, source_height) + + def resolve_target_resolution( resolution: TargetResolution | None, source_width: int, source_height: int, ) -> tuple[int, int]: """Resolve the effective output size: the requested resolution if given, else the - source — always corrected to a valid (÷32, not-upscaled) size.""" + source — always corrected to a valid (÷32, not-upscaled) size. + """ target_width = resolution.width if resolution else source_width target_height = resolution.height if resolution else source_height return correct_resolution( - target_width, target_height, source_width=source_width, source_height=source_height + target_width, + target_height, + source_width=source_width, + source_height=source_height, ) diff --git a/backend/http_exception_handlers.py b/backend/http_exception_handlers.py new file mode 100644 index 000000000..aac630088 --- /dev/null +++ b/backend/http_exception_handlers.py @@ -0,0 +1,56 @@ +"""Shared HTTP exception handlers for desktop and remote FastAPI apps.""" + +from __future__ import annotations + +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +from fastapi.responses import JSONResponse +from starlette.exceptions import HTTPException as StarletteHTTPException + +from _routes._errors import HTTPError, build_http_error_response +from logging_policy import log_http_error, log_unhandled_exception + + +async def _http_error_handler(request: Request, exc: Exception) -> JSONResponse: + if isinstance(exc, HTTPError): + log_http_error(request, exc) + return JSONResponse(status_code=exc.status_code, content=exc.response.model_dump()) + return JSONResponse( + status_code=500, + content=build_http_error_response(500, str(exc)).model_dump(), + ) + + +async def _starlette_http_error_handler(_request: Request, exc: Exception) -> JSONResponse: + if isinstance(exc, StarletteHTTPException): + return JSONResponse( + status_code=exc.status_code, + content=build_http_error_response(exc.status_code, exc.detail).model_dump(), + ) + return JSONResponse( + status_code=500, + content=build_http_error_response(500, str(exc)).model_dump(), + ) + + +async def _validation_error_handler(_request: Request, exc: Exception) -> JSONResponse: + return JSONResponse( + status_code=422, + content=build_http_error_response(422, str(exc)).model_dump(), + ) + + +async def _unhandled_exception_handler(request: Request, exc: Exception) -> JSONResponse: + log_unhandled_exception(request, exc) + return JSONResponse( + status_code=500, + content=build_http_error_response(500, str(exc)).model_dump(), + ) + + +def install_http_exception_handlers(app: FastAPI) -> None: + """Register HTTPError, Starlette HTTP, validation, and unhandled exception handlers.""" + app.add_exception_handler(RequestValidationError, _validation_error_handler) + app.add_exception_handler(HTTPError, _http_error_handler) + app.add_exception_handler(StarletteHTTPException, _starlette_http_error_handler) + app.add_exception_handler(Exception, _unhandled_exception_handler) diff --git a/backend/ic_lora_preprocessing.py b/backend/ic_lora_preprocessing.py index 6ce4bd4f8..a90819065 100644 --- a/backend/ic_lora_preprocessing.py +++ b/backend/ic_lora_preprocessing.py @@ -41,6 +41,7 @@ class PreprocessingContext: outputs_dir: Path video_processor: VideoProcessor outpaint: OutpaintParams | None = None + on_frame: Callable[[], None] | None = None PreprocessingUtility = Callable[[MediaArtifact, dict[str, object], PreprocessingContext], MediaArtifact] @@ -62,10 +63,14 @@ def _image_to_frames( h, w = frame.shape[0], frame.shape[1] out_path = str(ctx.outputs_dir / f"_ic_lora_frames_{uuid.uuid4().hex[:8]}.mp4") writer = ctx.video_processor.create_writer(out_path, fourcc="mp4v", fps=fps, size=(int(w), int(h))) - for _ in range(count): - writer.write(frame) - ctx.video_processor.release(writer) - return MediaArtifact(path=out_path, kind="video", fps=fps, frame_count=count) + try: + for _ in range(count): + if ctx.on_frame is not None: + ctx.on_frame() + writer.write(frame) + return MediaArtifact(path=out_path, kind="video", fps=fps, frame_count=count) + finally: + ctx.video_processor.release(writer) def _outpaint_canvas( @@ -124,6 +129,8 @@ def _outpaint_canvas( written = 0 for _ in range(frame_count): + if ctx.on_frame is not None: + ctx.on_frame() frame = ctx.video_processor.read_frame(cap) if frame is None: break diff --git a/backend/ltx2_server.py b/backend/ltx2_server.py index 6031d0e2a..d93f8c86c 100644 --- a/backend/ltx2_server.py +++ b/backend/ltx2_server.py @@ -57,25 +57,20 @@ # LLM: bumping ltx-core / ltx-pipelines (backend/pyproject.toml) MUST re-verify every # import below (and mps_sdpa_torch later in this file). These monkey-patch private -# ltx-core / ltx-pipelines / safetensors symbols. For each module: confirm the -# upstream symbol still exists, the replacement still matches the contract, drop it -# if upstream now includes the fix (see that file's "Remove once ..." docstring), -# and run tests/test_.py. -import services.patches.record_stream_fix as _record_stream_fix # pyright: ignore[reportUnusedImport] # Remove once ltx-core includes the fix -del _record_stream_fix +# ltx-core / ltx-pipelines / safetensors symbols. Delete-first: drop a patch if +# upstream now includes the fix (see that file's "Remove once ..." docstring). +# Do not reorder this block relative to mps_prebuilt_ext / MPS_SDPA_SKIP_CALIBRATION. import services.patches.safetensors_loader_fix as _safetensors_loader_fix # pyright: ignore[reportUnusedImport] # Remove once safetensors/PyTorch fix the mmap issue del _safetensors_loader_fix +import services.patches.disk_streaming_pread as _disk_streaming_pread # Remove once ltx-core DiskTensorReader passes backend=pread on Darwin. No-op off Darwin. +_disk_streaming_pread.install() import services.patches.safetensors_metadata_fix as _safetensors_metadata_fix # pyright: ignore[reportUnusedImport] # Remove once safetensors supports read-only mmap del _safetensors_metadata_fix import services.patches.pinned_pool_fix as _pinned_pool_fix # pyright: ignore[reportUnusedImport] # Remove once ltx-core alloc_buffer does not report pinned-host failure as CUDA VRAM OOM (LTX-Desktop#141) del _pinned_pool_fix -import services.patches.ic_lora_stage2_lora as _ic_lora_stage2_lora # pyright: ignore[reportUnusedImport] # EXPERIMENTAL: remove once upstream ships PR #494 (use_lora_in_stage_2) -del _ic_lora_stage2_lora import services.patches.diffusion_stage_cache as _diffusion_stage_cache # pyright: ignore[reportUnusedImport] # EXPERIMENTAL: remove once DiffusionStage caches/reuses identical builds upstream del _diffusion_stage_cache -import services.patches.diffvae_mps_tiling_budget as _diffvae_mps_tiling_budget # pyright: ignore[reportUnusedImport] # Remove once ltx-pipelines queries MPS/unified free memory -del _diffvae_mps_tiling_budget -import services.patches.diffvae_decode_vram as _diffvae_decode_vram # pyright: ignore[reportUnusedImport] # Remove once ltx-pipelines offloads the transformer before DiffVAE decode +import services.patches.diffvae_decode_vram as _diffvae_decode_vram # pyright: ignore[reportUnusedImport] # Remove once upstream decode tiling is confirmed sufficient (E1) del _diffvae_decode_vram import services.patches.natten_libnatten_gate as _natten_libnatten_gate # pyright: ignore[reportUnusedImport] # Remove once ltx-core natten_available checks HAS_LIBNATTEN del _natten_libnatten_gate @@ -112,6 +107,9 @@ # Now that logging is configured, report which mps-sdpa attention backend is live # (the setup call at import time logs too early to be captured). No-op off Darwin. _mps_prebuilt_ext.log_mps_backend_status() +# install() ran before basicConfig, so its status log would have been dropped. +_disk_streaming_pread.log_status() +del _disk_streaming_pread # ============================================================ # SageAttention Integration @@ -234,6 +232,7 @@ def _resolve_app_data_dir() -> Path: DEFAULT_APP_SETTINGS = AppSettings() from app_factory import DEFAULT_ALLOWED_ORIGINS, create_app +from dataclasses import dataclass from state import RuntimeConfig, build_initial_state from runtime_config.runtime_policy import LocalGenerationMode, decide_local_generation_mode from server_utils.model_layout_migration import migrate_legacy_models_layout @@ -244,7 +243,15 @@ def _resolve_app_data_dir() -> Path: LTX_API_BASE_URL = "https://api.ltx.video" -def _resolve_local_generations_mode() -> LocalGenerationMode: +@dataclass(frozen=True) +class _LocalRuntime: + mode: LocalGenerationMode + vram_gb: int | None + available_ram_gb: int | None + darwin: bool + + +def _resolve_local_runtime() -> _LocalRuntime: from runtime_config.accelerator import accelerator_backend gpu_info = GpuInfoImpl() @@ -253,10 +260,10 @@ def _resolve_local_generations_mode() -> LocalGenerationMode: mps_available = gpu_info.get_mps_available() vram_gb = gpu_info.get_vram_total_gb() fp8_capable = accelerator_backend() == "cuda" - # On Darwin there's no discrete VRAM (unified memory), so gate on *available* RAM, - # not total — total overstates real headroom once the OS/Electron/app are running. - # See GpuInfoImpl.get_available_ram_gb. + # Darwin has no discrete VRAM (unified memory). Eligibility uses *total* RAM + # (``get_vram_total_gb`` / SKU). Job sizing still uses free RAM at launch. available_ram_gb = gpu_info.get_available_ram_gb() if system == "Darwin" else None + ram_gb = vram_gb if system == "Darwin" else None # Server-owned source of truth for mode selection. mode = decide_local_generation_mode( @@ -264,7 +271,7 @@ def _resolve_local_generations_mode() -> LocalGenerationMode: cuda_available=cuda_available, vram_gb=vram_gb, mps_available=mps_available, - ram_gb=available_ram_gb, + ram_gb=ram_gb, fp8_capable=fp8_capable, ) logger.info( @@ -278,10 +285,36 @@ def _resolve_local_generations_mode() -> LocalGenerationMode: available_ram_gb, fp8_capable, ) + return _LocalRuntime( + mode=mode, + vram_gb=vram_gb, + available_ram_gb=available_ram_gb, + darwin=system == "Darwin", + ) + + +_LOCAL_RUNTIME = _resolve_local_runtime() +LOCAL_GENERATIONS_MODE = _LOCAL_RUNTIME.mode + + +def _effective_local_generations_mode(mode: LocalGenerationMode) -> LocalGenerationMode: + """Dev-only: unlock Explore model specs when RAM check failed at launch.""" + if ( + os.environ.get("LTX_DEV_MODE") == "1" + and os.environ.get("LTX_DEV_FORCE_LOCAL_VIABLE") == "1" + and mode == "unsupported" + ): + logger.warning( + "Dev override LTX_DEV_FORCE_LOCAL_VIABLE: using streaming_models_loading " + "(detected mode was unsupported)" + ) + return "streaming_models_loading" return mode -LOCAL_GENERATIONS_MODE = _resolve_local_generations_mode() +_EFFECTIVE_LOCAL_GENERATIONS_MODE = _effective_local_generations_mode( + LOCAL_GENERATIONS_MODE +) CAMERA_MOTION_PROMPTS = { "none": "", @@ -306,7 +339,10 @@ def _resolve_local_generations_mode() -> LocalGenerationMode: outputs_dir=OUTPUTS_DIR, settings_file=SETTINGS_FILE, ltx_api_base_url=LTX_API_BASE_URL, - local_generations_mode=LOCAL_GENERATIONS_MODE, + local_generations_mode=_EFFECTIVE_LOCAL_GENERATIONS_MODE, + vram_gb=_LOCAL_RUNTIME.vram_gb, + available_ram_gb=_LOCAL_RUNTIME.available_ram_gb, + darwin_unified_memory=_LOCAL_RUNTIME.darwin, use_sage_attention=use_sage_attention, camera_motion_prompts=CAMERA_MOTION_PROMPTS, default_negative_prompt=DEFAULT_NEGATIVE_PROMPT, @@ -351,9 +387,11 @@ def log_hardware_info() -> None: logger.info(f"Device: {DEVICE} | Dtype: {DTYPE}") gpu_line = f"GPU: {gpu_info['name']} | VRAM: {vram_gb} GB" # On Apple Silicon there's no discrete VRAM — the figure above is total unified - # memory. Local generation is gated on *available* RAM at startup, so surface it. + # memory, which is also the local-generation eligibility check. if gpu.get_mps_available(): + total = gpu.get_vram_total_gb() avail = gpu.get_available_ram_gb() + gpu_line += f" | Total RAM: {total if total is not None else '?'} GB" gpu_line += f" | Available RAM: {avail if avail is not None else '?'} GB" logger.info( "LTX 2.5 decode uses eager SDPA on Mac (no Triton; slower than Linux/Windows)." diff --git a/backend/mps_prebuilt_ext.py b/backend/mps_prebuilt_ext.py index 06f0f2850..16061d755 100644 --- a/backend/mps_prebuilt_ext.py +++ b/backend/mps_prebuilt_ext.py @@ -26,6 +26,7 @@ import os import sys from pathlib import Path +from collections.abc import Iterator from typing import Any, Callable, cast from server_utils.units import gib @@ -127,10 +128,111 @@ def _guarded() -> dict[str, Any]: logger.info("mps_prebuilt_ext: installed fused_min_bytes=None → defaults guard") +def _torch_extensions_cache() -> Path: + override = os.environ.get("TORCH_EXTENSIONS_DIR") + if override: + return Path(override) + if sys.platform == "darwin": + return Path.home() / "Library/Caches/torch_extensions" + return Path.home() / ".cache" / "torch_extensions" + + +def _unlink_lock(path: Path) -> bool: + try: + path.unlink() + except FileNotFoundError: + return False + except OSError: + logger.warning("mps_prebuilt_ext: could not remove stale %s", path, exc_info=True) + return False + return True + + +def _remove_uncontended_ninja_lock(path: Path) -> bool: + """Unlink ninja's ``.ninja_lock`` only if no process holds ``LOCK_EX``. + + Ninja flocks this file for the compile. FileBaton's ``lock`` does not — + that path is unlinked separately. + """ + if sys.platform == "win32": + return _unlink_lock(path) + + import fcntl + + try: + fd = os.open(path, os.O_RDWR) + except FileNotFoundError: + return False + except OSError: + logger.warning("mps_prebuilt_ext: could not open %s", path, exc_info=True) + return False + + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + path.unlink() + return True + except BlockingIOError: + return False + except FileNotFoundError: + return False + except OSError: + logger.warning("mps_prebuilt_ext: could not remove stale %s", path, exc_info=True) + return False + finally: + os.close(fd) + + +def _iter_mps_sdpa_ext_dirs(root: Path) -> Iterator[Path]: + """Yield ``mps_sdpa_zc_ext`` dirs under both torch cache layouts. + + Default cache: ``//mps_sdpa_zc_ext``. + ``TORCH_EXTENSIONS_DIR`` override: ``/mps_sdpa_zc_ext`` (no version folder). + """ + direct = root / _EXT_NAME + if direct.is_dir(): + yield direct + yield from (path for path in root.glob(f"*/{_EXT_NAME}") if path.is_dir()) + + +def clear_stale_mps_extension_locks(cache_root: Path | None = None) -> list[Path]: + """Remove leftover JIT lock files from a killed mps-sdpa compile. + + SIGTERM during ``cpp_extension.load`` / ninja leaves ``lock`` and + ``.ninja_lock`` behind. The next import then sleeps on those files and + never reaches ``/health``, so the desktop loader stays on backendLoading. + + ``lock`` is torch FileBaton (O_CREAT|O_EXCL + exists-poll, no flock, no + pid). Live vs crash leftover is the same on disk; we unlink it at backend + start, before this process imports mps-sdpa. + + ``.ninja_lock`` is flocked by ninja. Unlink only after a non-blocking + exclusive flock succeeds, so a live ninja is not interrupted. + """ + root = cache_root if cache_root is not None else _torch_extensions_cache() + removed: list[Path] = [] + if not root.is_dir(): + return removed + for ext_dir in _iter_mps_sdpa_ext_dirs(root): + baton = ext_dir / "lock" + if _unlink_lock(baton): + removed.append(baton) + ninja_lock = ext_dir / ".ninja_lock" + if _remove_uncontended_ninja_lock(ninja_lock): + removed.append(ninja_lock) + return removed + + def setup_prebuilt_mps_extension() -> None: if sys.platform != "darwin": return + stale_locks = clear_stale_mps_extension_locks() + if stale_locks: + logger.warning( + "mps_prebuilt_ext: removed stale JIT lock(s) %s", + [str(path) for path in stale_locks], + ) + so = _prebuilt_so() if so is None: logger.info("mps_prebuilt_ext: no bundled prebuilt .so; torch will JIT-build if a compiler is present") diff --git a/backend/performance_runner/README.md b/backend/performance_runner/README.md index 999870014..48359469e 100644 --- a/backend/performance_runner/README.md +++ b/backend/performance_runner/README.md @@ -8,7 +8,7 @@ integrity (resolution/duration/fps/audio + file size/bitrate), and correctness a local dashboard (or the CLI). Everything runs against the same backend the app uses, so what you measure is -what ships. Because LTX Desktop runs on the *user's own* GPU and shares their +what ships. Because LTX Desktop runs on the _user's own_ GPU and shares their machine, the harness leans on desktop-shaped questions: will a config fit a 12 GB card, does it leak into system RAM, how slow is the first generation after launch. @@ -24,21 +24,22 @@ backend's `/api/gpu-info`) and hides whatever isn't measurable on your machine. - **Apple Silicon (MPS)** — Torch Compile and the cache patch are no-ops here, so those toggles and the patch/compile-specific runs (and the soak-trend chart) don't appear. What runs: the **scenario sweeps** and **cold-start**. There's no discrete VRAM, so the - memory signal is **unified / host RAM** — free RAM (the number that gates local - generation at server start), swap pressure, and how close the process sits to the MPS - memory ceiling (driver-allocated vs recommended-max). VRAM fit tiers, headroom %, and - the throttle heuristic need `nvidia-smi` and are CUDA-only. + memory signal is **unified / host RAM** — total RAM (the SKU number that gates + local generation at server start), free RAM, swap pressure, and how close the + process sits to the MPS memory ceiling (driver-allocated vs recommended-max). + VRAM fit tiers, headroom %, and the throttle heuristic need `nvidia-smi` and + are CUDA-only. ## What it does -| Tool | Question it answers | -|---|---| -| **Soak** (`soak_test.py`) | Does memory leak across many back-to-back generations? Gates on a flat inter-generation VRAM **floor**; also tracks the host-RAM floor (spill), GPU temp/clock (throttle), throughput (× realtime), and energy per gen. | -| **Correctness A/B** (`output_ab.py`) | Fixed seed, a setting OFF vs ON — do the outputs match? (decoded-frame PSNR). | -| **Decompose** (`decompose.py`) | How much wall-time does a given optimization save per generation? | -| **Cold-start** (`coldstart.py`) | How long is the first generation after a fresh backend launch (model load / disk read / build) vs the warm steady state? | +| Tool | Question it answers | +| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| **Soak** (`soak_test.py`) | Does memory leak across many back-to-back generations? Gates on a flat inter-generation VRAM **floor**; also tracks the host-RAM floor (spill), GPU temp/clock (throttle), throughput (× realtime), and energy per gen. | +| **Correctness A/B** (`output_ab.py`) | Fixed seed, a setting OFF vs ON — do the outputs match? (decoded-frame PSNR). | +| **Decompose** (`decompose.py`) | How much wall-time does a given optimization save per generation? | +| **Cold-start** (`coldstart.py`) | How long is the first generation after a fresh backend launch (model load / disk read / build) vs the warm steady state? | | **Sanity sweep** (`sanity.py` + `scenarios.py`) | Does the whole feature surface (t2v/i2v/a2v/ia2v/t2i/extend/retake/LoRA/IC-LoRA) still generate end-to-end? Records each scenario's **peak VRAM** (which card tier it fits + headroom %), **throughput** (× realtime), **energy**, and the output's resolution/size/bitrate, and reports an advisory **integrity** check (output vs request — never fails the sweep). Scenarios that need a LoRA/IC-LoRA are **skipped if it isn't downloaded** — availability is read from the app's own library (`/api/loras` + `/api/ic-loras`, the same source as `lora_catalog.json`), so a scenario references a catalog **id** and its weight path resolves from that listing. `--fast` caps to 540p/5s for a quick surface check. Collects each scenario's input + output into a viewer. | -| **Dashboard** (`dashboard/`) | One local page to launch all of the above, flip toggles, watch logs, and chart trends. | +| **Dashboard** (`dashboard/`) | One local page to launch all of the above, flip the same Settings controls (active LTX version, Fast decode, cache, Torch Compile), watch logs, and chart trends. | Every gate tool exits non-zero on FAIL, so the same scripts can gate CI. @@ -58,10 +59,9 @@ dashboard in a browser. Ctrl+C stops both. > loaded, open the app once to fetch a model, then re-run. > The runner measures **local** generation. The backend decides local-vs-API at -> startup from the hardware available *at that moment* — on Apple Silicon, the **free** -> (not total) unified RAM, since the GPU shares system memory. If it comes up in -> API-only mode, `perf:dev` stops and asks you to free RAM (close memory-heavy apps) -> and re-run, rather than opening a dashboard with no local work to measure. +> startup from the hardware available _at that moment_ — on Apple Silicon, **total** +> unified RAM (32 GiB minimum), not free RAM. If it comes up in API-only mode, +> `perf:dev` stops because this machine is below the local-gen floor. > **`perf:dev` measures the dev backend** — the same interpreter `pnpm dev` uses, with > the app's generation env mirrored (auth, app-data dir, MPS CPU-fallback). On CUDA that's @@ -71,6 +71,22 @@ dashboard in a browser. Ctrl+C stops both. > indicative, and point `run_dashboard.py` at the **running app** for release-accurate Mac > readings (at the cost of the app's own GPU/RAM contention). +### Starting the backend by hand (Apple Silicon) + +`pnpm perf:dev` and the app already do the right thing. If you launch `ltx2_server.py` +yourself, put the venv's `bin/` first on `PATH`: + +```bash +cd backend +PATH="$PWD/.venv/bin:$PATH" LTX_APP_DATA_DIR= LTX_PORT=41954 LTX_AUTH_TOKEN= \ + .venv/bin/python ltx2_server.py +``` + +Without it `ninja` is not found, the zero-copy attention backend (`mpsgraph_zc`) fails to +build, and the leaking `mpsgraph` fallback runs: driver memory climbs ~2 GB / 15 s and a +48 GB Mac is killed within a couple of generations. Check the first log line says +`picked=mpsgraph_zc active=True`. Details: `docs/mps-attention-memory-leak.md`. + ### Against the running app If the desktop app is already running, just launch the dashboard: @@ -88,7 +104,7 @@ Then paste the backend token (copy it from the app's **Logs** footer — the fai - **Header** — backend/token status and live memory telemetry: on CUDA, GPU util / VRAM / temp / clock / power; on Apple Silicon, GPU name + unified-memory use, - free RAM (the local-gen gate), swap, and the MPS ceiling. + free RAM, swap, and the MPS ceiling. - **Token** — paste it once; the header shows `token: set`. - **Toggles** — reflect the backend's live settings (cache patch, Torch Compile); disabled while a run is in progress so they can't be flipped mid-run. Off CUDA @@ -140,6 +156,7 @@ uv run python output_ab.py --seed 42 --run uv run python decompose.py --reps 5 uv run python coldstart.py --warm 3 # run right after a fresh backend start uv run python sanity.py # wired scenarios; --only / --include-unwired / --fast +uv run python sanity.py --model-id 2.5 --use-conv-vae # same as Settings → Base model + Fast decode ``` Set `PERF_AUTH_TOKEN` (and optionally `LTX_PORT`) in the environment first. Each @@ -165,6 +182,104 @@ library via **`catalog.py`**. Non-catalog control weights (canny/depth union-con depth processor) go in `required_files` as paths relative to `models_dir`, checked on disk. +## Live regression suite + +Run this by hand after any big change (LTX-2 bump, pipeline or runtime refactor, +dependency upgrade) to confirm every core flow still generates **and still behaves +correctly**. It needs real weights, a GPU/Apple Silicon box and a running backend, so it +is not part of CI. Run it on each platform you ship (Mac, Windows). + +```bash +cd backend/performance_runner +uv run python sanity.py --tags smoke # one small run per flow and code path +uv run python sanity.py --tags smoke full bump # + LoRAs, portrait, cancel on every route, full-size bump gate +uv run python sanity.py --only smoke_retake_silent_source # any single scenario +``` + +The dashboard has **regression: smoke** and **regression: full** buttons, and every +scenario is in the single-scenario dropdown. Scenarios whose weights or model offering are +missing are reported as SKIP, never as PASS. + +**Why smoke is small.** Local t2v at 270p/360p runs stage 1 only (the skip-stage-2 path); +540p and up runs the two-stage pipeline, so smoke has one of each, and keyframes on both. +Small canvases hide tiling/VRAM problems; the full-size `bump` scenarios cover those. + +**What passes means** (`checks.py`, on top of "the file exists"): it decodes end to end +with the expected duration and audio, no frame is black, blown out, or frozen, the first +and last keyframes appear in the output, A2V and video-only retakes carry the source +soundtrack, retakes/extends keep the parts of the source they must keep, a different seed +gives a different video, and the **same request re-run at the very end reproduces the +first run** (catches state leaking from any flow in between: adapters, caches, cancel). + +| Flow | Scenarios | +| --- | --- | +| t2v, both pipeline paths, seed handling | `smoke_t2v_270p`, `smoke_t2v_270p_seed_b`, `smoke_t2v_540p_2s`, `smoke_t2v_270p_repeat` | +| plain LoRA (`loras` in the request) | `smoke_lora_t2v` (Cozy Felt; skipped if not downloaded). Same request as the reference, so it must differ from it, and the final `_repeat` proves the adapter did not leak into later runs. Full: `lora_cozy_felt`, `lora_cozy_felt_openwheel` | +| i2v, keyframes (each path) | `smoke_i2v_270p`, `smoke_mkf_270p`, `smoke_mkf_540p` | +| audio-to-video | `smoke_a2v_270p`, `smoke_ia2v_270p` | +| image | `smoke_t2i` | +| extend / prepend | `smoke_extend_end`, `smoke_extend_start` | +| retake: every mode, silent source | `smoke_retake_av`, `_video_only`, `_audio_only`, `_silent_source` | +| IC-LoRA | `smoke_iclora_canny`, `_depth`, `_day_to_night` | +| cancel and recovery | `smoke_cancel_extend`; full: `full_cancel_a2v`, `full_cancel_iclora` | +| queued surface (smoke) | `smoke_q_t2v_270p`, `_i2v_end_270p`, `_a2v_270p`, `_extend_end`, `_retake_av`, `_batch_seeds` (3 jobs queued together), `_cancel_extend` | +| queued surface (full) | `full_q_t2v_540p_2s`, `_i2v_270p`, `_i2v_end_540p`, `_ia2v_270p`, `_extend_start`, `_retake_video`, `_retake_audio`, `_retake_silent_source` | + +Notes: + +- **Sleep:** `sanity.py` keeps the machine and its display on for the whole sweep, so no sleep, screen saver or idle lock screen (macOS `caffeinate -d -i`, Windows `SetThreadExecutionState`; released when the process ends, even if killed). Closing a laptop lid still sleeps it; keep the lid open or use power plus an external display. +- The thresholds in `checks.py` (frame/audio correlation, same-seed PSNR) are loose + heuristics. The first Windows (RTX 5090) and macOS (M5 Max) sweeps cleared them with + margin (see the `checks.py` docstring for the measured values). Each check reports its + measured value; tighten the constants if a regression slips through. A failure may be a + threshold, so read the detail before suspecting the app. +- `reproduces` / `differs_from` compare against the run recorded earlier **in the same + sweep**. Run alone they **fail** ("no reference recorded"): an unverified comparison must not look + green. Run them together with the scenario that records the reference. +- **Two surfaces.** The plain scenarios drive the synchronous GenSpace routes + (`/api/generate`, `/api/extend`, `/api/retake`, `/api/ic-lora/generate`, + `/api/generate-image`). The `*_q_*` scenarios (tag `queued`) drive the queued Home/Explore + surface (`/api/generations/...`) via `queued.py`: input files are ingested as assets, the + job is polled through the ledger, and cancel goes through `/generations/{id}/cancel`. + Both end in the same pipelines but not the same request schemas, edit executors or ledger. + Queued IC-LoRA and text-to-image have no queued route, so they are GenSpace-only. Run the + queued surface alone with `--tags queued`. Feature tags (`retake`, `a2v`, ...) also select the + older wired scenarios that carry them, not only the regression ones. +- The queued and GenSpace surfaces are not compared pixel for pixel: with local text + encoding GenSpace rewrites the prompt and Explore sends it as typed (auto-enhance off), so + the same seed yields different videos by design. Queued same-seed determinism is covered by + `smoke_q_batch_seeds` (seed A, B, A). +- Queued scenario bodies are validated against the backend's `Create*Request` models in CI + (`tests/test_perf_runner_queued.py`), so a schema change fails there first. +- Derived assets: `reference_video_silent.mp4` (`ffmpeg -an`), `reference_video_2s.mp4` + (first 2 s), `reference_keyframe_b.jpg` (frame at 3.5 s), all from `reference_video.mp4`. + +## LTX-2 bump gate + +Use this sweep when bumping `ltx-core` / `ltx-pipelines`. `--fast` is **not** the +bump gate: it forces 540p/5s and IC-LoRA `resolution_factor=1.0`, which hides the +tiling/VRAM bugs these scenarios exist to catch. + +```bash +cd backend/performance_runner +uv run python sanity.py --tags bump --gate-integrity +uv run python sanity.py --tags bump --model-id 2.5 --use-conv-vae --gate-integrity +uv run python soak_test.py --n 3 --label bump_e4 --set-cache on # E4 stage-cache floor +``` + +| Tag / key | Experiment | Watch | +| ----------------------------------- | --------------------------- | -------------------------------------- | +| `t2v_540p_8s`, `t2v_1080p_5s` | E1 decode VRAM | completes (no hang at device capacity) | +| those plus `last_frames_not_black` | E2 MPS tail-frame zeroing | each of last ~8 frames has non-zero luma (fails closed without ffmpeg) | +| `iclora_stage2_on` | E3 two-stage IC-LoRA | completes with `skip_stage_2=false` (stage 2 is not forced onto streaming) | +| `soak_test.py --n 3 --set-cache on` | E4 stage-cache soak | flat reserved-VRAM floor | +| `mkf_interpolation` | guiding-latent swap | output exists | +| `cancel_mid_denoise` | interrupt hook | generate returns `cancelled` after `phase=inference` | +| `iclora_day_to_night` | shipped skip_stage_2 tiling | no OOM / crawl | + +`--gate-integrity` fails a default-route scenario whose output duration/fps/requested +audio does not match the request (those diffs are advisory on a normal sweep). + ## Test assets `test_assets/` holds small, self-made fixtures used by the modality scenarios: a diff --git a/backend/performance_runner/checks.py b/backend/performance_runner/checks.py new file mode 100644 index 000000000..646dc6e33 --- /dev/null +++ b/backend/performance_runner/checks.py @@ -0,0 +1,264 @@ +"""Output oracles for the live regression suite. + +The original checks only prove that a file exists. These prove the output behaves like +the request: it decodes, is not blank or frozen, honours its image/audio/video +conditioning, and is reproducible per seed. They need only ffmpeg and the stdlib. + +Every factory returns a ``check(path) -> (ok, detail)`` compatible with +``Scenario.checks``. A check that cannot run (ffmpeg missing, unreadable file) FAILS: +a gate that silently skips is a false pass. + +Thresholds are deliberately loose heuristics. The first hardware runs (Windows RTX 5090 and +macOS M5 Max, ltx-core 1.4.1) cleared them with margin: identical same-seed runs score inf dB +against the 30 dB floor, a different seed 13.7 dB, a LoRA against the plain run 16.4 dB, and +frames kept from a source video correlate at 1.00 against the 0.85 floor. Tighten them from +real runs if a regression slips through (the detail string reports the measured value). +""" + +from __future__ import annotations + +import array +import re +import statistics +import subprocess +from collections.abc import Callable, Sequence +from functools import wraps + +import perf_config + +Check = Callable[[str | None], tuple[bool, str]] + +FRAME_MATCH_MIN_CORR = 0.85 # 32x18 grayscale thumbnail correlation vs a reference frame +AUDIO_MATCH_MIN_CORR = 0.80 # 0.1 s RMS-envelope correlation vs a reference soundtrack +SAME_SEED_MIN_PSNR_DB = 30.0 # same request twice must be near-identical +BLACK_LUMA_MAX = 8.0 # per-frame mean luma (0-255) at or below counts as black +WHITE_LUMA_MIN = 247.0 +FROZEN_MIN_MEAN_DIFF = 0.2 # mean abs frame-to-frame luma change below this = frozen +_THUMB_W, _THUMB_H = 32, 18 +_AUDIO_RATE, _AUDIO_WINDOW = 8000, 800 # 0.1 s windows + +_REMEMBERED: dict[str, str] = {} + + +def reset() -> None: + """Forget every remembered reference (a sweep starts with none).""" + _REMEMBERED.clear() + + +def _run(args: list[str], timeout: float = 180) -> subprocess.CompletedProcess[bytes]: + return subprocess.run(args, capture_output=True, timeout=timeout) + + +def _guarded(name: str) -> Callable[[Callable[..., tuple[bool, str]]], Callable[..., tuple[bool, str]]]: + """Name the check for the report and turn tool failures into a FAIL.""" + + def deco(fn: Callable[..., tuple[bool, str]]) -> Callable[..., tuple[bool, str]]: + @wraps(fn) + def wrapper(path: str | None) -> tuple[bool, str]: + if not path: + return False, "no output path" + try: + return fn(path) + except FileNotFoundError: + return False, "ffmpeg/ffprobe not on PATH" + except (RuntimeError, subprocess.TimeoutExpired) as exc: + return False, f"{type(exc).__name__}: {exc}" + + wrapper.__name__ = name + return wrapper + + return deco + + +def _thumbs(path: str) -> list[bytes]: + proc = _run([ + # passthrough: real frames only. A variable-frame-rate output (the queued retake + # asset) would otherwise be resampled to a constant rate with duplicated frames. + "ffmpeg", "-v", "error", "-i", path, "-an", "-fps_mode", "passthrough", + "-vf", f"scale={_THUMB_W}:{_THUMB_H},format=gray", + "-f", "rawvideo", "-pix_fmt", "gray", "pipe:1", + ]) + size = _THUMB_W * _THUMB_H + if proc.returncode != 0 or len(proc.stdout) < size: + raise RuntimeError((proc.stderr or b"").decode("utf-8", "replace")[:200] or "no frames decoded") + raw = proc.stdout + return [raw[i:i + size] for i in range(0, len(raw) - size + 1, size)] + + +def _corr(a: Sequence[float], b: Sequence[float]) -> float: + try: + return statistics.correlation(a, b) + except statistics.StatisticsError: # a constant signal (black frame, silence) matches nothing + return 0.0 + + +def _pick(frames: list[bytes], at: str | float, duration: float | None) -> bytes: + if at == "first": + return frames[0] + if at == "last": + return frames[-1] + if not duration: + raise RuntimeError(f"duration unknown, cannot pick the frame at {at}s") + return frames[min(len(frames) - 1, round(float(at) / duration * (len(frames) - 1)))] + + +def _duration(path: str) -> float | None: + return (perf_config.ffprobe_info(path) or {}).get("duration") + + +def _envelope(path: str) -> list[float]: + proc = _run(["ffmpeg", "-v", "error", "-i", path, "-vn", "-ac", "1", "-ar", str(_AUDIO_RATE), + "-f", "f32le", "pipe:1"]) + if proc.returncode != 0: + raise RuntimeError((proc.stderr or b"").decode("utf-8", "replace")[:200]) + samples = array.array("f") + samples.frombytes(proc.stdout[: len(proc.stdout) // 4 * 4]) + return [ + (sum(x * x for x in samples[i:i + _AUDIO_WINDOW]) / _AUDIO_WINDOW) ** 0.5 + for i in range(0, len(samples) - _AUDIO_WINDOW + 1, _AUDIO_WINDOW) + ] + + +def media_ok(*, audio: bool | None = None, duration: tuple[float, float] | None = None) -> Check: + """Decodes end to end with no errors; optional audio stream and duration window (seconds).""" + + @_guarded("media_ok") + def check(path: str) -> tuple[bool, str]: + proc = _run(["ffmpeg", "-v", "error", "-i", path, "-f", "null", "-"]) + if proc.returncode != 0 or proc.stderr.strip(): + return False, "decode errors: " + proc.stderr.decode("utf-8", "replace")[:160] + probe = perf_config.ffprobe_info(path) or {} + problems = [] + dur, fps, frames = probe.get("duration"), probe.get("fps"), probe.get("nb_frames") + if duration and not (dur and duration[0] <= dur <= duration[1]): + problems.append(f"duration {dur} not in {duration}") + if dur and fps and frames and abs(frames - dur * fps) > 3: + problems.append(f"{frames} frames != {dur:.2f}s*{fps:g}fps") + if audio and not probe.get("has_audio"): + problems.append("audio stream missing") + return not problems, "; ".join(problems) or f"{dur}s {fps}fps {frames}f audio={probe.get('has_audio')}" + + return check + + +def not_dead() -> Check: + """No black, blown-out, or frozen video (every frame is inspected, not just the tail).""" + + @_guarded("not_dead") + def check(path: str) -> tuple[bool, str]: + frames = _thumbs(path) + if len(frames) < 2: + return False, f"only {len(frames)} frame(s)" + means = [sum(f) / len(f) for f in frames] + dark = sum(m <= BLACK_LUMA_MAX for m in means) + bright = sum(m >= WHITE_LUMA_MIN for m in means) + motion = statistics.fmean( + sum(abs(x - y) for x, y in zip(a, b)) / len(a) for a, b in zip(frames, frames[1:]) + ) + problems = [] + if dark: + problems.append(f"{dark} black frame(s)") + if bright: + problems.append(f"{bright} blown-out frame(s)") + if motion < FROZEN_MIN_MEAN_DIFF: + problems.append(f"frozen (motion {motion:.2f})") + return not problems, "; ".join(problems) or f"{len(frames)} frames, motion {motion:.2f}" + + return check + + +def frame_matches( + reference: str, + *, + at: str | float = "first", + reference_at: str | float = "first", + min_corr: float = FRAME_MATCH_MIN_CORR, +) -> Check: + """A frame of the output (``first``/``last``/seconds) resembles a frame of ``reference`` + (an image or a video). Used for keyframes and for regions a retake/extend must keep.""" + + @_guarded(f"frame_matches[{at}]") + def check(path: str) -> tuple[bool, str]: + got = _pick(_thumbs(path), at, _duration(path)) + want = _pick(_thumbs(reference), reference_at, _duration(reference)) + corr = _corr(list(got), list(want)) + return corr >= min_corr, f"corr={corr:.2f} (min {min_corr})" + + return check + + +def audio_matches(reference: str, *, min_corr: float = AUDIO_MATCH_MIN_CORR) -> Check: + """The output soundtrack follows ``reference``'s loudness envelope (A2V returns the + source audio; a video-only retake keeps it). Silence never matches.""" + + @_guarded("audio_matches") + def check(path: str) -> tuple[bool, str]: + got, want = _envelope(path), _envelope(reference) + n = min(len(got), len(want)) + if n < 5: + return False, f"too little audio to compare ({len(got)} vs {len(want)} windows)" + corr = _corr(got[:n], want[:n]) + return corr >= min_corr, f"corr={corr:.2f} over {n / 10:.1f}s (min {min_corr})" + + return check + + +def _psnr(a: str, b: str) -> float: + proc = _run(["ffmpeg", "-v", "info", "-i", a, "-i", b, "-lavfi", "psnr", "-f", "null", "-"]) + match = re.search(r"average:(inf|[0-9.]+)", proc.stderr.decode("utf-8", "replace")) + if not match: + raise RuntimeError("psnr unavailable (different sizes?)") + return float("inf") if match.group(1) == "inf" else float(match.group(1)) + + +def remember(key: str) -> Check: + """Record this output as the reference ``key`` for a later ``reproduces``/``differs_from``.""" + + @_guarded(f"remember[{key}]") + def check(path: str) -> tuple[bool, str]: + _REMEMBERED[key] = path + return True, f"saved as '{key}'" + + return check + + +def _compare(key: str, want_same: bool) -> Check: + @_guarded(f"{'reproduces' if want_same else 'differs_from'}[{key}]") + def check(path: str) -> tuple[bool, str]: + ref = _REMEMBERED.get(key) + if ref is None: # never pass on nothing: an unverified comparison is not a green one + return False, f"no reference '{key}' recorded: run its scenario first, in the same sweep" + psnr = _psnr(path, ref) + same = psnr >= SAME_SEED_MIN_PSNR_DB + return same == want_same, f"psnr={psnr:.1f}dB (same-seed threshold {SAME_SEED_MIN_PSNR_DB})" + + return check + + +def reproduces(key: str) -> Check: + """Same request as the remembered run: near-identical output (seed, cache and adapter hygiene).""" + return _compare(key, want_same=True) + + +def differs_from(key: str) -> Check: + """A visibly different output than the remembered run: another seed is honoured, or an + adapter that was requested on an otherwise identical request is really applied.""" + return _compare(key, want_same=False) + + +def seed_batch() -> Callable[[list[str | None]], tuple[bool, str]]: + """For three jobs submitted together with seeds A, B, A: the two A outputs match and B + differs. Proves back-to-back queued jobs neither leak into nor drop each other.""" + + def check(outs: list[str | None]) -> tuple[bool, str]: + if len(outs) != 3 or not all(outs): + return False, f"expected 3 outputs, got {outs}" + try: + same, other = _psnr(str(outs[0]), str(outs[2])), _psnr(str(outs[0]), str(outs[1])) + except (FileNotFoundError, RuntimeError, subprocess.TimeoutExpired) as exc: + return False, f"{type(exc).__name__}: {exc}" + ok = same >= SAME_SEED_MIN_PSNR_DB > other + return ok, f"same-seed psnr={same:.1f}dB, other-seed psnr={other:.1f}dB (threshold {SAME_SEED_MIN_PSNR_DB})" + + check.__name__ = "seed_batch" + return check diff --git a/backend/performance_runner/dashboard/app.js b/backend/performance_runner/dashboard/app.js index 4cfdbcaec..732e7831b 100644 --- a/backend/performance_runner/dashboard/app.js +++ b/backend/performance_runner/dashboard/app.js @@ -20,6 +20,7 @@ const jpost = async (u, b) => (await fetch(u, {method:'POST', headers:{'Content- let selected = null; // selected run id (drives the run log + chart) let logSource = 'run'; // 'run' = selected run's log · 'backend' = session log let toggleSyncPausedUntil = 0; // don't let a poll clobber a just-clicked toggle +let runtimeLocked = false; // a run is in progress — don't flip Settings mid-gen // ==== token + toggles ====================================================== // async function setToken(){ @@ -33,8 +34,30 @@ async function setToken(){ async function toggle(route, checked, label){ toggleSyncPausedUntil = Date.now() + 2500; - try { await jpost(route, {enabled:checked}); $('#tgMsg').textContent = `${label} ${checked?'ON':'OFF'}`; } - catch { $('#tgMsg').textContent = `${label} toggle failed (token?)`; } + try { + const res = await fetch(route, {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({enabled:checked})}); + const data = await res.json(); + if(!res.ok){ + $('#tgMsg').textContent = data.error || `${label} failed`; + toggleSyncPausedUntil = 0; + await syncToggles(); + return; + } + $('#tgMsg').textContent = `${label} ${checked?'ON':'OFF'}`; + } catch { $('#tgMsg').textContent = `${label} toggle failed (token?)`; } +} + +async function setActiveModel(modelId){ + toggleSyncPausedUntil = Date.now() + 2500; + try { + const res = await fetch('/api/active-ltx-model', {method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify({model_id:modelId})}); + const data = await res.json(); + if(!res.ok){ $('#tgMsg').textContent = data.error || 'model switch failed'; return; } + $('#tgMsg').textContent = 'active model set'; + lastVersionsJson = ''; + await syncToggles(); + await refreshScenarios(); + } catch { $('#tgMsg').textContent = 'model switch failed (token?)'; } } let envKnown = false; @@ -49,14 +72,50 @@ async function refreshEnv(){ document.body.classList.toggle('no-cuda', !e.cuda); } +let lastVersionsJson = ''; async function syncToggles(){ if(Date.now() < toggleSyncPausedUntil) return; try { const t = await jget('/api/toggles'); if(t.cache != null) $('#tgCache').checked = t.cache; if(t.torch_compile != null) $('#tgCompile').checked = t.torch_compile; - if(t.cache == null && t.torch_compile == null) $('#tgMsg').textContent = t.error ? 'settings unreadable (token?)' : ''; - else if($('#tgMsg').textContent === 'reading live settings…') $('#tgMsg').textContent = ''; + const versions = t.versions || []; + const vjson = JSON.stringify(versions); + if(vjson !== lastVersionsJson){ + lastVersionsJson = vjson; + $('#modelList').innerHTML = versions.length + ? versions.map(v => { + const tip = v.installed ? (v.model_id || '') : 'not installed — download it in Settings'; + return ``; + }).join('') + : '
no versions (token?)
'; + } else { + versions.forEach(v => { + const el = document.querySelector(`input[name="ltxModel"][value="${CSS.escape(v.model_id)}"]`); + if(el){ el.checked = !!v.active; el.disabled = !v.installed || runtimeLocked; } + }); + } + const active = versions.find(v => v.active); + const on25 = String(active?.model_id || '').startsWith('ltx-2.5'); + const vaes = t.vaes || {}; + const row = $('#fastDecodeRow'); + row.hidden = !on25; + const box = $('#tgConvVae'); + if(t.use_conv_vae != null) box.checked = t.use_conv_vae; + const canSwitchToOther = box.checked ? vaes.diff : vaes.conv; + box.disabled = runtimeLocked || !on25 || !canSwitchToOther; + box.title = !on25 ? 'Fast decode is LTX 2.5 only' + : (box.checked && !vaes.diff) ? 'DiffVAE not downloaded — download it in Settings to switch' + : (!box.checked && !vaes.conv) ? 'conv VAE not downloaded — download it in Settings to switch' + : 'same as Settings → Fast decode (on = conv VAE, off = DiffVAE)'; + if(t.cache == null && t.torch_compile == null && t.use_conv_vae == null) + $('#tgMsg').textContent = t.error ? 'settings unreadable (token?)' : ''; + else if($('#tgMsg').textContent === 'same as the app Settings modal' + || $('#tgMsg').textContent === 'reading live settings…') $('#tgMsg').textContent = ''; } catch {} } @@ -73,6 +132,7 @@ function runSummary(kind, p){ if(kind === 'sanity'){ const fast = p.fast ? ' — FAST (540p/5s, surface check only)' : ''; if(p.only && p.only.length) return `Run scenario "${p.only.join(', ')}" end-to-end (1 generation)${fast}.`; + if(p.tags && p.tags.length) return `Start regression suite (tags: ${p.tags.join(', ')}). Scenarios whose weights are missing are skipped.`; return `Start sanity sweep${p.include_unwired ? ' (incl. UNWIRED — expect failures)' : ' (wired scenarios)'}${fast}.`; } return `Start ${kind}?`; @@ -159,15 +219,19 @@ const scenTip = x => scenAvail(x) ? (x.title || '') : (x.unavailable_reason || ' async function refreshScenarios(){ scenarios = await jget('/api/scenarios'); - const mark = x => !scenAvail(x) ? '⬇' : x.needs_wiring ? '⚠︎' : '✓'; + const mark = x => !scenAvail(x) + ? (String(x.unavailable_reason||'').startsWith('not supported') ? '⊘' : '⬇') + : x.needs_wiring ? '⚠︎' : '✓'; $('#scenarios').innerHTML = scenarios.map(x => `
` + `${mark(x)} ${esc(x.key)} ${esc(x.title)}
`).join(''); const cur = $('#scenSel').value; - // Unavailable scenarios are disabled in the picker (can't be selected to run). + const suffix = x => !scenAvail(x) + ? (String(x.unavailable_reason||'').startsWith('not supported') ? ' (not on this model)' : ' (not downloaded)') + : ''; $('#scenSel').innerHTML = scenarios.map(x => `` + + `${!scenAvail(x)?'⬇ ':x.needs_wiring?'⚠︎ ':''}${esc(x.key)} — ${esc(x.title)}${suffix(x)}` ).join(''); if(cur && scenarios.some(x => x.key === cur && scenAvail(x))) $('#scenSel').value = cur; updateRunScenarioBtn(); @@ -225,6 +289,12 @@ async function refreshRuns(){ }); $('#tgCache').disabled = anyRunning; $('#tgCompile').disabled = anyRunning; + runtimeLocked = anyRunning; + document.querySelectorAll('input[name="ltxModel"]').forEach(el => { + const installed = !el.parentElement.classList.contains('unavail'); + el.disabled = anyRunning || !installed; + }); + if($('#tgConvVae') && anyRunning) $('#tgConvVae').disabled = true; } // ==== log + chart ========================================================== // @@ -297,6 +367,7 @@ function clearChart(){ // ==== wire-up + polling ==================================================== // $('#tgCache').onchange = e => toggle('/api/cache', e.target.checked, 'cache'); $('#tgCompile').onchange = e => toggle('/api/torch-compile', e.target.checked, 'torch compile (applies next gen)'); +$('#tgConvVae').onchange = e => toggle('/api/fast-decode', e.target.checked, 'Fast decode'); $('#scenSel').onchange = updateRunScenarioBtn; const POLLERS = [[refreshTop,3000], [refreshRuns,3000], [refreshLog,3000], [syncToggles,3000], [refreshEnv,3000]]; diff --git a/backend/performance_runner/dashboard/index.html b/backend/performance_runner/dashboard/index.html index f2f2cf288..8ae2a380e 100644 --- a/backend/performance_runner/dashboard/index.html +++ b/backend/performance_runner/dashboard/index.html @@ -28,11 +28,17 @@

Backend token

Copy it from the app's Logs footer (the •••••). Held in memory only.
-
-

Toggles

- - -
reading live settings…
+
+

Settings

+
reading installed models…
+ +
+ + +
+
same controls as the app Settings modal
@@ -55,6 +61,10 @@

Run

+
+ + +
diff --git a/backend/performance_runner/dashboard/server.py b/backend/performance_runner/dashboard/server.py index 88154be81..2561bc430 100644 --- a/backend/performance_runner/dashboard/server.py +++ b/backend/performance_runner/dashboard/server.py @@ -2,10 +2,10 @@ """Perf dashboard control server (localhost-only). A thin FastAPI app that lets the HTML dashboard fully drive the perf suite — set -the backend auth token, flip the cache + Torch Compile toggles, launch soak / -A/B / decompose / sanity runs, poll their logs/status, stop them, view sanity -results, and chart the soak trend. It reuses perf_config.py directly, so it -inherits the same single-seam wiring. +the backend auth token, flip the same Settings controls (active LTX version, Fast +decode, cache, Torch Compile), launch soak / A/B / decompose / sanity runs, poll +their logs/status, stop them, view sanity results, and chart the soak trend. It +reuses perf_config.py directly, so it inherits the same single-seam wiring. All run artifacts (logs, soak CSVs, sanity results) live in one folder, `perf_config.RUNS_DIR`; run metadata is persisted alongside so the runs table @@ -78,6 +78,10 @@ class TokenReq(BaseModel): token: str +class ModelReq(BaseModel): + model_id: str + + # --------------------------------------------------------------------------- # # Run lifecycle # --------------------------------------------------------------------------- # @@ -332,12 +336,16 @@ def set_token(req: TokenReq) -> dict: @app.get("/api/toggles") def toggles() -> dict: - """Live cache + Torch-Compile state read from the backend, so the UI reflects its - actual settings.""" + """Live Settings state: cache, Torch Compile, Fast decode, and LTX versions. + + Versions/installed/active are GET /api/models/ltx-versions (BaseModelSection). + Fast decode is useConvVae; VAE-on-disk comes from /api/models/describe. + """ try: s = perf_config.get_settings() except Exception as exc: # noqa: BLE001 - return {"cache": None, "torch_compile": None, "error": str(exc)} + return {"cache": None, "torch_compile": None, "use_conv_vae": None, + "versions": [], "vaes": {"diff": False, "conv": False}, "error": str(exc)} def pick(*keys: str) -> bool | None: for k in keys: @@ -345,9 +353,18 @@ def pick(*keys: str) -> bool | None: return bool(s[k]) return None + try: + versions = perf_config.ltx_versions() + vaes = perf_config.described_vaes() + except Exception: # noqa: BLE001 + versions, vaes = [], {"diff": False, "conv": False} + return { "cache": pick("diffusionStageCacheEnabled", "diffusion_stage_cache_enabled"), "torch_compile": pick("useTorchCompile", "use_torch_compile"), + "use_conv_vae": pick("useConvVae", "use_conv_vae"), + "versions": versions, + "vaes": vaes, } @@ -363,19 +380,42 @@ def set_torch_compile(req: ToggleReq) -> dict: return {"torch_compile_enabled": req.enabled} +@app.post("/api/fast-decode") +def set_fast_decode(req: ToggleReq) -> JSONResponse: + try: + perf_config.set_use_conv_vae(req.enabled) + return JSONResponse({"use_conv_vae": req.enabled}) + except RuntimeError as exc: + return JSONResponse({"error": str(exc)}, status_code=409) + + +@app.post("/api/active-ltx-model") +def set_active_ltx_model(req: ModelReq) -> JSONResponse: + try: + model_id = perf_config.activate_ltx_model(req.model_id) + return JSONResponse({"model_id": model_id}) + except RuntimeError as exc: + return JSONResponse({"error": str(exc)}, status_code=409) + + @app.get("/api/scenarios") def list_scenarios() -> list[dict]: - """Scenarios plus availability, crossed with the app's LoRA/IC-LoRA library (SSOT). - `available` is False when a required catalog weight isn't downloaded; the reason points - the user at the app's library. Availability uses the catalog cache — POST /api/catalog/ - refresh after downloading a weight in the app to re-check without restarting.""" + """Scenarios plus availability, crossed with the app's LoRA/IC-LoRA library (SSOT) + and the active model's local offerings (retake/extend/canny from models-specs).""" + caps = perf_config.scenario_caps() out: list[dict] = [] for s in scn.all_scenarios(): missing = s.unavailable() - reason = ("needs download (open the app → LoRA / IC-LoRA library): " + ", ".join(missing) - if missing else "") + cap_reason = s.blocked_by_caps(caps) + if cap_reason: + reason = cap_reason + elif missing: + reason = "needs download (open the app → LoRA / IC-LoRA library): " + ", ".join(missing) + else: + reason = "" out.append({"key": s.key, "title": s.title, "needs_wiring": s.needs_wiring, - "tags": s.tags, "available": not missing, "unavailable_reason": reason}) + "tags": s.tags, "available": not missing and not cap_reason, + "unavailable_reason": reason}) return out diff --git a/backend/performance_runner/dashboard/style.css b/backend/performance_runner/dashboard/style.css index 0ede84c53..e81745762 100644 --- a/backend/performance_runner/dashboard/style.css +++ b/backend/performance_runner/dashboard/style.css @@ -38,6 +38,8 @@ button.stop { background:#2a1416; border-color:#5a2a2a; color:#f0a0a0; padding:2 button.ghost { background:transparent; border-color:var(--line); color:var(--mut); padding:2px 8px; font-size:12px; } button.ghost:hover { color:var(--fg); border-color:var(--acc); } #scenarios .unavail { opacity:.5; } /* scenario needs a weight downloaded from the app */ +#modelList .unavail { opacity:.5; } +#fastDecodeRow[hidden] { display:none !important; } label.tog { display:flex; align-items:center; gap:8px; margin:6px 0; } input, select { background:var(--field); color:var(--fg); border:1px solid var(--line); border-radius:5px; padding:4px 6px; font:inherit; } diff --git a/backend/performance_runner/keep_awake.py b/backend/performance_runner/keep_awake.py new file mode 100644 index 000000000..e5c9c9258 --- /dev/null +++ b/backend/performance_runner/keep_awake.py @@ -0,0 +1,60 @@ +"""Keep the machine fully active while a long sweep runs. + +A regression sweep takes from half an hour to several hours. If the machine idles into +sleep the backend stalls and the run dies with a connection error halfway through. The +display is held on too, so the screen saver and the lock screen that follows it never start. + +* macOS: ``caffeinate -d -i -w `` prevents display and idle sleep and exits on + its own when this process does, even if this process is killed. +* Windows: ``SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED)`` + holds the system and display on until it is cleared or the process ends. +* Other platforms: nothing (no portable way without wrapping the whole process). + +Closing a laptop lid still sleeps it on both platforms unless it is on power with an +external display; that is an OS rule these calls cannot override. +""" + +from __future__ import annotations + +import atexit +import ctypes +import os +import shutil +import subprocess +import sys +from collections.abc import Callable + +_ES_CONTINUOUS = 0x80000000 +_ES_SYSTEM_REQUIRED = 0x00000001 +_ES_DISPLAY_REQUIRED = 0x00000002 + + +def start() -> None: + """Hold the machine awake until this process exits. Failure only warns: a run that + cannot prevent sleep is still worth running.""" + try: + release = _hold_macos() if sys.platform == "darwin" else _hold_windows() if sys.platform == "win32" else None + except OSError as exc: + print(f"[sanity] could not keep the machine awake ({exc}); disable sleep manually for long runs", + file=sys.stderr) + return + if release is None: + return + atexit.register(release) + print("[sanity] keeping the machine awake while the sweep runs", flush=True) + + +def _hold_macos() -> Callable[[], None]: + if shutil.which("caffeinate") is None: + raise OSError("caffeinate not found") + proc = subprocess.Popen(["caffeinate", "-d", "-i", "-w", str(os.getpid())]) + return proc.terminate + + +def _hold_windows() -> Callable[[], None]: + if sys.platform != "win32": # also tells the type checker that windll exists below + raise OSError("not Windows") + kernel32 = ctypes.windll.kernel32 + if kernel32.SetThreadExecutionState(_ES_CONTINUOUS | _ES_SYSTEM_REQUIRED | _ES_DISPLAY_REQUIRED) == 0: + raise OSError("SetThreadExecutionState failed") + return lambda: kernel32.SetThreadExecutionState(_ES_CONTINUOUS) diff --git a/backend/performance_runner/perf_config.py b/backend/performance_runner/perf_config.py index 2abd83f4b..20aa14de4 100644 --- a/backend/performance_runner/perf_config.py +++ b/backend/performance_runner/perf_config.py @@ -18,6 +18,7 @@ import statistics import subprocess import sys +import threading import time import urllib.request from dataclasses import dataclass @@ -34,6 +35,7 @@ BASE_URL = os.environ.get("PERF_BASE_URL") or f"http://127.0.0.1:{_PORT}" HEALTH_PATH = "/health" # backend/_routes/health.py GPU_INDEX = int(os.environ.get("PERF_GPU_INDEX", "0")) # nvidia-smi index of the 5090 +_MAX_IDLE_POLLS = 5 # consecutive "idle" polls = nothing is running HTTP_TIMEOUT_S = 1800 # a 1080p/20s gen can take minutes # Auth: the backend requires a Bearer token on every request when it's launched @@ -85,6 +87,7 @@ def _app_data_dir() -> Path: # strict=True -> field names and types must match EXACTLY (no extras). # --------------------------------------------------------------------------- # GENERATE_PATH = "/api/generate" # POST, blocks until terminal +CANCEL_PATH = "/api/generate/cancel" # POST, cooperative interrupt STATUS_PATH = "/api/generation/progress" # GET, poll fallback # Default: 540p / 5s "fast" distilled two-stage. The leak accumulates per @@ -157,6 +160,81 @@ def trigger_generation(overrides: dict[str, Any] | None = None) -> str | None: return _poll_until_done() +def cancel_generation() -> Any: + """POST /api/generate/cancel. Empty body.""" + return _post(CANCEL_PATH, {}) + + +def trigger_generation_cancellable( + *, + after_s: float, + payload: dict[str, Any], + path: str = GENERATE_PATH, + wait_timeout_s: float = 120.0, +) -> dict[str, Any]: + """Start a generation on a thread, wait until denoise has started, sleep ``after_s``, + then cancel. Returns the generate response, which must be ``status=cancelled``. + + ``path`` / ``payload`` are the full POST (GenSpace generate, extend, retake, ic-lora); + they share the same cancel and progress endpoints. + + Waits for ``phase=inference``, not merely ``status=running``: the progress endpoint + reports running/starting during reservation and model load, before DiffusionStage + wraps the denoiser. + + Raises if the generate finishes first, inference never starts, cancel is refused, + or the POST errors. + """ + holder: dict[str, Any] = {} + errors: list[BaseException] = [] + + def _run() -> None: + try: + holder["resp"] = _post(path, payload) + except BaseException as exc: # noqa: BLE001 + errors.append(exc) + + thread = threading.Thread(target=_run, daemon=True) + thread.start() + deadline = time.time() + wait_timeout_s + saw_inference = False + try: + while time.time() < deadline: + if errors: + break + if "resp" in holder: + break + try: + st = _get(STATUS_PATH) or {} + except Exception: # noqa: BLE001 + st = {} + if st.get("status") == "running" and st.get("phase") == "inference": + saw_inference = True + break + time.sleep(0.2) + if saw_inference: + time.sleep(after_s) + finally: + # Always cancel + join, including wait-timeout / cancel-POST failure. Otherwise + # the next bump scenario hits a still-running generate (409 or mixed output). + try: + cancel_generation() + except BaseException as exc: # noqa: BLE001 + errors.append(exc) + thread.join(timeout=HTTP_TIMEOUT_S) + if errors: + raise errors[0] + if not saw_inference: + raise RuntimeError( + f"generate never reached phase=inference within {wait_timeout_s:.0f}s " + f"(got {holder.get('resp')!r})" + ) + resp = holder.get("resp") + if not isinstance(resp, dict) or resp.get("status") != "cancelled": + raise RuntimeError(f"expected cancelled generate, got {resp!r}") + return resp + + def set_torch_compile_enabled(enabled: bool) -> None: """Flip AppSettings.use_torch_compile. @@ -192,6 +270,79 @@ def get_settings() -> dict: return _get(SETTINGS_PATH) or {} +# Same endpoints the Settings modal uses: BaseModelSection (ltx-versions / +# active-ltx-model) and Fast decode (useConvVae). Caps come from models-specs +# (GenSpace) plus ltx-ic-lora-recommendation (canny/depth). +_DIFF_VAE_CP = "ltx-2.5-video-vae" +_CONV_VAE_CP = "ltx-2.5-video-vae-conv" + + +def ltx_versions() -> list[dict[str, Any]]: + return (_get("/api/models/ltx-versions") or {}).get("versions") or [] + + +def activate_ltx_model(want: str) -> str: + """Activate by model_id or Settings label ('2.5', '2.3'). Must already be installed.""" + versions = ltx_versions() + match = next((v for v in versions if v.get("model_id") == want or v.get("label") == want), None) + if match is None: + known = ", ".join(str(v.get("label") or v.get("model_id")) for v in versions) or "none" + raise RuntimeError(f"unknown LTX version {want!r} (known: {known})") + if not match.get("installed"): + raise RuntimeError(f"LTX {match.get('label')} is not installed — download it in Settings") + _post("/api/models/active-ltx-model", {"model_id": match["model_id"]}) + return str(match["model_id"]) + + +def described_vaes() -> dict[str, bool]: + """Which 2.5 video VAEs are on disk (POST /api/models/describe).""" + try: + payload = _post("/api/models/describe", {"cp_ids": [_DIFF_VAE_CP, _CONV_VAE_CP]}) + except Exception: # noqa: BLE001 + return {"diff": False, "conv": False} + by_id = { + str(c.get("cp_id")): bool(c.get("downloaded")) + for c in (payload or {}).get("checkpoints") or [] + } + return {"diff": by_id.get(_DIFF_VAE_CP, False), "conv": by_id.get(_CONV_VAE_CP, False)} + + +def set_use_conv_vae(enabled: bool) -> None: + """Fast decode on/off. Same setting as Settings → Fast decode (useConvVae).""" + active = next((v for v in ltx_versions() if v.get("active")), None) + if not str((active or {}).get("model_id") or "").startswith("ltx-2.5"): + raise RuntimeError("Fast decode only applies to LTX 2.5") + vaes = described_vaes() + need, name = ("conv", "conv VAE") if enabled else ("diff", "DiffVAE") + if not vaes.get(need): + raise RuntimeError(f"{name} weights are not downloaded — download them in Settings") + _post(SETTINGS_PATH, {"useConvVae": enabled}) + + +def scenario_caps() -> dict[str, Any] | None: + """Active local offering flags for greying out scenarios the current model cannot run. + + `retake` / `extend` / `ic_lora` come from GET /api/generate/models-specs (same payload + GenSpace uses). Built-in canny/depth is GET /api/models/ltx-ic-lora-recommendation + (`supported`). Unreachable backend → None so the sweep still attempts. + """ + try: + specs = _get("/api/generate/models-specs") or {} + models = specs.get("local_models") or [] + caps = ((models[0].get("spec") or {}).get("capabilities") if models else None) + if not isinstance(caps, dict): + return None + rec = _get("/api/models/ltx-ic-lora-recommendation") or {} + active = next((v for v in ltx_versions() if v.get("active")), None) + return { + **caps, + "builtin_control": bool(rec.get("supported")), + "family": (active or {}).get("label") or (active or {}).get("model_id"), + } + except Exception: # noqa: BLE001 + return None + + _MODELS_DIR: Path | None = None @@ -416,6 +567,10 @@ def wait_for_backend(timeout_s: int = 120) -> None: """Block until /health responds ok.""" deadline = time.time() + timeout_s last = None + auth = "set" if AUTH_TOKEN else "NOT set (PERF_AUTH_TOKEN)" + print(f"[perf] waiting for the backend at {BASE_URL} (auth token {auth}, up to {timeout_s}s). " + "This does not start a backend: run `pnpm perf:dev` or the app first.", flush=True) + next_report = time.time() + 10 while time.time() < deadline: try: h = _get(HEALTH_PATH) @@ -423,6 +578,9 @@ def wait_for_backend(timeout_s: int = 120) -> None: return except Exception as exc: # noqa: BLE001 last = exc + if time.time() >= next_report: + print(f"[perf] still waiting for {BASE_URL}{HEALTH_PATH}: {last}", flush=True) + next_report = time.time() + 10 time.sleep(1.0) raise RuntimeError(f"backend not healthy after {timeout_s}s (last: {last})") @@ -455,10 +613,19 @@ def _poll_until_done(interval_s: float = 1.0) -> str | None: GenerationProgressResponse.status is one of idle|running|complete|cancelled|error; the output (if any) is in `result` (str | list[str] | None). + + Bounded: the caller only polls after the POST returned without an output, so a run + that stays ``idle`` (nothing running, nothing produced) or never finishes is an error, + not something to wait on forever. """ - while True: + deadline = time.time() + HTTP_TIMEOUT_S + idle_polls = 0 + while time.time() < deadline: st = _get(STATUS_PATH) or {} status = st.get("status", "") + idle_polls = idle_polls + 1 if status == "idle" else 0 + if idle_polls >= _MAX_IDLE_POLLS: + raise RuntimeError("generation returned no output and the backend is idle") if status == "complete": result = st.get("result") if isinstance(result, list): @@ -467,3 +634,4 @@ def _poll_until_done(interval_s: float = 1.0) -> str | None: if status in {"error", "cancelled"}: raise RuntimeError(f"generation failed: {st}") time.sleep(interval_s) + raise RuntimeError(f"generation still not finished after {HTTP_TIMEOUT_S}s") diff --git a/backend/performance_runner/queued.py b/backend/performance_runner/queued.py new file mode 100644 index 000000000..8847b4aef --- /dev/null +++ b/backend/performance_runner/queued.py @@ -0,0 +1,125 @@ +"""Driver for the queued generation surface (``/api/generations/...``, Home/Explore). + +The synchronous routes in ``perf_config`` (GenSpace) and this surface share the pipelines +but not the request schemas, input-asset handling, ledger status, cancel/retry, or +job ordering. A scenario with ``queued=[QueuedJob(...)]`` is driven through here instead. + +A job is described by the same intent as its GenSpace twin: ``params`` is the create body's +``params`` (``model`` is filled in from the active LTX version), ``inputs`` maps an input +name (``video``, ``audio``, ``startFrame``, ``endFrame``) to a local file that is ingested +as an asset first. +""" + +from __future__ import annotations + +import time +from dataclasses import dataclass, field +from typing import Any + +import perf_config + +QUEUE_PATH = "/api/generation-queue" +_ACTIVE = {"queued", "running", "cancelling"} +_POLL_S = 1.0 +_WAIT_TIMEOUT_S = 3600.0 +_CANCEL_SETTLE_S = 180.0 # a cancel that has not settled by then is a hang, not a slow job + +_ASSET_IDS: dict[str, str] = {} + + +def reset() -> None: + """Forget ingested assets (a fresh sweep re-registers its inputs).""" + _ASSET_IDS.clear() + + +@dataclass(frozen=True) +class QueuedJob: + route: str + params: dict[str, Any] + inputs: dict[str, str] = field(default_factory=dict) # input name -> local file path + + +def offering_id() -> str: + """The queued ``params.model`` for the active LTX version (Settings → Base model).""" + active = next((v for v in perf_config.ltx_versions() if v.get("active")), {}) + label = f"{active.get('label') or ''} {active.get('model_id') or ''}" + for version, offering in (("2.5", "ltx-2.5-fast"), ("2.3", "ltx-2.3-fast")): + if version in label: + return offering + raise RuntimeError(f"cannot map the active LTX version ({label.strip() or 'none'}) to a queued offering") + + +def _asset_id(path: str) -> str: + if path not in _ASSET_IDS: + _ASSET_IDS[path] = perf_config._post("/api/assets", {"path": path})["id"] + return _ASSET_IDS[path] + + +def request_body(job: QueuedJob) -> dict[str, Any]: + body: dict[str, Any] = {"params": {"model": offering_id(), **job.params}} + if job.inputs: + body["inputs"] = {name: {"assetId": _asset_id(path)} for name, path in job.inputs.items()} + return body + + +def _create(job: QueuedJob) -> str: + return perf_config._post(job.route, request_body(job))["id"] + + +def _wait(generation_id: str, timeout_s: float = _WAIT_TIMEOUT_S) -> dict[str, Any]: + deadline = time.time() + timeout_s + while time.time() < deadline: + generation = perf_config._get(f"/api/generations/{generation_id}") + if generation["status"] not in _ACTIVE: + return generation + time.sleep(_POLL_S) + raise RuntimeError(f"generation {generation_id} still active after {timeout_s:.0f}s") + + +def _output(generation: dict[str, Any]) -> str | None: + if generation["status"] != "succeeded": + raise RuntimeError( + f"generation {generation['id']} {generation['status']} (error_code={generation.get('error_code')})" + ) + outputs = generation.get("outputs") or [] + return outputs[0]["path"] if outputs else None + + +def trigger(jobs: list[QueuedJob]) -> list[str | None]: + """Submit every job first (so several really queue up), then wait for each in order.""" + ids = [_create(job) for job in jobs] + return [_output(_wait(generation_id)) for generation_id in ids] + + +def trigger_cancellable(job: QueuedJob, *, after_s: float, wait_timeout_s: float = 120.0) -> dict[str, Any]: + """Create the job, wait for ``phase=inference``, sleep ``after_s``, cancel via the ledger. + + Returns the final generation, which must be ``cancelled``. The job is always cancelled and + awaited, even when inference never starts, so the next scenario finds an idle queue.""" + generation_id = _create(job) + saw_inference = False + cancel_error: Exception | None = None + try: + deadline = time.time() + wait_timeout_s + while time.time() < deadline: + active = (perf_config._get(QUEUE_PATH) or {}).get("active") or {} + if (active.get("generation") or {}).get("id") == generation_id: + saw_inference = (active.get("progress") or {}).get("phase") == "inference" + if saw_inference: + break + elif perf_config._get(f"/api/generations/{generation_id}")["status"] not in _ACTIVE: + break + time.sleep(0.2) + if saw_inference: + time.sleep(after_s) + finally: + try: + perf_config._post(f"/api/generations/{generation_id}/cancel", {}) + except Exception as exc: # noqa: BLE001 e.g. 409 because the job already finished + cancel_error = exc + final = _wait(generation_id, _CANCEL_SETTLE_S) + if not saw_inference: + raise RuntimeError(f"queued job never reached phase=inference (ended {final['status']})") + if final["status"] != "cancelled": + raise RuntimeError(f"expected cancelled, got {final['status']} (cancel request: {cancel_error or 'accepted'})") + return final diff --git a/backend/performance_runner/regression_queued.py b/backend/performance_runner/regression_queued.py new file mode 100644 index 000000000..cb4a0aff5 --- /dev/null +++ b/backend/performance_runner/regression_queued.py @@ -0,0 +1,113 @@ +"""Queued-surface (Home/Explore, ``/api/generations/...``) twins of the regression suite. + +Same intent, same assertions (``regression_scenarios`` check builders) as the GenSpace +scenarios, but driven through the queue: input files are ingested as assets, the job is +created and polled through the ledger, and cancel goes through ``/generations/{id}/cancel``. +That covers what the synchronous routes cannot: the ``Create*Request`` schemas, the edit +executors, ledger status, and jobs queued back to back. + +Smoke holds one twin per flow (t2v, i2v with an end frame, A2V, extend, retake, a +multi-job batch, cancel). The remaining variants are in ``full`` to keep smoke short. +Queued IC-LoRA and text-to-image have no queued route, so they stay GenSpace-only. +""" + +from __future__ import annotations + +import checks as chk +from queued import QueuedJob +from regression_scenarios import ( + CANCELS, + KEYFRAME_B, + LOW_RES, + PROMPT, + SMALL, + TWO_STAGE, + VIDEO_SILENT, + a2v_checks, + add_regression, + extend_checks, + keyframe_checks, + retake_checks, +) +from scenarios import AUDIO_ASSET, IMAGE_ASSET, VIDEO_ASSET + +_T2V, _I2V, _A2V = "/api/generations/text-to-video", "/api/generations/image-to-video", "/api/generations/audio-to-video" +_EXTEND, _RETAKE = "/api/generations/extend", "/api/generations/retake" +_FULL = ("full",) +_VIDEO_2S = (1.5, 2.6) + + +def _video(size: dict, **params) -> dict: + return {"prompt": PROMPT, "seed": 42, "aspectRatio": "16:9", **size, **params} + + +def _add(key: str, title: str, jobs: list[QueuedJob], checks: list, *, tags: tuple[str, ...], + tiers: tuple[str, ...] = ("smoke",), **kwargs) -> None: + add_regression(key, title, {}, checks, tiers=tiers, tags=("queued", *tags), queued=jobs, **kwargs) + + +def _t2v(size: dict, **params) -> QueuedJob: + return QueuedJob(_T2V, _video(size, **params)) + + +def _i2v(size: dict, end_frame: str | None = None) -> QueuedJob: + inputs = {"startFrame": IMAGE_ASSET, **({"endFrame": end_frame} if end_frame else {})} + return QueuedJob(_I2V, {**_video(size), "prompt": "gentle zoom in", "aspectRatio": "auto"}, inputs) + + +def _a2v(*, with_image: bool = False) -> QueuedJob: + inputs = {"audio": AUDIO_ASSET, **({"startFrame": IMAGE_ASSET} if with_image else {})} + return QueuedJob(_A2V, {"prompt": "a cartoon character telling a joke", "aspectRatio": "16:9", + "resolution": "270p", "fps": 24, "seed": 42}, inputs) + + +def _extend(mode: str) -> QueuedJob: + return QueuedJob(_EXTEND, {"prompt": "the duck flaps its wings and flies away", "duration": 2.0, "mode": mode, + "resolution": LOW_RES, "seed": 42}, {"video": VIDEO_ASSET}) + + +def _retake(mode: str, source: str = VIDEO_ASSET) -> QueuedJob: + return QueuedJob(_RETAKE, {"prompt": "the duck flaps hard and flies right out of the frame", "startTime": 1.0, + "duration": 2.0, "mode": mode, "resolution": LOW_RES, "seed": 42}, {"video": source}) + + +_t2v_checks = [chk.media_ok(duration=_VIDEO_2S), chk.not_dead()] + +# -- smoke: one twin per flow ------------------------------------------------------------- +# Not compared with GenSpace's smoke_t2v_270p: with local text encoding GenSpace rewrites the +# prompt and Explore sends it as typed, so the two surfaces run different prompts. Same-seed +# determinism on this surface is smoke_q_batch_seeds. +_add("smoke_q_t2v_270p", "Queued T2V 270p / 2s", [_t2v(SMALL)], _t2v_checks, tags=("t2v",)) +_add("smoke_q_i2v_end_270p", "Queued I2V 270p with end frame (start and end frames honoured)", + [_i2v(SMALL, end_frame=KEYFRAME_B)], keyframe_checks(), tags=("i2v", "mkf")) +_add("smoke_q_a2v_270p", "Queued A2V 270p (length follows the audio, speech carried)", + [_a2v()], a2v_checks(), tags=("a2v", "speech")) +_add("smoke_q_extend_end", "Queued extend end +2s", [_extend("end")], extend_checks("end"), tags=("extend",), + requires_caps=["extend"]) +_add("smoke_q_retake_av", "Queued retake 1-3s, audio+video", [_retake("replace_audio_and_video")], + retake_checks("replace_audio_and_video"), tags=("retake",), requires_caps=["retake"]) +_add("smoke_q_batch_seeds", "Queued: three t2v jobs submitted together (seed A, B, A)", + [_t2v(SMALL), _t2v(SMALL, seed=43), _t2v(SMALL)], _t2v_checks, tags=("t2v", "batch"), + batch_checks=[chk.seed_batch()]) +_add("smoke_q_cancel_extend", "Queued: cancel an extend through the ledger", + [QueuedJob(_EXTEND, {"prompt": "the duck runs away", "duration": 8.0, "mode": "end", "seed": 42}, + {"video": VIDEO_ASSET})], + [], tags=("cancel", "extend"), requires_caps=["extend"], cancel_after_s=1.5, order=CANCELS) + +# -- full: the remaining variants ----------------------------------------------------------- +_add("full_q_t2v_540p_2s", "Queued T2V 540p / 2s (two-stage path)", [_t2v(TWO_STAGE)], _t2v_checks, + tiers=_FULL, tags=("t2v",)) +_add("full_q_i2v_270p", "Queued I2V 270p (first frame is the image)", [_i2v(SMALL)], + [*_t2v_checks, chk.frame_matches(IMAGE_ASSET, at="first")], tiers=_FULL, tags=("i2v",)) +_add("full_q_i2v_end_540p", "Queued I2V 540p with end frame (two-stage keyframe swap)", + [_i2v(TWO_STAGE, end_frame=KEYFRAME_B)], keyframe_checks(), tiers=_FULL, tags=("i2v", "mkf")) +_add("full_q_ia2v_270p", "Queued image+A2V 270p", [_a2v(with_image=True)], a2v_checks(with_image=True), + tiers=_FULL, tags=("ia2v", "speech")) +_add("full_q_extend_start", "Queued extend start +2s", [_extend("start")], extend_checks("start"), + tiers=_FULL, tags=("extend",), requires_caps=["extend"]) +for _mode, _label in (("replace_video", "video only"), ("replace_audio", "audio only")): + _add(f"full_q_retake_{_mode.removeprefix('replace_')}", f"Queued retake 1-3s, {_label}", [_retake(_mode)], + retake_checks(_mode), tiers=_FULL, tags=("retake",), requires_caps=["retake"]) +_add("full_q_retake_silent_source", "Queued retake 1-3s on a clip with no audio track", + [_retake("replace_audio_and_video", VIDEO_SILENT)], retake_checks("replace_audio_and_video", VIDEO_SILENT), + tiers=_FULL, tags=("retake", "silent"), requires_caps=["retake"]) diff --git a/backend/performance_runner/regression_scenarios.py b/backend/performance_runner/regression_scenarios.py new file mode 100644 index 000000000..c4b775314 --- /dev/null +++ b/backend/performance_runner/regression_scenarios.py @@ -0,0 +1,220 @@ +"""Live regression suite: run by hand after any big change (LTX-2 bump, pipeline or +runtime refactor, dependency upgrade) to confirm every core flow still generates AND +still behaves correctly. Not for CI: it needs real weights, a GPU, and a running backend. + +Tiers (select with ``--tags``, or the dashboard's "regression" buttons): + +* ``smoke`` one small generation per flow and code path, a few minutes each at most. + ``python sanity.py --tags smoke`` +* ``full`` smoke plus the slow scenarios (plain LoRAs, portrait, cancel on every route) + and the existing full-size ``bump`` gate. + ``python sanity.py --tags smoke full bump`` + +Sizes are small on purpose. Local t2v at 270p/360p runs stage 1 only (the skip-stage-2 +path) while 540p and up runs the two-stage pipeline, so smoke covers one of each. Small +canvases hide tiling/VRAM problems; the full-size ``bump`` scenarios are for those. + +Each scenario adds behavioural checks (see ``checks.py``) on top of "the file exists": +keyframes and audio must be honoured, a retake must keep what it was told to keep, and +the same seed must reproduce after all the other flows have run. +""" + +from __future__ import annotations + +import os + +import checks as chk +from scenarios import ( + AUDIO_ASSET, + CP_DEPTH_PROCESSOR, + CP_UNION_CONTROL, + IMAGE_ASSET, + SCENARIOS, + VIDEO_ASSET, + Scenario, + output_exists, + output_nonempty, +) + +_ASSETS = os.path.dirname(IMAGE_ASSET) +KEYFRAME_B = os.path.join(_ASSETS, "reference_keyframe_b.jpg") # a different scene (felt duck) +VIDEO_SILENT = os.path.join(_ASSETS, "reference_video_silent.mp4") # VIDEO_ASSET with no audio stream +VIDEO_2S = os.path.join(_ASSETS, "reference_video_2s.mp4") # first 2 s: cheap IC-LoRA input + +SMALL = {"resolution": "270p", "duration": 2, "fps": 24} # stage-1-only local t2v path +TWO_STAGE = {"resolution": "540p", "duration": 2, "fps": 24} +LOW_RES = {"width": 576, "height": 320} # extend/retake/IC-LoRA output size +PROMPT = "a red sports car driving fast down a city street, camera tracking alongside" +KEYFRAME_LAST = 48 # 2 s @ 24 fps is 49 frames: index 48 is the last +REF = "t2v_270p_seed42" + +# Run positions (Scenario.order): references first, cancels then the reproduction check last. +FIRST, CANCELS, LAST = -10, 5, 10 + + +def add_regression(key: str, title: str, overrides: dict, checks: list, *, tiers: tuple[str, ...] = ("smoke",), + tags: tuple[str, ...] = (), **kwargs) -> None: + cancelling = kwargs.get("cancel_after_s") is not None # a cancelled run has no output to check + SCENARIOS[key] = Scenario( + key, title, overrides, + checks=[] if cancelling else [output_exists, output_nonempty, *checks], + tags=["regression", *tiers, *tags], + **kwargs, + ) + + +def _keyframes(last_image: str) -> list[dict]: + return [ + {"imagePath": IMAGE_ASSET, "frameIndex": 0, "strength": 1.0}, + {"imagePath": last_image, "frameIndex": KEYFRAME_LAST, "strength": 1.0}, + ] + + +def keyframe_checks() -> list: + return [ + chk.media_ok(duration=(1.5, 2.6)), + chk.not_dead(), + chk.frame_matches(IMAGE_ASSET, at="first"), + chk.frame_matches(KEYFRAME_B, at="last"), + ] + + +def a2v_checks(*, with_image: bool = False) -> list: + """Output length follows the audio; the source speech is carried through.""" + checks = [chk.media_ok(audio=True, duration=(4.5, 6.0)), chk.not_dead(), chk.audio_matches(AUDIO_ASSET)] + return [*checks, chk.frame_matches(IMAGE_ASSET, at="first")] if with_image else checks + + +def extend_checks(mode: str) -> list: + """The source clip is kept at the boundary the new footage attaches to.""" + keep = {"at": "first", "reference_at": "first"} if mode == "end" else {"at": "last", "reference_at": "last"} + return [chk.media_ok(audio=True, duration=(6.0, 9.0)), chk.not_dead(), chk.frame_matches(VIDEO_ASSET, **keep)] + + +def retake_checks(mode: str, source: str = VIDEO_ASSET) -> list: + """Whatever the mode leaves alone must match the source: frames outside the window, the + picture for an audio-only retake, the soundtrack for a video-only one.""" + checks = [chk.media_ok(duration=(4.4, 5.7)), chk.not_dead()] + if mode == "replace_video": + return [*checks, chk.media_ok(audio=True), chk.audio_matches(source)] + if mode == "replace_audio": + return [*checks, chk.media_ok(audio=True), chk.frame_matches(source, at=2.0, reference_at=2.0)] + return [*checks, chk.frame_matches(source, at="first"), chk.frame_matches(source, at="last", reference_at="last")] + + +# -- text / image / audio -> video (default route) ------------------------------------- +add_regression("smoke_t2v_270p", "T2V 270p / 2s (stage-1-only path; reference for reproduction)", + {"prompt": PROMPT, "seed": 42, **SMALL}, + [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead(), chk.remember(REF)], + tags=("t2v",), order=FIRST) +add_regression("smoke_t2v_270p_seed_b", "T2V 270p / 2s, different seed (seed is honoured)", + {"prompt": PROMPT, "seed": 43, **SMALL}, + [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead(), chk.differs_from(REF)], + tags=("t2v",), order=FIRST) +add_regression("smoke_lora_t2v", "T2V 270p / 2s with a style LoRA (same request as the reference: adapter changes the video)", + {"prompt": PROMPT, "seed": 42, **SMALL}, + [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead(), chk.differs_from(REF)], + tags=("t2v", "lora"), required_loras=["cozy-felt-style"]) +add_regression("smoke_t2v_540p_2s", "T2V 540p / 2s (two-stage path)", + {"prompt": PROMPT, "seed": 42, **TWO_STAGE}, + [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead()], tags=("t2v",)) +add_regression("smoke_i2v_270p", "I2V 270p / 2s (first frame is the image)", + {"prompt": "gentle zoom in", "seed": 42, "imagePath": IMAGE_ASSET, **SMALL}, + [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead(), chk.frame_matches(IMAGE_ASSET, at="first")], + tags=("i2v",)) +add_regression("smoke_mkf_270p", "Keyframes 270p: first and last frame honoured (stage-1-only swap)", + {"prompt": "a fox and a panda walking through a sunlit forest", "seed": 42, + "keyframes": _keyframes(KEYFRAME_B), **SMALL}, + keyframe_checks(), tags=("mkf",)) +add_regression("smoke_mkf_540p", "Keyframes 540p: first and last frame honoured (two-stage swap)", + {"prompt": "a fox and a panda walking through a sunlit forest", "seed": 42, + "keyframes": _keyframes(KEYFRAME_B), **TWO_STAGE}, + keyframe_checks(), tags=("mkf",)) +add_regression("smoke_a2v_270p", "A2V 270p / 5s (output carries the source speech)", + {"prompt": "a cartoon character telling a joke, talking to camera", "seed": 42, + "audio": True, "audioPath": AUDIO_ASSET, "resolution": "270p", "duration": 5}, + a2v_checks(), tags=("a2v", "speech")) +add_regression("smoke_ia2v_270p", "Image+A2V 270p / 5s (first frame is the image, speech kept)", + {"prompt": "two cartoon animals chatting at a cafe table", "seed": 42, "audio": True, + "imagePath": IMAGE_ASSET, "audioPath": AUDIO_ASSET, "resolution": "270p", "duration": 5}, + a2v_checks(with_image=True), tags=("ia2v", "speech")) + +# -- image ------------------------------------------------------------------------------ +add_regression("smoke_t2i", "Text-to-Image", + {"prompt": "a cozy felt duck in a sunlit room", "width": 1024, "height": 576, "numSteps": 4, "numImages": 1}, + [], route="/api/generate-image", tags=("t2i", "image")) + +# -- extend ----------------------------------------------------------------------------- +_extend = {"video_path": VIDEO_ASSET, "duration": 2.0, "resolution": LOW_RES} +add_regression("smoke_extend_end", "Extend end +2s (source kept at the start)", + {**_extend, "mode": "end", "prompt": "the duck flaps its wings and flies up out of the frame"}, + extend_checks("end"), + route="/api/extend", tags=("extend",), requires_caps=["extend"]) +add_regression("smoke_extend_start", "Extend start +2s (source kept at the end)", + {**_extend, "mode": "start", "prompt": "the felt duck crouches low and springs upward"}, + extend_checks("start"), + route="/api/extend", tags=("extend",), requires_caps=["extend"]) + +# -- retake: every mode, plus a source with no audio track --------------------------------- +def _retake(mode: str, source: str = VIDEO_ASSET) -> dict: + return {"video_path": source, "start_time": 1.0, "duration": 2.0, "mode": mode, + "prompt": "the duck flaps hard and flies right out of the frame", "resolution": LOW_RES} + + +add_regression("smoke_retake_av", "Retake 1-3s, audio+video (frames outside the window kept)", + _retake("replace_audio_and_video"), + retake_checks("replace_audio_and_video"), + route="/api/retake", tags=("retake",), requires_caps=["retake"]) +add_regression("smoke_retake_video_only", "Retake 1-3s, video only (soundtrack untouched)", + _retake("replace_video"), + retake_checks("replace_video"), + route="/api/retake", tags=("retake",), requires_caps=["retake"]) +add_regression("smoke_retake_audio_only", "Retake 1-3s, audio only (picture untouched)", + _retake("replace_audio"), + retake_checks("replace_audio"), + route="/api/retake", tags=("retake",), requires_caps=["retake"]) +add_regression("smoke_retake_silent_source", "Retake 1-3s on a clip with no audio track", + _retake("replace_audio_and_video", VIDEO_SILENT), + retake_checks("replace_audio_and_video", VIDEO_SILENT), + route="/api/retake", tags=("retake", "silent"), requires_caps=["retake"]) + +# -- IC-LoRA ------------------------------------------------------------------------------ +_iclora_checks = [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead()] +add_regression("smoke_iclora_canny", "IC-LoRA canny (2s clip)", + {"conditioning_type": "canny", "video_path": VIDEO_2S, "resolution": LOW_RES, + "prompt": "a glossy yellow rubber duck on a wooden tabletop, warm sunlit kitchen behind, cinematic"}, + _iclora_checks, route="/api/ic-lora/generate", tags=("iclora", "control"), + required_files=[CP_UNION_CONTROL], requires_caps=["builtin_control"]) +add_regression("smoke_iclora_depth", "IC-LoRA depth (2s clip)", + {"conditioning_type": "depth", "video_path": VIDEO_2S, "resolution": LOW_RES, + "prompt": "a green frog on a mossy rock, lush garden foliage in the blurred background"}, + _iclora_checks, route="/api/ic-lora/generate", tags=("iclora", "control"), + required_files=[CP_UNION_CONTROL, CP_DEPTH_PROCESSOR], requires_caps=["builtin_control"]) +add_regression("smoke_iclora_day_to_night", "IC-LoRA day-to-night (2s clip, skip-stage-2 tiled path)", + {"ic_lora_id": "day-to-night", "conditioning_type": "custom", "input_path": VIDEO_2S, + "prompt": "turn day into night", "resolution_factor": 1.0}, + _iclora_checks, route="/api/ic-lora/generate", tags=("iclora", "transform"), + required_ic_loras=["day-to-night"]) + +# -- cancel, then prove the backend recovered --------------------------------------------- +# Cancel targets are large so they can never finish before the cancel lands. The next +# scenario (and finally the reproduction check) proves the backend is usable afterwards. +add_regression("smoke_cancel_extend", "Cancel an extend mid-denoise", + {"video_path": VIDEO_ASSET, "duration": 8.0, "mode": "end", "prompt": "the duck runs away"}, + [], route="/api/extend", tags=("cancel", "extend"), requires_caps=["extend"], + cancel_after_s=1.5, order=CANCELS) +add_regression("full_cancel_a2v", "Cancel an A2V mid-denoise", + {"prompt": "a cartoon character telling a joke", "seed": 42, "audio": True, "audioPath": AUDIO_ASSET, + "resolution": "540p", "duration": 10}, + [], tiers=("full",), tags=("cancel", "a2v"), cancel_after_s=3.0, order=CANCELS + 1) +add_regression("full_cancel_iclora", "Cancel an IC-LoRA mid-denoise", + {"ic_lora_id": "day-to-night", "conditioning_type": "custom", "input_path": VIDEO_ASSET, + "prompt": "turn day into night"}, + [], tiers=("full",), route="/api/ic-lora/generate", tags=("cancel", "iclora"), + required_ic_loras=["day-to-night"], cancel_after_s=3.0, order=CANCELS + 2) + +# -- last: identical request as the first scenario, after every other flow ------------------ +add_regression("smoke_t2v_270p_repeat", "T2V 270p / 2s again (reproduces after all other flows)", + {"prompt": PROMPT, "seed": 42, **SMALL}, + [chk.media_ok(duration=(1.5, 2.6)), chk.not_dead(), chk.reproduces(REF)], + tags=("t2v",), order=LAST) diff --git a/backend/performance_runner/sanity.py b/backend/performance_runner/sanity.py index a8d93e505..7d9a172e3 100644 --- a/backend/performance_runner/sanity.py +++ b/backend/performance_runner/sanity.py @@ -17,6 +17,7 @@ python sanity.py # run all wired scenarios python sanity.py --only t2v_540p_20s i2v python sanity.py --tags modality # run scenarios matching a tag + python sanity.py --tags bump --model-id 2.5 --use-conv-vae --gate-integrity python sanity.py --include-unwired # attempt everything (expect failures) Emits sanity_runs// (index.html + copied media + results.json) and a table. @@ -30,10 +31,14 @@ import os import shutil import statistics +import sys import time from pathlib import Path +import checks +import keep_awake import perf_config +import queued import scenarios as scn from gpu_sampler import GpuSampler @@ -54,6 +59,8 @@ def _fast_overrides(s: scn.Scenario) -> dict: """Scenario overrides with the fast caps applied (leaves the original untouched).""" ov = dict(s.overrides) + if "regression" in s.tags: # already minimal; --fast would inflate 270p/2s to 540p/5s + return ov if s.route is None: # default video route (Literal knobs) ov.update(_FAST_VIDEO) elif s.route in _FAST_DURATION_CAP_ROUTES and isinstance(ov.get("duration"), (int, float)): @@ -83,7 +90,7 @@ def _integrity(payload: dict, probe: dict) -> tuple[bool, str]: return (not issues, "ok" if not issues else ", ".join(issues)) -def run_one(s: scn.Scenario, fast: bool = False) -> dict: +def run_one(s: scn.Scenario, fast: bool = False, gate_integrity: bool = False) -> dict: t0 = time.time() row: dict = {"key": s.key, "title": s.title, "status": "", "wall_s": 0.0, "detail": "", "output": None, "inputs": s.input_paths(), @@ -92,12 +99,34 @@ def run_one(s: scn.Scenario, fast: bool = False) -> dict: overrides = s.build_overrides(_fast_overrides(s) if fast else s.overrides) route = s.route or perf_config.GENERATE_PATH payload = overrides if s.route else {**perf_config.GEN_PAYLOAD_TEMPLATE, **overrides} - print(f"[sanity] request POST {route}") - print(f"[sanity] payload {json.dumps(payload)}") sampler = GpuSampler(hz=5).start() try: + if s.queued: # queued surface: one create body per job (see queued.py) + for job in s.queued: + print(f"[sanity] request POST {job.route} (queued)") + print(f"[sanity] payload {json.dumps(queued.request_body(job))}") + else: + print(f"[sanity] request POST {route}") + print(f"[sanity] payload {json.dumps(payload)}") sampler.mark("start") - out = perf_config.trigger(s.route, overrides) if s.route else perf_config.trigger_generation(overrides) + if s.cancel_after_s is not None: + if s.queued: + resp = queued.trigger_cancellable(s.queued[0], after_s=s.cancel_after_s) + else: + resp = perf_config.trigger_generation_cancellable( + after_s=s.cancel_after_s, payload=payload, path=route + ) + sampler.mark("end") + row["wall_s"] = round(time.time() - t0, 1) + row["status"] = "PASS" + row["detail"] = f"cancelled after {s.cancel_after_s}s running ({resp.get('status')})" + return row + outs: list[str | None] = [] + if s.queued: + outs = queued.trigger(s.queued) + out = outs[-1] + else: + out = perf_config.trigger(s.route, overrides) if s.route else perf_config.trigger_generation(overrides) sampler.mark("end") row["output"] = out row["wall_s"] = round(time.time() - t0, 1) @@ -106,6 +135,10 @@ def run_one(s: scn.Scenario, fast: bool = False) -> dict: ok, msg = chk(out) ok_all = ok_all and ok details.append(f"{chk.__name__}={'ok' if ok else 'FAIL'}({msg})") + for batch_chk in s.batch_checks: + ok, msg = batch_chk(outs) + ok_all = ok_all and ok + details.append(f"{batch_chk.__name__}={'ok' if ok else 'FAIL'}({msg})") wall = row["wall_s"] # Peak VRAM this scenario needed -> which card tier runs it, and how close to OOM. peak = sampler.window_peak("start", "end") @@ -120,9 +153,8 @@ def run_one(s: scn.Scenario, fast: bool = False) -> dict: row["energy_wh"] = round(power * wall / 3600.0, 2) if power else None if row["energy_wh"]: details.append(f"energy={row['energy_wh']}Wh") - # Output: resolution, throughput (video seconds per wall second), and an ADVISORY - # integrity note. Integrity never fails the smoke sweep — a valid file that - # generated PASSES; the note just surfaces any mismatch vs the request. + # Output: resolution, throughput (video seconds per wall second), and an + # integrity note. Integrity is advisory unless --gate-integrity. probe = perf_config.ffprobe_info(out) row["media"] = probe if probe: @@ -130,9 +162,11 @@ def run_one(s: scn.Scenario, fast: bool = False) -> dict: if probe.get("duration") and wall: row["realtime"] = round(probe["duration"] / wall, 2) details.append(f"{row['realtime']}x realtime") - if s.route is None: # default video route: duration/fps/audio are in the request + if s.route is None and not s.queued: # default video route: duration/fps/audio are in the request ok_i, msg_i = _integrity(payload, probe) details.append(f"integrity={'ok' if ok_i else 'DIFF'}({msg_i})") + if gate_integrity and not ok_i: + ok_all = False row["status"] = "PASS" if ok_all else "FAIL" row["detail"] = "; ".join(details) except Exception as exc: # noqa: BLE001 @@ -156,6 +190,14 @@ def _media_tag(rel: str) -> str: return f'{r}' +def _backend_up() -> bool: + try: + perf_config._get("/health") + except Exception: # noqa: BLE001 connection refused, reset, timeout: all mean "not serving" + return False + return True + + def collect_results(rows: list[dict], ts: str) -> Path: """Copy each scenario's input(s) + output into sanity_runs// and write an index.html that shows them side by side. Returns the run folder.""" @@ -238,7 +280,7 @@ def _copy(src: str | None, dest_name: str) -> str | None: {''.join(cards)} """ (run_dir / "index.html").write_text(doc, encoding="utf-8") - with open(run_dir / "results.json", "w") as f: + with open(run_dir / "results.json", "w", encoding="utf-8") as f: json.dump(rows, f, indent=2) return run_dir @@ -251,12 +293,38 @@ def main() -> int: ap.add_argument("--include-unwired", action="store_true") ap.add_argument("--fast", action="store_true", help="cheapest valid knobs (540p/5s) — quick 'does each path run' surface check") + ap.add_argument("--gate-integrity", action="store_true", + help="fail a default-route scenario whose output duration/fps/audio " + "mismatches the request (advisory unless this flag is set)") + ap.add_argument("--model-id", + help="activate an LTX version first (Settings label or model_id, e.g. 2.5); " + "must already be installed") + ap.add_argument("--use-conv-vae", action=argparse.BooleanOptionalAction, default=None, + help="Fast decode on/off (same as Settings); 2.5 only, weights must be on disk") args = ap.parse_args() + # A Windows console is often cp1252: never let a "≥" in a detail string kill the sweep. + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if reconfigure is not None: + reconfigure(errors="replace") + perf_config.wait_for_backend() + try: + if args.model_id: + perf_config.activate_ltx_model(args.model_id) + if args.use_conv_vae is not None: + perf_config.set_use_conv_vae(args.use_conv_vae) + except RuntimeError as exc: + print(f"[sanity] {exc}", file=sys.stderr) + return 1 if args.only: - pool = [scn.SCENARIOS[k] for k in args.only if k in scn.SCENARIOS] + unknown = [k for k in args.only if k not in scn.SCENARIOS] + if unknown: + print(f"[sanity] unknown scenario key(s): {', '.join(unknown)}", file=sys.stderr) + return 1 + pool = [scn.SCENARIOS[k] for k in args.only] elif args.tags: pool = [s for s in scn.all_scenarios() if set(s.tags) & set(args.tags)] elif args.include_unwired: @@ -264,14 +332,38 @@ def main() -> int: else: pool = scn.ready() + if not pool: # an empty selection must never look like a green run + print("[sanity] no scenarios selected (check --only / --tags)", file=sys.stderr) + return 1 + missing_tools = [t for t in ("ffmpeg", "ffprobe") if shutil.which(t) is None] + if missing_tools and any("regression" in s.tags for s in pool): + # Every oracle decodes the output with these; without them the run can only report noise. + print(f"[sanity] {' and '.join(missing_tools)} not on PATH: the regression checks need them. " + "Install ffmpeg (Windows: `winget install Gyan.FFmpeg`, macOS: `brew install ffmpeg`), " + "open a new terminal and re-run.", file=sys.stderr) + return 1 + if not args.only: + pool.sort(key=lambda s: s.order) # stable: registration order within the same position + checks.reset() + queued.reset() + keep_awake.start() # a long sweep must not idle into sleep and kill the backend + ts = time.strftime("%Y%m%d_%H%M%S") rows: list[dict] = [] - for s in pool: + caps = perf_config.scenario_caps() + for pos, s in enumerate(pool): + print(f"[sanity] Running test {pos + 1}/{len(pool)}", flush=True) if s.needs_wiring and not args.include_unwired and not args.only: rows.append({"key": s.key, "title": s.title, "status": "SKIP", "wall_s": 0.0, "detail": "needs_wiring", "output": None, "inputs": s.input_paths()}) print(f"[sanity] SKIP {s.key:<18} (needs wiring)") continue + cap_reason = s.blocked_by_caps(caps) + if cap_reason: + rows.append({"key": s.key, "title": s.title, "status": "SKIP", "wall_s": 0.0, + "detail": cap_reason, "output": None, "inputs": s.input_paths()}) + print(f"[sanity] SKIP {s.key:<18} ({cap_reason})") + continue missing = s.unavailable() if missing: detail = "needs download (open the app → LoRA / IC-LoRA library): " + ", ".join(missing) @@ -280,9 +372,17 @@ def main() -> int: print(f"[sanity] SKIP {s.key:<18} ({detail})") continue print(f"[sanity] run {s.key:<18} ...", flush=True) - row = run_one(s, fast=args.fast) + row = run_one(s, fast=args.fast, gate_integrity=args.gate_integrity) rows.append(row) print(f"[sanity] {row['status']:<5} {s.key:<18} {row['wall_s']:>6.1f}s out={row['output']} {row['detail']}") + if row["status"] == "ERROR" and not _backend_up(): + # A crashed backend (OOM, kill) would otherwise turn every remaining scenario into noise. + print("[sanity] backend unreachable: aborting the sweep", file=sys.stderr) + for rest in pool[pos + 1:]: + rows.append({"key": rest.key, "title": rest.title, "status": "SKIP", "wall_s": 0.0, + "detail": "backend unreachable (crashed earlier in the sweep)", + "output": None, "inputs": rest.input_paths()}) + break run_dir = collect_results(rows, ts) diff --git a/backend/performance_runner/scenarios.py b/backend/performance_runner/scenarios.py index 03ad1f9ec..c68af32be 100644 --- a/backend/performance_runner/scenarios.py +++ b/backend/performance_runner/scenarios.py @@ -14,9 +14,12 @@ from __future__ import annotations import os +import subprocess from dataclasses import dataclass, field from typing import Any, Callable +from queued import QueuedJob + # Bundled fixtures (backend/perf/test_assets) so the modality scenarios are # runnable without hand-supplying media. Absolute paths so they resolve regardless # of backend cwd. @@ -56,6 +59,21 @@ class Scenario: required_ic_loras: list[str] = field(default_factory=list) # Non-catalog weights (relative to models_dir) checked on disk (union-control, depth). required_files: list[str] = field(default_factory=list) + # If set, sanity starts /api/generate then POSTs /api/generate/cancel after this + # many seconds of phase=inference (not merely status=running). PASS = cancelled. + cancel_after_s: float | None = None + # Run position within a sweep (stable sort, default 0). Lets a reference scenario run + # first and a "still reproduces after everything else" scenario run last, regardless + # of registration order. See regression_scenarios.py. + order: int = 0 + # Queued surface (Home/Explore, /api/generations/...): when set, the scenario is driven + # through queued.py instead of `route`/`overrides`. Several jobs are submitted together; + # `checks` run on the last output and `batch_checks` on all outputs (submission order). + queued: list[QueuedJob] | None = None + batch_checks: list[Callable[[list[str | None]], tuple[bool, str]]] = field(default_factory=list) + # Local-offering flags this scenario needs (retake / extend / builtin_control). + # Greyed out when the active LTX family does not offer them. + requires_caps: list[str] = field(default_factory=list) def input_paths(self) -> list[str]: """On-disk input assets referenced by this scenario (for the results viewer).""" @@ -65,6 +83,13 @@ def input_paths(self) -> list[str]: v = self.overrides.get(k) if isinstance(v, str) and os.path.exists(v): out.append(v) + for kf in self.overrides.get("keyframes") or []: + if isinstance(kf, dict): + p = kf.get("imagePath") + if isinstance(p, str) and os.path.exists(p): + out.append(p) + for job in self.queued or []: + out += [p for p in job.inputs.values() if os.path.exists(p) and p not in out] return out def build_overrides(self, base: dict[str, Any]) -> dict[str, Any]: @@ -94,6 +119,20 @@ def unavailable(self) -> list[str]: missing += [rel for rel in self.required_files if not (base / rel).exists()] return missing + def blocked_by_caps(self, caps: dict[str, object] | None) -> str | None: + """Why this scenario cannot run on the active LTX family, or None if ok. + + ``caps`` is ``perf_config.scenario_caps`` (models-specs + IC-LoRA recommendation). + Unreachable backend -> None so the sweep still attempts and surfaces the real error. + """ + if not caps or not self.requires_caps: + return None + family = caps.get("family") or "this model" + for feat in self.requires_caps: + if not caps.get(feat, True): + return f"not supported on LTX {family} ({feat})" + return None + # ---- reusable checks -------------------------------------------------------- # def output_exists(path: str | None) -> tuple[bool, str]: @@ -110,7 +149,50 @@ def output_nonempty(path: str | None) -> tuple[bool, str]: return sz > 1024, f"{sz} bytes" +# E2 signature: a full-width eager K=11 NA tile on MPS silently zeros the last +# several frames. Per-frame mean luma below this (0-255) counts as black. +_BLACK_LUMA_MAX = 8.0 + + +def last_frames_not_black(path: str | None, n_frames: int = 8) -> tuple[bool, str]: + """Fail if any of the last ~n_frames have near-zero luma. + + ``-sseof -1`` seeks one second before EOF; ``-vf reverse,scale=1:1`` then + ``-frames:v n`` takes the true last n frames as 1-byte gray samples (without + reverse, ``-frames:v`` would decode the *first* n frames after the seek). + Missing ffmpeg is a failure — a gate that skips is a false pass. + """ + if not path or not os.path.exists(path): + return False, "no file" + try: + proc = subprocess.run( + [ + "ffmpeg", "-v", "error", "-sseof", "-1", "-i", path, + "-an", "-vf", "reverse,scale=1:1,format=gray", "-frames:v", str(n_frames), + "-f", "rawvideo", "-pix_fmt", "gray", + "pipe:1", + ], + capture_output=True, + timeout=60, + ) + except FileNotFoundError: + return False, "ffmpeg not on PATH" + except subprocess.TimeoutExpired: + return False, "ffmpeg timed out decoding tail frames" + raw = proc.stdout + if proc.returncode != 0 or not raw: + err = (proc.stderr or b"").decode("utf-8", errors="replace")[:200] + return False, f"ffmpeg failed: {err or 'no pixels'}" + # One byte per frame after scale=1:1. Mean-of-all-tail-pixels would pass a + # mostly-bright clip whose last few frames are black. + per_frame = list(raw) + worst = min(per_frame) + ok = worst > _BLACK_LUMA_MAX + return ok, f"tail min luma={worst:.1f} / {len(per_frame)} frames ({'ok' if ok else 'BLACK'})" + + DEFAULT_CHECKS = [output_exists, output_nonempty] +BUMP_VIDEO_CHECKS = [output_exists, output_nonempty, last_frames_not_black] # ---- feature scenarios (seeded from Desktop's surface) ---------------------- # @@ -169,7 +251,10 @@ def _add(s: Scenario) -> None: checks=DEFAULT_CHECKS, tags=["lora", "t2v", "combo"], required_loras=["cozy-felt-style", "openwheel-tcam-style"])) -# IC-LoRA — the streaming stage_2 path exercises the patch's NON-CACHEABLE bypass. +# IC-LoRA. Catalog defaults skip_stage_2; `iclora_stage2_on` (E3) overrides that +# so both stages run. 1.3.0 no longer forces stage 2 onto streaming +# (`use_lora_in_stage_2` is gone). Low-VRAM streaming still hits the cache's +# non-cacheable eviction via `_is_streaming`. # Scoped to what the app actually supports today: # - canny / depth: production control IC-LoRAs (api_types.ConditioningType). # Route: POST /api/extract-conditioning then POST /api/generate (ic_lora.py, @@ -189,7 +274,8 @@ def _add(s: Scenario) -> None: "prompt": "the duck suddenly flaps its wings and flies up out of the frame", "mode": "end"}, route="/api/extend", - checks=DEFAULT_CHECKS, tags=["extend"])) + checks=DEFAULT_CHECKS, tags=["extend"], + requires_caps=["extend"])) # Prepend note: extend(start) must END on the clip's first frame (duck already in # scene, mid-jump), so the generated segment is anchored to a boundary that already # CONTAINS the duck. An "entrance from an empty frame" is physically impossible here — @@ -202,13 +288,15 @@ def _add(s: Scenario) -> None: "springs upward, beginning to jump", "mode": "start"}, route="/api/extend", - checks=DEFAULT_CHECKS, tags=["extend"])) + checks=DEFAULT_CHECKS, tags=["extend"], + requires_caps=["extend"])) _add(Scenario("retake", "Retake / re-roll (2.0–5.0s)", {"video_path": VIDEO_ASSET, "start_time": 2.0, "duration": 3.0, "prompt": "the duck flaps hard and flies right out of the frame", "mode": "replace_audio_and_video"}, route="/api/retake", - checks=DEFAULT_CHECKS, tags=["retake"])) + checks=DEFAULT_CHECKS, tags=["retake"], + requires_caps=["retake"])) # IC-LoRA control (canny/depth): /api/ic-lora/generate re-derives conditioning from # the source video internally. Requires the canny/depth IC-LoRA + depth models to be @@ -225,7 +313,8 @@ def _add(s: Scenario) -> None: "in the background, cozy morning light, cinematic product shot, high detail"}, route="/api/ic-lora/generate", checks=DEFAULT_CHECKS, tags=["iclora", "control"], - required_files=[CP_UNION_CONTROL])) + required_files=[CP_UNION_CONTROL], + requires_caps=["builtin_control"])) _add(Scenario("iclora_depth", "IC-LoRA control: depth", {"conditioning_type": "depth", "video_path": VIDEO_ASSET, "prompt": "a cute green frog hopping across a mossy rock, lush green garden foliage " @@ -233,7 +322,8 @@ def _add(s: Scenario) -> None: "daylight, shallow depth of field, high detail"}, route="/api/ic-lora/generate", checks=DEFAULT_CHECKS, tags=["iclora", "control"], - required_files=[CP_UNION_CONTROL, CP_DEPTH_PROCESSOR])) + required_files=[CP_UNION_CONTROL, CP_DEPTH_PROCESSOR], + requires_caps=["builtin_control"])) # IC-LoRA transformation (catalog): day-to-night. Uses input_path (not video_path); # requires the "day-to-night" IC-LoRA downloaded (else 409 IC_LORA_NOT_DOWNLOADED). @@ -241,12 +331,64 @@ def _add(s: Scenario) -> None: {"ic_lora_id": "day-to-night", "conditioning_type": "custom", "input_path": VIDEO_ASSET, "prompt": "turn day into night"}, route="/api/ic-lora/generate", - checks=DEFAULT_CHECKS, tags=["iclora", "transform"], + checks=DEFAULT_CHECKS, tags=["iclora", "transform", "bump"], required_ic_loras=["day-to-night"])) +# LTX-2 bump gate (`python sanity.py --tags bump --gate-integrity`). E1/E2/E3/cancel/MKF. +# Do NOT run these under --fast: that forces 540p/5s and IC-LoRA resolution_factor=1.0, +# which hides the tiling/VRAM bugs the bump is checking. +_add(Scenario("t2v_540p_8s", "T2V 540p / 8s (E1 decode VRAM)", + {"prompt": "a calm ocean at sunset", "seed": 42, + "resolution": "540p", "duration": 8, "fps": 24}, + checks=BUMP_VIDEO_CHECKS, tags=["t2v", "resolution", "bump", "e1"])) +SCENARIOS["t2v_1080p_5s"].tags.append("bump") +SCENARIOS["t2v_1080p_5s"].tags.append("e1") +SCENARIOS["t2v_1080p_5s"].checks = list(BUMP_VIDEO_CHECKS) + +# 5s @ 24fps = 120 frames. Same still at 0 / mid / last — exercises the Distilled +# guiding-latent swap (distilled_keyframe_guiding), not visual variety. +_add(Scenario("mkf_interpolation", "Multi-keyframe interpolation (guiding swap)", + {"prompt": "a fox and a panda walking through a sunlit forest", + "seed": 42, "resolution": "540p", "duration": 5, "fps": 24, + "keyframes": [ + {"imagePath": IMAGE_ASSET, "frameIndex": 0, "strength": 1.0}, + {"imagePath": IMAGE_ASSET, "frameIndex": 60, "strength": 1.0}, + {"imagePath": IMAGE_ASSET, "frameIndex": 119, "strength": 1.0}, + ]}, + checks=BUMP_VIDEO_CHECKS, tags=["t2v", "mkf", "bump"])) + +# Catalog never sets skip_stage_2=false; E3 needs stage 2 actually running. +_add(Scenario("iclora_stage2_on", "IC-LoRA: Day to Night (stage 2 ON, E3)", + {"ic_lora_id": "day-to-night", "conditioning_type": "custom", + "input_path": VIDEO_ASSET, "prompt": "turn day into night", + "skip_stage_2": False}, + route="/api/ic-lora/generate", + checks=DEFAULT_CHECKS, tags=["iclora", "transform", "bump", "e3"], + required_ic_loras=["day-to-night"])) + +_add(Scenario("cancel_mid_denoise", "Cancel mid-denoise (t2v 540p/8s)", + {"prompt": "a calm ocean at sunset", "seed": 42, + "resolution": "540p", "duration": 8, "fps": 24}, + checks=[], tags=["t2v", "bump", "cancel"], + cancel_after_s=4.0)) + +# Full tier of the live regression suite: existing scenarios worth running after a big +# change but too slow for the smoke tier (plain-LoRA adapters, portrait aspect ratio). +for _key in ("lora_cozy_felt", "lora_cozy_felt_openwheel", "t2v_720p_9x16"): + SCENARIOS[_key].tags.append("full") + +# Registers the smoke/full regression scenarios. Imported last: it needs the names above, +# and importing it first is safe (it imports this module back, which finishes first). +import regression_scenarios # noqa: E402,F401 +import regression_queued # noqa: E402,F401 + + def ready() -> list[Scenario]: - """Scenarios whose payloads are wired (safe to run today).""" - return [s for s in SCENARIOS.values() if not s.needs_wiring] + """Scenarios whose payloads are wired (safe to run today). + + Excludes the regression suite (tag ``regression``): it has its own tiers and would + triple the plain sweep. Run it with ``--tags smoke`` / ``--tags smoke full bump``.""" + return [s for s in SCENARIOS.values() if not s.needs_wiring and "regression" not in s.tags] def all_scenarios() -> list[Scenario]: diff --git a/backend/performance_runner/test_assets/reference_keyframe_b.jpg b/backend/performance_runner/test_assets/reference_keyframe_b.jpg new file mode 100644 index 000000000..c3e4c67de Binary files /dev/null and b/backend/performance_runner/test_assets/reference_keyframe_b.jpg differ diff --git a/backend/performance_runner/test_assets/reference_video_2s.mp4 b/backend/performance_runner/test_assets/reference_video_2s.mp4 new file mode 100644 index 000000000..76a7a1c47 Binary files /dev/null and b/backend/performance_runner/test_assets/reference_video_2s.mp4 differ diff --git a/backend/performance_runner/test_assets/reference_video_silent.mp4 b/backend/performance_runner/test_assets/reference_video_silent.mp4 new file mode 100644 index 000000000..a7a64a01b Binary files /dev/null and b/backend/performance_runner/test_assets/reference_video_silent.mp4 differ diff --git a/backend/pyproject.toml b/backend/pyproject.toml index 7092a1f63..10a7a1824 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -5,6 +5,7 @@ description = "LTX-2 Video Generation Backend" requires-python = ">=3.12" dependencies = [ "pillow>=12.3.0", + "av>=16.1.0", # macOS caps at <2.12: ltx-core imports torchaudio (audio VAE), torchaudio tops out at # 2.11.0 with empty torch metadata, so an uncapped torch resolves to 2.12.1 and the # torchaudio 2.11.0 ABI mismatch crashes `import torchaudio` on Apple Silicon. Pinning @@ -16,17 +17,23 @@ dependencies = [ "torchvision>=0.18.0", "huggingface-hub>=0.23.0", "tqdm>=4.66.0", + # Windows ships no IANA timezone database. ZoneInfo needs this for dashboard ranges. + "tzdata>=2024.1", "pynvml>=11.5.0; sys_platform != 'darwin'", "psutil>=5.9.0", "pydantic>=2.7.0", - # LTX-2 inference dependencies (v1.2.0 is the 2.5-capable release). + # LTX-2 inference dependencies (v1.4.1). # LLM: changing ltx-core / ltx-pipelines version or git tag requires re-checking # every monkey-patch in backend/services/patches/ (imported from ltx2_server.py). # Those rebind private upstream symbols; drop a patch only if upstream now includes # the fix (see each module's "Remove once ..." docstring) and its tests still pass. - "ltx-core==1.2.0", - "ltx-pipelines==1.2.0", + "ltx-core==1.4.1", + "ltx-pipelines==1.4.1", "diffusers>=0.39.0", + # ltx-core 1.4 imports colour-science. Without matplotlib, colour.plotting puts MagicMock + # objects in sys.modules["matplotlib"], and diffusers' importlib.util.find_spec("matplotlib") + # then raises "matplotlib.__spec__ is not set", so the backend dies at startup. + "matplotlib>=3.8", "ftfy>=6.0.0", "imageio>=2.37.2", "imageio-ffmpeg>=0.6.0", @@ -77,23 +84,25 @@ torchvision = [ # Linux keeps resolving sageattention from PyPI (no reported Blackwell crashes there yet). sageattention = { url = "https://github.com/woct0rdho/SageAttention/releases/download/v2.2.0-windows.post5/sageattention-2.2.0+cu128torch2.10.0andhigher.post5-cp310-abi3-win_amd64.whl", marker = "sys_platform == 'win32'" } natten = { url = "https://storage.googleapis.com/ltx-desktop-artifacts/wheels/natten-0.21.6+torch2100cu128-cp313-cp313-win_amd64.whl", marker = "sys_platform == 'win32'" } -# Official LTX-2 v1.2.0 packages (not on PyPI). Same git+subdirectory pattern as -# 2.3; the tag is the 2.5-capable release. We do not take ltx-core's own +# Official LTX-2 v1.4.1 packages (not on PyPI). We do not take ltx-core's own # tool.uv.sources (cu132) — this app's pytorch-cu128 pin above owns torch. +# Do not take ltx-core's natten extra (0.21.7+torch2130cu132 plus torch==2.13.0). # LLM: bumping this tag/version → re-verify backend/services/patches/ (see ltx2_server.py). -ltx-core = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-core", tag = "v1.2.0" } -ltx-pipelines = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-pipelines", tag = "v1.2.0" } +ltx-core = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-core", tag = "v1.4.1" } +ltx-pipelines = { git = "https://github.com/Lightricks/LTX-2.git", subdirectory = "packages/ltx-pipelines", tag = "v1.4.1" } -# v1.2.0's library pyproject pins torch to a cu132 index. Static metadata lets uv +# v1.4.1's library pyproject pins torch to a cu132 index. Static metadata lets uv # resolve without reading that table, so this app's cu128 pin above stays in charge. [[tool.uv.dependency-metadata]] name = "ltx-core" -version = "1.2.0" +version = "1.4.1" requires-dist = [ "torch~=2.7", "torchaudio", + "torchvision", "einops", "numpy", + "colour-science", "av", "transformers>=5.8.0,<5.15", "safetensors", @@ -104,13 +113,21 @@ requires-dist = [ [[tool.uv.dependency-metadata]] name = "ltx-pipelines" -version = "1.2.0" +version = "1.4.1" requires-dist = ["ltx-core", "av", "tqdm", "pillow", "openimageio", "cloudpickle>=3.1"] [project.optional-dependencies] -test = ["pytest>=8.0", "requests>=2.34.2", "httpx>=0.27"] +test = [ + "pytest>=8.0", + "requests>=2.34.2", + "httpx>=0.27", + "pytest-split>=0.11.0", +] dev = ["pyright>=1.1.380", "debugpy>=1.8"] [tool.pytest.ini_options] testpaths = ["tests"] pythonpath = ["."] +markers = [ + "ci_os: needs the real Windows runner. Linux CI runs the full suite; Windows runs only this marker.", +] diff --git a/backend/remote/__init__.py b/backend/remote/__init__.py new file mode 100644 index 000000000..0fb33367e --- /dev/null +++ b/backend/remote/__init__.py @@ -0,0 +1 @@ +"""Isolated remote-facing HTTP surface. Not mounted on the desktop FastAPI app.""" diff --git a/backend/remote/app.py b/backend/remote/app.py new file mode 100644 index 000000000..03769b8e5 --- /dev/null +++ b/backend/remote/app.py @@ -0,0 +1,256 @@ +"""Dark remote FastAPI app. Not mounted on create_app; served on its own port.""" + +from __future__ import annotations + +import re +from collections.abc import Awaitable, Callable +from pathlib import Path +from typing import Any, Literal +from urllib.parse import urlsplit + +from fastapi import FastAPI, Request +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import HTMLResponse, JSONResponse +from fastapi.staticfiles import StaticFiles +from pydantic import BaseModel, ConfigDict +from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.middleware.trustedhost import TrustedHostMiddleware +from starlette.responses import Response as StarletteResponse + +from _routes._errors import HTTPError, build_http_error_response +from _routes.assets import phone_assets_router +from _routes.feature_flags import router as feature_flags_router +from _routes.generation_seed import phone_generation_seed_router +from _routes.stats import phone_stats_router +from _routes.generation import specs_router as generate_specs_router +from api_types import HTTPErrorResponse +from app_handler import AppHandler +from http_exception_handlers import install_http_exception_handlers +from remote.generations import router as generations_router +from remote.hf_auth import router as hf_auth_router +from remote.loras import router as loras_router +from remote.net import lan_ip, remote_port +from remote.pairing import ExchangeRequest, PairingError, RemotePairing +from remote.prompt_enhancement import router as prompt_enhancement_router +from remote.redact import RedactingJSONResponse +from state import get_state_service + +_BYTES_PATH = re.compile(r"^/api/assets/([^/]+)/(?:thumbnail/)?bytes$") +_EXCHANGE_PATH = "/api/pairing/exchange" + +FALLBACK_HTML = """ + +LTX Remote + +

Remote client is not built

+

The API is up. From the repo root run pnpm build:remote, then toggle Remote on again.

+ + +""" + +_ERROR_RESPONSES: dict[int | str, dict[str, Any]] = { + "4XX": {"model": HTTPErrorResponse, "description": "Client Error"}, + "5XX": {"model": HTTPErrorResponse, "description": "Server Error"}, +} + + +class _RemoteHealthResponse(BaseModel): + model_config = ConfigDict(extra="forbid") + + status: Literal["ok"] = "ok" + + +def _is_public_path(path: str) -> bool: + if path == "/health" or path == _EXCHANGE_PATH: + return True + return not path.startswith("/api/") + + +def _unauthorized() -> JSONResponse: + return JSONResponse( + status_code=401, + content=build_http_error_response(401, "Unauthorized").model_dump(), + ) + + +def _forbidden() -> JSONResponse: + return JSONResponse( + status_code=403, + content=build_http_error_response(403, "Forbidden").model_dump(), + ) + + +def _unavailable() -> JSONResponse: + return JSONResponse( + status_code=503, + content=build_http_error_response(503, "STORE_UNAVAILABLE").model_dump(), + ) + + +def _peer_ip(request: Request) -> str | None: + if request.client is None: + return None + return request.client.host + + +def _peer_host(request: Request) -> str: + return _peer_ip(request) or "unknown" + + +def _bearer_token(request: Request) -> str | None: + auth_header = request.headers.get("authorization", "") + if auth_header.startswith("Bearer "): + return auth_header[7:] + return None + + +class SpaStaticFiles(StaticFiles): + """Serve index.html for unknown client routes. Never mask missing /api paths.""" + + async def get_response(self, path: str, scope: Any) -> StarletteResponse: + posix_path = path.replace("\\", "/") + if posix_path == "api" or posix_path.startswith("api/"): + raise StarletteHTTPException(status_code=404) + try: + return await super().get_response(path, scope) + except StarletteHTTPException as exc: + if exc.status_code == 404 and self.html: + return await super().get_response("index.html", scope) + raise + + +def create_remote_app( + *, + handler: AppHandler, + pairing: RemotePairing | None = None, + remote_token: str | None = None, + client_dir: Path | None = None, +) -> FastAPI: + """Remote surface: Bearer sessions on /api, signed query on media bytes.""" + if pairing is None: + if remote_token is None or remote_token == "": + raise ValueError("pairing or remote_token is required") + pairing = RemotePairing.for_known_session(remote_token) + app = FastAPI( + title="LTX Remote", + responses=_ERROR_RESPONSES, + docs_url=None, + redoc_url=None, + openapi_url=None, + default_response_class=RedactingJSONResponse, + ) + app.state.remote_pairing = pairing + app.dependency_overrides[get_state_service] = lambda: handler + port = remote_port() + lan = lan_ip() + app.add_middleware( + CORSMiddleware, + allow_origins=[ + f"http://127.0.0.1:{port}", + f"http://localhost:{port}", + f"http://{lan}:{port}", + ], + allow_methods=["*"], + allow_headers=["*"], + ) + app.add_middleware( + TrustedHostMiddleware, + allowed_hosts=[ + "testserver", + "localhost", + "127.0.0.1", + lan, + ], + ) + + @app.middleware("http") + async def _remote_auth_middleware( # pyright: ignore[reportUnusedFunction] + request: Request, + call_next: Callable[[Request], Awaitable[StarletteResponse]], + ) -> StarletteResponse: + if request.method == "OPTIONS": + return await call_next(request) + if _is_public_path(request.url.path): + return await call_next(request) + bytes_match = _BYTES_PATH.match(request.url.path) + if bytes_match is not None: + if request.query_params.get("t") is not None: + return _unauthorized() + try: + device = pairing.authenticate_media( + request.url.path, + urlsplit(str(request.url)).query, + asset_id=bytes_match.group(1), + ) + except PairingError as exc: + if exc.status_code == 503: + return _unavailable() + raise + if device is None: + if request.query_params.get("sig") is None: + return _unauthorized() + return _forbidden() + request.state.paired_device = device + return await call_next(request) + provided = _bearer_token(request) + if provided is None: + return _unauthorized() + try: + device = pairing.authenticate_bearer( + provided, + ip=_peer_ip(request), + user_agent=request.headers.get("user-agent"), + ) + except PairingError as exc: + if exc.status_code == 503: + return _unavailable() + raise + if device is None: + return _unauthorized() + request.state.paired_device = device + return await call_next(request) + + install_http_exception_handlers(app) + + @app.get("/health", response_model=_RemoteHealthResponse) + def route_health() -> _RemoteHealthResponse: # pyright: ignore[reportUnusedFunction] + return _RemoteHealthResponse() + + @app.get("/api/session", response_model=_RemoteHealthResponse) + def route_session() -> _RemoteHealthResponse: # pyright: ignore[reportUnusedFunction] + return _RemoteHealthResponse() + + @app.post("/api/pairing/exchange") + def route_pairing_exchange( # pyright: ignore[reportUnusedFunction] + body: ExchangeRequest, request: Request + ) -> Any: + client_host = _peer_host(request) + try: + return pairing.exchange( + body.code, + ip=client_host, + user_agent=request.headers.get("user-agent"), + existing_token=_bearer_token(request), + ) + except PairingError as exc: + raise HTTPError(exc.status_code, exc.code) from exc + + app.include_router(generations_router) + app.include_router(phone_stats_router) + app.include_router(phone_generation_seed_router) + app.include_router(generate_specs_router) + app.include_router(phone_assets_router) + app.include_router(loras_router) + app.include_router(hf_auth_router) + app.include_router(feature_flags_router) + app.include_router(prompt_enhancement_router) + + if client_dir is not None and client_dir.is_dir() and (client_dir / "index.html").is_file(): + app.mount("/", SpaStaticFiles(directory=str(client_dir), html=True), name="remote-client") + else: + + @app.get("/", response_class=HTMLResponse, include_in_schema=False) + def _missing_client() -> HTMLResponse: # pyright: ignore[reportUnusedFunction] + return HTMLResponse(FALLBACK_HTML) + + return app diff --git a/backend/remote/controller.py b/backend/remote/controller.py new file mode 100644 index 000000000..461d93de4 --- /dev/null +++ b/backend/remote/controller.py @@ -0,0 +1,336 @@ +"""Start/stop the isolated remote HTTP server when Settings remote is on.""" + +from __future__ import annotations + +import logging +import os +import threading +import time +from dataclasses import dataclass +from typing import TYPE_CHECKING + +from pydantic import BaseModel, ConfigDict + +from logging_policy import log_background_exception +from remote.app import create_remote_app +from remote.net import ENV_AUTH, advertised_lan_urls, bound_server_port, origin_url, remote_port, resolve_client_dir +from remote.pairing import PairedDevicePublic, RemotePairing +from remote.status import RemoteStatusResponse +from state.app_settings import RemoteExposure, remote_is_on + +if TYPE_CHECKING: + from app_handler import AppHandler + import uvicorn + +logger = logging.getLogger(__name__) + +_BIND_WAIT_S = 8.0 +_BIND_POLL_S = 0.05 +_JOIN_TIMEOUT_S = 5.0 +_LAN_BIND_HOST = "0.0.0.0" + + +class AdvertisedEndpoints(BaseModel): + model_config = ConfigDict(frozen=True) + + url: str + local_url: str + lan_url: str + + +@dataclass(frozen=True) +class _Running: + server: uvicorn.Server + thread: threading.Thread + port: int + + +@dataclass(frozen=True) +class _Stopping: + server: uvicorn.Server + thread: threading.Thread + + +class RemoteExposureController: + def __init__(self, handler: AppHandler) -> None: + self._handler = handler + self._lock = threading.Lock() + self._ownership: _Running | _Stopping | None = None + self._exposure: RemoteExposure = "off" + self._last_reason: str = "not started" + self._pairing = RemotePairing.from_app_data(handler.config.app_data_dir) + + def status(self) -> RemoteStatusResponse: + with self._lock: + self._reap_dead_locked() + serving = False + advertised: AdvertisedEndpoints | None = None + match self._ownership: + case _Running(server=server, port=port) if server.started: + serving = True + grant = self._pairing.current_grant() + lan, local = advertised_lan_urls(bound_server_port(server, port), grant) + advertised = AdvertisedEndpoints(url=lan, local_url=local, lan_url=lan) + case _: + pass + exposure = self._exposure + reason = None if serving else self._last_reason + permitted, gate_reason = self._permit() + if not permitted: + return RemoteStatusResponse( + permitted=False, + serving=False, + reason=gate_reason, + mode=exposure, + ) + if not serving or advertised is None: + return RemoteStatusResponse( + permitted=True, + serving=False, + reason=reason, + mode=exposure, + ) + return RemoteStatusResponse( + permitted=True, + serving=True, + url=advertised.url, + localUrl=advertised.local_url, + lanUrl=advertised.lan_url, + mode=exposure, + ) + + def sync(self) -> None: + permitted, reason = self._permit() + exposure = self._handler.settings.get_settings_snapshot().remote_exposure + should_run = permitted and remote_is_on(exposure) + stop_target: _Stopping | None = None + with self._lock: + self._reap_dead_locked() + if isinstance(self._ownership, _Stopping): + if self._ownership.thread.is_alive(): + return + self._finish_stop_locked(self._ownership, reason=self._last_reason) + running = isinstance(self._ownership, _Running) + mode_changed = running and self._exposure != exposure + if should_run and (not running or mode_changed): + if running: + stop_target = self._begin_stop_locked() + else: + self._start_locked() + elif not should_run and running: + stop_target = self._begin_stop_locked() + elif not should_run: + self._exposure = exposure + if not permitted: + self._last_reason = reason + else: + self._last_reason = "disabled in Settings" + if stop_target is None: + return + self._join_stop(stop_target) + with self._lock: + self._finish_stop_locked(stop_target) + self._restart_if_desired_locked() + + def stop(self) -> None: + with self._lock: + stop_target = self._begin_stop_locked() + if stop_target is None: + return + self._join_stop(stop_target) + with self._lock: + self._finish_stop_locked(stop_target) + + def list_devices(self) -> list[PairedDevicePublic]: + return self._pairing.list_public_devices() + + def revoke_device(self, device_id: str) -> bool: + return self._pairing.revoke(device_id) + + def _reap_dead_locked(self) -> None: + match self._ownership: + case _Running(thread=thread) if not thread.is_alive(): + self._last_reason = "remote server stopped unexpectedly" + logger.error("Remote server thread exited") + self._clear_locked() + case _: + return + + def _permit(self) -> tuple[bool, str]: + if not os.environ.get(ENV_AUTH, "").strip(): + return False, "LTX_AUTH_TOKEN is empty" + return True, "" + + def _start_locked(self) -> None: + import uvicorn + + if self._ownership is not None: + return + exposure = self._handler.settings.get_settings_snapshot().remote_exposure + if not remote_is_on(exposure): + self._exposure = exposure + self._last_reason = "disabled in Settings" + return + port = remote_port() + app = create_remote_app( + handler=self._handler, + pairing=self._pairing, + client_dir=resolve_client_dir(), + ) + log_config: dict[str, object] = { + "version": 1, + "disable_existing_loggers": False, + "handlers": { + "default": { + "class": "logging.StreamHandler", + "stream": "ext://sys.stdout", + }, + }, + "loggers": { + "uvicorn": {"handlers": ["default"], "level": "INFO"}, + "uvicorn.error": {"handlers": ["default"], "level": "INFO", "propagate": False}, + "uvicorn.access": {"handlers": ["default"], "level": "INFO", "propagate": False}, + }, + } + config = uvicorn.Config( + app, + host=_LAN_BIND_HOST, + port=port, + log_level="info", + access_log=False, + log_config=log_config, + ) + server = uvicorn.Server(config) + thread = threading.Thread( + target=self._run_server, + args=(server,), + name="ltx-remote", + daemon=True, + ) + self._ownership = _Running(server=server, thread=thread, port=port) + self._exposure = exposure + self._last_reason = "starting" + thread.start() + threading.Thread( + target=self._await_bind, + args=(server, thread, port), + name="ltx-remote-bind", + daemon=True, + ).start() + + def _await_bind(self, server: uvicorn.Server, thread: threading.Thread, port: int) -> None: + deadline = time.monotonic() + _BIND_WAIT_S + while time.monotonic() < deadline: + if server.started: + with self._lock: + owned = self._ownership + if not isinstance(owned, _Running) or owned.server is not server: + return + bound = bound_server_port(server, owned.port) + if bound != owned.port: + self._ownership = _Running( + server=owned.server, thread=owned.thread, port=bound + ) + grant = self._pairing.current_grant() + lan, local = advertised_lan_urls(bound, grant) + logger.info("Remote client listening on %s", origin_url(lan)) + logger.info("Remote client (this machine): %s", origin_url(local)) + return + if not thread.is_alive(): + self._fail_start( + server, + reason="remote server failed to start", + log_msg="Remote server thread exited before bind", + signal_exit=False, + ) + return + time.sleep(_BIND_POLL_S) + self._fail_start( + server, + reason="remote server failed to bind", + log_msg=f"Remote server did not bind on port {port}", + signal_exit=True, + ) + + def _fail_start( + self, + server: uvicorn.Server, + *, + reason: str, + log_msg: str, + signal_exit: bool, + ) -> None: + with self._lock: + owned = self._ownership + if not isinstance(owned, _Running) or owned.server is not server: + return + if signal_exit: + server.should_exit = True + self._last_reason = reason + logger.error(log_msg) + stopping = _Stopping(server=owned.server, thread=owned.thread) + self._ownership = stopping + self._join_stop(stopping) + with self._lock: + if stopping.thread.is_alive(): + return + self._finish_stop_locked(stopping, reason=reason) + + def _run_server(self, server: uvicorn.Server) -> None: + try: + server.run() + except SystemExit: + # uvicorn.Server.startup calls sys.exit(1) on bind failure (EADDRINUSE). + logger.error("Remote server exited during startup") + except Exception as exc: + log_background_exception("ltx-remote", exc) + + def _begin_stop_locked(self) -> _Stopping | None: + match self._ownership: + case _Stopping() as stopping: + return stopping + case None: + self._clear_locked() + self._last_reason = "stopped" + logger.info("Remote client stopped") + return None + case _Running(server=server, thread=thread): + server.should_exit = True + stopping = _Stopping(server=server, thread=thread) + self._ownership = stopping + self._last_reason = "stopped" + return stopping + + def _join_stop(self, target: _Stopping) -> None: + if target.thread.is_alive(): + target.thread.join(timeout=_JOIN_TIMEOUT_S) + + def _finish_stop_locked(self, target: _Stopping, *, reason: str = "stopped") -> None: + match self._ownership: + case _Stopping(server=server, thread=thread) if ( + server is target.server and thread is target.thread + ): + self._clear_locked() + self._last_reason = reason + logger.info("Remote client stopped") + case _: + return + + def _restart_if_desired_locked(self) -> None: + if self._ownership is not None: + return + permitted, _reason = self._permit() + exposure = self._handler.settings.get_settings_snapshot().remote_exposure + if permitted and remote_is_on(exposure): + self._start_locked() + + def _clear_locked(self) -> None: + self._ownership = None + self._exposure = "off" + + +def remote_controller_from_app(app: object) -> RemoteExposureController | None: + controller: object = getattr(getattr(app, "state", None), "remote_controller", None) + if isinstance(controller, RemoteExposureController): + return controller + return None diff --git a/backend/remote/deps.py b/backend/remote/deps.py new file mode 100644 index 000000000..21b50db28 --- /dev/null +++ b/backend/remote/deps.py @@ -0,0 +1,48 @@ +"""Origin-agnostic pairing/session helpers for remote routes.""" + +from __future__ import annotations + +from dataclasses import dataclass + +from fastapi import Request + +from _routes._errors import HTTPError +from api_types import Asset, Generation +from remote.dto import RemoteAsset, RemoteGeneration, to_remote_asset, to_remote_generation +from remote.media_urls import MediaUrlSigner +from remote.pairing import AuthenticatedDevice, RemotePairing + + +@dataclass(frozen=True) +class RemoteContext: + signer: MediaUrlSigner + device: AuthenticatedDevice + + def asset(self, asset: Asset) -> RemoteAsset: + return to_remote_asset(asset, signer=self.signer, device_id=self.device.id) + + def generation(self, generation: Generation) -> RemoteGeneration: + return to_remote_generation( + generation, signer=self.signer, device_id=self.device.id + ) + + +def get_remote_pairing(request: Request) -> RemotePairing: + pairing = getattr(request.app.state, "remote_pairing", None) + if not isinstance(pairing, RemotePairing): + raise HTTPError(500, "PAIRING_UNAVAILABLE") + return pairing + + +def get_paired_device(request: Request) -> AuthenticatedDevice: + device = getattr(request.state, "paired_device", None) + if not isinstance(device, AuthenticatedDevice): + raise HTTPError(401, "Unauthorized") + return device + + +def get_remote_context(request: Request) -> RemoteContext: + return RemoteContext( + signer=get_remote_pairing(request).signer, + device=get_paired_device(request), + ) diff --git a/backend/remote/dto.py b/backend/remote/dto.py new file mode 100644 index 000000000..06465ea7c --- /dev/null +++ b/backend/remote/dto.py @@ -0,0 +1,387 @@ +"""Remote-safe Asset and Generation projections. + +Desktop `Asset`/`Generation` stay the storage and local HTTP contract. The phone +only receives this allowlisted view: no filesystem paths, no LoRA refs, and no +arbitrary stored spec JSON. +""" + +from __future__ import annotations + +from collections.abc import Callable +from typing import cast, get_args + +from pydantic import BaseModel, ConfigDict, Field, JsonValue, field_serializer + +from api_types import ( + Asset, + AssetCore, + ExtendMode, + IcLoraAudioMode, + Generation, + GenerationCore, + QueueEntry, + QueueProgress, + QueueSnapshot, + RetakeMode, +) +from remote.media_urls import MediaUrlSigner + +_SAFE_PARAM_STRINGS = frozenset( + { + "prompt", + "model", + "aspectRatio", + "promptProvenance", + "mode", + "audioMode", + } +) +_REMOTE_AUDIO_MODES = frozenset(get_args(IcLoraAudioMode)) +_SAFE_PARAM_NUMBERS = frozenset({"duration", "fps", "startTime"}) +_REMOTE_MODES = frozenset((*get_args(RetakeMode), *get_args(ExtendMode))) + + +class RemoteAsset(AssetCore): + """Asset identity and metadata without Desktop filesystem paths.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + bytes_url: str = Field(min_length=1) + thumbnail_url: str | None = None + + +class RemoteAssetListItem(RemoteAsset): + in_use: bool + has_thumbnail: bool + + +class RemoteAssetListResponse(BaseModel): + items: list[RemoteAssetListItem] + next_cursor: str | None = None + + +class RemoteInputAssetRef(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + assetId: str = Field(min_length=1) + + +class RemoteTargetResolution(BaseModel): + """Home Retake/Extend target size. Tier ids stay strings.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + width: int = Field(gt=0) + height: int = Field(gt=0) + + +class RemoteVideoParams(BaseModel): + """T2V/I2V/A2V form and result-meta fields only.""" + + model_config = ConfigDict(strict=True, extra="forbid") + + prompt: str | None = None + model: str | None = None + resolution: str | RemoteTargetResolution | None = None + duration: int | float | None = None + fps: int | float | None = None + aspectRatio: str | None = None + promptProvenance: str | None = None + scale: int | float | None = None + numFrames: int | None = None + mode: RetakeMode | ExtendMode | None = None + startTime: int | float | None = None + seed: int | None = None + audioMode: IcLoraAudioMode | None = None + + +class RemoteVideoInputs(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + startFrame: RemoteInputAssetRef | None = None + endFrame: RemoteInputAssetRef | None = None + audio: RemoteInputAssetRef | None = None + video: RemoteInputAssetRef | None = None + image: RemoteInputAssetRef | None = None + + +class RemoteGenerationSpec(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + params: RemoteVideoParams = Field(default_factory=RemoteVideoParams) + inputs: RemoteVideoInputs | None = None + + +class RemoteGeneration(GenerationCore): + model_config = ConfigDict(strict=True, extra="forbid") + + spec: RemoteGenerationSpec + outputs: list[RemoteAsset] + + @field_serializer("spec") + def _serialize_spec(self, spec: RemoteGenerationSpec) -> dict[str, JsonValue]: + return spec.model_dump(mode="json", exclude_none=True) + + +class RemoteQueueEntry(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + generation: RemoteGeneration + input_assets: list[RemoteAsset] + progress: QueueProgress | None = None + + +class RemoteQueueSnapshot(BaseModel): + model_config = ConfigDict(strict=True, extra="forbid") + + active: RemoteQueueEntry | None + queued: list[RemoteQueueEntry] + done: list[RemoteQueueEntry] = Field(default_factory=list[RemoteQueueEntry]) + failed: list[RemoteQueueEntry] = Field(default_factory=list[RemoteQueueEntry]) + unseen_ids: list[str] = Field(default_factory=list[str]) + + +def to_remote_asset( + asset: Asset, *, signer: MediaUrlSigner, device_id: str +) -> RemoteAsset: + thumbnail_url = ( + signer.thumbnail_url(asset.id, device_id) + if asset.thumbnail_path is not None + else None + ) + return RemoteAsset( + id=asset.id, + media_kind=asset.media_kind, + origin=asset.origin, + mime_type=asset.mime_type, + name=asset.name, + metadata=asset.metadata, + created_at=asset.created_at, + bytes_url=signer.bytes_url(asset.id, device_id), + thumbnail_url=thumbnail_url, + ) + + +def to_remote_list_item( + asset: Asset, *, in_use: bool, signer: MediaUrlSigner, device_id: str +) -> RemoteAssetListItem: + projected = to_remote_asset(asset, signer=signer, device_id=device_id) + return RemoteAssetListItem( + **projected.model_dump(), + in_use=in_use, + has_thumbnail=asset.thumbnail_path is not None, + ) + + +def to_remote_generation( + generation: Generation, *, signer: MediaUrlSigner, device_id: str +) -> RemoteGeneration: + return RemoteGeneration( + id=generation.id, + feature=generation.feature, + contract_version=generation.contract_version, + status=generation.status, + spec=project_remote_spec(generation.spec), + error_code=generation.error_code, + created_at=generation.created_at, + queued_at=generation.queued_at, + attempt_count=generation.attempt_count, + started_at=generation.started_at, + finished_at=generation.finished_at, + outputs=[ + to_remote_asset(asset, signer=signer, device_id=device_id) + for asset in generation.outputs + ], + ) + + +def to_remote_queue_entry( + entry: QueueEntry, *, signer: MediaUrlSigner, device_id: str +) -> RemoteQueueEntry: + return RemoteQueueEntry( + generation=to_remote_generation( + entry.generation, signer=signer, device_id=device_id + ), + input_assets=[ + to_remote_asset(asset, signer=signer, device_id=device_id) + for asset in entry.input_assets + ], + progress=entry.progress, + ) + + +def to_remote_queue_snapshot( + snapshot: QueueSnapshot, + *, + signer: MediaUrlSigner, + device_id: str, + feature_is_allowed: Callable[[str], bool], +) -> RemoteQueueSnapshot: + active = snapshot.active + done = [ + to_remote_queue_entry(entry, signer=signer, device_id=device_id) + for entry in snapshot.done + if feature_is_allowed(entry.generation.feature) + ] + visible_done_ids = {entry.generation.id for entry in done} + return RemoteQueueSnapshot( + active=( + to_remote_queue_entry(active, signer=signer, device_id=device_id) + if active is not None and feature_is_allowed(active.generation.feature) + else None + ), + queued=[ + to_remote_queue_entry(entry, signer=signer, device_id=device_id) + for entry in snapshot.queued + if feature_is_allowed(entry.generation.feature) + ], + done=done, + failed=[ + to_remote_queue_entry(entry, signer=signer, device_id=device_id) + for entry in snapshot.failed + if feature_is_allowed(entry.generation.feature) + ], + unseen_ids=[ + generation_id + for generation_id in snapshot.unseen_ids + if generation_id in visible_done_ids + ], + ) + + +def project_remote_spec(spec: dict[str, JsonValue]) -> RemoteGenerationSpec: + return RemoteGenerationSpec( + params=_project_params(spec.get("params")), + inputs=_project_inputs(spec.get("inputs")), + ) + + +def _project_params(value: object) -> RemoteVideoParams: + mapping = _string_mapping(value) + if mapping is None: + return RemoteVideoParams() + strings = { + key: extracted + for key in _SAFE_PARAM_STRINGS + if (extracted := _optional_str(mapping.get(key))) is not None + } + numbers = { + key: extracted + for key in _SAFE_PARAM_NUMBERS + if (extracted := _optional_number(mapping.get(key))) is not None + } + return RemoteVideoParams( + prompt=strings.get("prompt"), + model=strings.get("model"), + resolution=_project_resolution(mapping.get("resolution")), + duration=numbers.get("duration"), + fps=numbers.get("fps"), + aspectRatio=strings.get("aspectRatio"), + promptProvenance=strings.get("promptProvenance"), + scale=_project_lora_scale(mapping.get("loras")), + numFrames=_optional_int(mapping.get("numFrames")), + mode=_project_mode(strings.get("mode")), + startTime=_non_negative_number(numbers.get("startTime")), + seed=_optional_int(mapping.get("seed")), + audioMode=_project_audio_mode(strings.get("audioMode")), + ) + + +def _project_lora_scale(value: object) -> int | float | None: + """Strength from ``loras[0].scale`` (recipes) — the ref itself is never projected.""" + if not isinstance(value, list) or not value: + return None + first = _string_mapping(cast(list[object], value)[0]) + if first is None: + return None + return _optional_number(first.get("scale")) + + +def _project_inputs(value: object) -> RemoteVideoInputs | None: + mapping = _string_mapping(value) + if mapping is None: + return None + start = _input_asset_ref(mapping.get("startFrame")) + end = _input_asset_ref(mapping.get("endFrame")) + audio = _input_asset_ref(mapping.get("audio")) + video = _input_asset_ref(mapping.get("video")) + image = _input_asset_ref(mapping.get("image")) + if all(ref is None for ref in (start, end, audio, video, image)): + return None + return RemoteVideoInputs( + startFrame=start, endFrame=end, audio=audio, video=video, image=image + ) + + +def _input_asset_ref(value: object) -> RemoteInputAssetRef | None: + mapping = _string_mapping(value) + if mapping is None: + return None + asset_id = _optional_str(mapping.get("assetId")) + if asset_id is None or asset_id == "": + return None + if "/" in asset_id or "\\" in asset_id: + return None + return RemoteInputAssetRef(assetId=asset_id) + + +def _string_mapping(value: object) -> dict[str, object] | None: + if not isinstance(value, dict): + return None + return cast(dict[str, object], value) + + +def _project_resolution(value: object) -> str | RemoteTargetResolution | None: + """Tier id (`"720p"`) or a Retake/Extend `{width, height}`. Anything else is dropped.""" + text = _optional_str(value) + if text is not None and text != "": + return text + mapping = _string_mapping(value) + if mapping is None: + return None + width = _positive_int(mapping.get("width")) + height = _positive_int(mapping.get("height")) + if width is None or height is None: + return None + return RemoteTargetResolution(width=width, height=height) + + +def _optional_str(value: object) -> str | None: + return value if isinstance(value, str) else None + + +def _optional_number(value: object) -> int | float | None: + if isinstance(value, bool) or not isinstance(value, int | float): + return None + return value + + +def _non_negative_number(value: int | float | None) -> int | float | None: + if value is None or value < 0: + return None + return value + + +def _project_mode(value: str | None) -> RetakeMode | ExtendMode | None: + if value in _REMOTE_MODES: + return cast(RetakeMode | ExtendMode, value) + return None + + +def _project_audio_mode(value: str | None) -> IcLoraAudioMode | None: + if value in _REMOTE_AUDIO_MODES: + return cast(IcLoraAudioMode, value) + return None + + +def _optional_int(value: object) -> int | None: + if isinstance(value, bool) or not isinstance(value, int): + return None + return value + + +def _positive_int(value: object) -> int | None: + number = _optional_int(value) + if number is None or number <= 0: + return None + return number diff --git a/backend/remote/generations.py b/backend/remote/generations.py new file mode 100644 index 000000000..753e75b1d --- /dev/null +++ b/backend/remote/generations.py @@ -0,0 +1,360 @@ +"""Remote-only generation HTTP surface. + +Desktop generation CRUD stays unfiltered. This module is the remote contract: +only Home/Remote text-to-video, image-to-video, audio-to-video, retake, +extend, and IC-LoRA recipes, plus get/retry/cancel/delete when the generation's feature is in that +allowlist. Recently used uses the same feature set on both apps. +""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, Path, Query + +from _routes._errors import HTTPError +from api_types import ( + CreateAudioToVideoRequest, + CreateIcLoraRecipeRequest, + CreateExtendRequest, + CreateImageToVideoRequest, + CreateLoraRecipeRequest, + CreateRetakeRequest, + CreateTextToVideoRequest, + Generation, + QueueSnapshot, + ReorderGenerationQueueRequest, + StatusResponse, +) +from app_handler import AppHandler +from remote.deps import RemoteContext, get_remote_context +from remote.dto import RemoteGeneration, RemoteQueueSnapshot, to_remote_queue_snapshot +from services.features.queued_features import QUEUED_GENERATION_FEATURES +from state import get_state_service + +# Same set the desktop recents endpoint uses, so Electron and remote agree. +REMOTE_GENERATION_FEATURES = QUEUED_GENERATION_FEATURES + +router = APIRouter(prefix="/api") + + +def _require_remote_feature(feature: str) -> None: + if feature not in REMOTE_GENERATION_FEATURES: + raise HTTPError(404, "GENERATION_NOT_FOUND") + + +def _require_remote_generation(handler: AppHandler, generation_id: str) -> Generation: + generation = handler.queued_generations.get_generation(generation_id) + _require_remote_feature(generation.feature) + return generation + + +def _project_queue(snapshot: QueueSnapshot, remote: RemoteContext) -> RemoteQueueSnapshot: + return to_remote_queue_snapshot( + snapshot, + signer=remote.signer, + device_id=remote.device.id, + feature_is_allowed=REMOTE_GENERATION_FEATURES.__contains__, + ) + + +@router.get( + "/generation-queue", + response_model=RemoteQueueSnapshot, + tags=["generations"], +) +def route_get_generation_queue( + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteQueueSnapshot: + return to_remote_queue_snapshot( + handler.queued_generations.get_queue_snapshot(), + signer=remote.signer, + device_id=remote.device.id, + feature_is_allowed=REMOTE_GENERATION_FEATURES.__contains__, + ) + + +@router.post( + "/generation-queue/reorder", + response_model=RemoteQueueSnapshot, + tags=["generations"], +) +def route_reorder_generation_queue( + req: ReorderGenerationQueueRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteQueueSnapshot: + _require_remote_generation(handler, req.generation_id) + if req.before_generation_id is not None: + _require_remote_generation(handler, req.before_generation_id) + return _project_queue( + handler.queued_generations.reorder_queue( + req.generation_id, req.before_generation_id + ), + remote, + ) + + +@router.post( + "/generation-queue/done/clear", + response_model=RemoteQueueSnapshot, + tags=["generations"], +) +def route_clear_generation_queue_done( + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteQueueSnapshot: + return _project_queue( + handler.queued_generations.clear_done( + feature_is_allowed=REMOTE_GENERATION_FEATURES.__contains__, + ), + remote, + ) + + +@router.post( + "/generation-queue/failed/clear", + response_model=RemoteQueueSnapshot, + tags=["generations"], +) +def route_clear_generation_queue_failed( + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteQueueSnapshot: + return _project_queue( + handler.queued_generations.clear_failed( + feature_is_allowed=REMOTE_GENERATION_FEATURES.__contains__, + ), + remote, + ) + + +@router.post( + "/generation-queue/done/{generation_id}/seen", + response_model=RemoteQueueSnapshot, + tags=["generations"], +) +def route_mark_generation_queue_done_seen( + generation_id: str = Path(min_length=1), + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteQueueSnapshot: + _require_remote_generation(handler, generation_id) + return _project_queue(handler.queued_generations.mark_done_seen(generation_id), remote) + + +@router.post( + "/generation-queue/done/{generation_id}/dismiss", + response_model=RemoteQueueSnapshot, + tags=["generations"], +) +def route_dismiss_generation_queue_done( + generation_id: str = Path(min_length=1), + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteQueueSnapshot: + _require_remote_generation(handler, generation_id) + return _project_queue(handler.queued_generations.dismiss_done(generation_id), remote) + + +@router.post( + "/generations/text-to-video", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_text_to_video( + req: CreateTextToVideoRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_text_to_video( + req, analytics_client="remote" + ) + ) + + +@router.post( + "/generations/image-to-video", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_image_to_video( + req: CreateImageToVideoRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_image_to_video( + req, analytics_client="remote" + ) + ) + + +@router.post( + "/generations/recipes/{recipe_id}", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_lora_recipe( + req: CreateLoraRecipeRequest, + recipe_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + # create_lora_recipe already rejects unknown/unsupported recipe ids with a + # typed 422 before enqueue; the resolved LoRA ref is stripped by the DTO. + return remote.generation( + handler.queued_generations.create_lora_recipe( + recipe_id, req, analytics_client="remote" + ) + ) + + +@router.post( + "/generations/audio-to-video", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_audio_to_video( + req: CreateAudioToVideoRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_audio_to_video( + req, analytics_client="remote" + ) + ) + + +@router.post( + "/generations/retake", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_retake( + req: CreateRetakeRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_retake(req, analytics_client="remote") + ) + + +@router.post( + "/generations/extend", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_extend( + req: CreateExtendRequest, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_extend(req, analytics_client="remote") + ) + + +@router.post( + "/generations/ic-lora-recipes/{recipe_id}", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_create_ic_lora_recipe( + req: CreateIcLoraRecipeRequest, + recipe_id: str = Path(pattern=r"^[a-z0-9-]+$", max_length=64), + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation( + handler.queued_generations.create_ic_lora_recipe( + recipe_id, req, analytics_client="remote" + ) + ) + + +@router.get( + "/generations/recent-features", + response_model=list[str], + tags=["generations"], +) +def route_list_recent_features( + limit: int = Query(default=4, ge=1, le=20), + handler: AppHandler = Depends(get_state_service), + _remote: RemoteContext = Depends(get_remote_context), +) -> list[str]: + return handler.queued_generations.list_recent_features( + limit=limit, + allowed=REMOTE_GENERATION_FEATURES, + ) + + +@router.get( + "/generations", response_model=list[RemoteGeneration], tags=["generations"] +) +def route_list_generations( + feature: str, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> list[RemoteGeneration]: + _require_remote_feature(feature) + return [ + remote.generation(generation) + for generation in handler.queued_generations.list_generations(feature) + ] + + +@router.get( + "/generations/{generation_id}", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_get_generation( + generation_id: str, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + return remote.generation(_require_remote_generation(handler, generation_id)) + + +@router.post( + "/generations/{generation_id}/retry", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_retry_generation( + generation_id: str, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + _require_remote_generation(handler, generation_id) + return remote.generation(handler.queued_generations.retry_generation(generation_id)) + + +@router.post( + "/generations/{generation_id}/cancel", + response_model=RemoteGeneration, + tags=["generations"], +) +def route_cancel_generation( + generation_id: str, + handler: AppHandler = Depends(get_state_service), + remote: RemoteContext = Depends(get_remote_context), +) -> RemoteGeneration: + _require_remote_generation(handler, generation_id) + return remote.generation(handler.queued_generations.cancel_generation(generation_id)) + + +@router.delete( + "/generations/{generation_id}", + response_model=StatusResponse, + tags=["generations"], +) +def route_delete_generation( + generation_id: str, handler: AppHandler = Depends(get_state_service) +) -> StatusResponse: + _require_remote_generation(handler, generation_id) + handler.queued_generations.delete_generation(generation_id) + return StatusResponse(status="ok") diff --git a/backend/remote/hf_auth.py b/backend/remote/hf_auth.py new file mode 100644 index 000000000..e592f7929 --- /dev/null +++ b/backend/remote/hf_auth.py @@ -0,0 +1,42 @@ +"""Remote HuggingFace auth surface: status / login / logout. + +Mirrors ``_routes.hf_auth`` minus the OAuth ``/callback`` (the provider redirect +is handled by the desktop backend). Exposed so gated LoRA recipes can check auth +state from a paired session. Note: the shipped ``cozy-felt`` recipe is ungated +(``requires_hf_login: false``), so this surface is dormant for it today. +""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends + +from api_types import ( + HuggingFaceAuthStatusResponse, + HuggingFaceLoginResponse, + HuggingFaceLogoutResponse, +) +from app_handler import AppHandler +from state import get_state_service + +router = APIRouter(prefix="/api/auth/huggingface", tags=["hf_auth"]) + + +@router.post("/login", response_model=HuggingFaceLoginResponse) +def route_hf_login( + handler: AppHandler = Depends(get_state_service), +) -> HuggingFaceLoginResponse: + return handler.hf_auth.start_login() + + +@router.get("/status", response_model=HuggingFaceAuthStatusResponse) +def route_hf_auth_status( + handler: AppHandler = Depends(get_state_service), +) -> HuggingFaceAuthStatusResponse: + return handler.hf_auth.get_auth_status() + + +@router.post("/logout", response_model=HuggingFaceLogoutResponse) +def route_hf_logout( + handler: AppHandler = Depends(get_state_service), +) -> HuggingFaceLogoutResponse: + return handler.hf_auth.logout() diff --git a/backend/remote/loras.py b/backend/remote/loras.py new file mode 100644 index 000000000..6c30df0f5 --- /dev/null +++ b/backend/remote/loras.py @@ -0,0 +1,76 @@ +"""Remote LoRA-catalog surface: list + download for the recipe preflight. + +Mirrors the plain-LoRA endpoints of ``_routes.lora_catalog``. IC-LoRA downloads +stay on the desktop. The phone only lists IC-LoRAs so a Home feature can tell +whether the weights are already installed. The response models carry no desktop +filesystem paths (only the HF ``repo_id`` and variant filenames), so they are +safe to hand to a paired session. +""" + +from __future__ import annotations + +from fastapi import APIRouter, Depends, Query + +from api_types import ( + ActiveLoraDownloadResponse, + CatalogDownloadStartResponse, + IcLoraListResponse, + LoraDownloadProgressResponse, + LoraDownloadRequest, + LoraListResponse, +) +from app_handler import AppHandler +from state import get_state_service + +router = APIRouter(prefix="/api") + + +@router.get("/ic-loras", response_model=IcLoraListResponse, tags=["ic-loras"]) +def route_list_ic_loras( + handler: AppHandler = Depends(get_state_service), +) -> IcLoraListResponse: + return handler.catalog.list_ic_loras() + + +@router.get("/loras", response_model=LoraListResponse, tags=["loras"]) +def route_list_loras( + handler: AppHandler = Depends(get_state_service), +) -> LoraListResponse: + return handler.catalog.list_loras() + + +@router.post( + "/loras/download", + response_model=CatalogDownloadStartResponse, + tags=["loras"], +) +def route_lora_download( + req: LoraDownloadRequest, + handler: AppHandler = Depends(get_state_service), +) -> CatalogDownloadStartResponse: + return handler.catalog.start_lora_download( + req.lora_id, use_hf_auth=req.use_hf_auth, variant_id=req.variant_id + ) + + +@router.get( + "/loras/download/progress", + response_model=LoraDownloadProgressResponse, + tags=["loras"], +) +def route_lora_download_progress( + sessionId: str = Query(...), + handler: AppHandler = Depends(get_state_service), +) -> LoraDownloadProgressResponse: + return handler.catalog.get_lora_download_progress(sessionId) + + +@router.get( + "/loras/download/active", + response_model=ActiveLoraDownloadResponse, + tags=["loras"], +) +def route_lora_download_active( + handler: AppHandler = Depends(get_state_service), +) -> ActiveLoraDownloadResponse: + return handler.catalog.get_active_lora_download() diff --git a/backend/remote/media_urls.py b/backend/remote/media_urls.py new file mode 100644 index 000000000..c275bac32 --- /dev/null +++ b/backend/remote/media_urls.py @@ -0,0 +1,121 @@ +"""Host-minted HMAC media URLs. Method-agnostic so GET/HEAD/Range share one sig.""" + +from __future__ import annotations + +import base64 +import hmac +import secrets +import time +from hashlib import sha256 +from pathlib import Path +from urllib.parse import parse_qs, urlencode, urlsplit + +MEDIA_TTL_S = 300 +_SECRET_NAME = "remote_media_hmac.key" + + +def load_or_create_media_secret(app_data_dir: Path) -> bytes: + path = app_data_dir / _SECRET_NAME + if path.is_file(): + secret = path.read_bytes() + if len(secret) == 32: + return secret + secret = secrets.token_bytes(32) + path.write_bytes(secret) + return secret + + +def bucket_exp(now_s: int | None = None) -> int: + now = int(time.time() if now_s is None else now_s) + return ((now // MEDIA_TTL_S) + 2) * MEDIA_TTL_S + + +def _b64(data: bytes) -> str: + return base64.urlsafe_b64encode(data).decode("ascii").rstrip("=") + + +def _b64decode(value: str) -> bytes | None: + padded = value + "=" * (-len(value) % 4) + try: + return base64.urlsafe_b64decode(padded.encode("ascii")) + except (ValueError, TypeError): + return None + + +class MediaUrlSigner: + def __init__(self, secret: bytes) -> None: + if len(secret) < 32: + raise ValueError("media HMAC secret must be at least 32 bytes") + self._secret = secret + + def sign(self, path: str, *, asset_id: str, device_id: str, exp: int | None = None) -> str: + expiry = bucket_exp() if exp is None else exp + digest = hmac.new( + self._secret, + _payload(path, expiry, device_id, asset_id), + sha256, + ).digest() + query = urlencode({"exp": expiry, "did": device_id, "sig": _b64(digest)}) + return f"{path}?{query}" + + def bytes_url(self, asset_id: str, device_id: str) -> str: + return self.sign( + f"/api/assets/{asset_id}/bytes", + asset_id=asset_id, + device_id=device_id, + ) + + def thumbnail_url(self, asset_id: str, device_id: str) -> str: + return self.sign( + f"/api/assets/{asset_id}/thumbnail/bytes", + asset_id=asset_id, + device_id=device_id, + ) + + def verify( + self, + path: str, + query: str, + *, + asset_id: str, + now_s: int | None = None, + ) -> str | None: + params = parse_qs(query, keep_blank_values=True) + exp_raw = _one(params, "exp") + device_id = _one(params, "did") + sig_raw = _one(params, "sig") + if exp_raw is None or device_id is None or sig_raw is None: + return None + try: + expiry = int(exp_raw) + except ValueError: + return None + now = int(time.time() if now_s is None else now_s) + if expiry <= now: + return None + provided = _b64decode(sig_raw) + if provided is None: + return None + expected = hmac.new( + self._secret, + _payload(path, expiry, device_id, asset_id), + sha256, + ).digest() + if not hmac.compare_digest(provided, expected): + return None + return device_id + + +def path_without_query(url: str) -> str: + return urlsplit(url).path + + +def _payload(path: str, exp: int, device_id: str, asset_id: str) -> bytes: + return f"{path}\n{exp}\n{device_id}\n{asset_id}".encode("utf-8") + + +def _one(params: dict[str, list[str]], key: str) -> str | None: + values = params.get(key) + if values is None or len(values) != 1 or values[0] == "": + return None + return values[0] diff --git a/backend/remote/net.py b/backend/remote/net.py new file mode 100644 index 000000000..5354fac68 --- /dev/null +++ b/backend/remote/net.py @@ -0,0 +1,112 @@ +"""Env helpers and pairing URLs for the isolated remote server.""" + +from __future__ import annotations + +import os +import socket +from pathlib import Path +from typing import cast +from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit + +from runtime_config.port_constant import REMOTE_PORT + +ENV_PORT = "LTX_REMOTE_PORT" +ENV_CLIENT_DIR = "LTX_REMOTE_CLIENT_DIR" +ENV_AUTH = "LTX_AUTH_TOKEN" +PAIRING_PATH = "/pairing" + + +def remote_port() -> int: + """Configured listen port. + + ``LTX_REMOTE_PORT=0`` is a test hook so the kernel assigns an ephemeral port. + It is not a supported app setting. Unset or invalid values use ``REMOTE_PORT``. + """ + raw = os.environ.get(ENV_PORT, "").strip() + if not raw: + return REMOTE_PORT + try: + parsed = int(raw) + except ValueError: + return REMOTE_PORT + if parsed < 0 or parsed > 65535: + return REMOTE_PORT + return parsed + + +def bound_server_port(server: object, fallback: int) -> int: + """Port uvicorn actually bound, including kernel-assigned ``port=0``.""" + for asyncio_server in getattr(server, "servers", ()) or (): + for sock in getattr(asyncio_server, "sockets", None) or (): + try: + host_port = cast(tuple[object, ...], sock.getsockname()) + except OSError: + continue + if len(host_port) < 2: + continue + port_raw = host_port[1] + if isinstance(port_raw, int) and port_raw > 0: + return port_raw + return fallback + + +def resolve_client_dir() -> Path | None: + env_dir = os.environ.get(ENV_CLIENT_DIR, "").strip() + candidates: list[Path] = [] + if env_dir: + candidates.append(Path(env_dir)) + candidates.append(Path(__file__).resolve().parents[2] / "dist-remote") + for path in candidates: + if path.is_dir() and (path / "index.html").is_file(): + return path + return None + + +def lan_ip() -> str: + sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + try: + sock.connect(("1.1.1.1", 80)) + ip = sock.getsockname()[0] + if isinstance(ip, str) and ip: + return ip + except OSError: + pass + finally: + sock.close() + return "127.0.0.1" + + +def origin_url(url: str) -> str: + """Strip query/fragment so logs never include the pairing grant.""" + parts = urlsplit(url) + path = parts.path if parts.path else "/" + return urlunsplit((parts.scheme, parts.netloc, path, "", "")) + + +def attach_token(base_url: str, token: str) -> str: + """Put the one-time grant in `?t=` so QR codes and Open keep it. + + Fragments (`#t=`) are dropped by many phone scanners and by macOS + `open` / Electron `openExternal`. The remote server disables access + logs; `origin_url` still redacts query from our own logs. + """ + parts = urlsplit(base_url) + query = dict(parse_qsl(parts.query, keep_blank_values=True)) + query["t"] = token + path = parts.path if parts.path else "/" + return urlunsplit((parts.scheme, parts.netloc, path, urlencode(query), parts.fragment)) + + +def client_url(host: str, port: int, token: str, *, scheme: str = "http") -> str: + if scheme == "https" and port == 443: + return attach_token(f"https://{host}{PAIRING_PATH}", token) + if scheme == "http" and port == 80: + return attach_token(f"http://{host}{PAIRING_PATH}", token) + return attach_token(f"{scheme}://{host}:{port}{PAIRING_PATH}", token) + + +def advertised_lan_urls(port: int, token: str) -> tuple[str, str]: + """LAN and loopback pairing URLs, both carrying the generated token.""" + lan = client_url(lan_ip(), port, token) + local = client_url("127.0.0.1", port, token) + return lan, local diff --git a/backend/remote/pairing.py b/backend/remote/pairing.py new file mode 100644 index 000000000..f25c1c87f --- /dev/null +++ b/backend/remote/pairing.py @@ -0,0 +1,496 @@ +"""One-time QR grant exchange and hashed device sessions.""" + +from __future__ import annotations + +import hashlib +import hmac +import ipaddress +import re +import secrets +import threading +import time +import uuid +from dataclasses import dataclass +from pathlib import Path +from typing import Protocol + +from pydantic import BaseModel, ConfigDict, Field + +from remote.media_urls import MediaUrlSigner, load_or_create_media_secret +from services.records import PairedDeviceRecord, UnavailableError +from services.sqlite_store import SqliteStore + +GRANT_TTL_S = 300.0 +_MAX_EXCHANGE_FAILURES = 8 +_FAILURE_WINDOW_S = 60.0 +_TOUCH_MIN_INTERVAL_MS = 60_000 +_MAX_USER_AGENT_LEN = 512 +_DEVICE_NAME_RE = re.compile(r"[\x00-\x1f]+") + + +class PairingError(Exception): + def __init__(self, status_code: int, code: str) -> None: + self.status_code = status_code + self.code = code + super().__init__(code) + + +class PairedDevicePublic(BaseModel): + model_config = ConfigDict(extra="forbid") + + id: str + name: str + created_at: int + last_seen_at: int + ip: str | None = None + revoked_at: int | None = None + + +class ExchangeResponse(BaseModel): + model_config = ConfigDict(extra="forbid") + + device_id: str + token: str + name: str + + +class ExchangeRequest(BaseModel): + model_config = ConfigDict(extra="forbid") + + code: str = Field(min_length=1, max_length=128) + + +class PairedDeviceRepository(Protocol): + def insert_paired_device(self, record: PairedDeviceRecord) -> PairedDeviceRecord: ... + def get_paired_device_by_token_hash( + self, token_hash: str + ) -> PairedDeviceRecord | None: ... + def get_paired_device(self, device_id: str) -> PairedDeviceRecord | None: ... + def list_paired_devices(self) -> list[PairedDeviceRecord]: ... + def revoke_paired_device(self, device_id: str, *, now_ms: int) -> bool: ... + def touch_paired_device( + self, + device_id: str, + *, + now_ms: int | None = None, + ip: str | None = None, + user_agent: str | None = None, + ) -> None: ... + + +def hash_session_token(token: str) -> str: + return hashlib.sha256(token.encode("utf-8")).hexdigest() + + +def device_name_from_user_agent(user_agent: str | None) -> str: + if user_agent is None: + return "Paired device" + cleaned = _DEVICE_NAME_RE.sub(" ", user_agent).strip() + if cleaned == "": + return "Paired device" + if not (cleaned.startswith("Mozilla/") or "AppleWebKit" in cleaned): + return cleaned[:80] + browser = _browser_from_user_agent(cleaned) + platform = _platform_from_user_agent(cleaned) + if browser and platform: + return f"{browser} on {platform}" + if browser: + return browser + if platform: + return platform + return "Paired device" + + +def _platform_from_user_agent(ua: str) -> str | None: + if re.search(r"\biPhone\b", ua, re.I): + return "iPhone" + if re.search(r"\biPad\b", ua, re.I): + return "iPad" + if re.search(r"\bAndroid\b", ua, re.I): + return "Android" + if re.search(r"\bMacintosh\b|\bMac OS X\b", ua, re.I): + return "Mac" + if re.search(r"\bWindows\b", ua, re.I): + return "Windows" + if re.search(r"\bCrOS\b", ua, re.I): + return "Chromebook" + if re.search(r"\bLinux\b", ua, re.I): + return "Linux" + return None + + +def _browser_from_user_agent(ua: str) -> str | None: + if re.search(r"\bEdg(?:e|A|iOS)?/", ua, re.I): + return "Edge" + if re.search(r"\bOPR/|\bOpera/", ua, re.I): + return "Opera" + if re.search(r"\bCriOS/", ua, re.I) or ( + re.search(r"\bChrome/", ua, re.I) and not re.search(r"\bEdg", ua, re.I) + ): + return "Chrome" + if re.search(r"\bFxiOS/", ua, re.I) or re.search(r"\bFirefox/", ua, re.I): + return "Firefox" + if ( + re.search(r"\bSafari/", ua, re.I) + and not re.search(r"\bChrome/", ua, re.I) + and not re.search(r"\bCriOS/", ua, re.I) + ): + return "Safari" + if re.search(r"\biPhone\b|\biPad\b", ua, re.I) and re.search(r"\bAppleWebKit\b", ua, re.I): + return "Safari" + return None + + +class MemoryPairedDeviceStore: + def __init__(self) -> None: + self._by_id: dict[str, PairedDeviceRecord] = {} + self._lock = threading.Lock() + + def insert_paired_device(self, record: PairedDeviceRecord) -> PairedDeviceRecord: + with self._lock: + self._by_id[record.id] = record + return record + + def get_paired_device_by_token_hash( + self, token_hash: str + ) -> PairedDeviceRecord | None: + with self._lock: + for record in self._by_id.values(): + if record.token_hash == token_hash: + return record + return None + + def get_paired_device(self, device_id: str) -> PairedDeviceRecord | None: + with self._lock: + return self._by_id.get(device_id) + + def list_paired_devices(self) -> list[PairedDeviceRecord]: + with self._lock: + return sorted( + self._by_id.values(), + key=lambda record: (-record.created_at, record.id), + ) + + def revoke_paired_device(self, device_id: str, *, now_ms: int) -> bool: + with self._lock: + record = self._by_id.get(device_id) + if record is None or record.revoked_at is not None: + return False + self._by_id[device_id] = record.model_copy(update={"revoked_at": now_ms}) + return True + + def touch_paired_device( + self, + device_id: str, + *, + now_ms: int | None = None, + ip: str | None = None, + user_agent: str | None = None, + ) -> None: + with self._lock: + record = self._by_id.get(device_id) + if record is None or record.revoked_at is not None: + return + updates: dict[str, object] = {} + if now_ms is not None: + updates["last_seen_at"] = now_ms + cleaned_ip = _public_ip(ip) + if cleaned_ip is not None and _public_ip(record.first_seen_ip) is None: + updates["first_seen_ip"] = cleaned_ip + cleaned_ua = _public_user_agent(user_agent) + if cleaned_ua is not None and _public_user_agent(record.first_seen_user_agent) is None: + updates["first_seen_user_agent"] = cleaned_ua + if updates: + self._by_id[device_id] = record.model_copy(update=updates) + + +class PairingGrant: + def __init__(self, *, ttl_s: float = GRANT_TTL_S) -> None: + self._ttl_s = ttl_s + self._lock = threading.Lock() + self._code: str | None = None + self._expires_at = 0.0 + + def issue(self) -> str: + with self._lock: + return self._issue_locked() + + def current(self) -> str: + with self._lock: + if self._code is None or time.monotonic() >= self._expires_at: + return self._issue_locked() + return self._code + + def consume(self, code: str) -> bool: + with self._lock: + current = self._code + if ( + current is None + or time.monotonic() >= self._expires_at + or not hmac.compare_digest(current, code) + ): + return False + self._code = None + self._expires_at = 0.0 + return True + + def _issue_locked(self) -> str: + self._code = secrets.token_urlsafe(32) + self._expires_at = time.monotonic() + self._ttl_s + return self._code + + +class ExchangeLimiter: + def __init__( + self, + *, + max_failures: int = _MAX_EXCHANGE_FAILURES, + window_s: float = _FAILURE_WINDOW_S, + ) -> None: + self._max_failures = max_failures + self._window_s = window_s + self._lock = threading.Lock() + self._failures: dict[str, list[float]] = {} + + def check(self, ip: str) -> None: + with self._lock: + now = time.monotonic() + recent = [stamp for stamp in self._failures.get(ip, []) if now - stamp < self._window_s] + self._failures[ip] = recent + if len(recent) >= self._max_failures: + raise PairingError(429, "PAIRING_RATE_LIMITED") + + def record_failure(self, ip: str) -> None: + with self._lock: + now = time.monotonic() + recent = [stamp for stamp in self._failures.get(ip, []) if now - stamp < self._window_s] + recent.append(now) + self._failures[ip] = recent + + def record_success(self, ip: str) -> None: + with self._lock: + self._failures.pop(ip, None) + + +@dataclass(frozen=True) +class AuthenticatedDevice: + id: str + name: str + + +class RemotePairing: + def __init__( + self, + store: PairedDeviceRepository, + signer: MediaUrlSigner, + *, + grants: PairingGrant | None = None, + limiter: ExchangeLimiter | None = None, + ) -> None: + self._store = store + self.signer = signer + self._grants = grants if grants is not None else PairingGrant() + self._limiter = limiter if limiter is not None else ExchangeLimiter() + + @classmethod + def from_app_data(cls, app_data_dir: Path) -> RemotePairing: + return cls( + SqliteStore(app_data_dir), + MediaUrlSigner(load_or_create_media_secret(app_data_dir)), + ) + + @classmethod + def for_known_session(cls, token: str, *, secret: bytes | None = None) -> RemotePairing: + store = MemoryPairedDeviceStore() + pairing = cls( + store, + MediaUrlSigner(secret if secret is not None else b"t" * 32), + ) + pairing._insert_session(token, name="Test device", ip=None, user_agent=None) + pairing.current_grant() + return pairing + + def current_grant(self) -> str: + return self._grants.current() + + def rotate_grant(self) -> str: + return self._grants.issue() + + def exchange( + self, + code: str, + *, + ip: str, + user_agent: str | None, + existing_token: str | None = None, + ) -> ExchangeResponse: + self._limiter.check(ip) + try: + existing = ( + self._lookup_active_session(existing_token) if existing_token else None + ) + except UnavailableError as exc: + raise PairingError(503, "STORE_UNAVAILABLE") from exc + if not self._grants.consume(code): + self._limiter.record_failure(ip) + raise PairingError(401, "PAIRING_INVALID") + self._limiter.record_success(ip) + if existing is not None: + assert existing_token is not None + self._touch(existing.id, ip=ip, user_agent=user_agent) + self._grants.issue() + return ExchangeResponse( + device_id=existing.id, token=existing_token, name=existing.name + ) + token = secrets.token_urlsafe(32) + try: + cleaned_ua = _public_user_agent(user_agent) + record = self._insert_session( + token, + name=device_name_from_user_agent(cleaned_ua), + ip=ip, + user_agent=cleaned_ua, + ) + except UnavailableError as exc: + raise PairingError(503, "STORE_UNAVAILABLE") from exc + self._grants.issue() + return ExchangeResponse(device_id=record.id, token=token, name=record.name) + + def authenticate_bearer( + self, + token: str, + *, + ip: str | None = None, + user_agent: str | None = None, + ) -> AuthenticatedDevice | None: + try: + record = self._lookup_active_session(token) + except UnavailableError as exc: + raise PairingError(503, "STORE_UNAVAILABLE") from exc + if record is None: + return None + self._touch( + record.id, + last_seen_at=record.last_seen_at, + ip=None if _public_ip(record.first_seen_ip) else ip, + user_agent=( + None if _public_user_agent(record.first_seen_user_agent) else user_agent + ), + ) + return AuthenticatedDevice(id=record.id, name=record.name) + + def authenticate_media( + self, path: str, query: str, *, asset_id: str + ) -> AuthenticatedDevice | None: + device_id = self.signer.verify(path, query, asset_id=asset_id) + if device_id is None: + return None + try: + record = self._store.get_paired_device(device_id) + except UnavailableError as exc: + raise PairingError(503, "STORE_UNAVAILABLE") from exc + if record is None or not _is_active(record): + return None + return AuthenticatedDevice(id=record.id, name=record.name) + + def list_public_devices(self) -> list[PairedDevicePublic]: + records = self._store.list_paired_devices() + return [_to_public(record) for record in records] + + def revoke(self, device_id: str) -> bool: + return self._store.revoke_paired_device(device_id, now_ms=_now_ms()) + + def _insert_session( + self, + token: str, + *, + name: str, + ip: str | None, + user_agent: str | None, + ) -> PairedDeviceRecord: + now = _now_ms() + record = PairedDeviceRecord( + id=str(uuid.uuid4()), + name=name, + token_hash=hash_session_token(token), + created_at=now, + last_seen_at=now, + first_seen_ip=_public_ip(ip), + first_seen_user_agent=_public_user_agent(user_agent), + ) + return self._store.insert_paired_device(record) + + def _lookup_active_session(self, token: str) -> PairedDeviceRecord | None: + record = self._store.get_paired_device_by_token_hash(hash_session_token(token)) + if record is None or not _is_active(record): + return None + return record + + def _touch( + self, + device_id: str, + *, + last_seen_at: int | None = None, + ip: str | None = None, + user_agent: str | None = None, + ) -> None: + now = _now_ms() + skip_last_seen = ( + last_seen_at is not None and now - last_seen_at < _TOUCH_MIN_INTERVAL_MS + ) + cleaned_ip = _public_ip(ip) + cleaned_ua = _public_user_agent(user_agent) + if skip_last_seen and cleaned_ip is None and cleaned_ua is None: + return + try: + self._store.touch_paired_device( + device_id, + now_ms=None if skip_last_seen else now, + ip=cleaned_ip, + user_agent=cleaned_ua, + ) + except UnavailableError: + return + + +def _is_active(record: PairedDeviceRecord) -> bool: + return record.revoked_at is None + + +def _to_public(record: PairedDeviceRecord) -> PairedDevicePublic: + source = record.first_seen_user_agent or record.name + return PairedDevicePublic( + id=record.id, + name=device_name_from_user_agent(source), + created_at=record.created_at, + last_seen_at=record.last_seen_at, + ip=_public_ip(record.first_seen_ip), + revoked_at=record.revoked_at, + ) + + +def _public_ip(ip: str | None) -> str | None: + if ip is None: + return None + cleaned = ip.strip() + if cleaned == "" or cleaned.lower() == "unknown": + return None + if cleaned.startswith("[") and cleaned.endswith("]"): + cleaned = cleaned[1:-1] + try: + return ipaddress.ip_address(cleaned).compressed + except ValueError: + return None + + +def _public_user_agent(user_agent: str | None) -> str | None: + if user_agent is None: + return None + cleaned = _DEVICE_NAME_RE.sub(" ", user_agent).strip() + if cleaned == "": + return None + return cleaned[:_MAX_USER_AGENT_LEN] + + +def _now_ms() -> int: + return int(time.time() * 1000) diff --git a/backend/remote/prompt_enhancement.py b/backend/remote/prompt_enhancement.py new file mode 100644 index 000000000..1b38596d0 --- /dev/null +++ b/backend/remote/prompt_enhancement.py @@ -0,0 +1,102 @@ +"""Remote Explore Enhance: status + prompt rewrite. Asset ids only — no paths.""" + +from __future__ import annotations + +from pathlib import Path +from typing import Literal + +from fastapi import APIRouter, Depends +from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator + +from _routes._errors import HTTPError +from api_types import ( + EnhancePromptRequest, + EnhancePromptResponse, + PromptEnhancerStatusResponse, +) +from app_handler import AppHandler +from services.prompt_enhancement.resolve_enhance_assets import resolve_enhance_image_assets +from state import get_state_service + +router = APIRouter(prefix="/api", tags=["prompt-enhancement"]) + + +class RemoteEnhancePromptRequest(BaseModel): + """Phone Enhance body. Filesystem paths stay off this port.""" + + model_config = ConfigDict(strict=True, extra="forbid") + prompt: str + loraCatalogIds: list[str] = Field(default_factory=list) + imageAssetId: str | None = None + lastImageAssetId: str | None = None + provider: Literal["local", "api"] | None = None + mediaType: Literal["video"] = "video" + + @field_validator("imageAssetId", "lastImageAssetId", mode="before") + @classmethod + def _asset_id_must_be_present_when_set(cls, value: object) -> object: + if value is None: + return None + if not isinstance(value, str): + return value + stripped = value.strip() + if not stripped: + raise ValueError("Asset id cannot be blank") + return stripped + + @model_validator(mode="after") + def _last_frame_needs_first(self) -> RemoteEnhancePromptRequest: + if self.lastImageAssetId and not self.imageAssetId: + raise ValueError("Last frame requires a first-frame image") + if not self.prompt.strip() and not self.imageAssetId: + raise ValueError("Prompt is required unless an image is provided") + return self + + +@router.get("/prompt-enhancer", response_model=PromptEnhancerStatusResponse) +def route_remote_prompt_enhancer( + handler: AppHandler = Depends(get_state_service), +) -> PromptEnhancerStatusResponse: + return handler.prompt_enhancement.status(prefer_gemini=True) + + +def _looks_like_filesystem_path(detail: str) -> bool: + stripped = detail.strip() + if not stripped: + return False + if Path(stripped).is_absolute(): + return True + return "/" in stripped or "\\" in stripped + + +def _sanitize_enhance_http_error(exc: HTTPError) -> HTTPError: + """Keep resolved image paths out of Remote error bodies.""" + if _looks_like_filesystem_path(exc.detail): + return HTTPError(exc.status_code, "ASSET_UNAVAILABLE") + return exc + + +@router.post("/enhance-prompt", response_model=EnhancePromptResponse) +def route_remote_enhance_prompt( + req: RemoteEnhancePromptRequest, + handler: AppHandler = Depends(get_state_service), +) -> EnhancePromptResponse: + provider = req.provider + if provider is None: + provider = handler.prompt_enhancement.status( + prefer_gemini=True + ).defaultProvider + desktop_req = EnhancePromptRequest( + prompt=req.prompt, + loraCatalogIds=req.loraCatalogIds, + imageAssetId=req.imageAssetId, + lastImageAssetId=req.lastImageAssetId, + provider=provider, + mediaType=req.mediaType, + ) + try: + return handler.prompt_enhancement.enhance( + resolve_enhance_image_assets(handler.assets, desktop_req) + ) + except HTTPError as exc: + raise _sanitize_enhance_http_error(exc) from exc diff --git a/backend/remote/redact.py b/backend/remote/redact.py new file mode 100644 index 000000000..c621c8f7c --- /dev/null +++ b/backend/remote/redact.py @@ -0,0 +1,38 @@ +"""Defense-in-depth: strip leftover Asset-shaped filesystem paths from remote JSON. + +Remote Asset/Generation payloads are projected in `remote.dto`. This response +class only rewrites `path` / `thumbnail_path` on objects that still look like a +Desktop Asset (`media_kind` + `id` + `path`). It is not the remote contract. +""" + +from __future__ import annotations + +from typing import Any, cast + +from fastapi.responses import JSONResponse + +_ASSET_PATH_KEYS = frozenset({"path", "thumbnail_path"}) + + +def redact_asset_paths(value: object) -> object: + """Replace `path` / `thumbnail_path` on Asset-shaped objects; recurse otherwise.""" + if isinstance(value, dict): + payload = cast(dict[str, Any], value) + is_asset = "media_kind" in payload and "id" in payload and "path" in payload + redacted: dict[str, object] = {} + for key, inner in payload.items(): + if is_asset and key in _ASSET_PATH_KEYS: + redacted[key] = None if key == "thumbnail_path" else "" + else: + redacted[key] = redact_asset_paths(inner) + return redacted + if isinstance(value, list): + return [redact_asset_paths(item) for item in cast(list[object], value)] + return value + + +class RedactingJSONResponse(JSONResponse): + """Default JSON response for the remote app: never leak Desktop filesystem paths.""" + + def render(self, content: Any) -> bytes: + return super().render(redact_asset_paths(content)) diff --git a/backend/remote/status.py b/backend/remote/status.py new file mode 100644 index 000000000..913a5bbec --- /dev/null +++ b/backend/remote/status.py @@ -0,0 +1,19 @@ +"""Status payload advertised to Desktop Settings.""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict + +from state.app_settings import RemoteExposure + + +class RemoteStatusResponse(BaseModel): + model_config = ConfigDict(extra="forbid") + + permitted: bool + serving: bool + url: str | None = None + localUrl: str | None = None + lanUrl: str | None = None + reason: str | None = None + mode: RemoteExposure | None = None diff --git a/backend/runtime_config/grid_fit.py b/backend/runtime_config/grid_fit.py new file mode 100644 index 000000000..fd1bc0bf4 --- /dev/null +++ b/backend/runtime_config/grid_fit.py @@ -0,0 +1,34 @@ +"""Aspect-preserving fit of a source size into a box, on a pixel grid.""" + +from __future__ import annotations + +# The grid can force a shape error: 1280x720 has no 64-grid size with the same aspect +# that is not smaller than 1280x704 (2.3% off). Accept a size up to 3% off. +_ASPECT_TOLERANCE = 0.03 + + +def fit_in_box(width: int, height: int, box_width: int, box_height: int, grid: int) -> tuple[int, int]: + """Largest grid size inside the box and inside the source, close to the source aspect. + + The result never has an edge above the box or above the source, so it never + upscales. Each grid size inside that limit has an aspect error against the source. + The largest area wins among sizes within 3% of the source aspect. If the grid leaves + none within 3%, the smallest error wins. A limit below one grid cell gives one cell: + the minimum canvas, the same floor that the other two-stage recipes have. + """ + limit_width = min(width, box_width) + limit_height = min(height, box_height) + aspect = width / height + sizes = [ + (candidate_w, candidate_h) + for candidate_w in range(grid, max(grid, limit_width // grid * grid) + 1, grid) + for candidate_h in range(grid, max(grid, limit_height // grid * grid) + 1, grid) + ] + + def aspect_error(size: tuple[int, int]) -> float: + return abs(size[0] / size[1] - aspect) / aspect + + close = [size for size in sizes if aspect_error(size) <= _ASPECT_TOLERANCE] + if close: + return max(close, key=lambda size: (size[0] * size[1], -aspect_error(size))) + return min(sizes, key=lambda size: (aspect_error(size), -size[0] * size[1])) diff --git a/backend/runtime_config/ic_lora_chunking.py b/backend/runtime_config/ic_lora_chunking.py new file mode 100644 index 000000000..718abf1e3 --- /dev/null +++ b/backend/runtime_config/ic_lora_chunking.py @@ -0,0 +1,75 @@ +"""IC-LoRA temporal chunking rule, read by the job budget. + +A large job runs in overlapping windows (ltx-pipelines ``ChunkConfig``), so memory +follows the window, not the clip. The rule sizes the heaviest pass that carries the +IC-LoRA reference: stage 1 for a single-stage job, the stage-2 canvas for a recipe that +keeps the IC-LoRA on stage 2. A two-stage job without the IC-LoRA on stage 2 never +chunks. The rule fires only above the former 1024x576 size and past the largest +one-window token count with a measured pass. A chunked run is not measured yet. + +The job budget (``decide_ic_lora_job``) also chunks a job that may chunk but does not fit +unchunked. It is the one place that decides. The pipeline receives the window it returns. +""" + +from __future__ import annotations + +from frame_math import snap_to_frame_grid +from runtime_config.ic_lora_stage_mode import IcLoraStageMode, heavy_pass_size +from runtime_config.ic_lora_tiling import IcLoraTiling, transformer_pass_size +from runtime_config.video_job_budget import video_tokens + +# ltx-pipelines default layout: 97-frame windows, 25-frame carry. +IC_LORA_CHUNK_PIXEL_FRAMES = 97 +IC_LORA_CHUNK_CARRY_FRAMES = 25 + +_FORMER_CAP_PIXELS = 1024 * 576 +IC_LORA_MAX_SINGLE_WINDOW_TOKENS = 32_940 + + +def ic_lora_may_chunk( + stage1_width: int, + stage1_height: int, + frames: int, + *, + stage_mode: IcLoraStageMode, + tiling: IcLoraTiling | None = None, +) -> bool: + """True when a job may run chunked: a layout that chunks, a heavy pass above the + former 1024x576 size, and a clip longer than one window. + + A tiled job sizes the pass by its tile, not by the canvas. + + A two-stage job without the IC-LoRA on stage 2 never chunks. The clip length is + counted in latent frames, so a count off the 8k+1 grid (123) acts like the grid + count below it (121). + """ + if stage_mode is IcLoraStageMode.STAGE_1_LORA: + return False + if snap_to_frame_grid(frames, floor=1) <= IC_LORA_CHUNK_PIXEL_FRAMES: + return False + width, height = transformer_pass_size(*heavy_pass_size(stage_mode, stage1_width, stage1_height), tiling) + return width * height > _FORMER_CAP_PIXELS + + +def ic_lora_chunk_pixel_frames( + stage1_width: int, + stage1_height: int, + frames: int, + *, + stage_mode: IcLoraStageMode, + tiling: IcLoraTiling | None = None, +) -> int | None: + """Window length in pixel frames when a rule says chunk, else None. + + A LoRA with a fixed window (``IcLoraTiling.window_frames``) chunks every clip longer + than that window, whatever its size. Otherwise the size and token rule decides. + """ + if tiling is not None and tiling.window_frames is not None: + if snap_to_frame_grid(frames, floor=1) > tiling.window_frames: + return tiling.window_frames + if not ic_lora_may_chunk(stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling): + return None + width, height = transformer_pass_size(*heavy_pass_size(stage_mode, stage1_width, stage1_height), tiling) + if video_tokens(height, width, snap_to_frame_grid(frames, floor=1)) <= IC_LORA_MAX_SINGLE_WINDOW_TOKENS: + return None + return IC_LORA_CHUNK_PIXEL_FRAMES diff --git a/backend/runtime_config/ic_lora_job_budget.py b/backend/runtime_config/ic_lora_job_budget.py new file mode 100644 index 000000000..de93ce634 --- /dev/null +++ b/backend/runtime_config/ic_lora_job_budget.py @@ -0,0 +1,344 @@ +"""IC-LoRA job budget: reference-append tokens ×2, plus measured spatial No.""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Literal + +from api_types import REFERENCE_STILL_FRAME_IDX, IcLoraCatalogItem, IcLoraControl, IcLoraSettings +from frame_math import compute_num_frames +from runtime_config.ic_lora_chunking import ( + IC_LORA_CHUNK_PIXEL_FRAMES, + ic_lora_chunk_pixel_frames, + ic_lora_may_chunk, +) +from runtime_config.ic_lora_local_envelope import ( + effective_denoise_stage1, + ic_lora_output_canvas, + over_spatial_cap, +) +from runtime_config.ic_lora_stage_mode import IcLoraStageMode, heavy_pass_size +from runtime_config.ic_lora_tiling import IcLoraTiling, transformer_pass_size +from runtime_config.runtime_policy import LocalGenerationMode +from runtime_config.video_job_budget import ( + LoadMode, + VideoJobReject, + decide_load_mode, + estimated_giB, + video_tokens, +) + +# Compat-matrix preview of a Home IC-LoRA job. Home runs entries that skip stage 2 and +# entries that keep the IC-LoRA on stage 2 (Layout To Render). This preview is the +# single-stage case, the lightest one. resolution_factor is not a Home control; 1.5 is +# the catalog preview bucket this estimate has always used. +HOME_IC_LORA_PREVIEW_SETTINGS = IcLoraSettings(skip_stage_2=True, resolution_factor=1.5) + +# Fast full-vs-stream headroom is 2 GiB. IC-LoRA 5s 540p full ~22.5 GiB is OK; +# 8s/10s Ingredients paged on a 5090 while the linear full estimate (~25–26 GiB) +# still fit 29 usable. 7 GiB so 8s+ streams without changing the stream-over 422. +# 8s/540p vs 32−7=25.0 usable is a ~0.03 GiB miss by design — do not round this +# to 6 or 8 without re-measuring; 6 would full-load and page, 8 would stream 5s. +_IC_LORA_FULL_HEADROOM_GIB = 7.0 + +# List-time duration filter has no user image. skip_stage_2: 9:16 768×1280 through +# the 768 bucket × factor 1.5 is stage-1 576×960 (Ingredients default). Two-stage +# sizes to the user's source, so preview a local 1080p sheet or the filter is +# optimistic (~8 GiB under a real 1080p two-stage 20s). +_CATALOG_PREVIEW_SKIP_STAGE2_WIDTH = 768 +_CATALOG_PREVIEW_SKIP_STAGE2_HEIGHT = 1280 +_CATALOG_PREVIEW_TWO_STAGE_WIDTH = 1920 +_CATALOG_PREVIEW_TWO_STAGE_HEIGHT = 1088 + +_DEFAULT_IC_LORA_FPS = 24 + + +@dataclass(frozen=True, slots=True) +class IcLoraJobLoad: + mode: LoadMode + seq: float + full_gib: float + stream_gib: float + # Window length when the job runs chunked, else None. The pipeline runs this value. + chunk_pixel_frames: int | None = None + + +@dataclass(frozen=True, slots=True) +class IcLoraJobReject: + reason: Literal["spatial", "stream_over", "unsupported"] + seq: float + full_gib: float + stream_gib: float + + +IcLoraJobDecision = IcLoraJobLoad | IcLoraJobReject + + +def ic_lora_sequence_tokens(width: int, height: int, frames: int) -> float: + """Video tokens plus the appended reference clip (same H×W×frames).""" + return video_tokens(height, width, frames) * 2.0 + + +def _heaviest_pass_tokens( + stage_mode: IcLoraStageMode, + stage1_width: int, + stage1_height: int, + frames: int, + stills: int, + tiling: IcLoraTiling | None, +) -> float: + """Tokens of the heaviest pass of the job. + + Stage 2 of a STAGE_1_LORA job has no reference, but it runs at twice the stage-1 + size. That is four times the stage-1 tokens, so it is heavier than stage 1 with its + reference (two times). The other layouts carry the reference in their largest pass. + Each reference still adds one latent frame of tokens to that pass. A STAGE_1_LORA job + takes no still. + + A tiled job (single stage) runs the transformer on one tile at a time. Its pass is the + tile, with the reference cropped to the same tile. + """ + width, height = transformer_pass_size(*heavy_pass_size(stage_mode, stage1_width, stage1_height), tiling) + if stage_mode is IcLoraStageMode.STAGE_1_LORA: + return max( + video_tokens(height, width, frames), + ic_lora_sequence_tokens(stage1_width, stage1_height, frames), + ) + still_tokens = stills * (height / 32.0) * (width / 32.0) + return ic_lora_sequence_tokens(width, height, frames) + still_tokens + + +def decide_ic_lora_job( + stage1_width: int, + stage1_height: int, + frames: int, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + stage_mode: IcLoraStageMode, + darwin: bool = False, + stills: int = 0, + tiling: IcLoraTiling | None = None, +) -> IcLoraJobDecision: + """422 definite-over jobs; per-job stream when full will not fit. + + ``stage_mode`` sets the heaviest pass (``heavy_pass_size``). That pass sets the priced + token count, the chunk rule and the spatial cap. The spatial cap checks the output + size, so a two-stage job is capped at its stage-2 canvas, not at stage 1. + + This is the one place that decides chunking. A job chunks when the size and token + rule says so, or when it may chunk and does not fit unchunked. + ``IcLoraJobLoad.chunk_pixel_frames`` carries the decision to the pipeline. + + ``stills`` is the number of reference stills. Each adds one latent frame of tokens to + each window, so a chunked job pays for it once per window. + + ``tiling`` sizes the priced pass by the tile. The spatial cap still checks the output + size, so a tiled job is capped like any other. + + Darwin and stream-only processes never return full. Unknown memory streams + rather than guessing full. Uses extra full-mode headroom so 8s+ 540p streams + on 32 GB; 5s stays full. Stream-over 422 compares to total VRAM on CUDA only; + Darwin skips it (unified memory, already-free RAM). + """ + token_width, token_height = heavy_pass_size(stage_mode, stage1_width, stage1_height) + + def price(window: int | None) -> IcLoraJobDecision: + # A chunked job holds one window at a time. + seq = _heaviest_pass_tokens( + stage_mode, stage1_width, stage1_height, frames if window is None else window, stills, tiling + ) + full_gib = estimated_giB("full_models_loading", seq) + stream_gib = estimated_giB("streaming_models_loading", seq) + if process_mode == "unsupported": + return IcLoraJobReject(reason="unsupported", seq=seq, full_gib=full_gib, stream_gib=stream_gib) + if over_spatial_cap(token_width, token_height): + return IcLoraJobReject(reason="spatial", seq=seq, full_gib=full_gib, stream_gib=stream_gib) + decision = decide_load_mode( + seq, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + full_headroom_gib=_IC_LORA_FULL_HEADROOM_GIB, + ) + if isinstance(decision, VideoJobReject): + return IcLoraJobReject( + reason=decision.reason, + seq=decision.seq, + full_gib=decision.full_gib, + stream_gib=decision.stream_gib, + ) + return IcLoraJobLoad( + mode=decision.mode, + seq=decision.seq, + full_gib=decision.full_gib, + stream_gib=decision.stream_gib, + chunk_pixel_frames=window, + ) + + window = ic_lora_chunk_pixel_frames( + stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling + ) + decision = price(window) + if ( + window is None + and isinstance(decision, IcLoraJobReject) + and decision.reason == "stream_over" + and ic_lora_may_chunk(stage1_width, stage1_height, frames, stage_mode=stage_mode, tiling=tiling) + ): + # Without this, a clip just under the token rule is priced whole and a longer + # clip is priced as one window, so the longer clip would be cheaper. + return price(IC_LORA_CHUNK_PIXEL_FRAMES) + return decision + + +def catalog_preview_stage1(settings: IcLoraSettings) -> tuple[int, int]: + """Stage-1 pixels for list-time duration filtering (no user image yet).""" + if settings.skip_stage_2: + input_width, input_height = ( + _CATALOG_PREVIEW_SKIP_STAGE2_WIDTH, + _CATALOG_PREVIEW_SKIP_STAGE2_HEIGHT, + ) + else: + input_width, input_height = ( + _CATALOG_PREVIEW_TWO_STAGE_WIDTH, + _CATALOG_PREVIEW_TWO_STAGE_HEIGHT, + ) + canvas_w, canvas_h, factor = ic_lora_output_canvas( + skip_stage_2=settings.skip_stage_2, + resolution_factor=settings.resolution_factor, + input_width=input_width, + input_height=input_height, + resolution=None, + stage_2_ic_lora=settings.stage_2_ic_lora, + ) + return effective_denoise_stage1( + canvas_w, canvas_h, skip_stage_2=settings.skip_stage_2, resolution_factor=factor + ) + + +def advertised_duration_options( + options: list[int], + *, + stage1_width: int, + stage1_height: int, + stage_mode: IcLoraStageMode, + fps: int, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool, + stills: int = 0, + tiling: IcLoraTiling | None = None, +) -> list[int]: + """Intersect catalog duration seconds with ``decide_ic_lora_job``. + + ``stage_mode`` must be the mode the pipeline runs, or the filter prices another job. + ``stills`` is the number of reference stills the job can carry. ``tiling`` is the + LoRA's tile size, if any. + """ + kept: list[int] = [] + for seconds in options: + frames = compute_num_frames(seconds, max(1, fps)) + decision = decide_ic_lora_job( + stage1_width, + stage1_height, + frames, + memory_gb=memory_gb, + process_mode=process_mode, + stage_mode=stage_mode, + darwin=darwin, + stills=stills, + tiling=tiling, + ) + if isinstance(decision, IcLoraJobLoad): + kept.append(seconds) + return kept + + +def with_budgeted_duration_controls( + item: IcLoraCatalogItem, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool, +) -> IcLoraCatalogItem: + """Copy ``item`` with duration ``options`` intersected against the job budget. + + Generate still 422s if a client posts a dropped duration. If every option is + over budget, leave the control unchanged so the payload stays valid. + Unsupported machines get empty duration options instead of the full table. + """ + if memory_gb is None and process_mode != "unsupported": + return item + + stage1_w, stage1_h = catalog_preview_stage1(item.default_settings) + stage_mode = item.default_settings.stage_mode + fps = catalog_output_fps(item) + # The optional look still is priced as present, so the filter is not optimistic. + stills = int(item.allows_reference_image and item.reference_image_frame == REFERENCE_STILL_FRAME_IDX) + controls: list[IcLoraControl] = [] + changed = False + for control in item.controls: + if control.id != "duration" or control.kind != "int" or control.options is None: + controls.append(control) + continue + raw_options = [o for o in control.options if type(o) is int] + kept = advertised_duration_options( + raw_options, + stage1_width=stage1_w, + stage1_height=stage1_h, + stage_mode=stage_mode, + fps=fps, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + stills=stills, + tiling=item.default_settings.tiling, + ) + if not kept: + if process_mode == "unsupported": + controls.append(control.model_copy(update={"options": []})) + changed = True + continue + controls.append(control) + continue + if kept == raw_options: + controls.append(control) + continue + default = control.default + if not isinstance(default, int) or default not in kept: + default = min(kept) + controls.append(control.model_copy(update={"options": kept, "default": default})) + changed = True + if not changed: + return item + return item.model_copy(update={"controls": controls}) + + +def catalog_output_fps(item: IcLoraCatalogItem) -> int: + """Control-video fps from ``image_to_frames``, or 24. + + Catalog JSON is ``dict[str, JsonValue]``. A None / object / junk ``fps`` must + not 500 ``GET /api/ic-loras``. + """ + for step in item.preprocessing: + if step.utility == "image_to_frames": + return _coerce_positive_fps(step.params.get("fps")) + return _DEFAULT_IC_LORA_FPS + + +def _coerce_positive_fps(value: object) -> int: + if type(value) is bool: + return _DEFAULT_IC_LORA_FPS + if type(value) is int and value > 0: + return value + if type(value) is float and value > 0: + return int(value) + if isinstance(value, str): + try: + parsed = int(value.strip()) + except ValueError: + return _DEFAULT_IC_LORA_FPS + if parsed > 0: + return parsed + return _DEFAULT_IC_LORA_FPS diff --git a/backend/runtime_config/ic_lora_local_envelope.py b/backend/runtime_config/ic_lora_local_envelope.py new file mode 100644 index 000000000..537e6723c --- /dev/null +++ b/backend/runtime_config/ic_lora_local_envelope.py @@ -0,0 +1,215 @@ +"""Measured IC-LoRA spatial envelope (LTX-2 1.3.0). + +NOT re-measured on 1.4.0. 1.4 moved the reference encode into the chunk flow, so re-run the +bump gate's IC-LoRA scenarios (``iclora_stage2_on``, ``iclora_day_to_night``) on CUDA and +confirm these limits still hold before tightening or loosening them. + +On 1.3.0, 720p/1080p source-dim hung in tiled reference VAE encode even after +tia2v-aligned stage-1 encode — an algorithmic failure, not a 5090 VRAM ceiling. The +spatial cap therefore applies on Darwin too. The cap is the local 1080p cell +(1920×1088) on the output frame: stage 1 for a single-stage job, the stage-2 +canvas for a two-stage job. Large single-stage jobs run chunked (``ic_lora_chunking``). +A few 1080p runs were done by hand on CUDA and finished. They are not a measured +envelope. The job budget still rejects a job that does not fit the card. +The token/VRAM *curve* does not apply on Darwin (unified memory). +Duration is not a hard 20s cap — CUDA token budget decides stream vs 422; Darwin +has no token ceiling yet. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from api_types import TargetResolution +from runtime_config.grid_fit import fit_in_box + +IC_LORA_SOURCE_TOO_LARGE = "IC_LORA_SOURCE_TOO_LARGE" +IC_LORA_V1_ENVELOPE_MESSAGE = ( + "This IC-LoRA job is larger than this machine can run locally right now " + "(max 1080p). Lower the resolution." +) + +# Local 1080p grid (ltx_capabilities._TWO_PASS_PIXELS_16_9). +_MAX_SHORT_EDGE = 1088 +_MAX_LONG_EDGE = 1920 + + +@dataclass(frozen=True, slots=True) +class EnvelopeError: + code: str + message: str + + +def stage1_size(canvas_width: int, canvas_height: int) -> tuple[int, int]: + """skip_stage_2 (and two-stage stage-1) run at canvas//2.""" + return canvas_width // 2, canvas_height // 2 + + +def over_spatial_cap(width: int, height: int) -> bool: + """True when a frame is larger than the 1920x1088 cell, turned either way. + + Pass the OUTPUT size: stage 1 for a single-stage job, the stage-2 canvas for a + two-stage job (``heavy_pass_size``). The job budget uses the same rule. + """ + too_wide = max(width, height) > _MAX_LONG_EDGE + too_tall = min(width, height) > _MAX_SHORT_EDGE + return too_tall or too_wide + + +def effective_denoise_stage1( + canvas_width: int, + canvas_height: int, + *, + skip_stage_2: bool, + resolution_factor: float, +) -> tuple[int, int]: + """Match ``LTXIcLoraPipeline.generate``: skip_stage_2 scales canvas by factor first.""" + width, height = canvas_width, canvas_height + if skip_stage_2: + width = max(128, round(width * resolution_factor / 128) * 128) + height = max(128, round(height * resolution_factor / 128) * 128) + return width // 2, height // 2 + + +# A two-stage run that keeps the IC-LoRA on stage 2 (Layout To Render) sizes the +# canvas to the source on a 64 grid, inside the 1920x1088 cell. Upstream needs +# only a multiple of 64 for two stages. The 128 grid stays for every other recipe. +# The VAE spatial stride is 32 px per latent cell. Stage 1 runs at canvas//2, so the +# canvas grid is 2 * 32 = 64 to keep the stage 1 latent on whole cells. +_VAE_SPATIAL_STRIDE = 32 +_STAGE_2_IC_LORA_GRID = 2 * _VAE_SPATIAL_STRIDE +_DEFAULT_GRID = 128 + + +def _cap_box(width: int, height: int) -> tuple[int, int]: + """The 1920x1088 cell, turned the same way as the source.""" + if width >= height: + return _MAX_LONG_EDGE, _MAX_SHORT_EDGE + return _MAX_SHORT_EDGE, _MAX_LONG_EDGE + + +def _two_stage_output_size( + input_width: int, + input_height: int, + resolution: TargetResolution | None, + *, + stage_2_ic_lora: bool = False, +) -> tuple[int, int]: + """Canvas for skip_stage_2=False. Stage 1 runs at canvas//2, and its latent must be + even for the 2x patchify. The canvas never upscales the source, except that every + edge has a one-grid-cell minimum (64 or 128). A source below that minimum is + rendered at the minimum cell. + + With the IC-LoRA on stage 2, the canvas fits the source into the requested + resolution (or the 1920x1088 cell) on a 64 grid, close to the source aspect + (``fit_in_box``). Every other recipe snaps each edge down to a multiple of 128, + which mirrors the t2v two-stage landing size. + """ + if stage_2_ic_lora: + box_w, box_h = _cap_box(input_width, input_height) + if resolution is not None: + box_w, box_h = min(box_w, resolution.width), min(box_h, resolution.height) + return fit_in_box(input_width, input_height, box_w, box_h, _STAGE_2_IC_LORA_GRID) + target_w = resolution.width if resolution else input_width + target_h = resolution.height if resolution else input_height + width = min(target_w, input_width) + height = min(target_h, input_height) + return ( + max(_DEFAULT_GRID, (width // _DEFAULT_GRID) * _DEFAULT_GRID), + max(_DEFAULT_GRID, (height // _DEFAULT_GRID) * _DEFAULT_GRID), + ) + + +def fit_ic_lora_stage1(width: int, height: int) -> tuple[int, int]: + """Stage-1 size the skip-stage-2 pipeline will actually emit, inside the cap. + + The pipeline rounds the 2× canvas onto a 128 grid, so a 270p/360p target + that is not on that grid is not the frame that renders. Sizes over the + 1024×576 cap shrink on the 64px grid and keep the aspect (1344×576 → 896×384). + """ + canvas_w = max(128, round(width * 2 / 128) * 128) + canvas_h = max(128, round(height * 2 / 128) * 128) + stage_w, stage_h = canvas_w // 2, canvas_h // 2 + if not over_spatial_cap(stage_w, stage_h): + return stage_w, stage_h + long_is_width = stage_w >= stage_h + long_edge = stage_w if long_is_width else stage_h + short_edge = stage_h if long_is_width else stage_w + scale = min(_MAX_LONG_EDGE / long_edge, _MAX_SHORT_EDGE / short_edge) + short = max(64, int(short_edge * scale) // 64 * 64) + ratio = long_edge / short_edge + long = max(64, round(short * ratio) // 64 * 64) + while short > 64 and (long > _MAX_LONG_EDGE or short > _MAX_SHORT_EDGE): + short -= 64 + long = max(64, round(short * ratio) // 64 * 64) + if long_is_width: + return long, short + return short, long + + +def ic_lora_output_canvas( + *, + skip_stage_2: bool, + resolution_factor: float, + input_width: int, + input_height: int, + resolution: TargetResolution | None, + stage_2_ic_lora: bool = False, +) -> tuple[int, int, float]: + """Canvas + factor for catalog and built-in (canny/depth) generate paths. + + Two-stage always sizes to source (snapped /128), not the skip-stage-2 768 bucket. + skip_stage_2 with an explicit resolution renders that size after it is fit + onto the pipeline's 128 grid and the 1024×576 cap. Canvas is 2× that stage-1 + size and the factor is 1.0. GenSpace's generate() rejects that combination. + Only the queued catalog entry sends it. + skip_stage_2 + resolution_factor 0 and no resolution is the "source dimensions" + sentinel: pass 2×source at factor 1.0. Anything else stays on the 768-wide bucket. + """ + if not skip_stage_2: + width, height = _two_stage_output_size( + input_width, input_height, resolution, stage_2_ic_lora=stage_2_ic_lora + ) + return width, height, 1.0 + if resolution is not None: + stage_w, stage_h = fit_ic_lora_stage1(resolution.width, resolution.height) + return stage_w * 2, stage_h * 2, 1.0 + if resolution_factor == 0: + return max(128, 2 * input_width), max(128, 2 * input_height), 1.0 + width = 768 + height = max(round(width * input_height / input_width / 128) * 128, 128) + return width, height, resolution_factor + + +def _too_large() -> EnvelopeError: + return EnvelopeError(code=IC_LORA_SOURCE_TOO_LARGE, message=IC_LORA_V1_ENVELOPE_MESSAGE) + + +def _spatial_error(width: int, height: int) -> EnvelopeError | None: + if over_spatial_cap(width, height): + return _too_large() + return None + + +def ic_lora_v1_envelope_error( + width: int, + height: int, + *, + duration_seconds: float, + fps: float = 24.0, +) -> EnvelopeError | None: + """Spatial error for an output size (see ``over_spatial_cap``).""" + del duration_seconds, fps # duration is the token budget, not a hard 20s cap + return _spatial_error(width, height) + + +def ic_lora_v1_canvas_envelope_error( + canvas_width: int, + canvas_height: int, + *, + frame_count: int, + fps: float, +) -> EnvelopeError | None: + del frame_count, fps + stage1_w, stage1_h = stage1_size(canvas_width, canvas_height) + return _spatial_error(stage1_w, stage1_h) diff --git a/backend/runtime_config/ic_lora_stage_mode.py b/backend/runtime_config/ic_lora_stage_mode.py new file mode 100644 index 000000000..d7cf2abb1 --- /dev/null +++ b/backend/runtime_config/ic_lora_stage_mode.py @@ -0,0 +1,40 @@ +"""IC-LoRA stage layout as one value, and the size of the pass that carries the LoRA. + +Three layouts exist. ``skip_stage_2`` plus ``stage_2_ic_lora`` is a pair of booleans with +four combinations, and ``skip_stage_2=True`` with ``stage_2_ic_lora=True`` means nothing: +stage 2 does not run. The mode removes that combination. Derive it once from the resolved +settings, then pass the mode. The chunk rule and the job budget both read it. + +No imports from other runtime modules, so both can import this one without a cycle. +""" + +from __future__ import annotations + +from enum import Enum + + +class IcLoraStageMode(Enum): + SINGLE_STAGE = "single_stage" # stage 2 is skipped; stage 1 carries the IC-LoRA + STAGE_1_LORA = "stage_1_lora" # two stages; the IC-LoRA runs on stage 1 only + STAGE_2_LORA = "stage_2_lora" # two stages; the IC-LoRA and reference also run on stage 2 + + +def ic_lora_stage_mode(*, skip_stage_2: bool, stage_2_ic_lora: bool) -> IcLoraStageMode: + """Stage layout of a job. ``stage_2_ic_lora`` is ignored when stage 2 is skipped.""" + if skip_stage_2: + return IcLoraStageMode.SINGLE_STAGE + if stage_2_ic_lora: + return IcLoraStageMode.STAGE_2_LORA + return IcLoraStageMode.STAGE_1_LORA + + +def heavy_pass_size(mode: IcLoraStageMode, stage1_width: int, stage1_height: int) -> tuple[int, int]: + """Width and height of the largest pass. This is also the size of the output frame. + + Stage 1 for a single-stage job. The stage-2 canvas (twice stage 1) for both + two-stage layouts, with or without the IC-LoRA on stage 2. The spatial cap and + the job budget both read this size. + """ + if mode is IcLoraStageMode.SINGLE_STAGE: + return stage1_width, stage1_height + return stage1_width * 2, stage1_height * 2 diff --git a/backend/runtime_config/ic_lora_tiling.py b/backend/runtime_config/ic_lora_tiling.py new file mode 100644 index 000000000..68483c022 --- /dev/null +++ b/backend/runtime_config/ic_lora_tiling.py @@ -0,0 +1,73 @@ +"""Spatial transformer tiling of a catalog IC-LoRA (Restore, Refine Details). + +These LoRAs trained on one tile size. Their cards say to run every output size in +overlapping tiles of that size, merged inside each denoising step, even at full HD. A +single untiled pass is outside the training bucket. ltx-pipelines runs this as +``ICLoraStageConfig.tiling`` (``FixedSizeSpatialTiling``, overlap 0.5 at most). + +Tiling is a property of the LoRA, so it lives in the catalog ``default_settings``. The job +budget reads the tile size as the size of the transformer pass. The spatial cap still +reads the output size. + +No imports from other runtime modules, so ``api_types`` and the budget can import it. +""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, Field, model_validator + +# The overlap fraction we request. It is the most upstream accepts, and the least the +# Refine Details card allows ("never lower the overlap below 0.5"). It is a request, not +# the layout: upstream ``split_by_size_pinned`` still caps the tile count so that no cell +# is covered by three tiles. A 1920x1088 canvas gets 2x2 tiles with a small overlap, not +# the card's 3x3 tiles at 50%. +IC_LORA_TILE_OVERLAP = 0.5 + +_TILE_GRID = 32 # pixel multiple of the transformer latent grid +_FRAME_GRID = 8 # pixel frames per latent frame; windows are 8k + 1 frames + + +class IcLoraTiling(BaseModel): + """Tile size of a catalog IC-LoRA, and an optional fixed temporal window. + + ``long_side`` and ``short_side`` are given for a landscape canvas. A portrait canvas + swaps them (Refine Details card: "1024x576, or 576x1024 portrait"). + + ``window_frames`` is set when the LoRA drifts over a longer clip (Restore: past 97 + frames detail is lost and colour drifts). A clip longer than the window always runs + in windows of this length. None leaves the choice to the job budget. + """ + + model_config = ConfigDict(strict=True, frozen=True) + long_side: int = Field(ge=64) + short_side: int = Field(ge=64) + window_frames: int | None = Field(default=None, ge=9) + + @model_validator(mode="after") + def _check_grid(self) -> "IcLoraTiling": + if self.long_side % _TILE_GRID or self.short_side % _TILE_GRID: + raise ValueError(f"tile sides must be multiples of {_TILE_GRID}") + if self.short_side > self.long_side: + raise ValueError("short_side must not exceed long_side") + if self.window_frames is not None and (self.window_frames - 1) % _FRAME_GRID: + raise ValueError(f"window_frames must be {_FRAME_GRID}k + 1") + return self + + def tile_size(self, width: int, height: int) -> tuple[int, int]: + """(width, height) of one tile on a canvas of this size. + + The tile follows the canvas orientation. An axis shorter than its tile stays + untiled, so the tile never exceeds the canvas. + """ + if height > width: + tile_width, tile_height = self.short_side, self.long_side + else: + tile_width, tile_height = self.long_side, self.short_side + return min(width, tile_width), min(height, tile_height) + + +def transformer_pass_size(width: int, height: int, tiling: IcLoraTiling | None) -> tuple[int, int]: + """Size of one transformer call on a canvas. The tile when tiled, else the canvas.""" + if tiling is None: + return width, height + return tiling.tile_size(width, height) diff --git a/backend/runtime_config/local_compat_matrix.py b/backend/runtime_config/local_compat_matrix.py new file mode 100644 index 000000000..bb6ace7b5 --- /dev/null +++ b/backend/runtime_config/local_compat_matrix.py @@ -0,0 +1,264 @@ +"""Project 181's process mode + decide_video_job into the published compat matrix. + +Not a second Yes table. CUDA 16 GB that cannot stream 720p/20s is No for that +cell in the Fast picker; the T2V row stays Yes because 540p still loads. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from pathlib import Path + +from api_types import ( + LTXLocalModelId, + LTXVideoGenResolution, + LTXVideoGenerationResolutionSpec, +) +from frame_math import compute_num_frames +from runtime_config.ic_lora_job_budget import ( + HOME_IC_LORA_PREVIEW_SETTINGS, + IcLoraJobLoad, + catalog_preview_stage1, + decide_ic_lora_job, +) +from runtime_config.ltx_capabilities import LtxCapabilityFeature, local_caps, pixels_for, supports +from runtime_config.model_download_specs import get_latest_ltx_model_id, get_ltx_model_spec +from runtime_config.runtime_policy import ( + CUDA_FULL_VRAM_GB, + CUDA_VRAM_FLOOR_GB, + DARWIN_ADVERTISED_FLOOR_GB, + DARWIN_STREAMING_FLOOR_GB, + LocalGenerationMode, + decide_local_generation_mode, +) +from runtime_config.video_job_budget import advertised_fast_durations, memory_gb_for_job + +_REPO_ROOT = Path(__file__).resolve().parents[2] +MATRIX_PATH = _REPO_ROOT / "docs" / "local-compat-matrix.md" + +# Typical 16 GB CUDA SKU used as the stream-column example (floor is 15). +_CUDA_STREAM_EXAMPLE_GB = 16 +_DARWIN_STREAM_EXAMPLE_GB = 48 + +# Retake/Extend are hardware-viable but only on 2.3, which is not the Explore default. +_LEGACY_LOCAL_MODEL_ID: LTXLocalModelId = "ltx-2.3-22b-distilled-1.1" +_LEGACY_ONLY_CELL = "2.3 only" + + +@dataclass(frozen=True, slots=True) +class _Band: + label: str + system: str + cuda_available: bool + vram_gb: int | None + mps_available: bool + ram_gb: int | None + + +_BANDS = ( + _Band("CUDA unsupported", "Linux", True, CUDA_VRAM_FLOOR_GB - 1, False, 64), + _Band("CUDA stream", "Linux", True, _CUDA_STREAM_EXAMPLE_GB, False, 64), + _Band("CUDA full", "Linux", True, CUDA_FULL_VRAM_GB, False, 64), + _Band("Darwin unsupported", "Darwin", False, None, True, DARWIN_STREAMING_FLOOR_GB - 1), + _Band("Darwin stream", "Darwin", False, None, True, _DARWIN_STREAM_EXAMPLE_GB), + _Band("Intel Mac / no GPU", "Darwin", False, None, False, 64), +) + +_ROWS = ( + "T2V", + "I2V", + "A2V", + "LoRAs", + "IC-LoRA", + "Retake", + "Extend", + "local text encoder", + "2.5 download", +) + +_CAPABILITY_BY_ROW: dict[str, LtxCapabilityFeature] = { + "T2V": "t2v", + "I2V": "i2v", + "A2V": "a2v", +} + + +def _durations_at_24( + specs: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] | None, +) -> dict[LTXVideoGenResolution, list[int]]: + if not specs: + return {} + return { + res: [int(duration) for duration in rspec.fps_to_durations.get(24, [])] + for res, rspec in specs.items() + } + + +def _fast_duration_maps() -> tuple[ + dict[LTXVideoGenResolution, list[int]], + dict[LTXVideoGenResolution, list[int]], +]: + spec = get_ltx_model_spec(get_latest_ltx_model_id()).supported_pipelines[0][1] + return ( + _durations_at_24(spec.supported_resolutions_durations), + _durations_at_24(spec.a2v_supported_resolutions_durations), + ) + + +def _process_mode(band: _Band) -> LocalGenerationMode: + return decide_local_generation_mode( + band.system, + band.cuda_available, + band.vram_gb, + mps_available=band.mps_available, + ram_gb=band.ram_gb, + ) + + +def _job_memory(band: _Band) -> float | None: + darwin = band.system == "Darwin" + return memory_gb_for_job( + vram_gb=band.vram_gb, + available_ram_gb=band.ram_gb, + darwin=darwin, + ) + + +def _any_fast_cell( + band: _Band, + process_mode: LocalGenerationMode, + duration_map: dict[LTXVideoGenResolution, list[int]], +) -> bool: + caps = local_caps(get_latest_ltx_model_id()) + darwin = band.system == "Darwin" + memory_gb = _job_memory(band) + for resolution, durations in duration_map.items(): + width, height = pixels_for(caps, resolution, "16:9") + kept = advertised_fast_durations( + width, + height, + 24, + durations, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + if kept: + return True + return False + + +def _ic_lora_viable(band: _Band, process_mode: LocalGenerationMode) -> bool: + """True when the lightest Home recipe (single-stage, 5 s) fits this band. + + A stage-2 recipe such as Layout To Render at 1080p is heavier. It can be rejected + on 12-20 GB cards where this returns True. + """ + stage1_w, stage1_h = catalog_preview_stage1(HOME_IC_LORA_PREVIEW_SETTINGS) + decision = decide_ic_lora_job( + stage1_w, + stage1_h, + compute_num_frames(5, 24), + memory_gb=_job_memory(band), + process_mode=process_mode, + stage_mode=HOME_IC_LORA_PREVIEW_SETTINGS.stage_mode, + darwin=band.system == "Darwin", + ) + return isinstance(decision, IcLoraJobLoad) + + +def _retake_extend_cell(feature: LtxCapabilityFeature, *, viable: bool) -> str: + """Never a bare Yes while the Explore default cannot run the feature. + + Explore defaults to local 2.5, which has no Retake/Extend; 2.3 still offers both. + Turns into a plain Yes on its own once 2.5 gains them. + """ + if not viable: + return "No" + if supports(local_caps(get_latest_ltx_model_id()), feature): + return "Yes" + if supports(local_caps(_LEGACY_LOCAL_MODEL_ID), feature): + return _LEGACY_ONLY_CELL + return "No" + + +def _cell( + row: str, + band: _Band, + t2v_i2v_map: dict[LTXVideoGenResolution, list[int]], + a2v_map: dict[LTXVideoGenResolution, list[int]], +) -> str: + process_mode = _process_mode(band) + viable = process_mode != "unsupported" + latest = get_latest_ltx_model_id() + if row in _CAPABILITY_BY_ROW: + if not supports(local_caps(latest), _CAPABILITY_BY_ROW[row]): + return "No" + duration_map = a2v_map if row == "A2V" else t2v_i2v_map + return "Yes" if _any_fast_cell(band, process_mode, duration_map) else "No" + if row == "IC-LoRA": + return "Yes" if _ic_lora_viable(band, process_mode) else "No" + if row in ("Retake", "Extend"): + return _retake_extend_cell("retake" if row == "Retake" else "extend", viable=viable) + if row == "LoRAs": + return "Yes" if viable and supports(local_caps(latest), "user_loras") else "No" + if row in ("local text encoder", "2.5 download"): + return "Yes" if viable else "No" + raise AssertionError(row) + + +def render_compat_matrix() -> str: + t2v_i2v_map, a2v_map = _fast_duration_maps() + headers = ["Tool", *(band.label for band in _BANDS)] + lines = [ + "# Local Explore compatibility matrix", + "", + "Generated from `decide_local_generation_mode` and `decide_video_job`.", + "A machine that cannot run a Fast cell is not offered that cell.", + "Regenerate: `cd backend && uv run python -m runtime_config.local_compat_matrix`.", + "", + "| " + " | ".join(headers) + " |", + "| " + " | ".join("---" for _ in headers) + " |", + ] + for row in _ROWS: + cells = [_cell(row, band, t2v_i2v_map, a2v_map) for band in _BANDS] + lines.append("| " + " | ".join([row, *cells]) + " |") + lines.extend( + [ + "", + f"Floors: CUDA integer **{CUDA_VRAM_FLOOR_GB}** GiB VRAM (`total_memory // 1024**3`);", + f"Darwin **{DARWIN_ADVERTISED_FLOOR_GB}** GiB total RAM; ~72 GB disk for the 2.5 Fast core pack", + "(kitchen-sink installs with 2.3, image models, and processors are larger).", + "", + f"CUDA stream ({_CUDA_STREAM_EXAMPLE_GB} GB) still runs T2V/I2V/A2V; the Fast picker hides 720p/20s", + f"and 1080p/10s because `decide_video_job` would reject them. CUDA full ({CUDA_FULL_VRAM_GB} GB)", + "keeps those cells (they stream). Darwin stream keeps the static Fast ceiling.", + "", + ] + ) + if any(_LEGACY_ONLY_CELL in line for line in lines): + lines.extend( + [ + f"`{_LEGACY_ONLY_CELL}`: hardware can run it, but not on Explore's default local 2.5", + f"(no local Retake/Extend there) — only after switching to {_LEGACY_LOCAL_MODEL_ID}.", + "", + ] + ) + lines.extend( + [ + "Footnote: Darwin IC-LoRA duration is unbounded past the 540p spatial cap", + "(no token 422). Do not invent a CUDA-curve ceiling for Darwin.", + "", + ] + ) + return "\n".join(lines) + + +def write_compat_matrix(path: Path = MATRIX_PATH) -> Path: + path.write_text(render_compat_matrix(), encoding="utf-8") + return path + + +if __name__ == "__main__": + written = write_compat_matrix() + print(written) diff --git a/backend/runtime_config/lora_catalog.json b/backend/runtime_config/lora_catalog.json index 2448e082e..b14ba00d7 100644 --- a/backend/runtime_config/lora_catalog.json +++ b/backend/runtime_config/lora_catalog.json @@ -4,15 +4,17 @@ { "id": "fpv-motion", "name": "FPV Motion", - "description": "Smoother FPV drone-style camera motion \u2014 steady, low-speed flying moves through the scene.", + "description": "Smoother FPV drone-style camera motion — steady, low-speed flying moves through the scene.", "download": { "repo_id": "chsengni/ltx2.3-fpv-motion", "variants": [ { - "id": "default", + "id": "ltx-2.3__fpv-motion", "label": "Default", "filename": "ltx2.3_fpv_motion.safetensors", - "size_bytes": 308666208 + "size_bytes": 308666208, + "base_model": "LTX-2.3", + "repo_id": "chsengni/ltx2.3-fpv-motion" } ] }, @@ -27,7 +29,10 @@ "url": "https://huggingface.co/chsengni/ltx2.3-fpv-motion" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "created_at": "2026-06-08", "tags": [ "motion" @@ -40,35 +45,41 @@ { "kind": "summary", "title": "What it does", - "body": "Adds smoother FPV (first-person-view) drone-style camera motion \u2014 steady, low-speed flying moves through the scene." + "body": "Adds smoother FPV (first-person-view) drone-style camera motion — steady, low-speed flying moves through the scene." }, { "kind": "prompting", "title": "Prompt", "body": [ - "No trigger word \u2014 describe an FPV / drone shot.", + "No trigger word — describe an FPV / drone shot.", "Example: a smooth low-speed FPV drone flight gliding through a forest canyon at golden hour." ] }, { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } + ], + "enhancement_examples": [ + "A cinematic FPV drone shot flying smoothly through a cozy wooden cabin in the woods and out into a stunning natural landscape, ending with a dramatic upward reveal.", + "a smooth low-speed FPV drone flight gliding through a forest canyon at golden hour, then emerging over a still lake with mist rising from a waterfall." ] }, { "id": "crt-animation-terminal", "name": "CRT / Retro Terminal", - "description": "Late-80s / early-90s CRT-monitor look \u2014 scanlines, phosphor glow, chromatic aberration, signal noise.", + "description": "Late-80s / early-90s CRT-monitor look — scanlines, phosphor glow, chromatic aberration, signal noise.", "download": { "repo_id": "lovis93/crt-animation-terminal-ltx-2.3-lora", "variants": [ { - "id": "default", + "id": "ltx-2.3__crt-animation-terminal", "label": "Default", "filename": "crtanim_10000.safetensors", - "size_bytes": 428150680 + "size_bytes": 428150680, + "base_model": "LTX-2.3", + "repo_id": "lovis93/crt-animation-terminal-ltx-2.3-lora" } ] }, @@ -83,7 +94,10 @@ "url": "https://huggingface.co/lovis93/crt-animation-terminal-ltx-2.3-lora" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -96,7 +110,7 @@ { "kind": "summary", "title": "What it does", - "body": "Locks generations into a real late-80s / early-90s CRT-monitor look \u2014 scanlines, phosphor glow, chromatic aberration, barrel curvature, dithering, signal noise and choppy limited-frame motion." + "body": "Locks generations into a real late-80s / early-90s CRT-monitor look — scanlines, phosphor glow, chromatic aberration, barrel curvature, dithering, signal noise and choppy limited-frame motion." }, { "kind": "prompting", @@ -111,8 +125,8 @@ "kind": "tips", "title": "Tips", "body": [ - "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed.", - "If the prompt calls for on-screen text, keep it to short strings (1\u20133 words) \u2014 longer text renders unreliably.", + "LoRA strength ~1.0. Text-to-video — no input clip needed.", + "If the prompt calls for on-screen text, keep it to short strings (1–3 words) — longer text renders unreliably.", "The look defaults to static framing; if camera movement is wanted, state it explicitly in the prompt rather than assuming it." ] } @@ -122,15 +136,17 @@ { "id": "openwheel-tcam-style", "name": "Open-Wheel Motorsport T-Cam", - "description": "Onboard T-cam / cockpit-cam open-wheel motorsport look \u2014 halo-structure POV of V6-hybrid-era F1-style race cars on track.", + "description": "Onboard T-cam / cockpit-cam open-wheel motorsport look — halo-structure POV of V6-hybrid-era F1-style race cars on track.", "download": { "repo_id": "mxturbo/Openwheel-motorsports-Cockpit-T-Cam-LTX2.3", "variants": [ { - "id": "default", + "id": "ltx-2.3__openwheel-tcam-style", "label": "Default", "filename": "openwheel-t-cam-ltx2.3_000000500.safetensors", - "size_bytes": 1348027408 + "size_bytes": 1348027408, + "base_model": "LTX-2.3", + "repo_id": "mxturbo/Openwheel-motorsports-Cockpit-T-Cam-LTX2.3" } ] }, @@ -145,7 +161,10 @@ "url": "https://huggingface.co/mxturbo/Openwheel-motorsports-Cockpit-T-Cam-LTX2.3" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "created_at": "2026-05-28", "tags": [ "style" @@ -155,38 +174,44 @@ { "kind": "summary", "title": "What it does", - "body": "Renders onboard T-cam / cockpit-cam open-wheel motorsport shots \u2014 the halo-structure POV of V6-hybrid-era F1-style cars on track, with sponsor liveries, curbs, and wet-weather racing." + "body": "Renders onboard T-cam / cockpit-cam open-wheel motorsport shots — the halo-structure POV of V6-hybrid-era F1-style cars on track, with sponsor liveries, curbs, and wet-weather racing." }, { "kind": "prompting", "title": "Prompt", "body": [ - "No single trigger word \u2014 use the onboard phrasing from the model card. '16LV6HybridF1' names the car type.", + "No single trigger word — use the onboard phrasing from the model card. '16LV6HybridF1' names the car type.", "Example: T-cam onboard view looking over the silver and cyan central halo structure of a red 16LV6HybridF1 car on a wet track, accelerating down a straight past sponsor bridges." ] }, { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Trained on T-cam/cockpit footage of current open-wheel categories. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Trained on T-cam/cockpit footage of current open-wheel categories. Text-to-video — no input clip needed." } ], "media": { "demo_video": "openwheel_tcam_style_demo.mp4" - } + }, + "enhancement_examples": [ + "T-cam onboard view looking over the silver and cyan central halo structure of a red 16LV6HybridF1 car racing in a tight pack on a wet track in heavy rain.", + "T-cam onboard view looking over the black central halo structure of a gold 16LV6HybridF1 car braking hard into a tight hairpin, sparks from the titanium skid block, helmet visor catching the track lights." + ] }, { "id": "fantasy-anime-style", "name": "Cinematic Fantasy Anime", - "description": "Cel-shaded high-fantasy anime illustration look \u2014 grounded fantasy worlds and characters in a cinematic anime style.", + "description": "Cel-shaded high-fantasy anime illustration look — grounded fantasy worlds and characters in a cinematic anime style.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Fantasy_Anime_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__fantasy-anime-style", "label": "Default", "filename": "Fantasy_Anime.safetensors", - "size_bytes": 352679880 + "size_bytes": 352679880, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Fantasy_Anime_Style_LoRa" } ] }, @@ -197,7 +222,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -207,20 +235,20 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes as a cinematic, cel-shaded high-fantasy anime illustration \u2014 grounded fantasy worlds, characters, and creatures with consistent anime styling (no IP used in training)." + "body": "Renders scenes as a cinematic, cel-shaded high-fantasy anime illustration — grounded fantasy worlds, characters, and creatures with consistent anime styling (no IP used in training)." }, { "kind": "prompting", "title": "Prompt", "body": [ "Trigger word f4nt4sy4n1m6 (also try 'cinematic fantasy anime cel-shaded illustration'); works without it too.", - "Example: f4nt4sy4n1m6 cinematic fantasy anime cel-shaded illustration, hand-drawn linework and painted shading, high-end fantasy anime film look. A young fantasy mage with flowing silver hair and expressive determined eyes stands on a windswept cliff at dusk, wearing an intricately layered fantasy robe with glowing arcane trim. She raises one hand and summons a swirling orb of glowing blue magic, radiant particles and wisps of light spiraling around her as her hair and robe billow in the magical wind. Beside her floats a small glowing spirit creature \u2014 a delicate fox-like being made of soft light and drifting embers, its form shimmering. Behind them, an epic fantasy landscape of floating rock islands and distant spires fades into atmospheric haze under a dramatic violet-and-gold sky with two moons. Vivid magical atmosphere, cinematic fantasy lighting, expressive character animation, painterly cel-shaded finish, dramatic storytelling composition. Swelling orchestral fantasy music, the hum of magic, and wind." + "Example: f4nt4sy4n1m6 cinematic fantasy anime cel-shaded illustration, hand-drawn linework and painted shading, high-end fantasy anime film look. A young fantasy mage with flowing silver hair and expressive determined eyes stands on a windswept cliff at dusk, wearing an intricately layered fantasy robe with glowing arcane trim. She raises one hand and summons a swirling orb of glowing blue magic, radiant particles and wisps of light spiraling around her as her hair and robe billow in the magical wind. Beside her floats a small glowing spirit creature — a delicate fox-like being made of soft light and drifting embers, its form shimmering. Behind them, an epic fantasy landscape of floating rock islands and distant spires fades into atmospheric haze under a dramatic violet-and-gold sky with two moons. Vivid magical atmosphere, cinematic fantasy lighting, expressive character animation, painterly cel-shaded finish, dramatic storytelling composition. Swelling orchestral fantasy music, the hum of magic, and wind." ] }, { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "media": { @@ -235,15 +263,17 @@ { "id": "fantasy-realism-style", "name": "Cinematic Fantasy Realism", - "description": "Grounded high-fantasy live-action cinematic look \u2014 realistic fantasy worlds, characters, and creatures.", + "description": "Grounded high-fantasy live-action cinematic look — realistic fantasy worlds, characters, and creatures.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Fantasy_Realism_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__fantasy-realism-style", "label": "Default", "filename": "Fantasy_Realism.safetensors", - "size_bytes": 352679888 + "size_bytes": 352679888, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Fantasy_Realism_Style_LoRa" } ] }, @@ -254,7 +284,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -264,7 +297,7 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes as a grounded high-fantasy, live-action cinematic film \u2014 realistic fantasy worlds, characters, armor, and creatures with a consistent cinematic identity (no IP used in training)." + "body": "Renders scenes as a grounded high-fantasy, live-action cinematic film — realistic fantasy worlds, characters, armor, and creatures with a consistent cinematic identity (no IP used in training)." }, { "kind": "prompting", @@ -277,7 +310,7 @@ { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "media": { @@ -292,15 +325,17 @@ { "id": "cinematic-cyberpunk-style", "name": "Cinematic Sci-Fi Cyberpunk", - "description": "Cinematic cyberpunk neo-noir look \u2014 rainy neon-lit streets, wet reflective pavement, holographic UI, teal-orange and magenta lighting.", + "description": "Cinematic cyberpunk neo-noir look — rainy neon-lit streets, wet reflective pavement, holographic UI, teal-orange and magenta lighting.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Cinematic_Sci-fi-Cyberpunk_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__cinematic-cyberpunk-style", "label": "Default", "filename": "Cinematic_sci-fi-cyberpunk.safetensors", - "size_bytes": 352679888 + "size_bytes": 352679888, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Cinematic_Sci-fi-Cyberpunk_Style_LoRa" } ] }, @@ -311,7 +346,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -321,7 +359,7 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes with a cinematic cyberpunk neo-noir mood \u2014 moody rainy cityscapes, wet reflective pavement, atmospheric fog and steam, glowing holographic interfaces, and teal-orange / magenta neon lighting." + "body": "Renders scenes with a cinematic cyberpunk neo-noir mood — moody rainy cityscapes, wet reflective pavement, atmospheric fog and steam, glowing holographic interfaces, and teal-orange / magenta neon lighting." }, { "kind": "prompting", @@ -334,7 +372,7 @@ { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "media": { @@ -349,15 +387,17 @@ { "id": "claymation-style", "name": "Claymation Style", - "description": "Stop-motion claymation diorama look \u2014 hand-sculpted clay, fingerprints, miniature sets.", + "description": "Stop-motion claymation diorama look — hand-sculpted clay, fingerprints, miniature sets.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Clay_Mation_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__claymation-style", "label": "Default", "filename": "Claymation.safetensors", - "size_bytes": 352679880 + "size_bytes": 352679880, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Clay_Mation_Style_LoRa" } ] }, @@ -368,7 +408,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -378,7 +421,7 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes in a handcrafted claymation diorama style inspired by classic stop-motion \u2014 sculpted clay subjects with visible fingerprints, rounded forms and miniature set environments." + "body": "Renders scenes in a handcrafted claymation diorama style inspired by classic stop-motion — sculpted clay subjects with visible fingerprints, rounded forms and miniature set environments." }, { "kind": "prompting", @@ -391,7 +434,7 @@ { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "media": { @@ -401,20 +444,26 @@ "license": { "name": "LTX-2 Community License", "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" - } + }, + "enhancement_examples": [ + "claymation style, stop motion clay, a handcrafted clay diorama of two cute clay polar bears relaxing on a sunny tropical beach, sipping cocktails. The polar bears have soft white sculpted clay fur with visible fingerprints and hand-shaped textures, round friendly faces, and little black noses, lounging back in tiny clay beach chairs wearing cool clay sunglasses.", + "claymation style, stop motion clay, a sculpted clay fox baking bread in a tiny clay bakery, visible fingerprints in the dough, warm miniature shop lighting, bouncy handmade stop-motion movement." + ] }, { "id": "cozy-felt-style", "name": "Cozy Felt Style", - "description": "Handcrafted felt-cutout diorama look \u2014 layered felt, visible stitching, plush textures.", + "description": "Handcrafted felt-cutout diorama look — layered felt, visible stitching, plush textures.", "download": { "repo_id": "vrgamedevgirl84/LTX2.3_Cozy_Felt_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__cozy-felt-style", "label": "Default", "filename": "CozyFelt.safetensors", - "size_bytes": 352679880 + "size_bytes": 352679880, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX2.3_Cozy_Felt_Style_LoRa" } ] }, @@ -425,7 +474,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -435,7 +487,7 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes as a cozy felt-cutout cinematic diorama \u2014 subjects and environments look assembled from soft felt pieces, with layered shapes, visible stitching, fuzzy fibers and embroidery detail." + "body": "Renders scenes as a cozy felt-cutout cinematic diorama — subjects and environments look assembled from soft felt pieces, with layered shapes, visible stitching, fuzzy fibers and embroidery detail." }, { "kind": "prompting", @@ -448,7 +500,7 @@ { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "media": { @@ -458,20 +510,26 @@ "license": { "name": "LTX-2 Community License", "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" - } + }, + "enhancement_examples": [ + "F3ltCut0u7 a felt red fox performing skateboard tricks in a sunny felt skatepark at golden hour, layered felt fur, visible stitched seams, plush rounded edges.", + "F3ltCut0u7 a felt T-rex plays golf on a sunny felt golf course, gripping a tiny felt golf club in its little short arms with intense concentration." + ] }, { "id": "fantasy-painterly-style", "name": "Fantasy Painterly Style", - "description": "Painterly fantasy cinematic look \u2014 oil-paint brushwork, luminous magical lighting.", + "description": "Painterly fantasy cinematic look — oil-paint brushwork, luminous magical lighting.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Fantasy_Painterly_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__fantasy-painterly-style", "label": "Default", "filename": "Fantasy_Painterly.safetensors", - "size_bytes": 352679888 + "size_bytes": 352679888, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Fantasy_Painterly_Style_LoRa" } ] }, @@ -482,7 +540,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -495,7 +556,7 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes as fantasy painterly cinematic imagery \u2014 expressive brush strokes, layered oil-paint texture, luminous magical lighting and atmospheric depth." + "body": "Renders scenes as fantasy painterly cinematic imagery — expressive brush strokes, layered oil-paint texture, luminous magical lighting and atmospheric depth." }, { "kind": "prompting", @@ -508,27 +569,33 @@ { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "trigger_placement": "anywhere", "license": { "name": "LTX-2 Community License", "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" - } + }, + "enhancement_examples": [ + "D4rkP41nt3r cinematic oil painting, the opening frame is an extreme cinematic close-up of an elderly forest keeper, with only half of their face visible while the rest fades into soft negative space. Deep expressive wrinkles, kind eyes, silver hair, and a moss-green hooded cloak are bathed in warm golden light.", + "D4rkP41nt3r fantasy painterly style, a winged knight riding through a luminous painted valley at dusk, visible brush strokes, layered oil-paint texture, magical rim light on armor." + ] }, { "id": "paper-cutout-style", "name": "Paper Cut-Out Style", - "description": "Handcrafted paper-cutout diorama look \u2014 stacked paper layers, clean cut edges, tape seams.", + "description": "Handcrafted paper-cutout diorama look — stacked paper layers, clean cut edges, tape seams.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Paper_Cut_Out_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__paper-cutout-style", "label": "Default", "filename": "PaperCutOutStyle.safetensors", - "size_bytes": 352679880 + "size_bytes": 352679880, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Paper_Cut_Out_Style_LoRa" } ] }, @@ -539,7 +606,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -549,20 +619,20 @@ { "kind": "summary", "title": "What it does", - "body": "Renders scenes as a cozy paper-cut-out cinematic diorama \u2014 subjects look assembled from layered paper with clean cut edges, folds, slight curl and tape seams." + "body": "Renders scenes as a cozy paper-cut-out cinematic diorama — subjects look assembled from layered paper with clean cut edges, folds, slight curl and tape seams." }, { "kind": "prompting", "title": "Prompt", "body": [ "Main trigger word Pap3rCut0u7.", - "Example: Pap3rCut0u7 handcrafted paper cut-out cinematic diorama style, everything constructed from layered paper pieces with visible cut edges, stacked paper layers, slight paper curl, folded paper details, and gentle layered shadows. A cute little paper rabbit with layered white-and-grey cut-paper fur, long folded paper ears, and simple round paper eyes sits at a small paper table doing origami. It carefully folds a flat square of paper with its little paper paws, creasing and turning it step by step, until it forms a neat little folded paper airplane. The rabbit holds up the finished paper airplane proudly, then draws its arm back and throws it \u2014 the little paper airplane glides smoothly forward through the air, banking and looping gently across the cozy paper room before soaring off. Around it, a warm paper-craft room with stacked paper books, little folded paper decorations, a paper window with cut-paper sunlight streaming in, and layered paper plants, all with visible cut edges and soft layered shadows. The camera follows the folding, then tracks the airplane's flight. Warm, cheerful, whimsical handcrafted storybook mood, with soft paper folding and creasing sounds, a gentle whoosh of the gliding airplane, and cozy ambience." + "Example: Pap3rCut0u7 handcrafted paper cut-out cinematic diorama style, everything constructed from layered paper pieces with visible cut edges, stacked paper layers, slight paper curl, folded paper details, and gentle layered shadows. A cute little paper rabbit with layered white-and-grey cut-paper fur, long folded paper ears, and simple round paper eyes sits at a small paper table doing origami. It carefully folds a flat square of paper with its little paper paws, creasing and turning it step by step, until it forms a neat little folded paper airplane. The rabbit holds up the finished paper airplane proudly, then draws its arm back and throws it — the little paper airplane glides smoothly forward through the air, banking and looping gently across the cozy paper room before soaring off. Around it, a warm paper-craft room with stacked paper books, little folded paper decorations, a paper window with cut-paper sunlight streaming in, and layered paper plants, all with visible cut edges and soft layered shadows. The camera follows the folding, then tracks the airplane's flight. Warm, cheerful, whimsical handcrafted storybook mood, with soft paper folding and creasing sounds, a gentle whoosh of the gliding airplane, and cozy ambience." ] }, { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0. Text-to-video — no input clip needed." } ], "media": { @@ -572,20 +642,26 @@ "license": { "name": "LTX-2 Community License", "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" - } + }, + "enhancement_examples": [ + "Pap3rCut0u7 handcrafted paper cut-out cinematic diorama style, a curious desert tortoise walks between towering saguaro cacti at golden hour, stacked paper layers, visible cut edges, soft layered shadows.", + "Pap3rCut0u7 a paper rabbit folding origami at a small paper table in a cozy cut-paper room with a paper window and streaming sunlight." + ] }, { "id": "soft-enhance-style", "name": "Soft Enhance", - "description": "Natural detail enhancer \u2014 adds subtle detail and clarity and softens LTX 2.3's harsher contrast for a smoother, more natural finish.", + "description": "Natural detail enhancer — adds subtle detail and clarity and softens LTX 2.3's harsher contrast for a smoother, more natural finish.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Soft_Enhance_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__soft-enhance-style", "label": "Default", "filename": "LTX2.3_Soft_Enhance.safetensors", - "size_bytes": 352679864 + "size_bytes": 352679864, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Soft_Enhance_Style_LoRa" } ] }, @@ -596,7 +672,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "enhance" ], @@ -605,20 +684,20 @@ { "kind": "summary", "title": "What it does", - "body": "A natural detail enhancer: adds subtle detail, improves clarity, and softens LTX 2.3's stronger contrast for a smoother, more organic finish \u2014 detail stays present without looking over-sharpened." + "body": "A natural detail enhancer: adds subtle detail, improves clarity, and softens LTX 2.3's stronger contrast for a smoother, more organic finish — detail stays present without looking over-sharpened." }, { "kind": "prompting", "title": "Prompt", "body": [ - "No trigger word \u2014 just apply it to any text-to-video prompt.", - "Example: A cinematic beauty close-up portrait of a pretty young woman with clear radiant skin, delicate features, expressive bright eyes, and soft colorful makeup with a touch of shimmer. She stands against a vibrant backdrop glowing with bright saturated colors \u2014 soft blends of pink, teal, orange, and purple light washing across the scene. Colorful soft lighting falls flatteringly across her face, warm and cool tones mingling on her skin with a subtle catchlight in her eyes, and a few strands of hair drift softly in a light breeze. Behind her, blurred colorful bokeh lights sparkle in vivid hues. She gives a gentle warm smile and a slow blink, breathing softly, tiny natural movements in her expression. Rich vibrant color, smooth gradual tonal transitions, refined natural skin texture, glowing colorful highlights, photorealistic, cinematic, soft flattering lighting, fine natural detail, gentle shallow depth of field, clean refined natural finish. Upbeat ambient tone." + "No trigger word — just apply it to any text-to-video prompt.", + "Example: A cinematic beauty close-up portrait of a pretty young woman with clear radiant skin, delicate features, expressive bright eyes, and soft colorful makeup with a touch of shimmer. She stands against a vibrant backdrop glowing with bright saturated colors — soft blends of pink, teal, orange, and purple light washing across the scene. Colorful soft lighting falls flatteringly across her face, warm and cool tones mingling on her skin with a subtle catchlight in her eyes, and a few strands of hair drift softly in a light breeze. Behind her, blurred colorful bokeh lights sparkle in vivid hues. She gives a gentle warm smile and a slow blink, breathing softly, tiny natural movements in her expression. Rich vibrant color, smooth gradual tonal transitions, refined natural skin texture, glowing colorful highlights, photorealistic, cinematic, soft flattering lighting, fine natural detail, gentle shallow depth of field, clean refined natural finish. Upbeat ambient tone." ] }, { "kind": "tips", "title": "Tips", - "body": "LoRA strength ~1.0; lower it for a lighter touch. The softer counterpart to Crisp Enhance \u2014 combine and balance the two for a custom look. Text-to-video \u2014 no input clip needed." + "body": "LoRA strength ~1.0; lower it for a lighter touch. The softer counterpart to Crisp Enhance — combine and balance the two for a custom look. Text-to-video — no input clip needed." } ], "media": { @@ -632,15 +711,17 @@ { "id": "wild-west-style", "name": "Wild West Style", - "description": "Grounded, cinematic Wild West frontier look \u2014 weathered cowboys, dusty towns, sunbaked landscapes.", + "description": "Grounded, cinematic Wild West frontier look — weathered cowboys, dusty towns, sunbaked landscapes.", "download": { "repo_id": "vrgamedevgirl84/LTX_2.3_Wild_West_Style_LoRa", "variants": [ { - "id": "default", + "id": "ltx-2.3__wild-west-style", "label": "Default", "filename": "Wild_West.safetensors", - "size_bytes": 705198384 + "size_bytes": 705198384, + "base_model": "LTX-2.3", + "repo_id": "vrgamedevgirl84/LTX_2.3_Wild_West_Style_LoRa" } ] }, @@ -651,7 +732,10 @@ "affiliation": "community" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "tags": [ "style" ], @@ -674,7 +758,7 @@ { "kind": "tips", "title": "Tips", - "body": "Strength 1.0 in the samples; 0.5\u20131.0 is usable." + "body": "Strength 1.0 in the samples; 0.5–1.0 is usable." } ], "media": { @@ -689,15 +773,17 @@ { "id": "product-ad-style", "name": "Product Ad Style", - "description": "Cinematic product-commercial look \u2014 luxury brand visuals, perfume/cosmetics ads, tech and fashion product shots with premium studio lighting.", + "description": "Cinematic product-commercial look — luxury brand visuals, perfume/cosmetics ads, tech and fashion product shots with premium studio lighting.", "download": { "repo_id": "SOLRICKS/ltx-2.3-product-ad-style", "variants": [ { - "id": "default", + "id": "ltx-2.3__product-ad-style", "label": "Default", "filename": "LTX23_Product_Commercial_LoRA.safetensors", - "size_bytes": 337360792 + "size_bytes": 337360792, + "base_model": "LTX-2.3", + "repo_id": "SOLRICKS/ltx-2.3-product-ad-style" } ] }, @@ -712,7 +798,10 @@ "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "created_at": "2026-07-06", "tags": [ "style" @@ -730,7 +819,7 @@ { "kind": "summary", "title": "What it does", - "body": "Applies a cinematic product-ad look \u2014 advertising-style lighting, glossy reflections, premium framing \u2014 for perfume, cosmetics, tech, fashion, and studio product shots." + "body": "Applies a cinematic product-ad look — advertising-style lighting, glossy reflections, premium framing — for perfume, cosmetics, tech, fashion, and studio product shots." }, { "kind": "prompting", @@ -755,15 +844,25 @@ { "id": "cinemagraph-motion", "name": "Cinemagraph Motion", - "description": "Selective-motion cinemagraph look \u2014 the whole scene stays frozen except one detail, which loops its motion seamlessly.", + "description": "Selective-motion cinemagraph look — the whole scene stays frozen except one detail, which loops its motion seamlessly.", "download": { "repo_id": "Lightricks/LTX-2.3-22b-LoRA-Cinemagraph", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__cinemagraph-motion", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-lora-cinemagraph-0.9.safetensors", + "size_bytes": 201462650, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-LoRA-Cinemagraph" + }, + { + "id": "ltx-2.3__cinemagraph-motion", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-lora-cinemagraph-0.9.safetensors", - "size_bytes": 201453416 + "size_bytes": 201453416, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-LoRA-Cinemagraph" } ] }, @@ -778,7 +877,10 @@ "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "created_at": "2026-07-06", "tags": [ "motion" @@ -801,7 +903,7 @@ { "kind": "input", "title": "Input", - "body": "A single reference image to animate \u2014 runs through the normal image-to-video flow, no special preprocessing." + "body": "A single reference image to animate — runs through the normal image-to-video flow, no special preprocessing." }, { "kind": "prompting", @@ -815,9 +917,9 @@ "kind": "tips", "title": "Tips", "body": [ - "Works best on short clips \u2014 5\u20136 seconds.", + "Works best on short clips — 5–6 seconds.", "LoRA strength ~1.0.", - "Out of scope: camera movement, character/body movement, complex dynamic scenes, or multiple moving subjects \u2014 it's trained on static, locked-off camera footage only. Describe everything except the one animated detail as frozen.", + "Out of scope: camera movement, character/body movement, complex dynamic scenes, or multiple moving subjects — it's trained on static, locked-off camera footage only. Describe everything except the one animated detail as frozen.", "If using a negative prompt, exclude terms like camera movement, pan, tilt, zoom, parallax, whole image moving, background sliding, person moving." ] } @@ -827,12 +929,411 @@ "CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera movement, the man and cow remain completely frozen, only the clouds in the sky move in fast time-lapse, clouds drift and roll across the sky, grass and foreground remain still, seamless natural loop.", "CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera movement, the woman is frozen, her face, eyes, hair, clothing, seat, and airplane interior remain completely frozen, only the illustrated tear drops move downward along her cheeks like a cutout collage animation, seamless natural loop." ] + }, + { + "id": "dolly-in", + "name": "Dolly In", + "description": "Camera-motion control — biases generations toward a dolly-in (camera pushes forward toward the subject, increasing subject scale and reducing background prominence).", + "download": { + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In", + "variants": [ + { + "id": "ltx-2__dolly-in", + "label": "Default", + "filename": "ltx-2-19b-lora-camera-control-dolly-in.safetensors", + "size_bytes": 327309208, + "base_model": "LTX-2", + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://huggingface.co/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2", + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], + "created_at": "2026-01-05", + "tags": [ + "motion" + ], + "recommended_strength": 1.0, + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "A camera-motion control LoRA trained to bias generations toward a dolly-in camera move: the camera pushes forward toward the subject, often increasing subject scale and reducing background prominence." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word — describe the destination of the movement (what the camera arrives at as it pushes forward).", + "Example: A cinematic dolly in toward a woman standing at a rain-soaked cafe window at dusk; the camera pushes steadily forward until her face fills the frame in a tight close-up, the street and passing cars falling out of focus behind her." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": "LoRA strength ~1.0. Home Dolly In is image-to-video: a start still is required. The library can also attach this adapter to text-to-video. Name the end of the shot (the close-up / destination) rather than only saying dolly in." + } + ], + "enhancement_examples": [ + "A cinematic dolly in toward a woman standing at a rain-soaked cafe window at dusk; the camera pushes steadily forward until her face fills the frame in a tight close-up, the street and passing cars falling out of focus behind her.", + "The camera dollies in down a museum hall toward a single marble statue under a spotlight, arriving at a close view of the carved face as the galleries recede and the subject grows to fill the frame.", + "A slow dolly in across a sunlit kitchen toward a steaming cup of coffee on a wooden table, ending in a close-up of the cup as the room and windows shrink in the background." + ] + }, + { + "id": "jib-up", + "name": "Jib Up", + "description": "Camera-motion control — biases generations toward a jib-up (camera rises vertically, revealing more of what sits above the initial frame).", + "download": { + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up", + "variants": [ + { + "id": "ltx-2__jib-up", + "label": "Default", + "filename": "ltx-2-19b-lora-camera-control-jib-up.safetensors", + "size_bytes": 2214978664, + "base_model": "LTX-2", + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://huggingface.co/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2", + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], + "created_at": "2026-01-05", + "tags": [ + "motion" + ], + "recommended_strength": 1.0, + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "A camera-motion control LoRA trained to bias generations toward a jib-up camera move: the camera rises vertically over the course of the shot, revealing more of what sits above the initial frame." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word — describe the destination of the movement (what the camera reveals as it rises).", + "Example: The camera slowly rises from a forest floor of ferns until it clears the canopy and the snow-capped mountain range beyond fills the sky." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": "LoRA strength ~1.0. Home Jib Up is image-to-video: a start still is required. Name what appears at the top of the shot rather than only saying jib up." + } + ], + "enhancement_examples": [ + "The camera slowly rises from a forest floor of ferns until it clears the canopy and the snow-capped mountain range beyond fills the sky.", + "A jib up from a candlelit dinner table to the vaulted restaurant ceiling, chandeliers coming into view as the diners shrink below.", + "The camera cranes upward from a crowded city sidewalk to the rooftops, revealing a golden-hour skyline and a distant river." + ] + }, + { + "id": "jib-down", + "name": "Jib Down", + "description": "Camera-motion control — biases generations toward a jib-down (camera descends vertically, revealing more of what sits lower in the scene).", + "download": { + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down", + "variants": [ + { + "id": "ltx-2__jib-down", + "label": "Default", + "filename": "ltx-2-19b-lora-camera-control-jib-down.safetensors", + "size_bytes": 2214978664, + "base_model": "LTX-2", + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://huggingface.co/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2", + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], + "created_at": "2026-01-05", + "tags": [ + "motion" + ], + "recommended_strength": 1.0, + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "A camera-motion control LoRA trained to bias generations toward a jib-down camera move: the camera descends vertically, revealing more of what sits lower in the scene and changing parallax." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word — describe the destination of the movement (what comes into view near the bottom of the frame as the camera descends).", + "Example: The camera slowly moves down from a hiker's face to their long hiking pants and muddy hiking shoes on a forest trail, the character staying still, soft sounds of nature." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": "LoRA strength ~1.0. Home Jib Down is image-to-video: a start still is required. Name floor details, low objects, or ground-level signage rather than only saying jib down." + } + ], + "enhancement_examples": [ + "The camera slowly moves down from a hiker's face to their long hiking pants and muddy hiking shoes on a forest trail, the character staying still.", + "A jib down from a cathedral rose window to the stone floor and kneeling congregation, candlelight catching the pews as the camera descends.", + "The camera descends from a chef's concentrated face to the sizzling pan and chopped herbs on the stainless-steel counter below." + ] + }, + { + "id": "dolly-out", + "name": "Dolly Out", + "description": "Camera-motion control — biases generations toward a dolly-out (camera pulls backward away from the subject, decreasing subject scale and revealing more of the environment).", + "download": { + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out", + "variants": [ + { + "id": "ltx-2__dolly-out", + "label": "Default", + "filename": "ltx-2-19b-lora-camera-control-dolly-out.safetensors", + "size_bytes": 327309208, + "base_model": "LTX-2", + "repo_id": "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://huggingface.co/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2", + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], + "created_at": "2026-01-05", + "tags": [ + "motion" + ], + "recommended_strength": 1.0, + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "A camera-motion control LoRA trained to bias generations toward a dolly-out camera move: the camera pulls backward away from the subject, often decreasing subject scale and revealing more of the environment." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word — describe the destination of the movement (what exists at the end of the shot as the camera pulls back).", + "Example: The camera slowly moves out, revealing the character in the black suit standing still with her hands loosely clasped in front of her waist, the full room coming into view behind her." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": "LoRA strength ~1.0. Home Dolly Out is image-to-video: a start still is required. Name the far side of the room, the full set, or the space behind the camera rather than only saying dolly out." + } + ], + "enhancement_examples": [ + "The camera slowly moves out, revealing the character in the black suit standing still with her hands loosely clasped in front of her waist, the full room coming into view behind her.", + "A dolly out from a close-up of a ringing telephone until the entire empty office is visible, late-afternoon light through the blinds.", + "The camera pulls back from a child's hands building a sandcastle until the whole beach, tide, and boardwalk fill the frame." + ] + }, + { + "id": "transition", + "name": "Transition", + "description": "First-to-last-frame guided morph — generate a seamless transformation between a start still and an end still.", + "download": { + "repo_id": "joyfox/LTX-2.3-Transition-LORA", + "variants": [ + { + "id": "ltx-2.3__transition", + "label": "Default", + "filename": "ltx2.3-transition.safetensors", + "size_bytes": 390229424, + "base_model": "LTX-2.3", + "repo_id": "joyfox/LTX-2.3-Transition-LORA" + } + ] + }, + "requires_hf_login": false, + "author": { + "name": "joyfox", + "url": "https://huggingface.co/joyfox", + "affiliation": "community" + }, + "license": { + "name": "Apache-2.0", + "url": "https://huggingface.co/joyfox/LTX-2.3-Transition-LORA" + }, + "base_model": "LTX-2.3", + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], + "created_at": "2026-03-20", + "tags": [ + "motion" + ], + "input": { + "kind": "image" + }, + "trigger": "zhuanchang", + "trigger_placement": "anywhere", + "recommended_strength": 1.0, + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "Generates a first-to-last-frame guided transition: given a starting and ending reference image, the model morphs one scene into the other with strong motion continuity." + }, + { + "kind": "input", + "title": "Input", + "body": "A start still and an end still. Home Transition requires both frames." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "Trigger word zhuanchang at the end of the prompt. Describe shot type and camera language, then the subject and the transformation in explicit temporal detail — what changes, how, over the course of the shot — then lighting and atmosphere.", + "Example: A high aerial shot glides low over a churning turquoise ocean as a massive wave rises and curls. As the wave crashes forward, its curling white foam morphs seamlessly into a snow-capped mountain peak. zhuanchang" + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": "LoRA strength ~1.0. Detailed, descriptive prompts outperform short keyword lists. Home Transition is image-to-video with a required start and end still." + } + ], + "enhancement_examples": [ + "Close-up tracking shot. A wilted grey flower in a cracked pot sits on a windowsill. Petals slowly unfurl and deepen from grey to vivid crimson as morning light spreads across the frame, the crack in the pot sealing itself as vines curl upward. Warm golden light, soft film grain, dreamlike atmosphere. zhuanchang", + "A high aerial shot glides low over a churning turquoise ocean as a massive wave rises and curls, its crest breaking into white foaming spray. As the wave crashes forward, its curling white foam morphs seamlessly into a snow-capped mountain peak. zhuanchang", + "A medium shot of a sunlit wooden room; as the camera slowly dollies forward, a young woman's features sharpen and her hair shortens, morphing her into a young man with a slight smirk, the floral sweater becoming a dark leaf motif. zhuanchang" + ] + }, + { + "id": "vbvr", + "name": "VBVR", + "description": "Image-to-video reasoning LoRA — improves multi-object motion, physical interactions, and prompt accuracy.", + "download": { + "repo_id": "LiconStudio/Ltx2.3-VBVR-lora-I2V", + "variants": [ + { + "id": "ltx-2.3__vbvr", + "label": "Default", + "filename": "Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors", + "size_bytes": 554006432, + "base_model": "LTX-2.3", + "repo_id": "LiconStudio/Ltx2.3-VBVR-lora-I2V" + } + ] + }, + "requires_hf_login": false, + "author": { + "name": "LiconStudio", + "url": "https://huggingface.co/LiconStudio", + "affiliation": "community" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2.3", + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], + "created_at": "2026-04-08", + "tags": [ + "motion" + ], + "input": { + "kind": "image" + }, + "recommended_strength": 1.0, + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "A general-purpose image-to-video LoRA tuned on the VBVR video-reasoning suite for complex prompt understanding and physically plausible motion — object interactions, collisions, multi-object scenes, and consistent camera framing." + }, + { + "kind": "input", + "title": "Input", + "body": "A single reference image to animate. Home VBVR is image-to-video: a start still is required." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word — favor concrete, physically-grounded descriptions of what happens and how objects interact or move over time, rather than a short static-scene description.", + "Example: The soccer player sprints across the field with powerful strides. The camera tracks smoothly, keeping him centered in the frame. Fast footsteps, heavy breathing, and distant crowd cheers fill the scene." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": "LoRA strength ~1.0. Home VBVR is image-to-video: a start still is required. Reward temporal and causal detail in the prompt." + } + ], + "enhancement_examples": [ + "The soccer player sprints across the field with powerful strides. The camera tracks smoothly, keeping him centered in the frame. Fast footsteps, heavy breathing, and distant crowd cheers fill the scene.", + "Two glass marbles roll toward each other on a wooden table, collide, and bounce apart along curved paths, the camera locked off and the lighting unchanged.", + "A red ball rolls down a staircase, bouncing on each step with natural gravity, then comes to rest against a closed door at the bottom." + ] } ], "ic_loras": [ { "id": "clean-plate", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Clean Plate", "description": "Remove people and vehicles from a video and reconstruct the static background.", "tags": [ @@ -842,10 +1343,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Clean-Plate", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__clean-plate", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-clean-plate-1.0.safetensors", + "size_bytes": 327318439, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Clean-Plate" + }, + { + "id": "ltx-2.3__clean-plate", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-clean-plate-1.0.safetensors", - "size_bytes": 327309305 + "size_bytes": 327309305, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Clean-Plate" } ] }, @@ -888,18 +1399,27 @@ { "kind": "tips", "title": "Tips", - "body": "LoRA strength 1.0. Name specific objects to remove in both positive and negative prompts for best results." + "body": [ + "LoRA strength 1.0.", + "Describe the empty scene. Name the people and vehicles to remove, as in \"no people and no vehicles\". The reference video already sets the camera move and the background." + ] } ], "default_settings": { "skip_stage_2": true, "resolution_factor": 1.5, "audio_mode": "source" - } + }, + "enhancement_examples": [ + "An empty clean plate of the exact same location: identical background, environment, structures and lighting as the source video, with no people, no humans, no figures, and no body parts such as arms, hands or legs anywhere in the frame." + ] }, { "id": "3d-render-to-real", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "3D Render to Photoreal", "description": "Turn a rough 3D viewport render (Blender blockout, game-engine viewport) into a photorealistic, cinematic video.", "tags": [ @@ -913,13 +1433,17 @@ "id": "strong-v2", "label": "Strong (v2)", "filename": "3DREAL-strong-v2.safetensors", - "size_bytes": 327287352 + "size_bytes": 327287352, + "base_model": "LTX-2.3", + "repo_id": "fal/LTX-2.3-3DREAL-LoRA" }, { "id": "light", "label": "Light", "filename": "3DREAL-light.safetensors", - "size_bytes": 163708856 + "size_bytes": 163708856, + "base_model": "LTX-2.3", + "repo_id": "fal/LTX-2.3-3DREAL-LoRA" } ] }, @@ -942,7 +1466,7 @@ { "kind": "summary", "title": "What it does", - "body": "Turns a rough grey 3D viewport render \u2014 Blender blockout, game-engine viewport or other CG/synthetic render \u2014 into a photorealistic, film-quality video, keeping the exact composition, camera move and layout of the input." + "body": "Turns a rough grey 3D viewport render — Blender blockout, game-engine viewport or other CG/synthetic render — into a photorealistic, film-quality video, keeping the exact composition, camera move and layout of the input." }, { "kind": "input", @@ -960,7 +1484,7 @@ { "kind": "tips", "title": "Tips", - "body": "Composition and camera are locked to the input render; the prompt drives realism, materials and lighting. Download Strong (v2) or Light from the library card \u2014 Light is a subtler push." + "body": "Composition and camera are locked to the input render; the prompt drives realism, materials and lighting. Download Strong (v2) or Light from the library card — Light is a subtler push." } ], "default_settings": { @@ -975,7 +1499,10 @@ }, { "id": "day-to-night", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Day to Night", "description": "Relight a daytime shot to look like it was filmed at night.", "tags": [ @@ -985,10 +1512,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Day-To-Night", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__day-to-night", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-day-to-night-0.9.safetensors", + "size_bytes": 327318440, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Day-To-Night" + }, + { + "id": "ltx-2.3__day-to-night", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-day-to-night-0.9.safetensors", - "size_bytes": 327309305 + "size_bytes": 327309305, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Day-To-Night" } ] }, @@ -1018,35 +1555,45 @@ { "kind": "input", "title": "Input", - "body": "A daytime video. Best near the training bucket: ~768\u00d7448 (or 448\u00d7768) at 97 frames (~4s), 24fps." + "body": "A daytime video. Best near the training bucket: ~768×448 (or 448×768) at 97 frames (~4s), 24fps." }, { "kind": "prompting", "title": "Prompt", "body": [ - "No trigger word \u2014 describe the night scene and its light sources.", - "Example: A realistic nighttime scene. A cafe interior looking out at a dark city street, warm overhead lights casting amber reflections on the furniture." + "No trigger word. Describe only the night lighting of the same shot: color temperature, practical lights, ambient darkness.", + "Do not invent a new location, subject, camera move, or action. The reference video already has those.", + "Example: A realistic nighttime outdoor scene. A mountain landscape under a dark sky filled with bright stars and a prominent Milky Way. Deep natural shadows across the terrain with very faint ambient starlight. Photorealistic night. Only the lighting changes from day to night; identical composition, framing, camera movement and motion." ] }, { "kind": "tips", "title": "Tips", "body": [ - "LoRA strength 1.0.", + "LoRA strength 1.0", "Longer clips are possible but the relight can drift over the shot.", - "Indoor scenes or heavily artificial-light sources are outside the primary training distribution \u2014 outdoor daylight-to-night conversions are the strongest case." + "Indoor scenes or heavily artificial-light sources are outside the primary training distribution — outdoor daylight-to-night conversions are the strongest case." ] } ], "default_settings": { "skip_stage_2": true, "resolution_factor": 1.5, - "audio_mode": "source" - } + "audio_mode": "source", + "lora_strength": 1 + }, + "enhancement_examples": [ + "A realistic nighttime outdoor scene. A mountain landscape under a dark sky filled with bright stars and a prominent Milky Way. Deep natural shadows across the terrain with very faint ambient starlight. Photorealistic night. Only the lighting changes from day to night; identical composition, framing, camera movement and motion.", + "A realistic nighttime scene. A cafe interior looking out at a dark city street at night. Warm overhead interior lights cast amber reflections on the furniture, contrasting with the cool ambient streetlights and deep shadows outside. Only the lighting changes from day to night; identical composition, framing, camera movement and motion.", + "A realistic nighttime scene. A dimly lit interior at night with a warm, low-intensity artificial light coming from the right, casting deep shadows across the room and soft amber highlights on the subject reading. Low-key lighting, high contrast. Only the lighting changes from day to night; identical composition, framing, camera movement and motion." + ] }, { "id": "colorization", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Colorization", "description": "Add realistic color to a grayscale video.", "tags": [ @@ -1057,10 +1604,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Colorization", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__colorization", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-colorization-0.9.safetensors", + "size_bytes": 906080571, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Colorization" + }, + { + "id": "ltx-2.3__colorization", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-colorization-0.9.safetensors", - "size_bytes": 906071437 + "size_bytes": 906071437, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Colorization" } ] }, @@ -1090,13 +1647,13 @@ { "kind": "input", "title": "Input", - "body": "A grayscale / B&W video. Training bucket is ~960\u00d7544 at 121 frames, 24fps." + "body": "A grayscale / B&W video. Training bucket is ~960×544 at 121 frames, 24fps." }, { "kind": "prompting", "title": "Prompt", "body": [ - "Trigger word COLORIZE, in a two-part shape \u2014 first describe the grayscale reference, then the colours you want: 'Reference shows {grayscale scene}. Edited shows the same scene with natural colors restored. COLORIZE {vivid colour description}.'", + "Trigger word COLORIZE, in a two-part shape — first describe the grayscale reference, then the colours you want: 'Reference shows {grayscale scene}. Edited shows the same scene with natural colors restored. COLORIZE {vivid colour description}.'", "Example: Reference shows a wild rabbit on textured boulders in high-contrast monochrome. Edited shows the same scene with natural colors restored. COLORIZE a brown cottontail with warm tan and grey-brown fur on grey stone." ] }, @@ -1104,9 +1661,9 @@ "kind": "tips", "title": "Tips", "body": [ - "Keep the identity and framing wording identical between the two halves \u2014 change only the colour words.", + "Keep the identity and framing wording identical between the two halves — change only the colour words.", "LoRA strength ~1.0; don't render far above the training bucket or colour weakens.", - "Not a fix for blur, compression artifacts, noise or low resolution \u2014 pair with Deblur/Decompression/Upscale first if the source needs that too." + "Not a fix for blur, compression artifacts, noise or low resolution — pair with Deblur/Decompression/Upscale first if the source needs that too." ] } ], @@ -1125,7 +1682,10 @@ }, { "id": "decompression", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Decompression", "description": "Remove compression artifacts and restore a degraded video.", "tags": [ @@ -1136,10 +1696,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Decompression", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__decompression", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-decompression-0.9.safetensors", + "size_bytes": 906080571, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Decompression" + }, + { + "id": "ltx-2.3__decompression", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-decompression-0.9.safetensors", - "size_bytes": 906071437 + "size_bytes": 906071437, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Decompression" } ] }, @@ -1164,12 +1734,12 @@ { "kind": "summary", "title": "What it does", - "body": "Strips compression artifacts \u2014 macroblocking, chroma bleed, ringing, banding \u2014 from low-bitrate video. It is not a denoiser or upscaler." + "body": "Strips compression artifacts — macroblocking, chroma bleed, ringing, banding — from low-bitrate video. It is not a denoiser or upscaler." }, { "kind": "input", "title": "Input", - "body": "A heavily compressed / low-bitrate video. Trained at 960\u00d7544 \u00d7 121 frames, 24fps." + "body": "A heavily compressed / low-bitrate video. Trained at 960×544 × 121 frames, 24fps." }, { "kind": "prompting", @@ -1204,7 +1774,10 @@ }, { "id": "deblur", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Deblur", "description": "Sharpen and remove blur from a video.", "tags": [ @@ -1215,10 +1788,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Deblur", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__deblur", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-deblur-0.9.safetensors", + "size_bytes": 906080571, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Deblur" + }, + { + "id": "ltx-2.3__deblur", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-deblur-0.9.safetensors", - "size_bytes": 906071437 + "size_bytes": 906071437, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Deblur" } ] }, @@ -1243,12 +1826,12 @@ { "kind": "summary", "title": "What it does", - "body": "Regenerates out-of-focus footage in sharp focus, preserving subject, framing and geometry. Handles genuine defocus only \u2014 not motion blur, compression repair, denoise or upscale." + "body": "Regenerates out-of-focus footage in sharp focus, preserving subject, framing and geometry. Handles genuine defocus only — not motion blur, compression repair, denoise or upscale." }, { "kind": "input", "title": "Input", - "body": "A defocused video, used directly as the reference. Trained at 960\u00d7544 \u00d7 121 frames, 24fps; renders well up to 1920\u00d71088." + "body": "A defocused video, used directly as the reference. Trained at 960×544 × 121 frames, 24fps; renders well up to 1920×1088." }, { "kind": "prompting", @@ -1283,7 +1866,10 @@ }, { "id": "cross-eyed", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Cross-Eyed", "description": "Turn a close-up portrait's eyes permanently crossed (inward), keeping expression and framing.", "tags": [ @@ -1293,10 +1879,12 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Cross-Eyed", "variants": [ { - "id": "default", + "id": "ltx-2.3__cross-eyed", "label": "Default", "filename": "ltx-2.3-22b-ic-lora-cross-eyed-0.9.safetensors", - "size_bytes": 327309305 + "size_bytes": 327309305, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Cross-Eyed" } ] }, @@ -1326,13 +1914,13 @@ { "kind": "input", "title": "Input", - "body": "A close-up portrait video with straight eyes. Frame count must satisfy frames % 8 == 1 (e.g. 49); buckets 960\u00d7544\u00d749 or 544\u00d7960\u00d749." + "body": "A close-up portrait video with straight eyes. Frame count must satisfy frames % 8 == 1 (e.g. 49); buckets 960×544×49 or 544×960×49." }, { "kind": "prompting", "title": "Prompt", "body": [ - "No trigger word \u2014 describe the crossed-eye result directly.", + "No trigger word — describe the crossed-eye result directly.", "Example: A close-up portrait video of a man with permanent severe convergent strabismus. Both eyes are continuously turned inward toward the nose throughout the shot. The subject maintains natural facial expression, head movement, lighting, and camera framing." ] } @@ -1345,7 +1933,10 @@ }, { "id": "water-simulation", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Water Simulation", "description": "Add simulated water / fluid VFX to a scene.", "tags": [ @@ -1356,10 +1947,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Water-Simulation", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__water-simulation", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-water-simulation-0.9.safetensors", + "size_bytes": 906080568, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Water-Simulation" + }, + { + "id": "ltx-2.3__water-simulation", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-water-simulation-0.9.safetensors", - "size_bytes": 906071437 + "size_bytes": 906071437, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Water-Simulation" } ] }, @@ -1384,12 +1985,12 @@ { "kind": "summary", "title": "What it does", - "body": "Adds water and fluid VFX \u2014 rivers, surf, rain, waterfalls, floods, splashes, spray, wet-surface speculars \u2014 onto a dry clip, keeping subject, clothing, pose, framing and background fixed." + "body": "Adds water and fluid VFX — rivers, surf, rain, waterfalls, floods, splashes, spray, wet-surface speculars — onto a dry clip, keeping subject, clothing, pose, framing and background fixed." }, { "kind": "input", "title": "Input", - "body": "A dry 'before' video at 24fps, 1920\u00d71088 (or 1088\u00d71920). Up to ~185 frames (~7.7s)." + "body": "A dry 'before' video at 24fps, 1920×1088 (or 1088×1920). Up to ~185 frames (~7.7s)." }, { "kind": "prompting", @@ -1423,7 +2024,9 @@ }, { "id": "ingredients", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3" + ], "name": "Ingredients", "description": "Keep a subject consistent across a video from a reference sheet.", "tags": [ @@ -1433,10 +2036,20 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Ingredients", "variants": [ { - "id": "default", - "label": "Default", + "id": "ltx-2.5__ingredients", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-ingredients-0.9.safetensors", + "size_bytes": 1308787472, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Ingredients" + }, + { + "id": "ltx-2.3__ingredients", + "label": "LTX-2.3", "filename": "ltx-2.3-22b-ic-lora-ingredients-0.9.safetensors", - "size_bytes": 1308778338 + "size_bytes": 1308778338, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Ingredients" } ] }, @@ -1483,18 +2096,18 @@ { "kind": "summary", "title": "What it does", - "body": "Drives a video from a reference sheet \u2014 a single composite image of characters, props and locations \u2014 so those elements stay visually consistent across the shot." + "body": "Drives a video from a reference sheet — a single composite image of characters, props and locations — so those elements stay visually consistent across the shot." }, { "kind": "input", "title": "Input", - "body": "A reference sheet image laying out each element in its own panel. Training bucket 768\u00d7448, 121 frames, 24fps." + "body": "A reference sheet image laying out each element in its own panel. Training bucket 768×448, 121 frames, 24fps." }, { "kind": "prompting", "title": "Prompt", "body": [ - "Two labelled parts, no caps trigger \u2014 first describe each panel of the sheet, then describe the action: 'Reference sheet: {panels \u2014 characters, props, settings}. Generated video: {the action}.'", + "Two labelled parts, no caps trigger — first describe each panel of the sheet, then describe the action: 'Reference sheet: {panels — characters, props, settings}. Generated video: {the action}.'", "Example: Reference sheet: a 3D owl mascot shown from several angles; a bright grocery aisle. Generated video: a high-quality 3D animated commercial outside a modern 'FreshMart' store." ] }, @@ -1502,9 +2115,9 @@ "kind": "tips", "title": "Tips", "body": [ - "Give characters clean close-ups / turnarounds and larger panels \u2014 bigger, clearer panels carry over more faithfully and prevent identity drift.", + "Give characters clean close-ups / turnarounds and larger panels — bigger, clearer panels carry over more faithfully and prevent identity drift.", "LoRA strength ~1.4.", - "The generated video won't invent identities that aren't on the reference sheet \u2014 every character, prop or location it needs to render must have its own panel.", + "The generated video won't invent identities that aren't on the reference sheet — every character, prop or location it needs to render must have its own panel.", "Suggested negative prompt: worst quality, inconsistent motion, blurry, jittery, distorted." ] } @@ -1524,7 +2137,10 @@ }, { "id": "instant-shave", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Instant Shave", "description": "Remove a beard / facial hair from a person in a video.", "tags": [ @@ -1535,10 +2151,12 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave", "variants": [ { - "id": "default", + "id": "ltx-2.3__instant-shave", "label": "Default", "filename": "ltx-2.3-22b-ic-lora-instant-shave-0.9.safetensors", - "size_bytes": 654465349 + "size_bytes": 654465349, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-Instant-Shave" } ] }, @@ -1563,12 +2181,12 @@ { "kind": "summary", "title": "What it does", - "body": "Removes facial hair \u2014 beard, moustache, stubble \u2014 from a person in the video, while keeping identity, expression, motion, lighting and composition." + "body": "Removes facial hair — beard, moustache, stubble — from a person in the video, while keeping identity, expression, motion, lighting and composition." }, { "kind": "input", "title": "Input", - "body": "A reference video of the bearded subject. 960\u00d7544 (or 544\u00d7960) at 25fps, 33\u2013121 frames; match the clip's fps to 25." + "body": "A reference video of the bearded subject. 960×544 (or 544×960) at 25fps, 33–121 frames; match the clip's fps to 25." }, { "kind": "prompting", @@ -1597,9 +2215,12 @@ }, { "id": "outpainting", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Outpainting", - "description": "Extend a video beyond its frame \u2014 widen it, change the aspect ratio, or fill new canvas around the shot.", + "description": "Extend a video beyond its frame — widen it, change the aspect ratio, or fill new canvas around the shot.", "tags": [ "compose" ], @@ -1607,10 +2228,12 @@ "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-In-Outpainting", "variants": [ { - "id": "default", + "id": "ltx-2.3__outpainting", "label": "Default", "filename": "ltx-2.3-22b-ic-lora-in-outpainting-0.9.safetensors", - "size_bytes": 1308778338 + "size_bytes": 1308778338, + "base_model": "LTX-2.3", + "repo_id": "Lightricks/LTX-2.3-22b-IC-LoRA-In-Outpainting" } ] }, @@ -1666,7 +2289,7 @@ { "kind": "tips", "title": "Tips", - "body": "Outpaint only (inpainting isn't supported here). LoRA strength 1.0. Keep additions modest \u2014 very large extensions are harder for the model to fill convincingly." + "body": "Outpaint only (inpainting isn't supported here). LoRA strength 1.0. Keep additions modest — very large extensions are harder for the model to fill convincingly." } ], "default_settings": { @@ -1686,10 +2309,12 @@ "repo_id": "OmerHagage/ltx2-greenscreen-avatar-ic-lora-vertical-v1", "variants": [ { - "id": "default", + "id": "ltx-2.3__greenscreen-avatar", "label": "Default", "filename": "lora_weights_step_05000.safetensors", - "size_bytes": 1308756416 + "size_bytes": 1308756416, + "base_model": "LTX-2.3", + "repo_id": "OmerHagage/ltx2-greenscreen-avatar-ic-lora-vertical-v1" } ] }, @@ -1704,7 +2329,10 @@ "url": "https://huggingface.co/OmerHagage/ltx2-greenscreen-avatar-ic-lora-vertical-v1" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "created_at": "2026-05-13", "input": { "kind": "video" @@ -1717,12 +2345,12 @@ { "kind": "summary", "title": "What it does", - "body": "Transforms a vertical talking-head clip into the same person on a flat green chroma-key background \u2014 keyed and ready to composite onto any background. Sized for portrait/mobile formats (Reels, Shorts, TikTok)." + "body": "Transforms a vertical talking-head clip into the same person on a flat green chroma-key background — keyed and ready to composite onto any background. Sized for portrait/mobile formats (Reels, Shorts, TikTok)." }, { "kind": "input", "title": "Input", - "body": "A vertical (portrait) talking-head video \u2014 a person facing the camera." + "body": "A vertical (portrait) talking-head video — a person facing the camera." }, { "kind": "prompting", @@ -1745,9 +2373,12 @@ }, { "id": "upscale", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "name": "Upscale (Refine)", - "description": "Generative second-pass refinement \u2014 turn a soft / low-res clip into a cleaner, more detailed one.", + "description": "Generative second-pass refinement — turn a soft / low-res clip into a cleaner, more detailed one.", "tags": [ "restore" ], @@ -1756,10 +2387,12 @@ "repo_id": "Zlikwid/LTX_2.3_Upscale_IC_Lora", "variants": [ { - "id": "default", + "id": "ltx-2.3__upscale", "label": "Default", "filename": "ltx2.3_upscale_ic-lora_06250.safetensors", - "size_bytes": 327287384 + "size_bytes": 327287384, + "base_model": "LTX-2.3", + "repo_id": "Zlikwid/LTX_2.3_Upscale_IC_Lora" } ] }, @@ -1784,12 +2417,12 @@ { "kind": "summary", "title": "What it does", - "body": "A generative refinement pass, not a plain upscaler \u2014 runs a soft or low-res clip back through LTX 2.3 to recover cleaner detail. Output can shift with settings, so it's meant as a second stage (e.g. after a stage-1-only run)." + "body": "A generative refinement pass, not a plain upscaler — runs a soft or low-res clip back through LTX 2.3 to recover cleaner detail. Output can shift with settings, so it's meant as a second stage (e.g. after a stage-1-only run)." }, { "kind": "input", "title": "Input", - "body": "Bicubic-upscale your source to the target resolution first, then feed that as the reference video. Example: 640\u00d7360 \u2192 bicubic to 1280\u00d7720 \u2192 upscale pass." + "body": "Bicubic-upscale your source to the target resolution first, then feed that as the reference video. Example: 640×360 → bicubic to 1280×720 → upscale pass." }, { "kind": "prompting", @@ -1817,7 +2450,7 @@ { "id": "crossview-prompt", "name": "CrossView Prompt", - "description": "Re-render a reference clip from a new camera angle \u2014 same scene and subject, different viewpoint. Uses a fixed camera-angle prompt vocabulary.", + "description": "Re-render a reference clip from a new camera angle — same scene and subject, different viewpoint. Uses a fixed camera-angle prompt vocabulary.", "tags": [ "camera" ], @@ -1826,10 +2459,12 @@ "repo_id": "Cseti/LTX2.3-22B_IC-LoRA-CrossView-Prompt", "variants": [ { - "id": "default", + "id": "ltx-2.3__crossview-prompt", "label": "Default", "filename": "LTX2.3-22B_IC-LoRA-CrossView-Prompt_v0.9_13700.safetensors", - "size_bytes": 100767456 + "size_bytes": 100767456, + "base_model": "LTX-2.3", + "repo_id": "Cseti/LTX2.3-22B_IC-LoRA-CrossView-Prompt" } ] }, @@ -1844,7 +2479,10 @@ "url": "https://huggingface.co/Cseti/LTX2.3-22B_IC-LoRA-CrossView-Prompt" }, "base_model": "LTX-2.3", - "supported_models": ["LTX-2.3", "LTX-2.5"], + "supported_models": [ + "LTX-2.3", + "LTX-2.5" + ], "created_at": "2026-07-11", "input": { "kind": "video" @@ -1870,16 +2508,16 @@ "body": [ "Every prompt must start with the trigger crossview. and follow this template (use the exact phrases):", "crossview. new camera angle: {azimuth}, {elevation}, {distance}.", - "Azimuth: same angle \u00b7 slightly to the left \u00b7 slightly to the right \u00b7 to the left \u00b7 to the right \u00b7 far to the left \u00b7 far to the right", - "Elevation: lower \u00b7 same height \u00b7 higher", - "Distance: closer \u00b7 same distance \u00b7 further", + "Azimuth: same angle · slightly to the left · slightly to the right · to the left · to the right · far to the left · far to the right", + "Elevation: lower · same height · higher", + "Distance: closer · same distance · further", "Example: crossview. new camera angle: to the right, lower, closer." ] }, { "kind": "tips", "title": "Tips", - "body": "Best on small, single-step angle changes. For a larger viewpoint shift, chain several small steps \u2014 feed the generated view back in as the new reference and apply another small angle. Views from behind are out of range (frontal sector only, about \u00b160\u00b0)." + "body": "Best on small, single-step angle changes. For a larger viewpoint shift, chain several small steps — feed the generated view back in as the new reference and apply another small angle. Views from behind are out of range (frontal sector only, about ±60°)." } ], "default_settings": { @@ -1918,6 +2556,329 @@ } } } + }, + { + "id": "alpha-gen", + "name": "AlphaGen", + "description": "Cut a subject out of a video without a green screen. Returns a grayscale alpha matte.", + "tags": [ + "effect" + ], + "download": { + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Alpha-Gen", + "variants": [ + { + "id": "ltx-2.5__alpha-gen", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-alpha-gen-0.9.safetensors", + "size_bytes": 1308787472, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Alpha-Gen" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2.5", + "supported_models": [ + "LTX-2.5" + ], + "input": { + "kind": "video" + }, + "preprocessing": [], + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "Generates a matching alpha matte for a video: white is the subject, black is the background. It handles hair, fur, smoke, fire, sheer fabric, glass and water, with no green screen, mask or prompt." + }, + { + "kind": "input", + "title": "Input", + "body": "A video of up to 145 frames (about 6s at 24fps). Longer clips can leak the colors of the video into the matte, so trim or split them first." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "Leave the prompt empty. The model decides the foreground on its own, and a prompt does not steer which object is matted." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": [ + "LoRA strength 1.0", + "The matte has the same size and length as the source, frame for frame. Use it as the alpha channel of the original clip.", + "There is no control over which object is matted." + ] + } + ], + "default_settings": { + "skip_stage_2": true, + "resolution_factor": 1.0, + "audio_mode": "source", + "lora_strength": 1 + }, + "allows_empty_prompt": true + }, + { + "id": "layout-to-render", + "name": "Layout to Render", + "description": "Turn a plain 3D layout video into a finished, photoreal shot. A still image sets the look.", + "tags": [ + "transform" + ], + "download": { + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Layout-To-Render", + "variants": [ + { + "id": "ltx-2.5__layout-to-render", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-layout-to-render-1.0.safetensors", + "size_bytes": 1308787439, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Layout-To-Render" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2.5", + "supported_models": [ + "LTX-2.5" + ], + "input": { + "kind": "video" + }, + "allows_reference_image": true, + "reference_image_required": true, + "reference_image_frame": -1, + "preprocessing": [], + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "Renders a plain 3D layout (simple shapes and a camera move) as a finished shot. The layout video sets the motion and the framing. The reference image sets the colors, the materials and the light." + }, + { + "kind": "input", + "title": "Input", + "body": "A layout video of up to 10 seconds, and a finished image of the first frame. The image is placed before the first frame, so it is a look reference and not a frame of the clip." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word. Describe the finished shot in one sentence." + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": [ + "LoRA strength 1.0", + "Use an image that matches the layout framing. The model takes the look from the image, and the motion from the layout." + ] + } + ], + "default_settings": { + "skip_stage_2": false, + "stage_2_ic_lora": true, + "resolution_factor": 1.0, + "audio_mode": "source", + "lora_strength": 1 + } + }, + { + "id": "restore", + "name": "Restore", + "description": "Restore old and damaged footage as a clean, colour, high-resolution video.", + "tags": [ + "restore" + ], + "download": { + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Restore", + "variants": [ + { + "id": "ltx-2.5__restore", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-restore-1.0.safetensors", + "size_bytes": 1711643914, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Restore" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2.5", + "supported_models": [ + "LTX-2.5" + ], + "input": { + "kind": "video" + }, + "allows_reference_image": true, + "reference_image_frame": 0, + "preprocessing": [], + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "Restores archive footage: low-resolution web rips, low-bitrate broadcast, tape, sepia or black-and-white film. It removes compression damage, tape and sepia casts, flicker, dirt and scratches. It renders the same shot in natural colour. Trained on LTX-2.3 and tested on LTX-2.5." + }, + { + "kind": "input", + "title": "Input", + "body": "An archive clip with progressive frames. Deinterlace an interlaced clip first. Do not denoise or sharpen it. Keep the aspect ratio: do not stretch a 4:3 scan to 16:9. An optional look image sets the colours and the details of the first frame. Use a restored still of the first frame of the clip." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word. Describe the period, the place, the light, the materials and what people wear. The prompt steers the colour.", + "Keep the prompt generic across the frame. Every tile of the frame receives the whole prompt.", + "Example: a steam locomotive arriving at a small rural railway station in 1896, passengers in period coats and hats waiting on the platform, wooden station buildings, natural colour" + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": [ + "LoRA strength 1.0. The strength works like a switch: at 0.7 the clip stays monochrome, and 1.4 over-tints.", + "Clean footage does not need this LoRA. It always restores.", + "A clip longer than 97 frames runs in 97-frame windows. This keeps the colour stable.", + "To add detail after the restoration, run the result through Refine Details." + ] + } + ], + "enhancement_examples": [ + "a 1950s girl with blonde hair at a table drinking a glass of milk, printed dress, living room, soft window light, natural colour", + "a steam locomotive arriving at a small rural railway station in 1896, passengers in period coats and hats waiting on the platform, wooden station buildings, natural colour", + "the Hindenburg airship close up at its mooring mast with ground crew on a grass field, ribbed silver fabric hull with painted lettering, overcast daylight, natural colour" + ], + "default_settings": { + "skip_stage_2": true, + "resolution_factor": 2.0, + "audio_mode": "source", + "lora_strength": 1, + "tiling": { + "long_side": 960, + "short_side": 544, + "window_frames": 97 + } + } + }, + { + "id": "refine-details", + "name": "Refine Details", + "description": "Rebuild fine detail in a soft, compressed or upscaled video.", + "tags": [ + "restore" + ], + "download": { + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Refine-Details", + "variants": [ + { + "id": "ltx-2.5__refine-details", + "label": "LTX-2.5", + "filename": "ltx-2.5-22b-ic-lora-refine-details-1.0.safetensors", + "size_bytes": 1308787534, + "base_model": "LTX-2.5", + "repo_id": "Lightricks/LTX-2.5-22b-IC-LoRA-Refine-Details" + } + ] + }, + "requires_hf_login": true, + "author": { + "name": "LTX", + "url": "https://huggingface.co/Lightricks", + "affiliation": "ltx" + }, + "license": { + "name": "LTX-2 Community License", + "url": "https://github.com/Lightricks/LTX-2/blob/main/LICENSE" + }, + "base_model": "LTX-2.5", + "supported_models": [ + "LTX-2.5" + ], + "input": { + "kind": "video" + }, + "allows_reference_image": true, + "reference_image_frame": 0, + "preprocessing": [], + "instructions": [ + { + "kind": "summary", + "title": "What it does", + "body": "Rebuilds the fine detail of a soft, compressed or upscaled clip: texture, edges and grain. The framing, the exposure and the colour stay the same." + }, + { + "kind": "input", + "title": "Input", + "body": "A delivery-grade clip, for example 1080p web video, a compressed clip or a generated clip. Do not sharpen or denoise it first. An optional look image sets the detail of the first frame. Use a sharp still of the first frame of the clip." + }, + { + "kind": "prompting", + "title": "Prompt", + "body": [ + "No trigger word. Describe the rendering (sharpness, texture, grain, light), not the subjects. Every tile of the frame receives the whole prompt.", + "Example: Locked-off wide shot of a clear mountain stream running over mossy granite boulders under a beech forest canopy, thousands of individual leaves, sunlight dappled evenly across the scene, water sparkling with fine ripples, ferns and lichen in the foreground, deep focus, tack sharp everywhere, nature documentary, photoreal, 8K, sharp photographic detail, crisp faces and clothing texture, natural grain, high resolution footage" + ] + }, + { + "kind": "tips", + "title": "Tips", + "body": [ + "LoRA strength 1.0.", + "Archive footage looks cleaner but emptier. Run Restore first, then refine.", + "A blurred area stays blurred: the model cannot add detail that the source never had.", + "Pristine cinema footage can come out slightly softer." + ] + } + ], + "enhancement_examples": [ + "Locked-off wide shot of a clear mountain stream running over mossy granite boulders under a beech forest canopy, thousands of individual leaves, sunlight dappled evenly across the scene, water sparkling with fine ripples, ferns and lichen in the foreground, deep focus, tack sharp everywhere, nature documentary, photoreal, 8K, sharp photographic detail, crisp faces and clothing texture, natural grain, high resolution footage", + "Slow dolly forward down a narrow neon-lit alley at night, glowing signs reading RAMEN, OPEN 24H, KARAOKE and BAR, wet pavement reflecting the colours, paper lanterns swaying gently, a few pedestrians with umbrellas walking away from camera, deep focus, photoreal, 8K, sharp photographic detail, crisp faces and clothing texture, natural grain, high resolution footage" + ], + "default_settings": { + "skip_stage_2": true, + "resolution_factor": 2.0, + "audio_mode": "source", + "lora_strength": 1, + "tiling": { + "long_side": 1024, + "short_side": 576 + } + } } ] } diff --git a/backend/runtime_config/low_performance_machine.py b/backend/runtime_config/low_performance_machine.py new file mode 100644 index 000000000..974819e0a --- /dev/null +++ b/backend/runtime_config/low_performance_machine.py @@ -0,0 +1,13 @@ +"""Detect a machine that runs heavy local generations slowly.""" + +from __future__ import annotations + +from runtime_config.runtime_config import RuntimeConfig + + +def detect_low_performance_machine(config: RuntimeConfig) -> bool: + """True when heavy local generations are likely to take a long time. + + For now only Darwin counts. Extend this with RAM or VRAM checks when needed. + """ + return config.darwin_unified_memory diff --git a/backend/runtime_config/ltx_capabilities.py b/backend/runtime_config/ltx_capabilities.py index 436995e96..009b7d1ff 100644 --- a/backend/runtime_config/ltx_capabilities.py +++ b/backend/runtime_config/ltx_capabilities.py @@ -13,6 +13,7 @@ from api_types import ( LOCAL_MULTI_KEYFRAME_MAX_COUNT, LTXLocalModelId, + LTXVideoGenAspectRatio, LTXVideoGenPipeline, LTXVideoGenResolution, ) @@ -29,7 +30,7 @@ "camera_motion", "auto_duration", ] -LtxAspectRatio = Literal["16:9", "9:16"] +LtxAspectRatio = LTXVideoGenAspectRatio @dataclass(frozen=True) @@ -46,7 +47,7 @@ class LtxOfferingCapabilities: camera_motion: bool # t2v/i2v only: send duration=null and the cloud worker picks length from the prompt. auto_duration: bool - # Label → (width, height) for 16:9; 9:16 is swapped at pixels_for(). + # Label → (width, height) for 16:9. Other ratios are derived in pixels_for(). resolution_pixels_16_9: dict[LTXVideoGenResolution, tuple[int, int]] @@ -62,14 +63,47 @@ class ApiOfferingCapabilities(LtxOfferingCapabilities): type can't be confused with local_caps()'s at the type-checker level.""" -# Local Fast sizes: one /64 two-stage grid for 2.3 and 2.5. Splitting 540p -# (2.3 960×544 vs 2.5 1024×576) made a model switch fail assert_resolution. -_LOCAL_PIXELS_16_9: dict[LTXVideoGenResolution, tuple[int, int]] = { +# Real two-pass canvases. Splitting 540p (2.3 960×544 vs 2.5 1024×576) made a +# model switch fail assert_resolution, so 2.3 and 2.5 share this grid. +_TWO_PASS_PIXELS_16_9: dict[LTXVideoGenResolution, tuple[int, int]] = { "540p": (1024, 576), "720p": (1280, 704), "1080p": (1920, 1088), } +# Text and image labels that denoise the parent canvas and return the first pass. +_STAGE1_PARENT: dict[LTXVideoGenResolution, LTXVideoGenResolution] = { + "270p": "540p", + "360p": "720p", +} + +# A2V finishes both passes, so these are the picture, not the text-to-video parent. +_A2V_TWO_PASS_PIXELS_16_9: dict[LTXVideoGenResolution, tuple[int, int]] = { + "270p": (576, 320), + "360p": (704, 384), +} + + +def _local_pixel_map() -> dict[LTXVideoGenResolution, tuple[int, int]]: + pixels = dict(_TWO_PASS_PIXELS_16_9) + for label, parent in _STAGE1_PARENT.items(): + pixels[label] = _TWO_PASS_PIXELS_16_9[parent] + return pixels + + +# 270p and 360p are the parent pair, not a second copy of those numbers. +_LOCAL_PIXELS_16_9: dict[LTXVideoGenResolution, tuple[int, int]] = _local_pixel_map() + +CanvasMode = Literal["video", "a2v"] + + +@dataclass(frozen=True) +class LocalCanvas: + width: int + height: int + skip_stage_2: bool + + _API_PIXELS_16_9: dict[LTXVideoGenResolution, tuple[int, int]] = { "720p": (1280, 720), "1080p": (1920, 1080), @@ -95,14 +129,13 @@ class ApiOfferingCapabilities(LtxOfferingCapabilities): # DistilledA2V is wired for local 2.5. Auto duration is DurationHead on the # distilled checkpoint (t2v/i2v; A2V length comes from the audio). Advertised # only when those weights are on disk — see effective_local_caps(). -# Retake/Extend match API 2.5 (unsupported); local 2.3 still offers both. _LOCAL_2_5 = LocalOfferingCapabilities( t2v=True, i2v=True, a2v=True, ic_lora=True, - retake=False, - extend=False, + retake=True, + extend=True, multi_keyframe=True, multi_keyframe_max_count=LOCAL_MULTI_KEYFRAME_MAX_COUNT, user_loras=True, @@ -241,15 +274,128 @@ def supports(caps: LtxOfferingCapabilities, feature: LtxCapabilityFeature) -> bo assert_never(feature) +_ASPECT_PARTS: dict[LtxAspectRatio, tuple[int, int]] = { + "21:9": (21, 9), + "16:9": (16, 9), + "3:2": (3, 2), + "4:3": (4, 3), + "1:1": (1, 1), + "4:5": (4, 5), + "9:16": (9, 16), +} + + +def _snap_nearest_64(value: int) -> int: + """Nearest multiple of 64. An exact halfway rounds up. + + Always rounding up turned a 4:5 long side of 720 into 768, which is 4:3. + Halfway still rounds up so a *.5 multiple cannot shrink the way Python's + half-to-even round did on the two-stage grid. + """ + remainder = value % 64 + if remainder == 0: + return value + if remainder < 32: + return value - remainder + return value + (64 - remainder) + + +def _pixels_from_anchor( + anchor: tuple[int, int], + aspect: LtxAspectRatio, + *, + snap: bool, +) -> tuple[int, int]: + """Short side is the 16:9 height. 16:9 itself stays the stored anchor.""" + if aspect == "16:9": + return anchor + short = anchor[1] + width_part, height_part = _ASPECT_PARTS[aspect] + if width_part >= height_part: + height = short + width = round(short * width_part / height_part) + else: + width = short + height = round(short * height_part / width_part) + if snap: + return _snap_nearest_64(width), _snap_nearest_64(height) + return width, height + + +def local_canvas(resolution: LTXVideoGenResolution, *, mode: CanvasMode) -> LocalCanvas: + """One record for a local label. Video 270p/360p skip stage 2 on the parent canvas.""" + if resolution not in _LOCAL_PIXELS_16_9: + raise KeyError(resolution) + if mode == "a2v": + override = _A2V_TWO_PASS_PIXELS_16_9.get(resolution) + if override is not None: + width, height = override + return LocalCanvas(width, height, skip_stage_2=False) + width, height = _LOCAL_PIXELS_16_9[resolution] + return LocalCanvas( + width, + height, + skip_stage_2=mode == "video" and resolution in _STAGE1_PARENT, + ) + + +def budget_size(canvas: LocalCanvas) -> tuple[int, int]: + """Pixels the job denoises. Stage-1-only labels are half the stored canvas.""" + if canvas.skip_stage_2: + return canvas.width // 2, canvas.height // 2 + return canvas.width, canvas.height + + +def budget_pixels( + caps: LtxOfferingCapabilities, + resolution: LTXVideoGenResolution, + aspect: LtxAspectRatio, + *, + mode: CanvasMode, +) -> tuple[int, int]: + """Denoised size for one ratio. Video 270p/360p are half the parent frame.""" + if mode == "a2v": + width, height = a2v_pixels_for(caps, resolution, aspect) + else: + width, height = pixels_for(caps, resolution, aspect) + if mode == "video" and resolution in _STAGE1_PARENT: + return width // 2, height // 2 + return width, height + + def pixels_for( caps: LtxOfferingCapabilities, resolution: LTXVideoGenResolution, aspect: LtxAspectRatio, ) -> tuple[int, int]: + """Short side is the 16:9 height. 16:9 itself stays the stored anchor. + + API sizes are the rounded short-side formula so they match ltxv-api tiles. + Local sizes then snap each edge to the nearest multiple of 64. + """ size = caps.resolution_pixels_16_9.get(resolution) if size is None: raise KeyError(resolution) - width, height = size - if aspect == "9:16": - return height, width - return width, height + return _pixels_from_anchor( + size, + aspect, + snap=isinstance(caps, LocalOfferingCapabilities), + ) + + +def a2v_pixels_for( + caps: LtxOfferingCapabilities, + resolution: LTXVideoGenResolution, + aspect: LtxAspectRatio, +) -> tuple[int, int]: + """A2V 270p/360p finish at their own canvas. Other labels use pixels_for.""" + if resolution not in caps.resolution_pixels_16_9: + raise KeyError(resolution) + override = _A2V_TWO_PASS_PIXELS_16_9.get(resolution) + if override is None: + return pixels_for(caps, resolution, aspect) + return _pixels_from_anchor( + override, + aspect, + snap=isinstance(caps, LocalOfferingCapabilities), + ) diff --git a/backend/runtime_config/model_download_specs.py b/backend/runtime_config/model_download_specs.py index 9bafad251..73e4eba87 100644 --- a/backend/runtime_config/model_download_specs.py +++ b/backend/runtime_config/model_download_specs.py @@ -10,12 +10,14 @@ from api_types import ( LTXLocalModelId, + LTXVideoGenAspectRatio, LTXVideoGenDuration, LTXVideoGenFps, LTXVideoGenPipeline, LTXVideoGenResolution, LTXVideoGenerationResolutionSpec, LTXVideoGenerationSpec, + LtxCatalogModelFamily, ModelCheckpointID, ) from runtime_config.ltx_api_text_encoder_ids import ( @@ -89,7 +91,9 @@ class LTXLocalModelSpec: # None for monolith 2.3 (DurationHead lives inside the fat checkpoint). Split 2.5 # ships it as model_patches/ltx-2.5-duration-head-bf16.safetensors. duration_head_cp: ModelCheckpointID | None - # None when the model has no built-in Union Control IC-LoRA (LTX 2.5 today). + # None when the model has no built-in Union Control IC-LoRA. 2.3 and 2.5 share + # `_DISTILLED_IC_LORAS` (the 2.3 union-control adapter); leave this off first-run + # required CPs so a 2.5 install still prompts from the IC-LoRA panel. ic_loras_spec: LtxIcLorasSpec | None relevance: LTXLocalModelRelevance supported_pipelines: tuple[tuple[LTXVideoGenPipeline, LTXVideoGenerationSpec], ...] @@ -114,15 +118,29 @@ class LTXLocalModelSpec: is_latest: bool = False +# Widest to tallest. Local text, image, and audio share this; the pipeline only requires /64. +_LOCAL_ASPECT_RATIOS: tuple[LTXVideoGenAspectRatio, ...] = ( + "21:9", + "16:9", + "3:2", + "4:3", + "1:1", + "4:5", + "9:16", +) + + def _local_resolution_spec( *, fps_to_durations: dict[LTXVideoGenFps, tuple[LTXVideoGenDuration, ...]], + aspect_ratios: tuple[LTXVideoGenAspectRatio, ...] = _LOCAL_ASPECT_RATIOS, ) -> LTXVideoGenerationResolutionSpec: return LTXVideoGenerationResolutionSpec( fps_to_durations={ fps: list(durations) for fps, durations in fps_to_durations.items() }, + aspect_ratios=list(aspect_ratios), ) @@ -131,32 +149,71 @@ def _local_resolution_spec( PERSON_DETECTOR_CP_ID: ModelCheckpointID = "yolox-l-torchscript" POSE_PROCESSOR_CP_ID: ModelCheckpointID = "dw-ll-ucoco-384-bs5" +# Static Fast ceiling. List-time hiding uses decide_video_job so CUDA 16 GB does +# not advertise 720p/20s or 1080p/10s; a 5090 that streams those cells still sees +# them. Darwin keeps this ceiling (no CUDA stream-curve compare). 1080p/20s is +# never in this table. Every duration list is listed at 24, 25, 48, and 50. +_LOCAL_FPS: tuple[LTXVideoGenFps, ...] = (24, 25, 48, 50) + + +def _local_fps_durations( + durations: tuple[LTXVideoGenDuration, ...], +) -> dict[LTXVideoGenFps, tuple[LTXVideoGenDuration, ...]]: + return {fps: durations for fps in _LOCAL_FPS} + + +_FAST_540P_DURATIONS = _local_resolution_spec( + fps_to_durations=_local_fps_durations((2, 3, 4, 5, 6, 8, 10, 20)), +) _FAST_LOCAL_RESOLUTIONS_DURATIONS: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] = { + # Same duration list as 540p. The pipeline runs the 540p/720p canvas and + # returns the first pass, so these cells are cheaper than that canvas. + "270p": _FAST_540P_DURATIONS, + "360p": _FAST_540P_DURATIONS, + "540p": _FAST_540P_DURATIONS, + "720p": _local_resolution_spec( + fps_to_durations=_local_fps_durations((2, 3, 4, 5, 6, 8, 10, 20)), + ), + "1080p": _local_resolution_spec( + fps_to_durations=_local_fps_durations((2, 3, 4, 5, 10)), + ), +} +# A2V keeps the previous durations. 270p/360p are smaller two-pass canvases, +# not the text-to-video first pass, and they share the 540p duration list. +_A2V_LOCAL_RESOLUTIONS_DURATIONS: dict[LTXVideoGenResolution, LTXVideoGenerationResolutionSpec] = { + "270p": _local_resolution_spec( + fps_to_durations=_local_fps_durations((5, 6, 8, 10, 20)), + ), + "360p": _local_resolution_spec( + fps_to_durations=_local_fps_durations((5, 6, 8, 10, 20)), + ), "540p": _local_resolution_spec( - fps_to_durations={ - 24: (5, 6, 8, 10, 20), - }, + fps_to_durations=_local_fps_durations((5, 6, 8, 10, 20)), ), "720p": _local_resolution_spec( - fps_to_durations={ - 24: (5, 6, 8, 10), - }, + fps_to_durations=_local_fps_durations((5, 6, 8, 10, 20)), ), "1080p": _local_resolution_spec( - fps_to_durations={ - 24: (5,), - }, + fps_to_durations=_local_fps_durations((5, 10)), ), } + +def local_aspect_ratios(resolution: str, *, is_a2v: bool) -> tuple[str, ...]: + """Aspects advertised for one local resolution cell. Closest-match reads this.""" + table = _A2V_LOCAL_RESOLUTIONS_DURATIONS if is_a2v else _FAST_LOCAL_RESOLUTIONS_DURATIONS + spec = table.get(cast(LTXVideoGenResolution, resolution)) + if spec is None: + raise KeyError(resolution) + return tuple(spec.aspect_ratios) + _DISTILLED_PIPELINES_2_3: tuple[tuple[LTXVideoGenPipeline, LTXVideoGenerationSpec], ...] = ( ( "fast", LTXVideoGenerationSpec( display_name="LTX 2.3 Fast", supported_resolutions_durations=_FAST_LOCAL_RESOLUTIONS_DURATIONS, - # DistilledA2VPipeline supports A2V at the same envelope as t2v/i2v. - a2v_supported_resolutions_durations=_FAST_LOCAL_RESOLUTIONS_DURATIONS, + a2v_supported_resolutions_durations=_A2V_LOCAL_RESOLUTIONS_DURATIONS, ), ), ) @@ -167,7 +224,7 @@ def _local_resolution_spec( LTXVideoGenerationSpec( display_name="LTX 2.5 Fast", supported_resolutions_durations=_FAST_LOCAL_RESOLUTIONS_DURATIONS, - a2v_supported_resolutions_durations=_FAST_LOCAL_RESOLUTIONS_DURATIONS, + a2v_supported_resolutions_durations=_A2V_LOCAL_RESOLUTIONS_DURATIONS, ), ), ) @@ -343,6 +400,7 @@ def get_model_cp_spec(cp_id: ModelCheckpointID) -> ModelCheckpointSpec: assert_never(cp_id) +# 2.3 Union Control adapter. 2.5 reuses the same file — many 2.3 IC-LoRAs run on 2.5. _DISTILLED_IC_LORAS = LtxIcLorasSpec( depth_cp="ltx-2.3-22b-ic-lora-union-control-ref0.5", canny_cp="ltx-2.3-22b-ic-lora-union-control-ref0.5", @@ -375,7 +433,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: video_vae_conv_cp="ltx-2.5-video-vae-conv", audio_vae_cp="ltx-2.5-audio-vae", duration_head_cp="ltx-2.5-duration-head", - ic_loras_spec=None, + ic_loras_spec=_DISTILLED_IC_LORAS, relevance=LTXLocalModelRelevant( upgrade_messages={ "ltx-2.3-22b-distilled": _DISTILLED_2_5_WHATS_NEW, @@ -383,7 +441,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: }, ), supported_pipelines=_DISTILLED_PIPELINES_2_5, - version_label="2.5", + version_label="LTX 2.5", api_prompt_embedding_model=LTX_2_5_API_PROMPT_EMBEDDING_MODEL, wants_audio_visual_captions=True, prompt_enhancer_cp="gemma-4-e2b-it", @@ -403,7 +461,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: upgrade_messages={"ltx-2.3-22b-distilled": _DISTILLED_1_1_WHATS_NEW}, ), supported_pipelines=_DISTILLED_PIPELINES_2_3, - version_label="2.3", + version_label="LTX 2.3", ) case "ltx-2.3-22b-distilled": return LTXLocalModelSpec( @@ -417,7 +475,7 @@ def get_ltx_model_spec(model_id: LTXLocalModelId) -> LTXLocalModelSpec: ic_loras_spec=_DISTILLED_IC_LORAS, relevance=LTXLocalModelRelevant(upgrade_messages={}), supported_pipelines=_DISTILLED_PIPELINES_2_3, - version_label="2.3 (1.0)", + version_label="LTX 2.3 (1.0)", ) case _: assert_never(model_id) @@ -634,7 +692,7 @@ def get_downloaded_ltx_model_id(models_dir: Path) -> LTXLocalModelId | None: return downloaded[0] -def _ltx_generation_bundle_on_disk(models_dir: Path, model_id: LTXLocalModelId) -> bool: +def ltx_generation_bundle_on_disk(models_dir: Path, model_id: LTXLocalModelId) -> bool: """True when the always-required generation checkpoints for ``model_id`` are present. Transformer + upscaler (+ split VAEs for 2.5) are required regardless of settings. The text @@ -660,16 +718,39 @@ def resolve_active_ltx_model_id( ) -> LTXLocalModelId | None: # Only honour ``preferred`` if its full generation bundle is on disk — otherwise it would # be picked and then die in get_existing_cp_path on a missing companion (e.g. upscaler). - if preferred is not None and _ltx_generation_bundle_on_disk(models_dir, preferred): + if preferred is not None and ltx_generation_bundle_on_disk(models_dir, preferred): return preferred # Prefer a version that can actually generate (newest first); fall back to whatever # transformer is on disk as a last resort so a partial install still resolves to something. for model_id in ALL_LTX_LOCAL_MODEL_IDS: - if _ltx_generation_bundle_on_disk(models_dir, model_id): + if ltx_generation_bundle_on_disk(models_dir, model_id): return model_id return get_downloaded_ltx_model_id(models_dir) +def ltx_catalog_family_for_model(model_id: LTXLocalModelId) -> LtxCatalogModelFamily: + if model_id.startswith("ltx-2.5"): + return "LTX-2.5" + return "LTX-2.3" + + +def installed_ltx_catalog_families(models_dir: Path) -> frozenset[LtxCatalogModelFamily]: + """LTX families with a runnable generation bundle on disk — not the active model.""" + return frozenset( + ltx_catalog_family_for_model(model_id) + for model_id in ALL_LTX_LOCAL_MODEL_IDS + if ltx_generation_bundle_on_disk(models_dir, model_id) + ) + + +def catalog_item_visible_for_installed_ltx( + supported_models: list[LtxCatalogModelFamily], models_dir: Path +) -> bool: + """True when at least one of ``supported_models`` is installed (runnable on disk).""" + installed = installed_ltx_catalog_families(models_dir) + return any(family in installed for family in supported_models) + + def _validate_model_cp_specs() -> None: relative_paths: dict[Path, ModelCheckpointID] = {} for cp_id in ALL_MODEL_CP_IDS: diff --git a/backend/runtime_config/offerings.py b/backend/runtime_config/offerings.py new file mode 100644 index 000000000..5c472c81c --- /dev/null +++ b/backend/runtime_config/offerings.py @@ -0,0 +1,52 @@ +"""Offering ids (`ltx-2.5-fast`) vs local checkpoints and future API ids. + +GenSpace/VideoEditor keep using pipeline ids (`fast` / `pro`). Desktop and Remote +create use these offering ids so a later API path can share the same `params.model` field. +""" + +from __future__ import annotations + +from pathlib import Path + +from api_types import OfferingId, LTXLocalModelId, LTXVideoGenPipeline +from runtime_config.model_download_specs import ltx_generation_bundle_on_disk + +# Newest first — same order as ALL_LTX_LOCAL_MODEL_IDS. +OFFERING_IDS: tuple[OfferingId, ...] = ("ltx-2.5-fast", "ltx-2.3-fast") + +# Preferred checkpoint first within an offering (2.3 1.1 before 2.3 1.0). +OFFERING_LOCAL_MODEL_IDS: dict[OfferingId, tuple[LTXLocalModelId, ...]] = { + "ltx-2.5-fast": ("ltx-2.5-22b-distilled",), + "ltx-2.3-fast": ("ltx-2.3-22b-distilled-1.1", "ltx-2.3-22b-distilled"), +} + +# ltxv-api ids. Unused in v1 (create stays local); keep next to the offering table +# so a cloud path does not invent a second mapping. +OFFERING_TO_API_MODEL: dict[OfferingId, str] = { + "ltx-2.3-fast": "ltx-2-3-fast", + "ltx-2.5-fast": "ltx-2-5-fast", +} + +# Home/Remote create remaps offering → this pipeline id at execute. One owner so +# T2V/I2V/A2V cannot diverge when a third offering is added. +LOCAL_OFFERING_PIPELINE: LTXVideoGenPipeline = "fast" + + +def local_pipeline_for_offering(_offering: OfferingId) -> LTXVideoGenPipeline: + return LOCAL_OFFERING_PIPELINE + + +def offering_id_for_local_model_id(model_id: LTXLocalModelId) -> OfferingId | None: + for offering, ids in OFFERING_LOCAL_MODEL_IDS.items(): + if model_id in ids: + return offering + return None + + +def resolve_offering_local_model_id( + models_dir: Path, offering: OfferingId +) -> LTXLocalModelId | None: + for model_id in OFFERING_LOCAL_MODEL_IDS[offering]: + if ltx_generation_bundle_on_disk(models_dir, model_id): + return model_id + return None diff --git a/backend/runtime_config/port_constant.py b/backend/runtime_config/port_constant.py index b5ef20f86..a45a6d517 100644 --- a/backend/runtime_config/port_constant.py +++ b/backend/runtime_config/port_constant.py @@ -1,3 +1,4 @@ -"""Default backend server port.""" +"""Default backend server ports.""" PORT = 41954 +REMOTE_PORT = 41955 diff --git a/backend/runtime_config/runtime_config.py b/backend/runtime_config/runtime_config.py index fb098549d..0f716300c 100644 --- a/backend/runtime_config/runtime_config.py +++ b/backend/runtime_config/runtime_config.py @@ -28,6 +28,12 @@ class RuntimeConfig: lora_catalog_source: str = "" # Bundled catalog used as a fallback when lora_catalog_source is a URL that fails to fetch. lora_catalog_fallback_path: str = "" + # Discrete GPU VRAM (CUDA). On Darwin this is total unified memory (SKU). + vram_gb: int | None = None + # Darwin: available (free) RAM at process start, used for per-job sizing. + available_ram_gb: int | None = None + # MPS unified-memory machines never load full; tests leave this False to simulate CUDA. + darwin_unified_memory: bool = False @property def force_api_generations(self) -> bool: diff --git a/backend/runtime_config/runtime_policy.py b/backend/runtime_config/runtime_policy.py index 6d9ed90ab..847c96edd 100644 --- a/backend/runtime_config/runtime_policy.py +++ b/backend/runtime_config/runtime_policy.py @@ -10,36 +10,25 @@ "unsupported", ] -# Below this, local generation isn't viable at all on Darwin. Roughly matches the -# measured ~13 GB RSS of the distilled pipeline streaming on an M4 Pro, plus margin -# — a single data point, not a hardware sweep. -DARWIN_STREAMING_FLOOR_GB = 15 - -# Full-resident on Darwin means the *full* bf16 transformer (no fp8 path on MPS, -# unlike CUDA) sitting in unified memory alongside the Gemma text encoder, VAE, -# upsampler, activations, and the OS/Electron/app itself. A live test at ram_gb=19 -# (48 GB machine, other apps open) picked this tier before this floor existed and -# stalled — torch/driver allocation climbed past torch.mps.recommended_max_memory() -# and the process sat there paging instead of progressing or erroring (no crash, no -# OOM, just stuck) — so the failure mode this floor guards against doesn't announce -# itself; there's no clean OOM to notice in testing by accident. -# -# 85 is arithmetic from real checkpoint bytes (model_download_specs.py), not a -# hardware measurement, converted to GiB since get_available_ram_gb() divides by -# 1024**3: -# - transformer (ltx-2.3-22b-distilled-1.1.safetensors): 46_149_345_334 B = 42.98 GiB -# - Gemma text encoder (gemma-3-12b-it-qat-q4_0-unquantized, bf16): 25_000_000_000 B = 23.28 GiB -# - VAE + active latent workspace: ~7.3 GiB estimate (unverified) for a 5s/1080p -# clip (this app's max local resolution/duration); decode is tiled -# (default_tiling_config() in ltx_pipeline_common.py), so this term likely -# doesn't scale up much with resolution the way a naive pixel-count estimate -# would suggest, but that's not confirmed either -# -> subtotal 73.5 GiB, +~15% margin for MPS allocator fragmentation/driver -# overhead against the silent-stall failure mode above -> 85 -# -# Still UNVERIFIED on real hardware. Do not lower further without confirming on a -# machine that actually has this much RAM free. -DARWIN_FULL_RESIDENT_FLOOR_GB = 85 +# Documented Darwin minimum (README, compat matrix). Keep product copy here. +DARWIN_ADVERTISED_FLOOR_GB = 32 + +# Unpublished API-only cutoff (integer GiB total RAM). Do not use in user-facing +# copy — ``DARWIN_ADVERTISED_FLOOR_GB`` is the documented minimum. +DARWIN_STREAMING_FLOOR_GB = 24 + +# CUDA discrete VRAM floors (integer GiB, ``total_memory // 1024**3``). Below the +# streaming floor local gen is not viable. At/above the full floor, fp8-capable +# cards can hold the halved transformer resident. +CUDA_VRAM_FLOOR_GB = 15 +CUDA_FULL_VRAM_GB = 31 + +# CUDA OffloadMode.CPU pre-pins every transformer block in host RAM. ltx-pipelines +# documents that path as ~36 GB RAM + ~5 GB VRAM. On Linux those buffers are +# page-locked (unswappable), so a 32 GB machine — the advertised local-gen floor — +# dies in the kernel OOM killer with VRAM still empty (LTX-Desktop#163). Below this +# total-RAM floor, stream from disk instead (OffloadMode.DISK, ~5 GB host). +CUDA_CPU_OFFLOAD_RAM_FLOOR_GB = 40 def decide_local_generation_mode( @@ -65,19 +54,25 @@ def decide_local_generation_mode( path regardless of VRAM: without fp8 the full ~42-46 GB bf16 transformer would try to stay resident at that floor and OOM. On Apple Silicon (Darwin) there is no discrete VRAM — the GPU shares system RAM — so ``ram_gb`` is the - *available* (free) RAM, not total: total RAM overstates real headroom once - the OS/Electron/app are already running. Gated on MPS being available - (i.e. Apple Silicon, not an Intel Mac, which has no MPS backend and stays - unsupported). ``fp8_capable`` is ignored on Darwin (no fp8 path on MPS). - - Darwin's "full_models_loading" (>=``DARWIN_FULL_RESIDENT_FLOOR_GB``) is NOT the - same regime as CUDA's: MPS has no fp8 path, so it holds the *full* ~46 GB bf16 - transformer resident — roughly 2x CUDA's resident footprint at its own - full-loading floor. Below that, Darwin streams (mmap via OffloadMode.DISK, not - CUDA's pinned-host-RAM-then-copy OffloadMode.CPU — see - ``services.ltx_pipeline_common.offload_mode_for_prefetch_count``). Streaming was - the only Darwin path validated end-to-end (M4 Pro, 48 GB); the full-resident - tier above is unverified on real hardware, see ``DARWIN_FULL_RESIDENT_FLOOR_GB``. + machine's *total* RAM (SKU), integer GiB, matching CUDA's total-VRAM floor. + Gated on MPS being available (i.e. Apple Silicon, not an Intel Mac, which + has no MPS backend and stays unsupported). ``fp8_capable`` is ignored on + Darwin (no fp8 path on MPS). + + Darwin always streams (mmap via OffloadMode.DISK, not CUDA's pinned-host + OffloadMode.CPU — see ``offload_mode_for_prefetch_count``). The original + reason was corruption: on an M5 Max 128 GB, full-resident plus a LoRA + decoded to green/gray frames. That was an unfenced MPS transfer in upstream + LoRA fusion (a fused H2D+cast issued non-blocking; the matmul read pre-blit + garbage), now fenced by ``ltx_core.devices.allow_async_transfer`` — full + resident is correct again. Streaming stays anyway: the interleaved F3 A/B + measured full resident only ~8% faster (138.6 s vs 149.9 s mean for + 540p/5s) while eating ~3.5x the MPS pool (~42 vs ~10 GiB) that unified + memory shares with the OS and apps — and full resident cannot run at all + on smaller Macs, while streaming serves them the same cells. Memory + universality plus a negligible speed delta keeps streaming as the policy. + Do not re-add a high-RAM full path without a controlled A/B showing a + meaningful win. """ if system == "Darwin": if not mps_available: @@ -86,8 +81,9 @@ def decide_local_generation_mode( return "unsupported" if ram_gb < DARWIN_STREAMING_FLOOR_GB: return "unsupported" - if ram_gb >= DARWIN_FULL_RESIDENT_FLOOR_GB: - return "full_models_loading" + # Always stream on MPS — see docstring. High RAM used to pick + # full_models_loading (>=85 GB); the corruption that ruled that out is + # fixed, but streaming still dominates it on speed and memory. return "streaming_models_loading" if system in ("Windows", "Linux"): @@ -95,10 +91,10 @@ def decide_local_generation_mode( return "unsupported" if vram_gb is None: return "unsupported" - if vram_gb < 15: + if vram_gb < CUDA_VRAM_FLOOR_GB: return "unsupported" - # full_models_loading's >=31 GB floor assumes the fp8-halved (~23 GB) transformer - # (see module docstring). Without fp8 (ROCm today — see + # full_models_loading's CUDA_FULL_VRAM_GB floor assumes the fp8-halved (~23 GB) + # transformer (see module docstring). Without fp8 (ROCm today — see # runtime_config.accelerator.accelerator_backend), holding the full bf16 # (~42-46 GB) transformer resident instead would OOM at this floor, so stay on # the streaming path regardless of VRAM until a real bf16-full-resident floor is @@ -106,7 +102,7 @@ def decide_local_generation_mode( # Originally contributed by boxwrench in https://github.com/Lightricks/LTX-Desktop/pull/160 if not fp8_capable: return "streaming_models_loading" - if vram_gb < 31: + if vram_gb < CUDA_FULL_VRAM_GB: return "streaming_models_loading" return "full_models_loading" @@ -114,6 +110,20 @@ def decide_local_generation_mode( return "unsupported" +def should_disk_stream_cuda_weights(system: str, ram_gb: int | None) -> bool: + """Whether CUDA streaming must mmap weights from disk instead of pinning them in RAM. + + Windows already allocates pageable host buffers (pinned_pool_fix / LTX-Desktop#141) + and stays on OffloadMode.CPU. Linux actually succeeds at cudaHostRegister, so the + 32 GB product floor cannot hold the pinned transformer. + """ + if system != "Linux": + return False + if ram_gb is None: + return True + return ram_gb < CUDA_CPU_OFFLOAD_RAM_FLOOR_GB + + def streaming_prefetch_count_for_mode(mode: LocalGenerationMode) -> int | None: """Return the streaming_prefetch_count to pass to a local pipeline. diff --git a/backend/runtime_config/video_job_budget.py b/backend/runtime_config/video_job_budget.py new file mode 100644 index 000000000..db611106b --- /dev/null +++ b/backend/runtime_config/video_job_budget.py @@ -0,0 +1,341 @@ +"""Token/VRAM estimator for local video jobs. + +Tool-agnostic: Fast t2v/i2v/a2v sizes advertised stage-2 H×W (not half-res +stage-1). IC-LoRA wraps this with a ×2 reference sequence and a measured +spatial No. + +Calibrated from RTX 5090 32 GB Sage-on logs (desktop sessions 379ffcbf / +41952c05 / 715d94b): + +- Full 5s 1024×576×121: seq ≈ 18432 (IC-LoRA ×2), peak alloc ≈ 22.5 GiB. +- Fast 720p 20s stage-2 1280×704×481: seq ≈ 53680. Full reserved 32.99 / + peak 30.76 / free=0 (paged). Stream reserved 19.54 / peak 14.15. +- Fast 1080p 10s stage-2 seq ≈ 63240 → full ~33.4 GiB, stream instead. +- 5s 720p IC-LoRA hung in tiled VAE encode in both modes → spatial No. + +Linear ``estimated_giB`` is intentionally a bit high so we 422 / stream early, +not late. Hang on a borderline mis-judge is acceptable. + +Stream was recalibrated to sit above measured reserved (~19.5 GiB at Fast +720p/20s) so 15–16 GB CUDA 422s that cell instead of paging. 540p/5s stream +still fits the 15 GB floor. Full-mode comparison keeps 2 GiB of total VRAM as +headroom so a card that reports 32 does not full-load 720p/20s (reserved ~33). +IC-LoRA uses 7 GiB of full-mode headroom so 8s/10s 540p streams on 32 GB; +5s stays full. +""" + +from __future__ import annotations + +from collections.abc import Callable, Sequence +from dataclasses import dataclass +from typing import Literal + +from frame_math import compute_num_frames +from runtime_config.runtime_policy import LocalGenerationMode + +LoadMode = Literal["full_models_loading", "streaming_models_loading"] + +VIDEO_JOB_TOO_LARGE = "VIDEO_JOB_TOO_LARGE" +VIDEO_JOB_TOO_LARGE_MESSAGE = ( + "This job is larger than this machine can run locally right now. " + "Lower the resolution or duration." +) +# Retake pads context back up to the encode cap, so a shorter selection often +# leaves the same window. Extend on a long source does the same. Resolution is +# the change that shrinks the job. +EDIT_JOB_TOO_LARGE_MESSAGE = ( + "This edit is larger than this machine can run locally right now. " + "Lower the resolution." +) +LOCAL_GENERATION_UNSUPPORTED = "LOCAL_GENERATION_UNSUPPORTED" +LOCAL_GENERATION_UNSUPPORTED_MESSAGE = "This machine cannot run local generation." + +# Full 5s 1024×576: intercept 18 + 0.000244 × 18432 ≈ 22.5 GiB. +_FULL_INTERCEPT_GIB = 18.0 +_FULL_GIB_PER_TOKEN = 0.000244 +# Stream: 540p/5s seq 9216 ≈ 6.0 GiB (15 GB floor still fits); 720p/20s seq 53680 ≈ 20.0 GiB +# (above measured reserved ~19.5, so 16 GB 422s). +_STREAM_INTERCEPT_GIB = 3.1 +_STREAM_GIB_PER_TOKEN = 0.000315 +# Full 720p/20s estimate ~31.10 GiB. A GPU that reports 32 would otherwise pick full +# and page (reserved ~32.99). Keep this off the full-mode comparison only. +_FULL_VRAM_HEADROOM_GIB = 2.0 +# Retake/extend 720p on a 5090 (1280×704×337, full estimate 27.2 GiB) reserved +# 31.91 GiB and paged: free=0, ~130s/step, while the same card streamed 1080p at +# ~23s/step. 5 GiB so that clip streams on a card that reports 31 or 32. Fast +# video keeps the 2 GiB headroom. Do not drop this to 4: a 32-report would +# full-load the clip again (27.2 fits in 32−4). +_EDIT_FULL_HEADROOM_GIB = 5.0 +# Fast 1080p/10s stream ≈ 23.02 GiB vs a 24 GB report: ~4% on a three-session fit. +# Do not round the stream intercept/slope without re-logging 16 GB and 24 GB cards. + + +def video_tokens(height: int, width: int, frames: int) -> float: + """LTX-2 latent tokens: 8-frame temporal, 32 px spatial.""" + temporal = (max(1, frames) - 1) / 8.0 + 1.0 + return temporal * (height / 32.0) * (width / 32.0) + + +def estimated_giB(mode: LoadMode, seq: float) -> float: + if mode == "full_models_loading": + return _FULL_INTERCEPT_GIB + _FULL_GIB_PER_TOKEN * seq + return _STREAM_INTERCEPT_GIB + _STREAM_GIB_PER_TOKEN * seq + + +def fits(seq: float, mode: LoadMode, memory_gb: float) -> bool: + return estimated_giB(mode, seq) <= memory_gb + + +def _full_memory_gb(memory_gb: float, headroom_gib: float = _FULL_VRAM_HEADROOM_GIB) -> float: + return max(0.0, memory_gb - headroom_gib) + + +def memory_gb_for_job( + *, + vram_gb: float | None, + available_ram_gb: float | None, + darwin: bool, +) -> float | None: + """Discrete VRAM on CUDA; free RAM on Darwin (already not total).""" + if darwin: + return available_ram_gb + return vram_gb + + +@dataclass(frozen=True, slots=True) +class OfferingCell: + """One advertised res×duration cell (t2v/i2v grid, or any similar table).""" + + resolution: str + duration_seconds: int + fps: int + width: int + height: int + + +def enumerate_envelope( + grid: Sequence[OfferingCell], + mode: LoadMode, + memory_gb: float, + *, + measured_no: Callable[[OfferingCell], bool] | None = None, +) -> list[OfferingCell]: + """Keep cells that fit ``mode`` at ``memory_gb``. Measured No still wins.""" + + kept: list[OfferingCell] = [] + for cell in grid: + if measured_no is not None and measured_no(cell): + continue + frames = _frames_for_duration(cell.duration_seconds, cell.fps) + seq = video_tokens(cell.height, cell.width, frames) + if fits(seq, mode, memory_gb): + kept.append(cell) + return kept + + +def _frames_for_duration(duration_seconds: int, fps: int) -> int: + return compute_num_frames(duration_seconds, fps) + + +@dataclass(frozen=True, slots=True) +class VideoJobLoad: + mode: LoadMode + seq: float + full_gib: float + stream_gib: float + + +@dataclass(frozen=True, slots=True) +class VideoJobReject: + seq: float + full_gib: float + stream_gib: float + reason: Literal["stream_over", "unsupported"] = "stream_over" + + +VideoJobDecision = VideoJobLoad | VideoJobReject + + +def decide_load_mode( + seq: float, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool = False, + full_headroom_gib: float = _FULL_VRAM_HEADROOM_GIB, +) -> VideoJobDecision: + """422 definite-over jobs; per-job stream when full will not fit. + + Does not change process ``local_generations_mode``. ``full_headroom_gib`` is + subtracted only from the full-vs-stream pick, not from the stream-over 422. + + Two Darwin policies (do not fold them together later): + + - Never full: MPS full-resident is only ~8% faster at ~3.5x the shared + unified-memory pool, and cannot serve smaller Macs at all + (see ``runtime_policy``). The green/gray corruption that first ruled + full out is fixed by ``ltx_core.devices.allow_async_transfer``. + Independent of the token curve. + - Never stream-over 422: the 5090 reserved curve is not unified memory, and + ``available_ram_gb`` is already free-at-launch. Comparing them 422'd M4 + 48 GB jobs that streamed. There is no Darwin-native token ceiling yet. + """ + full_gib = estimated_giB("full_models_loading", seq) + stream_gib = estimated_giB("streaming_models_loading", seq) + + if process_mode == "unsupported": + return VideoJobReject( + seq=seq, full_gib=full_gib, stream_gib=stream_gib, reason="unsupported" + ) + + if darwin: + return VideoJobLoad( + mode="streaming_models_loading", + seq=seq, + full_gib=full_gib, + stream_gib=stream_gib, + ) + + if memory_gb is None: + return VideoJobLoad( + mode="streaming_models_loading", + seq=seq, + full_gib=full_gib, + stream_gib=stream_gib, + ) + + if not fits(seq, "streaming_models_loading", memory_gb): + return VideoJobReject( + seq=seq, full_gib=full_gib, stream_gib=stream_gib, reason="stream_over" + ) + + if process_mode != "full_models_loading" or not fits( + seq, "full_models_loading", _full_memory_gb(memory_gb, full_headroom_gib) + ): + return VideoJobLoad( + mode="streaming_models_loading", + seq=seq, + full_gib=full_gib, + stream_gib=stream_gib, + ) + return VideoJobLoad( + mode="full_models_loading", seq=seq, full_gib=full_gib, stream_gib=stream_gib + ) + + +def decide_video_job( + width: int, + height: int, + frames: int, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool = False, +) -> VideoJobDecision: + """Fast t2v/i2v/a2v: advertised (stage-2) pixels, no ×2, no spatial cap.""" + return decide_load_mode( + video_tokens(height, width, frames), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + + +def decide_edit_job( + width: int, + height: int, + frames: int, + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool = False, +) -> VideoJobDecision: + """Retake/extend. Same curve as Fast, with more full-mode headroom. + + A 5090 that full-loaded 1280×704×337 reserved the whole card. Short 720p + still fits and stays full. + """ + return decide_load_mode( + video_tokens(height, width, frames), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + full_headroom_gib=_EDIT_FULL_HEADROOM_GIB, + ) + + +def max_edit_frames_that_load( + width: int, + height: int, + *, + frame_cap: int, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool = False, +) -> int: + """Largest frame count at or below ``frame_cap`` that ``decide_edit_job`` loads. + + 1920×1088×505 streams at about 43 GiB and 422s on 31 GB. That canvas is the + letterbox of a 1080p picture. Home passes this cap into the encode window + so the job runs at the longest window that fits. When nothing fits, return + ``frame_cap`` and let the loader 422. + """ + if frame_cap < 1: + return frame_cap + + def loads(frames: int) -> bool: + decision = decide_edit_job( + width, + height, + frames, + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + return isinstance(decision, VideoJobLoad) + + if loads(frame_cap): + return frame_cap + lo = 1 + hi = frame_cap - 1 + best = 0 + while lo <= hi: + mid = (lo + hi) // 2 + if loads(mid): + best = mid + lo = mid + 1 + else: + hi = mid - 1 + return best if best > 0 else frame_cap + + +def advertised_fast_durations( + width: int, + height: int, + fps: int, + durations: Sequence[int], + *, + memory_gb: float | None, + process_mode: LocalGenerationMode, + darwin: bool = False, +) -> list[int]: + """Keep Fast cells that ``decide_video_job`` would load. Not a full-mode envelope. + + Filtering with ``fits(..., "full_models_loading")`` would hide 720p/20s on a + 5090 that streams it. Darwin never compares free RAM to the CUDA stream curve. + """ + if process_mode == "unsupported": + return [] + kept: list[int] = [] + for duration in durations: + decision = decide_video_job( + width, + height, + compute_num_frames(duration, fps), + memory_gb=memory_gb, + process_mode=process_mode, + darwin=darwin, + ) + if isinstance(decision, VideoJobLoad): + kept.append(duration) + return kept diff --git a/backend/server_utils/heartbeat.py b/backend/server_utils/heartbeat.py index e6f5d2102..27640197c 100644 --- a/backend/server_utils/heartbeat.py +++ b/backend/server_utils/heartbeat.py @@ -1,14 +1,15 @@ """Generic progress heartbeat for long, callback-less blocking calls (generation). A daemon thread logs elapsed time on an interval while the wrapped block runs, so a -long generation is distinguishable from a hang. It also logs GPU memory per device: +long generation is distinguishable from a hang. On exit it logs ``done`` or ``failed``. +It also logs GPU memory per device: - CUDA: allocated / reserved / peak vs total device memory - MPS: torch-tracked / driver / max memory + the active mps-sdpa attention backend counts (surfaces the pyobjc-fallback leak — driver climbs while torch stays flat) - CPU-only: elapsed time only -Used by both plain video generation and IC-LoRA generation. +Used by video generation, IC-LoRA, retake, and extend. """ from __future__ import annotations @@ -17,15 +18,16 @@ import time from collections.abc import Iterator from contextlib import contextmanager -from threading import Event, Thread +from threading import Event, Lock, Thread from mps_prebuilt_ext import mps_memory_sample, reset_mps_sdpa_stats from server_utils.units import gib logger = logging.getLogger(__name__) +_active = Lock() -def _cuda_memory_sample() -> str | None: +def cuda_memory_sample() -> str | None: """One-line CUDA memory snapshot, or None when CUDA isn't the active device.""" import torch # noqa: PLC0415 @@ -46,7 +48,7 @@ def _cuda_memory_sample() -> str | None: def _device_sample() -> str | None: """GPU memory snapshot for whichever accelerator is active (CUDA or MPS), else None.""" - return _cuda_memory_sample() or mps_memory_sample() + return cuda_memory_sample() or mps_memory_sample() def _reset_stats() -> None: @@ -63,30 +65,47 @@ def _reset_stats() -> None: @contextmanager def log_heartbeat(label: str, interval_s: float = 15.0) -> Iterator[None]: - """Tick elapsed time (+ GPU memory when available) while the wrapped block runs.""" - _reset_stats() - stop = Event() - start = time.perf_counter() - - def _beat() -> None: - while not stop.wait(interval_s): + """Tick elapsed time (+ GPU memory when available) while the wrapped block runs. + + Only one ticker runs at a time. A nested or overlapping caller is silent so + Desktop and Remote QueueRunners in the same process cannot dump interleaved + heartbeats. A single queue loop already serializes GPU work; the lock is for + the dual-runner case (``remote/controller.py``). + """ + if not _active.acquire(blocking=False): + yield + return + try: + _reset_stats() + stop = Event() + start = time.perf_counter() + + def _beat() -> None: + while not stop.wait(interval_s): + elapsed = time.perf_counter() - start + sample = _device_sample() + if sample is not None: + logger.info("[heartbeat] %s %.0fs | %s", label, elapsed, sample) + else: + logger.info("[heartbeat] %s still running… %.0fs elapsed", label, elapsed) + + thread = Thread(target=_beat, name="generation-heartbeat", daemon=True) + thread.start() + failed = False + try: + yield + except BaseException: + failed = True + raise + finally: + stop.set() + thread.join(timeout=1.0) elapsed = time.perf_counter() - start + status = "failed" if failed else "done" sample = _device_sample() if sample is not None: - logger.info("[heartbeat] %s %.0fs | %s", label, elapsed, sample) + logger.info("[heartbeat] %s %s %.0fs | %s", label, status, elapsed, sample) else: - logger.info("[heartbeat] %s still running… %.0fs elapsed", label, elapsed) - - thread = Thread(target=_beat, name="generation-heartbeat", daemon=True) - thread.start() - try: - yield + logger.info("[heartbeat] %s %s %.0fs", label, status, elapsed) finally: - stop.set() - thread.join(timeout=1.0) - elapsed = time.perf_counter() - start - sample = _device_sample() - if sample is not None: - logger.info("[heartbeat] %s done %.0fs | %s", label, elapsed, sample) - else: - logger.info("[heartbeat] %s done %.0fs", label, elapsed) + _active.release() diff --git a/backend/server_utils/oriented_image.py b/backend/server_utils/oriented_image.py new file mode 100644 index 000000000..eae4f3784 --- /dev/null +++ b/backend/server_utils/oriented_image.py @@ -0,0 +1,105 @@ +"""Bake EXIF orientation into image pixels. + +Phone cameras store the sensor buffer sideways and record the display rotation +in the EXIF Orientation tag. ``Image.open`` leaves that tag unapplied, so every +decode of a user photo goes through this module. The stored file is left as-is. +""" + +from __future__ import annotations + +import io +import os +import tempfile +from collections.abc import Iterator +from contextlib import contextmanager +from dataclasses import dataclass +from pathlib import Path + +from PIL import Image, ImageOps + +from server_utils.media_validation import image_mime_type + +_ORIENTATION = 0x0112 +# High enough that a phone JPEG stays a photo, not a multi-tens-of-MB PNG. +_JPEG_QUALITY = 95 + + +def open_oriented_image(path: str | Path) -> Image.Image: + """Return a loaded image whose pixels match the EXIF display orientation. + + The result is detached from the file. Images with no orientation tag, or + orientation 1, keep their pixels. The original file format is preserved on + the returned image so callers can still reject unsupported types. + """ + with Image.open(path) as raw: + source_format = raw.format + loaded = ImageOps.exif_transpose(raw).copy() + if loaded.format is None: + loaded.format = source_format + return loaded + + +def open_oriented_rgb(path: str | Path) -> Image.Image: + return open_oriented_image(path).convert("RGB") + + +def oriented_image_payload(path: str | Path) -> tuple[bytes, str]: + """Bytes and MIME type for an API that will not apply EXIF orientation. + + Untagged and already-upright images are returned unchanged. A sideways JPEG + is re-encoded as a JPEG with the rotation baked in and the orientation tag + omitted. Any other sideways image is re-encoded as PNG for the same reason. + """ + source = Path(path) + if _exif_orientation(source) in (0, 1): + return source.read_bytes(), image_mime_type(str(source)) + encoded = _encode_oriented(source) + return encoded.data, encoded.mime + + +@contextmanager +def oriented_image_file(path: str | Path) -> Iterator[Path]: + """Yield a path whose pixels are display-oriented. + + The original path is yielded when no transpose is required. Otherwise a + temporary file is written and removed when the context exits. + """ + source = Path(path) + if _exif_orientation(source) in (0, 1): + yield source + return + encoded = _encode_oriented(source) + fd, name = tempfile.mkstemp(suffix=encoded.suffix) + os.close(fd) + dest = Path(name) + try: + dest.write_bytes(encoded.data) + yield dest + finally: + dest.unlink(missing_ok=True) + + +@dataclass(frozen=True, slots=True) +class _Encoded: + data: bytes + mime: str + suffix: str + + +def _encode_oriented(source: Path) -> _Encoded: + image = open_oriented_image(source) + buffer = io.BytesIO() + if str(image.format or "").upper() == "JPEG": + image.convert("RGB").save(buffer, format="JPEG", quality=_JPEG_QUALITY, exif=b"") + return _Encoded(buffer.getvalue(), "image/jpeg", ".jpg") + image.save(buffer, format="PNG") + return _Encoded(buffer.getvalue(), "image/png", ".png") + + +def _exif_orientation(path: Path) -> int: + with Image.open(path) as image: + value = image.getexif().get(_ORIENTATION, 1) + try: + return int(value) + except (TypeError, ValueError): + return 1 diff --git a/backend/services/a2v_pipeline/distilled_a2v_pipeline.py b/backend/services/a2v_pipeline/distilled_a2v_pipeline.py index 00fd986ea..27153ac78 100644 --- a/backend/services/a2v_pipeline/distilled_a2v_pipeline.py +++ b/backend/services/a2v_pipeline/distilled_a2v_pipeline.py @@ -8,17 +8,19 @@ from __future__ import annotations from collections.abc import Iterator, Sequence +from dataclasses import replace from typing import TYPE_CHECKING, Any, Protocol, cast import torch +from services.audio_channels import stereo_waveform from services.ltx_pipeline_common import offload_mode_for_prefetch_count from services.services_utils import AudioOrNone, TilingConfigType if TYPE_CHECKING: from ltx_core.loader.primitives import LoraPathStrengthAndSDOps - from ltx_pipelines.utils.args import ImageConditioningInput as LtxImageInput from ltx_pipelines.utils.model_paths import ModelPaths + from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput class _ImageCrfResolver(Protocol): @@ -30,7 +32,7 @@ def resolve_image_conditionings( image_conditioner: _ImageCrfResolver, ) -> list[LtxImageInput]: """Build LTX image inputs and fill checkpoint CRF via ImageConditioner.resolve_crf.""" - from ltx_pipelines.utils.args import ImageConditioningInput as LtxImageInput + from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput ltx_images = [LtxImageInput(path, frame_idx, strength) for path, frame_idx, strength in images] return image_conditioner.resolve_crf(ltx_images) @@ -144,9 +146,9 @@ def __call__( from ltx_core.types import Audio, AudioLatentShape from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES from ltx_pipelines.utils.denoisers import SimpleDenoiser - from ltx_pipelines.utils.helpers import assert_resolution + from ltx_pipelines.utils.helpers import assert_resolution, create_initial_video_latent from ltx_pipelines.utils.media_io import decode_audio_from_file - from ltx_pipelines.utils.types import ModalitySpec + from ltx_pipelines.utils.types import ModalitySpec, VideoAudio assert_resolution(height=height, width=width, is_two_stage=True) @@ -164,6 +166,10 @@ def __call__( # Audio encode. decoded_audio = decode_audio_from_file(audio_path, self.device, audio_start_time, audio_max_duration) assert decoded_audio is not None, "Audio file contains no audio stream" + decoded_audio = replace( + decoded_audio, + waveform=stereo_waveform(decoded_audio.waveform), + ) encoded_audio_latent = self.audio_conditioner( lambda enc: vae_encode_audio(decoded_audio, cast(Any, enc), None) ) @@ -175,6 +181,15 @@ def __call__( else: encoded_audio_latent = encoded_audio_latent[:, :, :target_frames] + # The same frozen, unnoised source audio drives both stages. + audio_spec = ModalitySpec( + latent=encoded_audio_latent, + conditioning_fps=frame_rate, + context=audio_context, + frozen=True, + noise_scale=0.0, + ) + # Stage 1: Half-resolution video generation with frozen audio. stage_1_sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device) stage_1_w, stage_1_h = width // 2, height // 2 @@ -188,24 +203,29 @@ def __call__( device=self.device, ) ) + stage_1_video_latent = create_initial_video_latent( + width=stage_1_w, + height=stage_1_h, + frames=num_frames, + fps=frame_rate, + device=self.device, + dtype=dtype, + # Transformer latent geometry, not the decoder's tiling scale (2x8x8 on the 2.5 DiffVAE). + scale_factors=self.stage.video_scale_factors, + ) video_state, _ = self.stage( denoiser=SimpleDenoiser(video_context, audio_context), sigmas=stage_1_sigmas, noiser=noiser, - width=stage_1_w, - height=stage_1_h, - frames=num_frames, - fps=frame_rate, - video=ModalitySpec( - context=video_context, - conditionings=stage_1_conditionings, - ), - audio=ModalitySpec( - context=audio_context, - frozen=True, - noise_scale=0.0, - initial_latent=encoded_audio_latent, + modalities=VideoAudio( + video=ModalitySpec( + latent=stage_1_video_latent, + conditioning_fps=frame_rate, + context=video_context, + conditionings=stage_1_conditionings, + ), + audio=audio_spec, ), ) @@ -230,21 +250,15 @@ def __call__( denoiser=SimpleDenoiser(video_context, audio_context), sigmas=stage_2_sigmas, noiser=noiser, - width=width, - height=height, - frames=num_frames, - fps=frame_rate, - video=ModalitySpec( - context=video_context, - conditionings=stage_2_conditionings, - noise_scale=stage_2_sigmas[0].item(), - initial_latent=upscaled_video_latent, - ), - audio=ModalitySpec( - context=audio_context, - frozen=True, - noise_scale=0.0, - initial_latent=encoded_audio_latent, + modalities=VideoAudio( + video=ModalitySpec( + latent=upscaled_video_latent, + conditioning_fps=frame_rate, + context=video_context, + conditionings=stage_2_conditionings, + noise_scale=stage_2_sigmas[0].item(), + ), + audio=audio_spec, ), ) diff --git a/backend/services/a2v_pipeline/ltx_a2v_pipeline.py b/backend/services/a2v_pipeline/ltx_a2v_pipeline.py index fbc37bae4..6e3d9d9ca 100644 --- a/backend/services/a2v_pipeline/ltx_a2v_pipeline.py +++ b/backend/services/a2v_pipeline/ltx_a2v_pipeline.py @@ -128,6 +128,8 @@ def generate( audio_max_duration: float | None, output_path: str, ) -> None: + from services.denoising_progress import distilled_total_steps, track_denoising + tiling_config = resolve_tiling_config( self.pipeline.video_decoder.checkpoint_path, height=height, @@ -135,20 +137,21 @@ def generate( num_frames=num_frames, device=self.pipeline.device, ) - video, audio = self._run_inference( - prompt=prompt, - negative_prompt=negative_prompt, - seed=seed, - height=height, - width=width, - num_frames=num_frames, - frame_rate=frame_rate, - num_inference_steps=num_inference_steps, - images=images, - audio_path=audio_path, - audio_start_time=audio_start_time, - audio_max_duration=audio_max_duration, - tiling_config=tiling_config, - ) + with track_denoising(distilled_total_steps()): + video, audio = self._run_inference( + prompt=prompt, + negative_prompt=negative_prompt, + seed=seed, + height=height, + width=width, + num_frames=num_frames, + frame_rate=frame_rate, + num_inference_steps=num_inference_steps, + images=images, + audio_path=audio_path, + audio_start_time=audio_start_time, + audio_max_duration=audio_max_duration, + tiling_config=tiling_config, + ) chunks = video_chunks_number(num_frames, tiling_config) encode_video_output(video=video, audio=audio, fps=int(frame_rate), output_path=output_path, video_chunks_number_value=chunks) diff --git a/backend/services/analytics.py b/backend/services/analytics.py new file mode 100644 index 000000000..3aed8b698 --- /dev/null +++ b/backend/services/analytics.py @@ -0,0 +1,403 @@ +"""Forward privacy-safe analytics events to the Electron sink.""" + +from __future__ import annotations + +import logging +import threading +import time +from collections.abc import Iterator +from contextlib import contextmanager +from typing import Literal, cast + +from api_types import PromptProvenance +from services.features.lora_recipes import get_lora_recipe +from services.http_client.http_client import HTTPClient, HttpTransportError +from services.records import GenerationRecord +from services.services_utils import JSONValue +from services.task_runner.task_runner import TaskRunner + +logger = logging.getLogger(__name__) + +GenerationEventName = Literal["generate_started", "generate_ended"] +GenerationOutcome = Literal["succeeded", "failed", "cancelled"] +PromptProvenanceLabel = Literal["raw", "manually-enhanced", "auto-enhanced"] +_HOME_QUEUE_KIND = "video" +_HOME_QUEUE_EXECUTION = "local" +_FORCED_UNENHANCED_FEATURES = frozenset({"retake", "extend"}) +# generate_ended joins generate_started on generation_id. It does not repeat +# the start payload; attempt stays so a retry of the same id still pairs. +# The full set is shared/analytics-ended-details.json. Electron drops anything else. +ENDED_DETAIL_KEYS = ( + "generation_id", + "attempt", + "outcome", + "runtime_ms", + "error_code", +) +_ENDED_LINK_KEYS = ("generation_id", "attempt") + + +class QueuedEnhancement: + """Explore enhance settings at the moment a home-queue event is sent.""" + + def __init__( + self, + *, + explore_auto_enhance_prompts: bool, + prompt_enhancer_enabled: bool, + use_local_encoding: bool, + local_enhancer_available: bool = False, + ) -> None: + self.explore_auto_enhance_prompts = explore_auto_enhance_prompts + self.prompt_enhancer_enabled = prompt_enhancer_enabled + self.use_local_encoding = use_local_encoding + self.local_enhancer_available = local_enhancer_available + + +def prompt_provenance_label( + provenance: str, + *, + enhanced_locally: bool, + enhance_via_api: bool, +) -> PromptProvenanceLabel: + """How this run asked for the prompt to be passed. Not the prompt text.""" + if provenance == "enhanced": + return "manually-enhanced" + if enhanced_locally or enhance_via_api: + return "auto-enhanced" + return "raw" + + +def unenhanced_prompt_provenance(provenance: str) -> PromptProvenanceLabel: + """Retake and extend always submit the prompt as-is.""" + if provenance == "enhanced": + return "manually-enhanced" + return "raw" + + +def resolution_for_provenance( + provenance: str, + *, + prompt: str, + explore_generation: bool, + explore_auto_enhance_prompts: bool, + use_local_encoding: bool, + prompt_enhancer_enabled: bool, + force_api: bool = False, + local_enhancer_available: bool = False, +) -> tuple[bool, bool, bool] | None: + """Shared enhance decision for generation and the analytics preview. + + None means a local rewrite will be attempted. Otherwise the tuple is + enhance_via_api, enhanced_locally, skip_recipe_wrap. + """ + skip_recipe_wrap = ( + explore_generation + and not explore_auto_enhance_prompts + and provenance != "enhanced" + ) + if provenance == "enhanced" or not prompt.strip() or skip_recipe_wrap: + return (False, False, skip_recipe_wrap) + # Home auto-enhance rewrites on the local checkpoint when it is installed. + # API text encoding is a different switch: leaving the rewrite to that path + # drops it for style recipes, because the scaffold wrap turns the API flag + # off so /prompt-embedding cannot rewrite the style lock. + if explore_generation and explore_auto_enhance_prompts and local_enhancer_available: + return None + if force_api or not use_local_encoding: + return (prompt_enhancer_enabled, False, skip_recipe_wrap) + return None + + +def _recipe_clears_api_enhance(feature: str) -> bool: + """Queued LoRA recipes pass a prompt wrap that forces API enhance off. + + A local rewrite still happens before that wrap. An API rewrite does not: + the scaffold would be rewritten, so the job encodes the wrapped prompt as-is. + """ + recipe = get_lora_recipe(feature) + return recipe is not None and recipe.mode in ("t2v", "i2v") + + +def _stored_provenance(value: object) -> PromptProvenance: + if value == "enhanced": + return "enhanced" + return "typed" + + +def queued_prompt_provenance( + generation: GenerationRecord, + enhancement: QueuedEnhancement, +) -> str | None: + params = generation.spec.get("params") + if not isinstance(params, dict): + return None + provenance = _stored_provenance(params.get("promptProvenance")) + prompt = params.get("prompt") + prompt_text = prompt if isinstance(prompt, str) else "" + if generation.feature in _FORCED_UNENHANCED_FEATURES: + return unenhanced_prompt_provenance(provenance) + resolved = resolution_for_provenance( + provenance, + prompt=prompt_text, + explore_generation=True, + explore_auto_enhance_prompts=enhancement.explore_auto_enhance_prompts, + use_local_encoding=enhancement.use_local_encoding, + prompt_enhancer_enabled=enhancement.prompt_enhancer_enabled, + local_enhancer_available=enhancement.local_enhancer_available, + ) + if resolved is None: + return prompt_provenance_label(provenance, enhanced_locally=True, enhance_via_api=False) + enhance_via_api, enhanced_locally, skip_recipe_wrap = resolved + if _recipe_clears_api_enhance(generation.feature) and not skip_recipe_wrap: + enhance_via_api = False + return prompt_provenance_label( + provenance, + enhanced_locally=enhanced_locally, + enhance_via_api=enhance_via_api, + ) + + +def pixel_resolution(width: int, height: int) -> str: + return f"{width}x{height}" + + +def _resolution_value(value: object) -> JSONValue | None: + if isinstance(value, str) and value: + return value + if isinstance(value, (int, float)) and not isinstance(value, bool): + return value + if not isinstance(value, dict): + return None + fields = cast(dict[str, object], value) + width = fields.get("width") + height = fields.get("height") + if ( + isinstance(width, int) + and not isinstance(width, bool) + and isinstance(height, int) + and not isinstance(height, bool) + and width > 0 + and height > 0 + ): + return pixel_resolution(width, height) + return None + + +def queued_generation_details( + generation: GenerationRecord, + *, + enhancement: QueuedEnhancement | None = None, +) -> dict[str, JSONValue] | None: + analytics = generation.spec.get("_analytics") + if not isinstance(analytics, dict): + return None + client = analytics.get("client") + if not isinstance(client, str) or client not in ("desktop", "remote"): + return None + + details: dict[str, JSONValue] = { + "generation_id": generation.id, + "attempt": generation.attempt_count, + "client": client, + "surface": "home", + "feature": generation.feature, + "kind": _HOME_QUEUE_KIND, + "execution": _HOME_QUEUE_EXECUTION, + } + params = generation.spec.get("params") + if not isinstance(params, dict): + return details + for source, target in ( + ("model", "model"), + ("duration", "duration_sec"), + ("fps", "fps"), + ): + value = params.get(source) + if isinstance(value, (str, int, float)) and not isinstance(value, bool): + details[target] = value + if "duration_sec" not in details: + num_frames = params.get("numFrames") + fps = params.get("fps") + if ( + isinstance(num_frames, int) + and not isinstance(num_frames, bool) + and isinstance(fps, (int, float)) + and not isinstance(fps, bool) + and fps > 0 + ): + details["duration_sec"] = (num_frames - 1) / float(fps) + resolution = _resolution_value(params.get("resolution")) + if resolution is not None: + details["resolution"] = resolution + + loras = params.get("loras") + if isinstance(loras, list): + catalog_ids: list[JSONValue] = [] + has_custom_lora = False + for lora in loras: + if not isinstance(lora, dict): + continue + catalog_id = lora.get("catalogId") + if isinstance(catalog_id, str) and catalog_id: + catalog_ids.append(catalog_id) + else: + has_custom_lora = True + if catalog_ids: + details["lora_catalog_ids"] = catalog_ids + if has_custom_lora: + details["has_custom_lora"] = True + if enhancement is not None: + provenance = queued_prompt_provenance(generation, enhancement) + if provenance is not None: + details["prompt_provenance"] = provenance + return details + + +def _ended_details( + details: dict[str, JSONValue], + *, + outcome: GenerationOutcome, + runtime_ms: int, + error_code: str | None, +) -> dict[str, JSONValue]: + """Identity plus what is only known when the run finishes.""" + ended: dict[str, JSONValue] = { + key: details[key] for key in _ENDED_LINK_KEYS if key in details + } + ended["outcome"] = outcome + ended["runtime_ms"] = max(0, runtime_ms) + if error_code is not None: + ended["error_code"] = error_code + return ended + + +class AnalyticsService: + def __init__( + self, + *, + http: HTTPClient, + task_runner: TaskRunner, + sink_url: str = "", + token: str = "", + ) -> None: + self._http = http + self._task_runner = task_runner + self._sink_url = sink_url + self._token = token + self._send_order = threading.Lock() + self._send_tail: threading.Lock | None = None + + def send_generation_started(self, details: dict[str, JSONValue]) -> None: + self._send("generate_started", details) + + def send_generation_ended( + self, + details: dict[str, JSONValue], + *, + outcome: GenerationOutcome, + runtime_ms: int, + error_code: str | None = None, + ) -> None: + self._send( + "generate_ended", + _ended_details( + details, + outcome=outcome, + runtime_ms=runtime_ms, + error_code=error_code, + ), + ) + + @contextmanager + def generation( + self, details: dict[str, JSONValue] + ) -> Iterator[GenerationAnalyticsTracker]: + tracker = GenerationAnalyticsTracker(self, details) + try: + tracker.start() + yield tracker + except Exception: + tracker.finish("failed") + raise + else: + tracker.finish("succeeded") + + def _send(self, event_name: GenerationEventName, details: dict[str, JSONValue]) -> None: + if self._sink_url == "" or self._token == "": + return + payload: dict[str, JSONValue] = { + "eventName": event_name, + "extraDetails": details, + } + # Chain posts in emission order. Each background post waits for the + # previous one, so a fast generate_ended cannot overtake its start. + finished = threading.Lock() + finished.acquire() + with self._send_order: + previous = self._send_tail + self._send_tail = finished + + def post() -> None: + try: + if previous is not None: + with previous: + pass + self._post(payload) + finally: + finished.release() + + try: + self._task_runner.run_background( + post, + task_name=f"analytics-{event_name}", + on_error=lambda exc: logger.warning("Analytics forward failed: %s", exc), + ) + except Exception as exc: + finished.release() + logger.warning("Analytics schedule failed: %s", exc) + + def _post(self, payload: dict[str, JSONValue]) -> None: + try: + response = self._http.post( + self._sink_url, + headers={ + "Authorization": f"Bearer {self._token}", + "Content-Type": "application/json", + }, + json_payload=payload, + timeout=5, + ) + except HttpTransportError as exc: + logger.warning("Analytics sink request failed: %s", exc) + return + if not 200 <= response.status_code < 300: + logger.warning("Analytics sink returned HTTP %s", response.status_code) + + +class GenerationAnalyticsTracker: + def __init__(self, service: AnalyticsService, details: dict[str, JSONValue]) -> None: + self._service = service + self._details = details + self._started_at = 0 + self._finished = False + + def start(self) -> None: + if self._started_at != 0: + return + self._started_at = int(time.time() * 1000) + self._service.send_generation_started(self._details) + + def finish( + self, outcome: GenerationOutcome, *, error_code: str | None = None + ) -> None: + if self._finished: + return + self._finished = True + now = int(time.time() * 1000) + self._service.send_generation_ended( + self._details, + outcome=outcome, + runtime_ms=now - self._started_at, + error_code=error_code, + ) diff --git a/backend/services/api_key_validation.py b/backend/services/api_key_validation.py new file mode 100644 index 000000000..43f36bb79 --- /dev/null +++ b/backend/services/api_key_validation.py @@ -0,0 +1,66 @@ +"""Cheap authenticated probes so Settings only stores Fal and Gemini keys the provider accepts. + +LTX has no key check that avoids a side effect, so a non-empty LTX key is stored as-is. +A rejected LTX key fails on the first real request and the generation dialog opens Settings. +""" + +from __future__ import annotations + +from typing import NoReturn + +from _routes._errors import HTTPError +from services.gemini_text_client import GEMINI_API_BASE_URL +from services.http_client.http_client import HTTPClient, HttpTransportError + +# Auth on this route is optional, but a bad Authorization header is rejected (401/403) +# rather than ignored. limit=1 keeps the probe from downloading the catalog. +# Do not point this at /v1/keys or /v1/models/usage — those need an admin key. +FAL_KEY_PROBE_URL = "https://api.fal.ai/v1/models?limit=1" + +_AUTH_REJECTED = frozenset({401, 403}) +_INVALID_KEY_MESSAGE = "This key isn’t valid." +_UNVERIFIED_MESSAGE = "Couldn’t verify this key. Try again in a moment." + + +def _raise_transport(provider: str, exc: HttpTransportError) -> NoReturn: + raise HTTPError(504, f"Couldn’t reach {provider}. Try again in a moment.") from exc + + +def _raise_unverified(*, code: str) -> NoReturn: + # Distinct from *_INVALID_API_KEY: the probe did not finish, so the key was not rejected. + raise HTTPError(502, _UNVERIFIED_MESSAGE, code=code) + + +def validate_gemini_api_key(http: HTTPClient, *, api_key: str) -> None: + """One-page models.list — Gemini returns 400/401 for junk keys.""" + try: + response = http.get( + f"{GEMINI_API_BASE_URL}/models?pageSize=1", + headers={"x-goog-api-key": api_key}, + timeout=15, + ) + except HttpTransportError as exc: + _raise_transport("Gemini", exc) + if response.status_code == 200: + return + # Google uses 400 for API_KEY_INVALID, and 401/403 for rejected credentials. + if response.status_code in _AUTH_REJECTED or response.status_code == 400: + raise HTTPError(400, _INVALID_KEY_MESSAGE, code="GEMINI_INVALID_API_KEY") + _raise_unverified(code="GEMINI_API_KEY_UNVERIFIED") + + +def validate_fal_api_key(http: HTTPClient, *, api_key: str) -> None: + """GET /v1/models — 401/403 means the key was rejected. 200 means it was accepted.""" + try: + response = http.get( + FAL_KEY_PROBE_URL, + headers={"Authorization": f"Key {api_key}"}, + timeout=15, + ) + except HttpTransportError as exc: + _raise_transport("FAL", exc) + if response.status_code == 200: + return + if response.status_code in _AUTH_REJECTED: + raise HTTPError(400, _INVALID_KEY_MESSAGE, code="FAL_INVALID_API_KEY") + _raise_unverified(code="FAL_API_KEY_UNVERIFIED") diff --git a/backend/services/audio_channels.py b/backend/services/audio_channels.py new file mode 100644 index 000000000..507867812 --- /dev/null +++ b/backend/services/audio_channels.py @@ -0,0 +1,29 @@ +"""Normalize decoded audio waveforms to the stereo layout the audio VAE expects.""" + +from __future__ import annotations + +import torch + + +def stereo_waveform(waveform: torch.Tensor) -> torch.Tensor: + """Return a waveform with exactly two channels. + + `decode_audio_from_file` yields `(batch, channels, samples)` or + `(channels, samples)`. The DistilledA2V audio VAE conv is stereo + (`in_channels=2`); mono STFT otherwise fails with CAPABILITY_FAILED. + """ + if waveform.ndim == 3: + channels = int(waveform.shape[1]) + if channels == 1: + return waveform.repeat(1, 2, 1) + if channels > 2: + return waveform[:, :2] + return waveform + if waveform.ndim == 2: + channels = int(waveform.shape[0]) + if channels == 1: + return waveform.repeat(2, 1) + if channels > 2: + return waveform[:2] + return waveform + raise ValueError(f"expected waveform with 2 or 3 dims, got {waveform.ndim}") diff --git a/backend/services/audio_trim.py b/backend/services/audio_trim.py new file mode 100644 index 000000000..e617509de --- /dev/null +++ b/backend/services/audio_trim.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +import subprocess +from collections.abc import Callable +from pathlib import Path + +from services.encoded_media import ( + check_output_size, + derived_file_name, + ingest_encoded, +) +from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, ffmpeg_seconds, run_ffmpeg +from services.media_probe import MAX_AUDIO_BYTES +from services.media_source import require_source +from services.records import AssetRecord, MediaError +from services.store import Store + + +def trim_audio_file(src: Path, dest: Path, start_sec: float, end_sec: float) -> None: + run_ffmpeg( + [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(src), + "-ss", + ffmpeg_seconds(start_sec), + "-t", + ffmpeg_seconds(end_sec - start_sec), + "-vn", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-fs", + str(MAX_AUDIO_BYTES), + str(dest), + ] + ) + + +def extract_audio_file(src: Path, dest: Path) -> None: + run_ffmpeg( + [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(src), + "-vn", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-fs", + str(MAX_AUDIO_BYTES), + str(dest), + ] + ) + + +def _write_audio_dest( + tmp_dir: Path, stem_name: str, suffix: str, encode: Callable[[Path], None] +) -> Path: + dest_m4a = tmp_dir / derived_file_name(stem_name, suffix, ".m4a") + try: + encode(dest_m4a) + except subprocess.CalledProcessError: + dest_wav = tmp_dir / derived_file_name(stem_name, suffix, ".wav") + encode(dest_wav) + check_output_size(dest_wav, MAX_AUDIO_BYTES, "audio") + return dest_wav + check_output_size(dest_m4a, MAX_AUDIO_BYTES, "audio") + return dest_m4a + + +def _ingest_encoded( + store: Store, + record: AssetRecord, + suffix: str, + encode: Callable[[Path], None], + *, + failure: str, +) -> AssetRecord: + return ingest_encoded( + store, + lambda tmp_dir: _write_audio_dest(tmp_dir, record.name, suffix, encode), + prefix="ltx-audio-trim-", + label="audio", + failure=failure, + ) + + +def trim_audio_asset( + store: Store, asset_id: str, start_sec: float, end_sec: float +) -> AssetRecord: + if end_sec <= start_sec: + raise ValueError("endSec must be greater than startSec") + record, source = require_source(store, asset_id, "audio") + + def encode(dest: Path) -> None: + trim_audio_file(source, dest, start_sec, end_sec) + + return _ingest_encoded( + store, record, "trim", encode, failure="ffmpeg failed to trim audio" + ) + + +def extract_audio_asset(store: Store, asset_id: str) -> AssetRecord: + record, source = require_source(store, asset_id, "video") + metadata = record.metadata + if metadata.mediaType != "video": + raise MediaError( + "UNSUPPORTED_MEDIA", + f"expected video asset, got {record.media_kind}", + ) + # ffmpeg turns a silent picture into "Output file does not contain any stream". + if metadata.metadata.audioStreamCount < 1: + raise MediaError("NO_AUDIO_STREAM", "video has no audio track") + + def encode(dest: Path) -> None: + extract_audio_file(source, dest) + + return _ingest_encoded( + store, record, "audio", encode, failure="ffmpeg failed to extract audio" + ) diff --git a/backend/services/dashboard_stats.py b/backend/services/dashboard_stats.py new file mode 100644 index 000000000..4b340a9a8 --- /dev/null +++ b/backend/services/dashboard_stats.py @@ -0,0 +1,534 @@ +"""Aggregate the generations dashboard from ``generation_stats`` and assets. + +Percentiles use linear interpolation between the nearest ranks: +``rank = (n - 1) * p``. +""" + +from __future__ import annotations + +import json +import logging +import sqlite3 +from datetime import date, datetime, timedelta +from typing import Literal, cast +from zoneinfo import ZoneInfo, ZoneInfoNotFoundError + +from pydantic import BaseModel, ConfigDict, Field + +from services.generation_stats_sql import generation_stats_sql + +DashboardWindow = Literal["7d", "30d", "all"] +_ACTIVITY_FEATURES = ( + "text-to-video", + "image-to-video", + "audio-to-video", + "lora", + "retake", + "extend", + "ic-lora", +) +_RENDER_GROUPS = frozenset( + {"text-to-video", "image-to-video", "audio-to-video", "lora"} +) +_EDIT_FEATURES = frozenset({"retake", "extend"}) +# Days before today included in a bounded window. 7d is today plus the six days before it. +_WINDOW_LOOKBACK_DAYS = {"7d": 6, "30d": 29} +# All zero-fills at most this many days. Older days appear only when a run finished then. +_MAX_ZERO_FILL_DAYS = 800 +_logger = logging.getLogger(__name__) + + +class InvalidTimezone(ValueError): + pass + + +class DashboardKpis(BaseModel): + model_config = ConfigDict(strict=True) + content_count: int = Field(ge=0) + footage_s: float = Field(ge=0) + gpu_ms: int = Field(ge=0) + succeeded: int = Field(ge=0) + failed: int = Field(ge=0) + cancelled: int = Field(ge=0) + success_rate: float | None = None + + +class ActivityDay(BaseModel): + model_config = ConfigDict(strict=True) + day: str + counts: dict[str, int] + + +class LoraUsage(BaseModel): + model_config = ConfigDict(strict=True) + feature: str + name: str + runs: int = Field(ge=0) + keep_rate: float | None = None + + +class LoraPanel(BaseModel): + model_config = ConfigDict(strict=True) + share: float | None = None + top: list[LoraUsage] + + +class RenderCell(BaseModel): + model_config = ConfigDict(strict=True) + model: str + resolution: str + aspect_ratio: str + duration_s: float + median_ms: float + p90_ms: float + count: int = Field(ge=1) + + +class FpsRenderCell(RenderCell): + """One render cell limited to a single frame rate. The pooled `render` list has no fps.""" + + fps: int + + +class FailureRow(BaseModel): + model_config = ConfigDict(strict=True) + error_code: str + count: int = Field(ge=1) + + +class KeepRate(BaseModel): + model_config = ConfigDict(strict=True) + kept: int = Field(ge=0) + total: int = Field(ge=0) + rate: float | None = None + + +class UsualSettings(BaseModel): + model_config = ConfigDict(strict=True) + resolution: str + aspect_ratio: str + duration_s: float + fps: int + + +class DashboardSnapshot(BaseModel): + model_config = ConfigDict(strict=True) + empty: bool + has_history: bool + range: DashboardWindow + tz: str + kpis: DashboardKpis + activity: list[ActivityDay] + loras: LoraPanel + render: list[RenderCell] + render_by_fps: list[FpsRenderCell] + aspect_ratios: list[str] + fps_values: list[int] + failures: list[FailureRow] + keep_rate: KeepRate + usual: UsualSettings | None = None + + +def percentile(values: list[float], p: float) -> float: + ordered = sorted(values) + if len(ordered) == 1: + return ordered[0] + rank = (len(ordered) - 1) * p + low = int(rank) + high = min(low + 1, len(ordered) - 1) + fraction = rank - low + return ordered[low] * (1 - fraction) + ordered[high] * fraction + + +def _zone(name: str) -> ZoneInfo: + try: + return ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError, OSError) as exc: + raise InvalidTimezone(name) from exc + + +def _lookback_days(window: Literal["7d", "30d"]) -> int: + return _WINDOW_LOOKBACK_DAYS[window] + + +def _window_start_ms( + window: DashboardWindow, zone: ZoneInfo, now: datetime +) -> int | None: + if window == "all": + return None + start_day = now.astimezone(zone).date() - timedelta(days=_lookback_days(window)) + start = datetime( + start_day.year, start_day.month, start_day.day, tzinfo=zone + ) + return int(start.timestamp() * 1000) + + +def _local_day(finished_at: int, zone: ZoneInfo) -> str: + return datetime.fromtimestamp(finished_at / 1000, zone).date().isoformat() + + +def _activity( + rows: list[sqlite3.Row], + *, + window: DashboardWindow, + zone: ZoneInfo, + today: date, +) -> list[ActivityDay]: + """Zero-fill recent days. A huge gap keeps only the days that have runs.""" + if window == "all": + dates = [ + datetime.fromtimestamp(int(row["finished_at"]) / 1000, zone).date() + for row in rows + ] + first = min(dates) if dates else today + else: + first = today - timedelta(days=_lookback_days(window)) + if window == "all" and (today - first).days > _MAX_ZERO_FILL_DAYS: + fill_from = today - timedelta(days=_MAX_ZERO_FILL_DAYS) + else: + fill_from = first + counts_by_day: dict[str, dict[str, int]] = { + day.isoformat(): {feature: 0 for feature in _ACTIVITY_FEATURES} + for day in ( + datetime.fromtimestamp(int(row["finished_at"]) / 1000, zone).date() + for row in rows + ) + if day < fill_from + } + counts_by_day = dict(sorted(counts_by_day.items())) + day = fill_from + while day <= today: + counts_by_day[day.isoformat()] = {feature: 0 for feature in _ACTIVITY_FEATURES} + day += timedelta(days=1) + for row in rows: + bucket = counts_by_day.setdefault( + _local_day(int(row["finished_at"]), zone), + {feature: 0 for feature in _ACTIVITY_FEATURES}, + ) + group = str(row["feature_group"]) + bucket[group] = bucket.get(group, 0) + 1 + return [ + ActivityDay(day=day_key, counts=counts) + for day_key, counts in sorted(counts_by_day.items()) + ] + + +def _clip_kept(asset: sqlite3.Row) -> bool: + """A clip is kept until the asset or its generation is soft-deleted.""" + return asset["asset_deleted_at"] is None and not int(asset["generation_deleted"]) + + +def _footage_s(feature: str, edited_span_s: float | None, metadata: str) -> float: + if feature in _EDIT_FEATURES: + return float(edited_span_s or 0) + try: + parsed: object = json.loads(metadata) + except json.JSONDecodeError: + return 0.0 + if not isinstance(parsed, dict): + return 0.0 + inner = cast(dict[str, object], parsed).get("metadata") + if not isinstance(inner, dict): + return 0.0 + duration_ms = cast(dict[str, object], inner).get("durationMs") + if isinstance(duration_ms, bool) or not isinstance(duration_ms, (int, float)): + return 0.0 + return float(duration_ms) / 1000 + + +def _render_ready(row: sqlite3.Row) -> bool: + return ( + row["status"] == "succeeded" + and row["feature_group"] in _RENDER_GROUPS + and row["run_ms"] is not None + and bool(row["resolution_label"]) + and row["render_duration_s"] is not None + and row["fps"] is not None + ) + + +def _group_render(rows: list[sqlite3.Row]) -> list[RenderCell]: + grouped: dict[tuple[str, str, str, float], list[float]] = {} + for row in rows: + key = ( + str(row["model"] or ""), + str(row["resolution_label"]), + str(row["aspect_ratio"] or ""), + round(float(row["render_duration_s"]), 4), + ) + grouped.setdefault(key, []).append(float(row["run_ms"])) + return [ + RenderCell( + model=model, + resolution=resolution, + aspect_ratio=aspect, + duration_s=duration_s, + median_ms=percentile(samples, 0.5), + p90_ms=percentile(samples, 0.9), + count=len(samples), + ) + for (model, resolution, aspect, duration_s), samples in sorted(grouped.items()) + ] + + +def _usual_ready(row: sqlite3.Row) -> bool: + if row["status"] != "succeeded" or row["feature"] in _EDIT_FEATURES: + return False + return bool( + row["resolution_label"] + and row["aspect_ratio"] + and row["fps"] is not None + and row["render_duration_s"] is not None + ) + + +def _log_exclusions(rows: list[sqlite3.Row]) -> None: + """Count rows dropped from one metric and still counted in the others.""" + render_excluded = sum( + 1 + for row in rows + if row["status"] == "succeeded" + and row["feature_group"] in _RENDER_GROUPS + and not _render_ready(row) + ) + usual_excluded = sum( + 1 + for row in rows + if row["status"] == "succeeded" + and row["feature"] not in _EDIT_FEATURES + and row["resolution_label"] + and not _usual_ready(row) + ) + unrecognized = sum( + 1 for row in rows if str(row["feature_group"]) not in _ACTIVITY_FEATURES + ) + for metric, count in ( + ("render", render_excluded), + ("usual_settings", usual_excluded), + ("feature_group", unrecognized), + ): + if count: + _logger.info("dashboard excluded %s rows from %s", count, metric) + + +def compute_dashboard( + conn: sqlite3.Connection, + *, + window: DashboardWindow, + tz: str, + now: datetime | None = None, +) -> DashboardSnapshot: + zone = _zone(tz) + moment = now if now is not None else datetime.now(zone) + if moment.tzinfo is None: + moment = moment.replace(tzinfo=zone) + start_ms = _window_start_ms(window, zone, moment) + conn.execute("BEGIN") + try: + rows, assets, has_history = _read(conn, start_ms) + finally: + conn.rollback() + return _snapshot( + rows, + assets, + has_history=has_history, + window=window, + tz=tz, + zone=zone, + moment=moment, + ) + + +def _read( + conn: sqlite3.Connection, start_ms: int | None +) -> tuple[list[sqlite3.Row], list[sqlite3.Row], bool]: + """Both reads share one transaction, so a run that finishes between them cannot skew a request.""" + rows = conn.execute( + generation_stats_sql( + """ + SELECT * + FROM generation_stats + WHERE finished_at IS NOT NULL + AND (? IS NULL OR finished_at >= ?) + """ + ), + (start_ms, start_ms), + ).fetchall() + assets = conn.execute( + generation_stats_sql( + """ + SELECT + a.deleted_at AS asset_deleted_at, + s.is_deleted AS generation_deleted, + a.metadata AS metadata, + s.feature AS feature, + s.feature_group AS feature_group, + s.edited_span_s AS edited_span_s, + s.id AS generation_id + FROM assets a + JOIN generation_stats s ON s.id = a.producer_generation_id + WHERE a.origin = 'generated' + AND a.media_kind = 'video' + AND s.status = 'succeeded' + AND s.finished_at IS NOT NULL + AND (? IS NULL OR s.finished_at >= ?) + """ + ), + (start_ms, start_ms), + ).fetchall() + has_history = bool(rows) or ( + start_ms is not None + and conn.execute( + generation_stats_sql( + "SELECT 1 FROM generation_stats WHERE finished_at IS NOT NULL LIMIT 1" + ) + ).fetchone() + is not None + ) + return rows, assets, has_history + + +def _snapshot( + rows: list[sqlite3.Row], + assets: list[sqlite3.Row], + *, + has_history: bool, + window: DashboardWindow, + tz: str, + zone: ZoneInfo, + moment: datetime, +) -> DashboardSnapshot: + succeeded = sum(1 for row in rows if row["status"] == "succeeded") + failed = sum(1 for row in rows if row["status"] == "failed") + cancelled = sum(1 for row in rows if row["status"] == "cancelled") + decided = succeeded + failed + gpu_ms = sum( + int(row["run_ms"]) + for row in rows + if row["status"] in {"succeeded", "failed"} and row["run_ms"] is not None + ) + footage_s = 0.0 + kept_assets = 0 + for asset in assets: + footage_s += _footage_s( + str(asset["feature"]), asset["edited_span_s"], str(asset["metadata"]) + ) + if _clip_kept(asset): + kept_assets += 1 + today = moment.astimezone(zone).date() + activity = _activity(rows, window=window, zone=zone, today=today) + + lora_runs: dict[str, list[sqlite3.Row]] = {} + for row in rows: + if row["feature_group"] != "lora": + continue + lora_runs.setdefault(str(row["feature"]), []).append(row) + lora_assets: dict[str, list[sqlite3.Row]] = {} + for asset in assets: + if asset["feature_group"] != "lora": + continue + lora_assets.setdefault(str(asset["feature"]), []).append(asset) + ranked = sorted( + lora_runs.items(), + key=lambda item: (-len(item[1]), item[0]), + ) + usages: list[LoraUsage] = [] + for feature, runs in ranked: + named = sorted( + (run for run in runs if run["lora_name"]), + key=lambda run: int(run["finished_at"]), + ) + feature_assets = lora_assets.get(feature, []) + kept = sum(1 for asset in feature_assets if _clip_kept(asset)) + usages.append( + LoraUsage( + feature=feature, + name=str(named[-1]["lora_name"]) if named else feature, + runs=len(runs), + keep_rate=(kept / len(feature_assets)) if feature_assets else None, + ) + ) + lora_total = sum(len(runs) for runs in lora_runs.values()) + + _log_exclusions(rows) + render_pool = [row for row in rows if _render_ready(row)] + aspect_ratios = sorted( + {str(row["aspect_ratio"]) for row in render_pool if row["aspect_ratio"]} + ) + fps_values = sorted( + {int(row["fps"]) for row in render_pool if row["fps"] is not None} + ) + cells = _group_render(render_pool) + by_fps = [ + FpsRenderCell(**cell.model_dump(), fps=value) + for value in fps_values + for cell in _group_render( + [row for row in render_pool if int(row["fps"]) == value] + ) + ] + + failures: dict[str, int] = {} + for row in rows: + if row["status"] != "failed": + continue + code = str(row["error_code"] or "UNKNOWN") + failures[code] = failures.get(code, 0) + 1 + + usual_counts: dict[tuple[str, str, float, int], tuple[int, int]] = {} + for row in rows: + if not _usual_ready(row): + continue + key = ( + str(row["resolution_label"]), + str(row["aspect_ratio"]), + round(float(row["render_duration_s"]), 4), + int(row["fps"]), + ) + count, latest = usual_counts.get(key, (0, 0)) + usual_counts[key] = (count + 1, max(latest, int(row["finished_at"]))) + usual = None + if usual_counts: + best = max(usual_counts.items(), key=lambda item: (item[1][0], item[1][1])) + resolution, ratio, duration_s, setting_fps = best[0] + usual = UsualSettings( + resolution=resolution, + aspect_ratio=ratio, + duration_s=duration_s, + fps=setting_fps, + ) + + total_assets = len(assets) + return DashboardSnapshot( + empty=len(rows) == 0, + has_history=has_history, + range=window, + tz=tz, + kpis=DashboardKpis( + content_count=total_assets, + footage_s=footage_s, + gpu_ms=gpu_ms, + succeeded=succeeded, + failed=failed, + cancelled=cancelled, + success_rate=(succeeded / decided) if decided else None, + ), + activity=activity, + loras=LoraPanel( + share=(lora_total / len(rows)) if rows else None, + top=usages, + ), + render=cells, + render_by_fps=by_fps, + aspect_ratios=aspect_ratios, + fps_values=fps_values, + failures=[ + FailureRow(error_code=code, count=count) + for code, count in sorted(failures.items(), key=lambda item: (-item[1], item[0])) + ], + keep_rate=KeepRate( + kept=kept_assets, + total=total_assets, + rate=(kept_assets / total_assets) if total_assets else None, + ), + usual=usual, + ) diff --git a/backend/services/denoising_progress.py b/backend/services/denoising_progress.py new file mode 100644 index 000000000..4408bf890 --- /dev/null +++ b/backend/services/denoising_progress.py @@ -0,0 +1,97 @@ +"""Exact denoise-step totals and in-flight step reporting. + +Drive the existing progress bar from real denoise steps instead of a guessed +duration. Step-based inference progress was proposed by Sergio Gil +(@jimeneztion). + +``ltx_pipelines`` sampler loops have no progress callback. Totals are derived +from the same sigma schedules the pipelines pass to ``DiffusionStage`` +(``len(sigmas) - 1`` per stage). Current step is advanced from the existing +``DiffusionStage.__call__`` patch as each loop iteration completes. + +Inference percent occupies 15–90 so loading/encoding stay below and decode/encode +can finish the bar. +""" + +from __future__ import annotations + +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar, Token +from dataclasses import dataclass + +from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES + +_INFERENCE_START = 15 +_INFERENCE_SPAN = 75 +_INFERENCE_END = 90 + +# Current ltx-pipelines distilled recipe (len(sigmas) - 1 per stage). Tests pin +# these so a schedule change fails loudly instead of silently stretching the bar. +DISTILLED_STAGE_1_STEPS = len(DISTILLED_SIGMA_VALUES) - 1 +DISTILLED_STAGE_2_STEPS = len(STAGE_2_DISTILLED_SIGMA_VALUES) - 1 +DISTILLED_TOTAL_STEPS = DISTILLED_STAGE_1_STEPS + DISTILLED_STAGE_2_STEPS + +_Sink = Callable[[int, int], None] + + +@dataclass +class _Session: + total: int + current: int = 0 + + +_session: ContextVar[_Session | None] = ContextVar("denoising_progress_session", default=None) +_sink: _Sink | None = None + + +def configure_sink(sink: _Sink | None) -> None: + global _sink + _sink = sink + + +def distilled_total_steps(*, stage_2: bool = True) -> int: + """Denoise iterations for a distilled run (Fast / A2V / IC-LoRA). + + Matches ``DiffusionStage``: ``len(sigmas) - 1`` per stage. Stage 2 is the + 2× upsample refinement; IC-LoRA ``skip_stage_2`` omits it. + """ + if stage_2: + return DISTILLED_TOTAL_STEPS + return DISTILLED_STAGE_1_STEPS + + +def inference_percent(current: int, total: int) -> int: + if total <= 0: + return _INFERENCE_START + return min(_INFERENCE_START + int(_INFERENCE_SPAN * current / total), _INFERENCE_END) + + +def _emit(current: int, total: int) -> None: + if _sink is not None: + _sink(current, total) + + +@contextmanager +def track_denoising(total_steps: int) -> Iterator[None]: + token: Token[_Session | None] = _session.set(_Session(total=total_steps, current=0)) + _emit(0, total_steps) + try: + yield + finally: + _session.reset(token) + + +def note_step() -> None: + session = _session.get() + if session is None or session.total <= 0: + return + session.current = min(session.current + 1, session.total) + _emit(session.current, session.total) + + +def reset() -> None: + """Drop an in-flight session and the progress sink (tests).""" + global _sink + _session.set(None) + _sink = None diff --git a/backend/services/encoded_media.py b/backend/services/encoded_media.py new file mode 100644 index 000000000..aaddcccfc --- /dev/null +++ b/backend/services/encoded_media.py @@ -0,0 +1,59 @@ +"""Shared tail of the asset transforms: size-check the encode, ingest it.""" + +from __future__ import annotations + +import re +import subprocess +import tempfile +from collections.abc import Callable +from pathlib import Path + +from services.records import AssetRecord, MediaError +from services.store import Store + +_UNSAFE_NAME_CHARS = re.compile(r'[\\/:*?"<>|\x00-\x1f]+') +_MAX_STEM_CHARS = 100 + + +def derived_file_name(source_name: str, suffix: str, extension: str) -> str: + """``talk.mov`` -> ``talk-trim.mp4``; ingest names the asset after the file.""" + stem = _UNSAFE_NAME_CHARS.sub("_", Path(source_name).stem).strip(" .") + return f"{stem[:_MAX_STEM_CHARS] or 'clip'}-{suffix}{extension}" + + +def check_output_size(path: Path, limit_bytes: int, label: str) -> None: + try: + size_bytes = path.stat().st_size + except OSError as exc: + raise MediaError( + "UNREADABLE_MEDIA", f"encoded {label} dest is unreadable" + ) from exc + # -fs truncates at the limit and still exits 0; a truncated clip must + # never be ingested as success. + if size_bytes >= limit_bytes: + raise MediaError("FILE_TOO_LARGE", f"encoded {label} exceeds size limit") + + +def ingest_encoded( + store: Store, + write: Callable[[Path], Path], + *, + prefix: str, + label: str, + failure: str, +) -> AssetRecord: + """``write`` encodes into the temp dir and returns the file to ingest.""" + try: + # A failed cleanup must not turn an ingested asset into a 500. + with tempfile.TemporaryDirectory( + prefix=prefix, ignore_cleanup_errors=True + ) as tmp: + dest = write(Path(tmp)) + try: + return store.ingest_upload(str(dest)) + except FileNotFoundError as exc: + raise MediaError( + "UNREADABLE_MEDIA", f"encoded {label} dest is unreadable" + ) from exc + except subprocess.CalledProcessError as exc: + raise MediaError("UNREADABLE_MEDIA", failure) from exc diff --git a/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py b/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py index 4fcf0a7a3..917963d7d 100644 --- a/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py +++ b/backend/services/fast_video_pipeline/distilled_keyframe_guiding.py @@ -1,8 +1,12 @@ -"""Per-call Distilled helper swap for multi-keyframe generate. +"""Per-call helper swap for multi-keyframe generate. -DistilledPipeline hardcodes ``combined_image_conditionings`` (frame 0 replaces -the latent). MKF interpolation needs ``image_conditionings_by_adding_guiding_latent`` -instead. This is scoped to one Fast generate so first/last i2v keeps replace-at-0. +``combined_image_conditionings`` replaces frame 0 and treats later images as +keyframes. MKF interpolation needs ``image_conditionings_by_adding_guiding_latent``, +which keeps every image (including frame 0) as a keyframe. The swap is scoped +to one Fast generate so first/last i2v keeps replace-at-0. + +v1.4 calls the helper from ``ltx_pipelines.chunks.conditionings``, which binds +the name at import, and the stage-1-only path looks it up on ``helpers``. """ from __future__ import annotations @@ -16,13 +20,17 @@ @contextmanager def distilled_keyframe_guiding() -> Iterator[None]: - import ltx_pipelines.distilled as distilled + import ltx_pipelines.chunks.conditionings as chunk_conditionings + import ltx_pipelines.utils.helpers as helpers from ltx_pipelines.utils.helpers import image_conditionings_by_adding_guiding_latent with _SWAP_LOCK: - original = distilled.combined_image_conditionings - distilled.combined_image_conditionings = image_conditionings_by_adding_guiding_latent + original_helpers = helpers.combined_image_conditionings + original_chunks = chunk_conditionings.combined_image_conditionings + helpers.combined_image_conditionings = image_conditionings_by_adding_guiding_latent + chunk_conditionings.combined_image_conditionings = image_conditionings_by_adding_guiding_latent try: yield finally: - distilled.combined_image_conditionings = original + helpers.combined_image_conditionings = original_helpers + chunk_conditionings.combined_image_conditionings = original_chunks diff --git a/backend/services/fast_video_pipeline/distilled_skip_stage_2.py b/backend/services/fast_video_pipeline/distilled_skip_stage_2.py new file mode 100644 index 000000000..3d9b6e65a --- /dev/null +++ b/backend/services/fast_video_pipeline/distilled_skip_stage_2.py @@ -0,0 +1,172 @@ +"""Stage-1-only decode for ``DistilledPipeline``. + +The vendor method has no ``skip_stage_2`` and always upsamples and refines. +``skip_stage_2=False`` forwards to that method. ``skip_stage_2=True`` denoises +the half-resolution canvas and decodes it, using the v1.4 latent-entry stage. + +Delete this file when a tag adds ``skip_stage_2`` to ``DistilledPipeline``. +""" + +from __future__ import annotations + +import logging +from collections.abc import Sequence +from typing import Any + +import torch +from ltx_core.components.noisers import GaussianNoiser +from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TilingConfig +from ltx_core.types import VideoPixelShape +import ltx_pipelines.distilled as distilled +import ltx_pipelines.utils.helpers as ltx_helpers +from ltx_pipelines.distilled import ANCESTRAL_NOISE_SEED_OFFSET +from ltx_pipelines.utils.blocks import require_num_frames_source, resolve_num_frames +from ltx_pipelines.utils.constants import DISTILLED_SIGMAS +from ltx_pipelines.utils.denoisers import SimpleDenoiser +from ltx_pipelines.utils.helpers import ( + assert_stage_supports_generated_keyframes, + create_initial_av_latents, + ensure_tiling_config, + generated_keyframe_conditionings, + has_generated_keyframes, + snap_frames_to_grid, + tiling_scale_factors_for_vae, +) +from ltx_pipelines.utils.media_io import EXRColorSpace +from ltx_pipelines.utils.types import ( + DEFAULT_AUTO_DURATION, + AutoDuration, + ImageConditioningInput, + ModalitySpec, + PipelineOutput, + VideoAudio, +) + +logger = logging.getLogger(__name__) + + +class DistilledPipelineWithSkipStage2(distilled.DistilledPipeline): + def __call__(self, *args: Any, skip_stage_2: bool = False, **kwargs: Any) -> PipelineOutput: + if skip_stage_2: + return self._call_stage_1_only(*args, **kwargs) + return super().__call__(*args, **kwargs) + + def _call_stage_1_only( # noqa: PLR0913 + self, + prompt: str, + seed: int, + height: int, + width: int, + frame_rate: float, + images: list[ImageConditioningInput], + num_frames: int | AutoDuration = DEFAULT_AUTO_DURATION, + vae_dtype: torch.dtype | None = None, + tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING, + enhance_prompt: bool = False, + enhance_static_cache: bool = False, + stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS, + color_space: EXRColorSpace | None = None, + generated_keyframes: int | Sequence[int] = 0, + ) -> PipelineOutput: + """Denoise stage 1 at canvas/2 and decode. + + Stage 2, keyframe decode, and chunking arguments are deliberately not accepted, so a + caller that passes one fails with ``TypeError`` instead of being ignored. + """ + require_num_frames_source(num_frames, self.duration_predictor) + images = self.image_conditioner.resolve_crf(images) + distilled.assert_resolution(height=height, width=width, is_two_stage=True) + if has_generated_keyframes(generated_keyframes): + assert_stage_supports_generated_keyframes(self.stage) + + generator = torch.Generator(device=self.device).manual_seed(seed) + noiser = GaussianNoiser(generator=generator) + dtype = torch.bfloat16 + if vae_dtype is None: + vae_dtype = dtype + + (ctx_p,) = self.prompt_encoder( + [prompt], + enhance_first_prompt=enhance_prompt, + enhance_static_cache=enhance_static_cache, + enhance_prompt_image=images[0][0] if len(images) > 0 else None, + ) + video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding + + num_frames = snap_frames_to_grid( + resolve_num_frames( + num_frames, + self.duration_predictor, + video_encoding=video_context, + audio_encoding=audio_context, + frame_rate=frame_rate, + ) + ) + + # Decode shape is stage-1 pixels (canvas/2). Distilled sizes tiling for the + # post-upsample canvas because it always runs stage 2. + stage_1_w, stage_1_h = width // 2, height // 2 + scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path) + tiling_config = ensure_tiling_config( + tiling_config, + scale_factors=scale_factors, + vae_checkpoint_path=self.video_decoder.checkpoint_path, + video_shape=VideoPixelShape( + batch=1, frames=num_frames, height=stage_1_h, width=stage_1_w, fps=frame_rate + ), + diffvae_optimization=self.video_decoder.diffvae_optimization, + device=self.device, + ) + + stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device) + # Look up on helpers so a keyframe patch can swap the helper. + stage_1_conditionings = self.image_conditioner( + lambda enc: ltx_helpers.combined_image_conditionings( + images=images, + height=stage_1_h, + width=stage_1_w, + video_encoder=enc, + dtype=dtype, + device=self.device, + color_space=color_space, + ) + ) + stage_1_conditionings.extend(generated_keyframe_conditionings(generated_keyframes, num_frames)) + + video_latent, audio_latent = create_initial_av_latents( + width=stage_1_w, + height=stage_1_h, + frames=num_frames, + fps=frame_rate, + device=self.device, + dtype=dtype, + # Transformer latent geometry. `scale_factors` above is the decoder's tiling scale + # (2x8x8 on the 2.5 DiffVAE) and is only right for sizing decode tiles. + video_scale_factors=self.stage.video_scale_factors, + ) + video_state, audio_state = self.stage( + denoiser=SimpleDenoiser(video_context, audio_context), + sigmas=stage_1_sigmas, + noiser=noiser, + modalities=VideoAudio( + video=ModalitySpec( + latent=video_latent, + conditioning_fps=frame_rate, + context=video_context, + conditionings=stage_1_conditionings, + ), + audio=ModalitySpec( + latent=audio_latent, + conditioning_fps=frame_rate, + context=audio_context, + ), + ), + **self._sampler_kwargs(seed, ANCESTRAL_NOISE_SEED_OFFSET), + ) + + logger.info("[fast] Skipping Stage 2 (skip_stage_2=True); decode %dx%d", stage_1_w, stage_1_h) + assert video_state is not None + assert audio_state is not None + decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype) + decoded_audio = self.audio_decoder(audio_state.latent) + return PipelineOutput(decoded_video, decoded_audio, num_frames, tiling_config) diff --git a/backend/services/fast_video_pipeline/fast_video_pipeline.py b/backend/services/fast_video_pipeline/fast_video_pipeline.py index bc1ac682d..fbe0214d4 100644 --- a/backend/services/fast_video_pipeline/fast_video_pipeline.py +++ b/backend/services/fast_video_pipeline/fast_video_pipeline.py @@ -41,6 +41,7 @@ def generate( output_path: str, *, guide_all_images: bool = False, + skip_stage_2: bool = False, ) -> None: ... diff --git a/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py b/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py index 36ace6e9a..a943d1fb4 100644 --- a/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py +++ b/backend/services/fast_video_pipeline/ltx_fast_video_pipeline.py @@ -64,7 +64,7 @@ def __init__( from ltx_core.loader.primitives import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy - from ltx_pipelines.distilled import DistilledPipeline + from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 self._checkpoint_path = checkpoint_path self._gemma_root = gemma_root @@ -82,7 +82,7 @@ def __init__( for path, scale in self._loras ] - self.pipeline = DistilledPipeline( + self.pipeline = DistilledPipelineWithSkipStage2( model_paths=build_model_paths( checkpoint_path, gemma_root, @@ -109,10 +109,11 @@ def _run_inference( tiling_config: PipelineTilingType, *, guide_all_images: bool = False, + skip_stage_2: bool = False, ) -> tuple[torch.Tensor | Iterator[torch.Tensor], AudioOrNone, int, TilingConfigType | None]: from contextlib import nullcontext - from ltx_pipelines.utils.args import ImageConditioningInput as _LtxImageInput + from ltx_pipelines.utils.types import ImageConditioningInput as _LtxImageInput from ltx_pipelines.utils.types import AutoDuration from services.fast_video_pipeline.distilled_keyframe_guiding import distilled_keyframe_guiding @@ -124,7 +125,7 @@ def _run_inference( ctx = distilled_keyframe_guiding() if guide_all_images else nullcontext() with ctx: - video, audio, resolved_frames, resolved_tiling = self.pipeline( + result = self.pipeline( prompt=prompt, seed=seed, height=height, @@ -133,8 +134,9 @@ def _run_inference( frame_rate=frame_rate, images=[_LtxImageInput(img.path, img.frame_idx, img.strength) for img in images], tiling_config=tiling_config, + skip_stage_2=skip_stage_2, ) - return video, audio, resolved_frames, resolved_tiling + return result.video, result.audio, result.num_frames, result.tiling_config @torch.inference_mode() def generate( @@ -149,18 +151,23 @@ def generate( output_path: str, *, guide_all_images: bool = False, + skip_stage_2: bool = False, ) -> None: - video, audio, resolved_frames, resolved_tiling = self._run_inference( - prompt=prompt, - seed=seed, - height=height, - width=width, - num_frames=num_frames, - frame_rate=frame_rate, - images=images, - tiling_config=auto_tiling_config(), - guide_all_images=guide_all_images, - ) + from services.denoising_progress import distilled_total_steps, track_denoising + + with track_denoising(distilled_total_steps(stage_2=not skip_stage_2)): + video, audio, resolved_frames, resolved_tiling = self._run_inference( + prompt=prompt, + seed=seed, + height=height, + width=width, + num_frames=num_frames, + frame_rate=frame_rate, + images=images, + tiling_config=auto_tiling_config(), + guide_all_images=guide_all_images, + skip_stage_2=skip_stage_2, + ) chunks = video_chunks_number(resolved_frames, resolved_tiling) encode_video_output(video=video, audio=audio, fps=int(frame_rate), output_path=output_path, video_chunks_number_value=chunks) @@ -189,14 +196,14 @@ def compile_transformer(self) -> None: from ltx_core.loader.primitives import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.model.transformer.compiling import CompilationConfig - from ltx_pipelines.distilled import DistilledPipeline + from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 lora_entries = [ LoraPathStrengthAndSDOps(path=path, strength=scale, sd_ops=LTXV_LORA_COMFY_RENAMING_MAP) for path, scale in self._loras ] - self.pipeline = DistilledPipeline( + self.pipeline = DistilledPipelineWithSkipStage2( model_paths=build_model_paths( self._checkpoint_path, self._gemma_root, diff --git a/backend/services/features/__init__.py b/backend/services/features/__init__.py new file mode 100644 index 000000000..d9e525ad9 --- /dev/null +++ b/backend/services/features/__init__.py @@ -0,0 +1 @@ +"""Feature executors used by the generation queue. Queue runtime stays generic.""" diff --git a/backend/services/features/ic_lora_recipes.py b/backend/services/features/ic_lora_recipes.py new file mode 100644 index 000000000..9746e966b --- /dev/null +++ b/backend/services/features/ic_lora_recipes.py @@ -0,0 +1,217 @@ +"""Home IC-LoRA recipes. One row per video-in catalog entry that shares this form. + +The path id is the recipe. The body does not repeat the catalog id. A row that +is not a Home recipe is rejected here so it cannot silently run on this +generic path. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path + +from api_types import ( + CreateIcLoraRecipeRequest, + IcLoraCatalogItem, + IcLoraRecipeStoredParams, + LoraEntry, +) +from runtime_config.model_download_specs import ( + downloaded_ic_lora_variant_ids, + is_ic_lora_downloaded, +) +from runtime_config.offerings import resolve_offering_local_model_id +from services.features.lora_recipes import RecipeCreateError, require_catalog_runnable +from services.lora_catalog import LoraCatalogProvider + + +@dataclass(frozen=True, slots=True) +class IcLoraRecipe: + recipe_id: str + catalog_id: str + # The model writes a matte. The recipe also bakes a WebM with alpha from it + # and stores both. Backend only: the shared table pins ids, not outputs. + cutout: bool = False + + +_CAP_PATH = Path(__file__).resolve().parents[3] / "shared" / "ic-lora-input-cap.json" +_CAP = json.loads(_CAP_PATH.read_text(encoding="utf-8")) +# Shared with the Home form via shared/ic-lora-input-cap.json. +MAX_IC_LORA_INPUT_VIDEO_SECONDS = int(_CAP["maxInputVideoSeconds"]) +MAX_IC_LORA_INPUT_FRAMES = int(_CAP["maxInputFrames"]) +_IC_LORA_DURATION_TOLERANCE_SECONDS = float(_CAP["durationToleranceSeconds"]) +_IC_LORA_FPS_MATCH_TOLERANCE = float(_CAP["fpsMatchTolerance"]) +IC_LORA_SUPPORTED_FPS: tuple[int, ...] = tuple(int(rate) for rate in _CAP["supportedFps"]) + + +def ic_lora_max_input_seconds(fps: float) -> float: + """Longest clip the selected output rate can run. 240 frames, and never past 10s.""" + return min(MAX_IC_LORA_INPUT_VIDEO_SECONDS, MAX_IC_LORA_INPUT_FRAMES / fps) + + +def _format_seconds(seconds: float) -> str: + rounded = round(seconds, 1) + if rounded == int(rounded): + return str(int(rounded)) + return f"{rounded:.1f}" + + +def ic_lora_input_cap_message(duration_ms: int, fps: float) -> str | None: + """Why this clip cannot run at ``fps``, or None when it fits.""" + limit = ic_lora_max_input_seconds(fps) + if duration_ms / 1000 > limit + _IC_LORA_DURATION_TOLERANCE_SECONDS: + return ( + f"This clip is longer than {_format_seconds(limit)}s at {fps:g}fps. " + "Trim it to continue." + ) + return None + + +def ic_lora_original_fps(source_fps: float) -> float: + """Supported rate closest to the source, never more than a half frame above it. + + A source slower than every supported rate keeps its own rate. An equal + distance picks the lower rate, so Original never prefers a faster rate. + """ + eligible = [ + rate + for rate in IC_LORA_SUPPORTED_FPS + if rate <= source_fps + _IC_LORA_FPS_MATCH_TOLERANCE + ] + if not eligible: + return source_fps + return min(eligible, key=lambda rate: (abs(rate - source_fps), rate)) + + +def ic_lora_fps_choices(source_fps: float) -> tuple[float, ...]: + """Original, then every supported rate below it, highest first.""" + original = ic_lora_original_fps(source_fps) + below = tuple( + sorted((rate for rate in IC_LORA_SUPPORTED_FPS if rate < original), reverse=True) + ) + return (original, *below) + + +def resolve_ic_lora_output_fps(source_fps: float, selected: float | None) -> float: + """The rate create stores. Omitted means Original. A faster selection is refused.""" + if selected is None: + return ic_lora_original_fps(source_fps) + if selected > source_fps + _IC_LORA_FPS_MATCH_TOLERANCE: + raise RecipeCreateError( + "Frame rate cannot be higher than the source clip.", + code="IC_LORA_FPS_ABOVE_SOURCE", + ) + return selected + + +# Order matches shared/ic-lora-recipes.json. +IC_LORA_RECIPES: dict[str, IcLoraRecipe] = { + "day-to-night": IcLoraRecipe(recipe_id="day-to-night", catalog_id="day-to-night"), + "alpha-gen": IcLoraRecipe( + recipe_id="alpha-gen", catalog_id="alpha-gen", cutout=True + ), + "deblur": IcLoraRecipe(recipe_id="deblur", catalog_id="deblur"), + "colorization": IcLoraRecipe(recipe_id="colorization", catalog_id="colorization"), + "clean-plate": IcLoraRecipe(recipe_id="clean-plate", catalog_id="clean-plate"), + "decompression": IcLoraRecipe(recipe_id="decompression", catalog_id="decompression"), + "water-simulation": IcLoraRecipe(recipe_id="water-simulation", catalog_id="water-simulation"), + "layout-to-render": IcLoraRecipe( + recipe_id="layout-to-render", catalog_id="layout-to-render" + ), + "restore": IcLoraRecipe(recipe_id="restore", catalog_id="restore"), +} + + +def get_ic_lora_recipe(recipe_id: str) -> IcLoraRecipe | None: + return IC_LORA_RECIPES.get(recipe_id) + + +def queued_ic_lora_recipes() -> tuple[IcLoraRecipe, ...]: + return tuple(IC_LORA_RECIPES.values()) + + +def resolve_ic_lora_recipe_create( + recipe_id: str, + req: CreateIcLoraRecipeRequest, + *, + catalog: LoraCatalogProvider, + models_dir: Path, + hf_authenticated: bool, + source_fps: float, +) -> tuple[IcLoraRecipe, IcLoraCatalogItem, IcLoraRecipeStoredParams]: + """Validate a recipe create and return the stored params, including ``loras``.""" + recipe = get_ic_lora_recipe(recipe_id) + if recipe is None: + raise RecipeCreateError(f"Unknown IC-LoRA recipe: {recipe_id}", code="IC_LORA_UNKNOWN") + item = catalog.get_ic_lora(recipe.catalog_id) + if item is None: + raise RecipeCreateError( + f"Catalog id '{recipe.catalog_id}' for recipe '{recipe_id}' not found", + code="IC_LORA_UNKNOWN", + ) + if not item.is_home_recipe(): + raise RecipeCreateError( + f"'{item.id}' needs its own form", + code="IC_LORA_UNSUPPORTED_RECIPE", + ) + if req.params.prompt.strip() == "" and not item.allows_empty_prompt: + raise RecipeCreateError("Prompt is required.", code="INVALID_GENERATION_SPEC") + if req.inputs.image is None and item.reference_image_required: + raise RecipeCreateError( + "Reference image is required.", code="INVALID_GENERATION_SPEC" + ) + if req.inputs.image is not None and not item.allows_reference_image: + raise RecipeCreateError( + f"'{item.id}' takes no reference image.", code="INVALID_GENERATION_SPEC" + ) + require_catalog_runnable( + item, + models_dir=models_dir, + hf_authenticated=hf_authenticated, + hf_code="IC_LORA_HF_AUTH_REQUIRED", + model_code="IC_LORA_UNSUPPORTED_MODEL", + local_model_id=resolve_offering_local_model_id(models_dir, req.params.model), + ) + installed = downloaded_ic_lora_variant_ids( + models_dir, + item.id, + [(variant.id, variant.filename) for variant in item.download.variants], + ) + variant = item.download.variant_for_run(req.params.variantId, installed) + if variant is None: + raise RecipeCreateError( + "UNKNOWN_DOWNLOAD_VARIANT", code="UNKNOWN_DOWNLOAD_VARIANT" + ) + if not is_ic_lora_downloaded(models_dir, item.id, variant.filename): + raise RecipeCreateError( + "IC_LORA_NOT_DOWNLOADED", code="IC_LORA_NOT_DOWNLOADED" + ) + fps = resolve_ic_lora_output_fps(source_fps, req.params.fps) + audio_mode = ( + req.params.audioMode + if req.params.audioMode is not None + else item.default_settings.audio_mode + ) + scale = ( + req.params.scale + if req.params.scale is not None + else item.default_settings.lora_strength + ) + stored = IcLoraRecipeStoredParams.model_validate( + { + **req.params.model_dump(exclude={"scale", "variantId"}), + "fps": fps, + "audioMode": audio_mode, + "loras": [ + LoraEntry( + ref="", + scale=scale, + catalogId=item.id, + displayName=item.name, + variantId=variant.id, + ) + ], + } + ) + return recipe, item, stored diff --git a/backend/services/features/lora_recipes.py b/backend/services/features/lora_recipes.py new file mode 100644 index 000000000..af54c8f3f --- /dev/null +++ b/backend/services/features/lora_recipes.py @@ -0,0 +1,483 @@ +"""LoRA recipe registry — the backend half of the io LoRA product config. + +One table keyed by the **web Explore id** (also the io route id and the enqueued +``feature``). Each row maps that id to a catalog adapter plus the metadata the +create path and the queued executor need: the generation ``mode``, the GPU +``devices`` the adapter is known to run on, and the fixed prompt scaffold applied +after enhancement. (Whether a recipe is surfaced on Home is a frontend concern — +see ``listed`` in ``shared/lora-recipes.json`` / ``frontend/lib/lora-recipes.ts``.) + +Unmapped ids resolve to ``None`` — the create path turns that into a typed +``LORA_UNKNOWN`` miss and never guesses a filesystem path. The frontend keeps a +mirrored registry (``frontend/lib/lora-recipes.ts``) for Home/router/Explore; the +shared id/catalogId/mode/devices contract is pinned on both sides against +``shared/lora-recipes.json`` by tests. Adding a template is a row here plus the +matching frontend row. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from typing import Literal + +from _routes._errors import HTTPError +from api_types import ( + CreateLoraRecipeRequest, + ImageToVideoInputs, + ImageToVideoRecipeParams, + LTXLocalModelId, + LoraCatalogItem, + LoraEntry, + TextToVideoParams, +) +from runtime_config.model_download_specs import ( + catalog_item_visible_for_installed_ltx, + downloaded_lora_variant_ids, + is_lora_downloaded, + ltx_catalog_family_for_model, + resolve_lora_path, +) +from services.lora_catalog import LoraCatalogProvider + +LoraRecipeMode = Literal["t2v", "i2v", "a2v"] +LoraRecipeDevice = Literal["cuda", "mps"] + + +@dataclass(frozen=True, slots=True) +class LoraRecipe: + """One io LoRA product, keyed by its web Explore id. + + ``prompt_template`` is the fixed scaffold (with a ``{prompt}`` placeholder) + applied to the generation prompt after enhancement. It is deliberately *not* + the catalog ``prompt_template`` (that is the IC-LoRA LLM template-fill path). + The wrap is idempotent — skipped when the scaffold prefix is already present + (see ``apply_recipe_prompt_template``). Explore auto-enhance off also skips + the wrap for typed prompts so Generate stays as-typed; a manual Enhance + still wraps. The trigger phrase lives on the catalog item and is enforced + by prompt enhancement, not stored here. + """ + + recipe_id: str + catalog_id: str + mode: LoraRecipeMode + devices: tuple[LoraRecipeDevice, ...] + prompt_template: str | None = None + requires_end_frame: bool = False + + +# Web Explore id -> recipe. Order matches Home LoRAs row / shared/lora-recipes.json. +LORA_RECIPES: dict[str, LoraRecipe] = { + "cozy-felt": LoraRecipe( + recipe_id="cozy-felt", + catalog_id="cozy-felt-style", + mode="t2v", + devices=("cuda", "mps"), + prompt_template=( + "F3ltCut0u7 handcrafted felt cutout cinematic diorama style, " + "everything constructed from soft layered felt with visible stitched " + "seams, fuzzy fibers, plush rounded edges, and embroidered details. " + "{prompt}" + ), + ), + "claymation": LoraRecipe( + recipe_id="claymation", + catalog_id="claymation-style", + mode="t2v", + devices=("cuda", "mps"), + prompt_template="Clay animation, claymation {prompt}", + ), + "fantasy-painterly": LoraRecipe( + recipe_id="fantasy-painterly", + catalog_id="fantasy-painterly-style", + mode="t2v", + devices=("cuda", "mps"), + prompt_template="D4rkP41nt3r, fantasy painterly style {prompt}", + ), + "paper-cut-out-style": LoraRecipe( + recipe_id="paper-cut-out-style", + catalog_id="paper-cutout-style", + mode="t2v", + devices=("cuda", "mps"), + prompt_template=( + "Pap3rCut0u7 {prompt}.\n Everything is handcrafted from layered " + "colored paper with visible cut edges, stacked cardstock, subtle " + "paper curl, textured paper fibers, hand-cut imperfections, soft " + "layered shadows, and a miniature paper diorama aesthetic" + ), + ), + "cinemagraph": LoraRecipe( + recipe_id="cinemagraph", + catalog_id="cinemagraph-motion", + mode="i2v", + devices=("cuda", "mps"), + prompt_template=( + "CINEMAGRAPH_MOTION, tripod locked-off static camera, zero camera " + "movement, {prompt}, seamless natural loop." + ), + ), + "jib-up": LoraRecipe( + recipe_id="jib-up", + catalog_id="jib-up", + mode="i2v", + devices=("cuda", "mps"), + prompt_template=( + "A smooth jib-up camera move rising vertically, revealing more of " + "what sits above the initial frame. {prompt}" + ), + ), + "jib-down": LoraRecipe( + recipe_id="jib-down", + catalog_id="jib-down", + mode="i2v", + devices=("cuda", "mps"), + prompt_template=( + "A smooth jib-down camera move descending vertically, revealing more " + "of what sits lower in the scene. {prompt}" + ), + ), + "dolly-in": LoraRecipe( + recipe_id="dolly-in", + catalog_id="dolly-in", + mode="i2v", + devices=("cuda", "mps"), + prompt_template=( + "A smooth dolly-in camera move pushing forward toward the subject, " + "increasing subject scale and reducing background prominence. {prompt}" + ), + ), + "dolly-out": LoraRecipe( + recipe_id="dolly-out", + catalog_id="dolly-out", + mode="i2v", + devices=("cuda", "mps"), + prompt_template=( + "A smooth dolly-out camera move pulling backward away from the " + "subject, revealing more of the environment. {prompt}" + ), + ), + "fpv-motion": LoraRecipe( + recipe_id="fpv-motion", + catalog_id="fpv-motion", + mode="t2v", + devices=("cuda", "mps"), + prompt_template="FPV footage, {prompt},", + ), + "openwheel-t-cam": LoraRecipe( + recipe_id="openwheel-t-cam", + catalog_id="openwheel-tcam-style", + mode="t2v", + devices=("cuda", "mps"), + prompt_template="T-cam onboard view {prompt}", + ), + "transition": LoraRecipe( + recipe_id="transition", + catalog_id="transition", + mode="i2v", + devices=("cuda", "mps"), + prompt_template="{prompt} zhuanchang", + requires_end_frame=True, + ), + "vbvr": LoraRecipe( + recipe_id="vbvr", + catalog_id="vbvr", + mode="i2v", + devices=("cuda", "mps"), + ), +} + + +def get_lora_recipe(recipe_id: str) -> LoraRecipe | None: + """The recipe for a web Explore id, or ``None`` for an unmapped id.""" + return LORA_RECIPES.get(recipe_id) + + +def t2v_lora_recipes() -> list[LoraRecipe]: + """Recipes that run on the queued text-to-video executor.""" + return [recipe for recipe in LORA_RECIPES.values() if recipe.mode == "t2v"] + + +def i2v_lora_recipes() -> list[LoraRecipe]: + """Recipes that run on the queued image-to-video executor.""" + return [recipe for recipe in LORA_RECIPES.values() if recipe.mode == "i2v"] + + +def queued_lora_recipes() -> list[LoraRecipe]: + """Recipes that have a queued executor (t2v or i2v). ``a2v`` is still unsupported.""" + return [recipe for recipe in LORA_RECIPES.values() if recipe.mode in ("t2v", "i2v")] + + +def apply_recipe_prompt_template(recipe: LoraRecipe, prompt: str) -> str: + """Wrap ``prompt`` in the recipe's scaffold, after enhancement. + + Skipped when the recipe has no template, when the template is malformed (no + ``{prompt}`` placeholder — fail closed and return the prompt untouched rather + than drop the user's scene), or when the prompt already *starts with* the + scaffold prefix (an idempotent re-wrap). + + The guard checks ``startswith``, not a substring: generation enhancement is + catalog-aware, and the adapter's prompting example embeds this same scaffold + sentence, so an enhanced rewrite can contain it *mid-prompt*. A substring + check would then skip the wrap and the style lock would never lead the + prompt — so the scaffold is prepended unless it is already at the front. + """ + template = recipe.prompt_template + if not template or "{prompt}" not in template: + return prompt + prefix, _, suffix = template.partition("{prompt}") + scaffold_prefix = prefix.strip() + scaffold_suffix = suffix.strip() + lowered = prompt.lower() + if scaffold_prefix and lowered.startswith(scaffold_prefix.lower()): + return prompt + if not scaffold_prefix and scaffold_suffix and lowered.endswith(scaffold_suffix.lower()): + return prompt + return template.replace("{prompt}", prompt, 1) + + +def make_recipe_prompt_wrap(recipe: LoraRecipe) -> Callable[[str], str]: + """A ``(prompt) -> prompt`` wrap the queued executor applies post-enhance. + + The executor always passes this wrap; ``generate_local_reserved`` decides + whether to apply it (skipped for typed Explore jobs when auto-enhance is off). + """ + return lambda prompt: apply_recipe_prompt_template(recipe, prompt) + + +def require_catalog_runnable( + item: LoraCatalogItem, + *, + models_dir: Path, + hf_authenticated: bool, + hf_code: str, + model_code: str, + local_model_id: LTXLocalModelId | None = None, +) -> None: + """The catalog gates shared by a style LoRA and a Home IC-LoRA. + + A missing Hugging Face login or an unsupported installed family fails before enqueue. + When ``local_model_id`` is set, the job's own family must be one this entry supports. + The caller still checks that the weights file itself is on disk. + """ + if item.requires_hf_login and not hf_authenticated: + raise RecipeCreateError("HuggingFace sign-in required", code=hf_code) + if not catalog_item_visible_for_installed_ltx(item.supported_models, models_dir): + raise RecipeCreateError( + f"'{item.id}' is not available with the installed LTX models", + code=model_code, + ) + if local_model_id is not None and not item.supports_family( + ltx_catalog_family_for_model(local_model_id) + ): + raise RecipeCreateError( + f"'{item.id}' does not support the selected LTX model", + code=model_code, + ) + + +class RecipeCreateError(Exception): + """A typed create-time miss for a LoRA recipe. + + Carries the wire ``code`` (``LORA_UNKNOWN``/``LORA_UNSUPPORTED_MODE``/…) so + the create route can map it to a 422 without the recipe-resolution logic + knowing about HTTP. + """ + + def __init__(self, message: str, *, code: str) -> None: + super().__init__(message) + self.code = code + + +def resolve_recipe_create( + recipe_id: str, + req: CreateLoraRecipeRequest, + *, + catalog: LoraCatalogProvider, + models_dir: Path, + device: str | None, + hf_authenticated: bool, +) -> tuple[str, TextToVideoParams | ImageToVideoRecipeParams, ImageToVideoInputs | None]: + """Validate a recipe create and hydrate its queued params. + + Returns ``(feature, params, inputs)`` — the Explore id to enqueue under, the + resolved params with the ``loras`` entry injected (empty ``ref`` until + execute), and ``inputs`` (a start frame for i2v recipes, else ``None``). + Every miss raises :class:`RecipeCreateError` *before* the caller enqueues + anything, so nothing is inserted and no GPU slot is taken on a bad request. + ``device`` is ``None`` when the caller has no runtime config to gate against + (the check is skipped, matching the plain t2v/i2v queued behavior on + unsupported hardware). + """ + recipe = get_lora_recipe(recipe_id) + if recipe is None: + raise RecipeCreateError(f"Unknown LoRA recipe: {recipe_id}", code="LORA_UNKNOWN") + if recipe.mode not in ("t2v", "i2v"): + raise RecipeCreateError( + f"LoRA recipe '{recipe_id}' mode '{recipe.mode}' is not supported yet", + code="LORA_UNSUPPORTED_MODE", + ) + if device is not None and device not in recipe.devices: + raise RecipeCreateError( + f"LoRA recipe '{recipe_id}' does not support device '{device}'", + code="LORA_UNSUPPORTED_DEVICE", + ) + + params = req.params + catalog_item = catalog.get_lora(recipe.catalog_id) + if catalog_item is None: + # A mapped recipe whose catalog id has no entry is a config error, but it is + # still "no adapter to resolve" from the client's side. + raise RecipeCreateError( + f"Catalog id '{recipe.catalog_id}' for recipe '{recipe_id}' not found", + code="LORA_UNKNOWN", + ) + if params.catalogId != recipe.catalog_id: + raise RecipeCreateError( + f"catalogId '{params.catalogId}' does not match recipe '{recipe_id}'", + code="LORA_UNKNOWN", + ) + require_catalog_runnable( + catalog_item, + models_dir=models_dir, + hf_authenticated=hf_authenticated, + hf_code="LORA_HF_AUTH_REQUIRED", + model_code="LORA_UNSUPPORTED_MODEL", + ) + + installed = downloaded_lora_variant_ids( + models_dir, + recipe.catalog_id, + [(variant.id, variant.filename) for variant in catalog_item.download.variants], + ) + variant = catalog_item.download.variant_for_run(params.variantId, installed) + if variant is None: + raise RecipeCreateError( + f"Unknown variant '{params.variantId}'", code="UNKNOWN_DOWNLOAD_VARIANT" + ) + if not is_lora_downloaded(models_dir, recipe.catalog_id, variant.filename): + raise RecipeCreateError( + f"LoRA '{recipe.catalog_id}' is not downloaded", code="LORA_NOT_DOWNLOADED" + ) + + loras = [ + LoraEntry( + ref="", + scale=params.scale, + catalogId=recipe.catalog_id, + displayName=catalog_item.name, + variantId=variant.id, + ) + ] + # Store catalogId + scale only; the weights path is resolved at execution by + # make_recipe_lora_resolver (no server path persisted, and a retry re-resolves). + if recipe.mode == "i2v": + if req.inputs is None: + raise RecipeCreateError("Start Frame is required.", code="INVALID_GENERATION_SPEC") + if recipe.requires_end_frame and req.inputs.endFrame is None: + raise RecipeCreateError("End Frame is required.", code="INVALID_GENERATION_SPEC") + if req.inputs.endFrame is not None and not recipe.requires_end_frame: + raise RecipeCreateError( + f"LoRA recipe '{recipe_id}' does not take an end frame", + code="INVALID_GENERATION_SPEC", + ) + i2v_params = ImageToVideoRecipeParams( + prompt=params.prompt, + resolution=params.resolution, + model=params.model, + cameraMotion=params.cameraMotion, + negativePrompt=params.negativePrompt, + duration=params.duration, + fps=params.fps, + seed=params.seed, + aspectRatio=params.aspectRatio, + promptProvenance=params.promptProvenance, + loras=loras, + ) + return ( + recipe.recipe_id, + i2v_params, + ImageToVideoInputs( + startFrame=req.inputs.startFrame, + endFrame=req.inputs.endFrame, + ), + ) + + if req.inputs is not None: + raise RecipeCreateError( + f"LoRA recipe '{recipe_id}' does not take a start frame", + code="INVALID_GENERATION_SPEC", + ) + if params.aspectRatio == "auto": + raise RecipeCreateError( + f"LoRA recipe '{recipe_id}' does not support aspectRatio 'auto'", + code="INVALID_GENERATION_SPEC", + ) + tt_params = TextToVideoParams( + prompt=params.prompt, + resolution=params.resolution, + model=params.model, + cameraMotion=params.cameraMotion, + negativePrompt=params.negativePrompt, + duration=params.duration, + fps=params.fps, + seed=params.seed, + aspectRatio=params.aspectRatio, + promptProvenance=params.promptProvenance, + loras=loras, + ) + return recipe.recipe_id, tt_params, None + + +def make_recipe_lora_resolver( + recipe: LoraRecipe, + *, + catalog: LoraCatalogProvider, + models_dir: Callable[[], Path], +) -> Callable[[list[LoraEntry]], list[LoraEntry]]: + """Hydrate a recipe LoRA's ``ref`` from its catalog id at execution time. + + The stored spec carries only ``catalogId`` + ``scale`` (empty ``ref``); this resolver + fills the absolute weights path against the *current* models dir just before the job + runs, re-checking that the LoRA is still downloaded. It runs inside the recipe's + executor, so a retry re-resolves rather than replaying a path captured at create time. + Entries whose ``catalogId`` isn't this recipe's are passed through untouched. + + Raises :class:`HTTPError` (mapped to a capability failure by the executor) when the + catalog entry vanished or the weights are no longer on disk. + """ + + def resolve(loras: list[LoraEntry]) -> list[LoraEntry]: + resolved: list[LoraEntry] = [] + for entry in loras: + if entry.catalogId != recipe.catalog_id: + resolved.append(entry) + continue + item = catalog.get_lora(recipe.catalog_id) + if item is None: + raise HTTPError( + 409, f"Catalog id '{recipe.catalog_id}' not found", code="LORA_UNKNOWN" + ) + variant = ( + item.download.resolve_variant(entry.variantId) + if entry.variantId is not None + else item.download.legacy_variant() + ) + if variant is None: + raise HTTPError( + 404, + "UNKNOWN_DOWNLOAD_VARIANT", + code="UNKNOWN_DOWNLOAD_VARIANT", + ) + base = models_dir() + if not is_lora_downloaded(base, recipe.catalog_id, variant.filename): + raise HTTPError( + 409, + f"LoRA '{recipe.catalog_id}' is not downloaded", + code="LORA_NOT_DOWNLOADED", + ) + ref = str(resolve_lora_path(base, recipe.catalog_id, variant.filename)) + resolved.append(entry.model_copy(update={"ref": ref})) + return resolved + + return resolve diff --git a/backend/services/features/queued_features.py b/backend/services/features/queued_features.py new file mode 100644 index 000000000..399041812 --- /dev/null +++ b/backend/services/features/queued_features.py @@ -0,0 +1,29 @@ +"""Feature ids stored on Explore generations. + +Desktop and remote Recently used both query this set, so the two apps show +the same features. +""" + +from __future__ import annotations + +from services.features.ic_lora_recipes import queued_ic_lora_recipes +from services.features.lora_recipes import queued_lora_recipes +from services.features.video import ( + AUDIO_TO_VIDEO_FEATURE, + EXTEND_FEATURE, + FEATURE as TEXT_TO_VIDEO_FEATURE, + IMAGE_TO_VIDEO_FEATURE, + RETAKE_FEATURE, +) + +QUEUED_GENERATION_FEATURES: frozenset[str] = frozenset( + { + TEXT_TO_VIDEO_FEATURE, + IMAGE_TO_VIDEO_FEATURE, + AUDIO_TO_VIDEO_FEATURE, + RETAKE_FEATURE, + EXTEND_FEATURE, + } + | {recipe.recipe_id for recipe in queued_lora_recipes()} + | {recipe.recipe_id for recipe in queued_ic_lora_recipes()} +) diff --git a/backend/services/features/video/__init__.py b/backend/services/features/video/__init__.py new file mode 100644 index 000000000..495d0bd0c --- /dev/null +++ b/backend/services/features/video/__init__.py @@ -0,0 +1,47 @@ +from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor +from services.features.video.audio_to_video import ( + FEATURE as AUDIO_TO_VIDEO_FEATURE, + AudioToVideoExecutor, +) +from services.features.video.image_to_video import ( + AssetResolver, + FEATURE as IMAGE_TO_VIDEO_FEATURE, + ImageToVideoExecutor, + RebindableAssetResolver, +) +from services.features.video.extend import ( + FEATURE as EXTEND_FEATURE, + ExtendExecutor, +) +from services.features.video.retake import ( + FEATURE as RETAKE_FEATURE, + RetakeExecutor, +) +from services.features.video.text_to_video import ( + FEATURE, + ReservedVideoGenerator, + TextToVideoExecutor, + VIDEO_OUTPUT_PLAN, + require_video_output, + require_supported_contract_version, +) + +__all__ = [ + "AUDIO_TO_VIDEO_FEATURE", + "IcLoraRecipeExecutor", + "AssetResolver", + "AudioToVideoExecutor", + "EXTEND_FEATURE", + "ExtendExecutor", + "FEATURE", + "IMAGE_TO_VIDEO_FEATURE", + "ImageToVideoExecutor", + "RETAKE_FEATURE", + "RebindableAssetResolver", + "ReservedVideoGenerator", + "RetakeExecutor", + "TextToVideoExecutor", + "VIDEO_OUTPUT_PLAN", + "require_video_output", + "require_supported_contract_version", +] diff --git a/backend/services/features/video/alpha_cutout.py b/backend/services/features/video/alpha_cutout.py new file mode 100644 index 000000000..e52895eda --- /dev/null +++ b/backend/services/features/video/alpha_cutout.py @@ -0,0 +1,219 @@ +"""AlphaGen cutout. Merge the source video and the generated matte into a WebM and a GIF with alpha. + +The model writes a grayscale matte (white is the subject). The cutout is the source +video with that matte as its alpha channel. VP9 alpha plays in Chromium, so the player +shows the cutout over any CSS background and the file is the download. The GIF is the +same cutout for apps that do not read a WebM. It has one bit of alpha, so its edges are +harder than the WebM edges. +""" + +from __future__ import annotations + +import logging +import subprocess +from pathlib import Path +from typing import NamedTuple + +from services.ffmpeg import ( + FFMPEG_PROTOCOL_WHITELIST, + FfmpegCancelledError, + run_ffmpeg, + timeout_for_source_duration, +) +from services.generation_interrupt import GenerationCancelledError, is_requested +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.media_probe import probe_file, video_fps, video_frame_count +from services.records import MediaError + +logger = logging.getLogger(__name__) + +CUTOUT_OUTPUT_PLAN = OutputPlan( + slot="output", + media_kind="video", + mime_type="video/webm", + name="output.webm", +) +MATTE_OUTPUT_PLAN = OutputPlan( + slot="matte", + media_kind="video", + mime_type="video/mp4", + name="matte.mp4", +) +GIF_OUTPUT_PLAN = OutputPlan( + slot="gif", + media_kind="image", + mime_type="image/gif", + name="output.gif", + # The WebM and the matte are the result. A run without the GIF still succeeds. + optional=True, +) +# The order is stored. The UI reads the WebM first, the matte second and the GIF third. +CUTOUT_OUTPUT_PLANS = (CUTOUT_OUTPUT_PLAN, MATTE_OUTPUT_PLAN, GIF_OUTPUT_PLAN) + +# The GIF fits in a box of this size. A smaller clip keeps its size. +GIF_MAX_EDGE = 720 + + +def require_cutout_outputs( + outputs: tuple[OutputAllocation, ...], +) -> tuple[OutputAllocation, OutputAllocation, OutputAllocation]: + """The cutout the user sees, the raw matte the model writes, then the GIF.""" + if tuple(output.plan.slot for output in outputs) != tuple( + plan.slot for plan in CUTOUT_OUTPUT_PLANS + ): + raise ValueError("a cutout recipe requires 'output', 'matte' and 'gif' allocations") + return outputs[0], outputs[1], outputs[2] + + +class _MatteGeometry(NamedTuple): + width: int + height: int + fps: float + frames: int + timeout: float + + +def _matte_geometry(matte: Path) -> _MatteGeometry: + _kind, _mime, probed = probe_file(matte) + if probed.mediaType != "video": + raise MediaError("UNREADABLE_MEDIA", "the matte is not a video") + return _MatteGeometry( + width=probed.metadata.width, + height=probed.metadata.height, + fps=video_fps(matte), + frames=video_frame_count(matte), + timeout=timeout_for_source_duration(probed.metadata.durationMs / 1000), + ) + + +def _alpha_merge_filters(geometry: _MatteGeometry) -> list[str]: + """The source with the matte as its alpha, as the straight RGBA stream ``[rgba]``.""" + return [ + f"[0:v]scale={geometry.width}:{geometry.height}:flags=lanczos,fps={geometry.fps:g}," + "setpts=PTS-STARTPTS,format=rgba[rgb]", + # format=gray already maps the matte's limited range (Y 16..235) to full range. A + # second expansion would crush soft alpha such as hair and glass edges. + "[1:v]format=gray,setpts=PTS-STARTPTS[alpha]", + # shortest=1 ends one frame early on two streams of the same length. The matte is + # already cut to the clip, so the output is capped at the matte length instead + # (`-frames:v` in `_run_bake`). + "[rgb][alpha]alphamerge[rgba]", + ] + + +def _run_bake( + source: Path, + matte: Path, + filters: list[str], + output_args: list[str], + geometry: _MatteGeometry, + failure: str, +) -> None: + args = [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(source), + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(matte), + "-filter_complex", + ";".join(filters), + "-frames:v", + str(geometry.frames), + *output_args, + ] + try: + run_ffmpeg( + args, + timeout=geometry.timeout, + # A cancel during the encode stops ffmpeg instead of waiting for it. + should_cancel=is_requested, + ) + except FfmpegCancelledError: + raise GenerationCancelledError() from None + except subprocess.CalledProcessError as exc: + # A bake miss must not read as a crop failure at the caller. + raise MediaError("UNREADABLE_MEDIA", failure) from exc + + +def bake_alpha_cutout(source: Path, matte: Path, dest: Path) -> None: + """Write ``dest`` (WebM, VP9 ``yuva420p``). The size and rate follow the matte. + + The source is scaled to the matte, which the model sized inside the 540p envelope. + Audio comes from the matte file, where the model already placed the chosen audio. + """ + geometry = _matte_geometry(matte) + _run_bake( + source, + matte, + _alpha_merge_filters(geometry), + [ + "-map", + "[rgba]", + "-map", + "1:a?", + "-c:v", + "libvpx-vp9", + "-pix_fmt", + "yuva420p", + "-auto-alt-ref", + "0", + "-b:v", + "0", + "-crf", + "18", + "-deadline", + "good", + "-cpu-used", + "4", + "-row-mt", + "1", + "-c:a", + "libopus", + "-b:a", + "128k", + str(dest), + ], + geometry, + "alpha cutout failed", + ) + + +def bake_alpha_gif(source: Path, matte: Path, dest: Path) -> None: + """Write ``dest`` (GIF, looping, no audio) of the same cutout as the WebM. + + One palette is built from the whole clip, with a slot kept for transparency. A GIF + pixel is clear or solid, so alpha under 128 becomes clear. The clip is not scaled up. + """ + geometry = _matte_geometry(matte) + _run_bake( + source, + matte, + [ + *_alpha_merge_filters(geometry), + f"[rgba]scale='min({GIF_MAX_EDGE},iw)':'min({GIF_MAX_EDGE},ih)'" + ":force_original_aspect_ratio=decrease:flags=lanczos,split[frames][palette_in]", + "[palette_in]palettegen=reserve_transparent=1[palette]", + "[frames][palette]paletteuse=alpha_threshold=128[gif]", + ], + ["-map", "[gif]", "-an", "-c:v", "gif", "-loop", "0", str(dest)], + geometry, + "alpha gif failed", + ) + # A GIF that ffmpeg wrote but nothing can read must not reach the store. + probe_file(dest) + + +def bake_alpha_gif_if_possible(source: Path, matte: Path, dest: Path) -> None: + """Write the GIF, or leave no file. The run keeps the WebM and the matte. + + A cancel still stops the run. Only a media failure of the GIF itself is skipped. + """ + try: + bake_alpha_gif(source, matte, dest) + except MediaError: + logger.warning("alpha gif skipped for %s", dest.name, exc_info=True) + dest.unlink(missing_ok=True) diff --git a/backend/services/features/video/audio_to_video.py b/backend/services/features/video/audio_to_video.py new file mode 100644 index 000000000..9a2a72be1 --- /dev/null +++ b/backend/services/features/video/audio_to_video.py @@ -0,0 +1,156 @@ +from __future__ import annotations + +from collections.abc import Mapping +from pathlib import Path + +from api_types import ( + AudioToVideoInputs, + AudioToVideoParams, + GenerateVideoCancelledResponse, + GenerateVideoRequest, +) +from _routes._errors import HTTPError +from services.features.video.image_to_video import ( + AssetResolver, + find_closest_aspect_ratio_option, +) +from services.features.video.job_common import ( + capability_failed_from_http, + model_from_spec, + require_existing_asset, + resolve_job_local_model_id, +) +from services.features.video.text_to_video import ( + ReservedVideoGenerator, + VIDEO_OUTPUT_PLAN, + offering_payload_from_params, + require_supported_contract_version, + require_video_output, +) +from runtime_config.model_download_specs import local_aspect_ratios +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.records import AssetRecord, GenerationRecord + +FEATURE = "audio-to-video" +# A2V always has audio and optionally a start image, and a path-leaking pipeline +# error does not say which one it choked on, so this stays slot-neutral. +_INPUT_ASSET_UNAVAILABLE = "input media is no longer available" + +class AudioToVideoExecutor: + def __init__( + self, + video_generation: ReservedVideoGenerator, + assets: AssetResolver, + ) -> None: + self._video_generation = video_generation + self._assets = assets + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + _params_from_spec(spec) + _inputs_from_spec(spec) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + return (VIDEO_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + params = _params_from_spec(generation.spec) + inputs = _inputs_from_spec(generation.spec) + audio = self._resolve_audio(inputs.audio.assetId) + start = ( + None + if inputs.startFrame is None + else self._resolve_image(inputs.startFrame.assetId, slot="startFrame") + ) + payload, offering = offering_payload_from_params(params) + payload.pop("numFrames", None) + payload["audioPath"] = audio.path + payload["audio"] = True + if start is not None: + payload["imagePath"] = start.path + payload["aspectRatio"] = _resolve_aspect_ratio(params, start) + elif params.aspectRatio == "auto": + payload["aspectRatio"] = "16:9" + req = GenerateVideoRequest.model_validate(payload) + output = require_video_output(outputs) + try: + self._video_generation.validate_local_a2v_request( + params, audio_duration_ms=_audio_duration_ms(audio) + ) + result = self._video_generation.generate_local_reserved( + req, + generation_id=generation.id, + output_path=Path(output.dest_path), + a2v_num_frames=params.numFrames, + a2v_audio_duration_seconds=_audio_duration_ms(audio) / 1000, + local_model_id=resolve_job_local_model_id( + self._video_generation.models_dir, offering + ), + ) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, HTTPError): + raise capability_failed_from_http( + exc, unavailable=_INPUT_ASSET_UNAVAILABLE + ) from exc + raise + if isinstance(result, GenerateVideoCancelledResponse): + raise GenerationCancelledError() + + def _resolve_audio(self, asset_id: str) -> AssetRecord: + return require_existing_asset( + self._assets, + asset_id, + media_kind="audio", + unavailable="audio is no longer available", + ) + + def _resolve_image(self, asset_id: str, *, slot: str) -> AssetRecord: + return require_existing_asset( + self._assets, + asset_id, + media_kind="image", + unavailable=f"{slot} image is no longer available", + ) + + +def _audio_duration_ms(asset: AssetRecord) -> int: + metadata = asset.metadata + if metadata.mediaType != "audio": + raise ValueError("audio asset has non-audio metadata") + return metadata.metadata.durationMs + + +def _resolve_aspect_ratio(params: AudioToVideoParams, start: AssetRecord) -> str: + if params.aspectRatio != "auto": + return params.aspectRatio + metadata = start.metadata + if metadata.mediaType != "image": + raise ValueError("startFrame must have image metadata") + return find_closest_aspect_ratio_option( + metadata.metadata.width, + metadata.metadata.height, + local_aspect_ratios(params.resolution, is_a2v=True), + ) + + +def _params_from_spec(spec: Mapping[str, object]) -> AudioToVideoParams: + return model_from_spec(spec, "params", AudioToVideoParams) + + +def _inputs_from_spec(spec: Mapping[str, object]) -> AudioToVideoInputs: + return model_from_spec(spec, "inputs", AudioToVideoInputs) diff --git a/backend/services/features/video/cutout_alignment.py b/backend/services/features/video/cutout_alignment.py new file mode 100644 index 000000000..20e5e599a --- /dev/null +++ b/backend/services/features/video/cutout_alignment.py @@ -0,0 +1,179 @@ +"""Alignment for a cutout recipe. The matte must line up with the clip in time and in space. + +Time: the pipeline snaps a frame count DOWN to 8k+1, so a 150 frame clip would lose 5 frames. +The model reads the clip with its last frame repeated, which lifts the snap UP to the grid. + +Space: the pipeline fills the stage canvas with a center crop of the guide clip. A clip whose +shape differs from the canvas (the canvas sits on a 64 px grid) would show the model a smaller +view than the bake sees, and the matte would drift from the subject. So the clip is fitted +INTO the canvas with its edge pixels smeared into the border. The pipeline then only scales it. + +After the run, the matte is cut back to the clip: the border off, the extra frames off. +""" + +from __future__ import annotations + +import os +import subprocess +from dataclasses import dataclass +from pathlib import Path + +from services.ffmpeg import ( + FFMPEG_PROTOCOL_WHITELIST, + FfmpegCancelledError, + ffmpeg_seconds, + run_ffmpeg, +) +from services.generation_interrupt import GenerationCancelledError, is_requested +from services.media_probe import video_frame_count +from services.records import MediaError + +# One frame grid step is 8 frames. Seven repeats lift any clip length to the next 8k+1, +# and the snap down drops the rest. A clip already on the grid keeps its length. +GRID_PAD_FRAMES = 7 +# The matte is stored again when the border is cut off. Near lossless keeps soft alpha edges. +_MATTE_CRF = "10" + + +def _even(value: int) -> int: + """yuv420p needs even sides and even offsets.""" + return value - value % 2 + + +@dataclass(frozen=True, slots=True) +class CanvasFit: + """Where the clip sits inside the stage canvas the model runs at.""" + + canvas_width: int + canvas_height: int + width: int + height: int + x: int + y: int + + @property + def fills_canvas(self) -> bool: + return self.width == self.canvas_width and self.height == self.canvas_height + + +def fit_clip_to_canvas( + clip_width: int, clip_height: int, canvas_width: int, canvas_height: int +) -> CanvasFit: + """The largest copy of the clip that fits the canvas, centered. The clip shape is kept.""" + scale = min(canvas_width / clip_width, canvas_height / clip_height) + width = min(canvas_width, max(2, _even(round(clip_width * scale)))) + height = min(canvas_height, max(2, _even(round(clip_height * scale)))) + return CanvasFit( + canvas_width=canvas_width, + canvas_height=canvas_height, + width=width, + height=height, + x=_even((canvas_width - width) // 2), + y=_even((canvas_height - height) // 2), + ) + + +def _fit_filter(fit: CanvasFit) -> str: + scale = f"scale={fit.width}:{fit.height}:flags=lanczos" + if fit.fills_canvas: + return scale + right = fit.canvas_width - fit.x - fit.width + bottom = fit.canvas_height - fit.y - fit.height + return ( + f"{scale},pad={fit.canvas_width}:{fit.canvas_height}:{fit.x}:{fit.y}," + f"fillborders=left={fit.x}:right={right}:top={fit.y}:bottom={bottom}:mode=smear" + ) + + +def _run(args: list[str], failure: str) -> None: + try: + run_ffmpeg(args, should_cancel=is_requested) + except FfmpegCancelledError: + raise GenerationCancelledError() from None + except subprocess.CalledProcessError as exc: + raise MediaError("UNREADABLE_MEDIA", failure) from exc + + +def prepare_clip_for_model( + source: Path, dest: Path, *, fit: CanvasFit, keep_audio: bool +) -> Path: + """Write ``dest``: the clip fitted into the canvas, with its last frame repeated. + + The guide stays lossless (``-qp 0``), so the model reads the same pixels the fit made. + """ + args = [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(source), + "-map", + "0:v:0", + "-vf", + f"{_fit_filter(fit)},tpad=stop_mode=clone:stop={GRID_PAD_FRAMES}", + "-c:v", + "libx264", + "-qp", + "0", + "-preset", + "veryfast", + "-pix_fmt", + "yuv420p", + ] + if keep_audio: + args += ["-map", "0:a?", "-c:a", "aac"] + else: + args += ["-an"] + args += ["-protocol_whitelist", FFMPEG_PROTOCOL_WHITELIST, str(dest)] + _run(args, "clip preparation failed") + return dest + + +def conform_matte_to_clip(matte: Path, *, frames: int, fps: float, fit: CanvasFit) -> None: + """Rewrite the matte in place: ``frames`` frames, with the canvas border cut off. + + The video is cut by frame count. A time cut keeps extra frames, because a B-frame + stream starts its timestamps late. The time limit only ends a source audio track. + A cut encodes the video again. A stream copy cuts in decode order, and with + B-frames that can leave a frame past the cut. + """ + if fit.fills_canvas and video_frame_count(matte) == frames: + # No border and no extra frame: nothing to cut, so keep the model file as it is. + return + conformed = matte.with_name(f"{matte.stem}-conform{matte.suffix}") + video = [ + # A clip that fills the canvas has no border to cut. + *([] if fit.fills_canvas else ["-vf", f"crop={fit.width}:{fit.height}:{fit.x}:{fit.y}"]), + "-c:v", + "libx264", + "-crf", + _MATTE_CRF, + "-preset", + "veryfast", + "-pix_fmt", + "yuv420p", + ] + args = [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(matte), + "-map", + "0", + *video, + "-c:a", + "copy", + "-frames:v", + str(frames), + "-t", + ffmpeg_seconds(frames / fps), + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + str(conformed), + ] + try: + _run(args, "matte alignment failed") + os.replace(conformed, matte) + finally: + conformed.unlink(missing_ok=True) diff --git a/backend/services/features/video/edit_executor.py b/backend/services/features/video/edit_executor.py new file mode 100644 index 000000000..7f9bcee22 --- /dev/null +++ b/backend/services/features/video/edit_executor.py @@ -0,0 +1,237 @@ +"""Template-method base for queued Home/Remote Retake and Extend.""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import ClassVar, Generic, Protocol, TypeVar + +from api_types import LTXLocalModelId, OfferingId +from _routes._errors import HTTPError +from runtime_config.ltx_capabilities import LtxCapabilityFeature +from server_utils.heartbeat import log_heartbeat +from services.features.video.job_common import ( + AssetLookup, + capability_failed_from_http, + require_capable_local_model, + require_existing_asset, + resolve_generation_seed, +) +from services.features.video.text_to_video import ( + VIDEO_OUTPUT_PLAN, + require_supported_contract_version, + require_video_output, +) +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.records import ( + AssetRecord, + CapabilityFailedError, + GenerationRecord, + MediaError, +) +from state.app_state_types import RetakePipelineState + + +class GpuJobSlot(Protocol): + def start_generation(self, generation_id: str) -> None: ... + + def complete_generation(self, result: str | list[str] | None = None) -> None: ... + + def fail_generation(self, error: str) -> None: ... + + +class RetakePipelineLoader(Protocol): + def load_retake_pipeline( + self, + *, + distilled: bool = True, + ltx_model_id: LTXLocalModelId | None = None, + width: int | None = None, + height: int | None = None, + frames: int | None = None, + queued_home: bool = False, + ) -> RetakePipelineState: ... + + def edit_encode_frame_cap(self, width: int, height: int) -> int: ... + + +class TextEncodingPrep(Protocol): + def prepare_text_encoding( + self, + prompt: str, + enhance_prompt: bool, + model_id: LTXLocalModelId | None = None, + ) -> None: ... + + def clear_api_embeddings(self) -> None: ... + + +class VideoEditParams(Protocol): + model: OfferingId + seed: int | None + prompt: str + + +class _VideoRef(Protocol): + # Pydantic model fields are descriptors; a Protocol attribute does not match. + @property + def assetId(self) -> str: ... + + +class VideoEditInputs(Protocol): + @property + def video(self) -> _VideoRef: ... + + +PParams = TypeVar("PParams", bound=VideoEditParams) +PInputs = TypeVar("PInputs", bound=VideoEditInputs) +PPrepared = TypeVar("PPrepared") + + +class VideoEditExecutor(ABC, Generic[PParams, PInputs, PPrepared]): + capability: ClassVar[LtxCapabilityFeature] + unsupported_code: ClassVar[str] + unsupported_message: ClassVar[str] + heartbeat_label: ClassVar[str] + + def __init__( + self, + pipelines: RetakePipelineLoader, + assets: AssetLookup, + text: TextEncodingPrep, + models_dir: Callable[[], Path], + default_negative_prompt: str, + generation: GpuJobSlot, + ) -> None: + self._pipelines = pipelines + self._assets = assets + self._text = text + self._models_dir = models_dir + self._default_negative_prompt = default_negative_prompt + self._generation = generation + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + self.parse_params(spec) + self.parse_inputs(spec) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + return (VIDEO_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + params = self.parse_params(generation.spec) + inputs = self.parse_inputs(generation.spec) + video = require_existing_asset( + self._assets, + inputs.video.assetId, + media_kind="video", + unavailable="video is no longer available", + ) + try: + local_model_id = require_capable_local_model( + self._models_dir(), + params.model, + self.capability, + unsupported_code=self.unsupported_code, + unsupported_message=self.unsupported_message, + ) + except HTTPError as exc: + raise capability_failed_from_http(exc) from exc + output = require_video_output(outputs) + seed = resolve_generation_seed(params.seed) + try: + self._text.prepare_text_encoding( + params.prompt, enhance_prompt=False, model_id=local_model_id + ) + except HTTPError as exc: + raise capability_failed_from_http(exc) from exc + except RuntimeError as exc: + raise CapabilityFailedError(str(exc)) from exc + dest = Path(output.dest_path) + windowed_path = str(dest.with_name(f"{dest.stem}.window{dest.suffix}")) + try: + prepared = self.prepare( + generation, + params, + video, + local_model_id, + seed, + dest, + windowed_path, + ) + + def _infer() -> None: + try: + with log_heartbeat(self.heartbeat_label): + self.generate(prepared) + self.stitch(prepared) + finally: + Path(windowed_path).unlink(missing_ok=True) + + run_gpu_job(self._generation, generation.id, str(dest), _infer) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, HTTPError): + raise capability_failed_from_http(exc) from exc + if isinstance(exc, CapabilityFailedError): + raise + if isinstance(exc, MediaError): + raise CapabilityFailedError(str(exc)) from exc + raise + finally: + self._text.clear_api_embeddings() + + @abstractmethod + def parse_params(self, spec: Mapping[str, object]) -> PParams: ... + + @abstractmethod + def parse_inputs(self, spec: Mapping[str, object]) -> PInputs: ... + + @abstractmethod + def prepare( + self, + generation: GenerationRecord, + params: PParams, + video: AssetRecord, + local_model_id: LTXLocalModelId, + seed: int, + dest: Path, + windowed_path: str, + ) -> PPrepared: ... + + @abstractmethod + def generate(self, prepared: PPrepared) -> None: ... + + @abstractmethod + def stitch(self, prepared: PPrepared) -> None: ... + + +def run_gpu_job( + slot: GpuJobSlot, + generation_id: str, + result_path: str, + run: Callable[[], None], +) -> None: + slot.start_generation(generation_id) + try: + run() + except Exception as exc: + if not is_cancel_exception(exc): + slot.fail_generation(str(exc)) + raise + slot.complete_generation(result_path) diff --git a/backend/services/features/video/extend.py b/backend/services/features/video/extend.py new file mode 100644 index 000000000..ee51fb0b7 --- /dev/null +++ b/backend/services/features/video/extend.py @@ -0,0 +1,191 @@ +from __future__ import annotations + +import logging +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path + +from api_types import ExtendInputs, ExtendParams, LTXLocalModelId +from handlers.video_resolution import ( + correct_frame_count, + generation_letterbox, + read_source_metadata, + resolve_home_edit_size, +) +from runtime_config.video_job_budget import ( + VIDEO_JOB_TOO_LARGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, +) +from services.features.video.edit_executor import VideoEditExecutor +from services.features.video.job_common import model_from_spec +from services.records import AssetRecord, CapabilityFailedError, GenerationRecord +from services.retake_pipeline.window import ( + MAX_INPUT_FRAMES, + ExtendEncodeWindow, + duration_to_extend_frames, + window_for_extend, +) +from services.retake_pipeline.extend_stitch import stitch_extend_output +from state.app_state_types import RetakePipelineState + +FEATURE = "extend" +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class _PreparedExtend: + params: ExtendParams + video: AssetRecord + pipeline_state: RetakePipelineState + seed: int + fps: float + content_width: int + content_height: int + canvas_width: int + canvas_height: int + window: ExtendEncodeWindow + extend_frames: int + dest_path: Path + windowed_path: str + + +class ExtendExecutor(VideoEditExecutor[ExtendParams, ExtendInputs, _PreparedExtend]): + """Queued Home/Remote extend. Same zero-pad as GenSpace ``POST /api/extend``.""" + + capability = "extend" + unsupported_code = "UNSUPPORTED_EXTEND" + unsupported_message = "Extend is not supported for the selected LTX model." + heartbeat_label = "extend inference" + + def parse_params(self, spec: Mapping[str, object]) -> ExtendParams: + return model_from_spec(spec, "params", ExtendParams) + + def parse_inputs(self, spec: Mapping[str, object]) -> ExtendInputs: + return model_from_spec(spec, "inputs", ExtendInputs) + + def prepare( + self, + generation: GenerationRecord, + params: ExtendParams, + video: AssetRecord, + local_model_id: LTXLocalModelId, + seed: int, + dest: Path, + windowed_path: str, + ) -> _PreparedExtend: + fps, source_width, source_height, source_frames = read_source_metadata( + video.path + ) + # Min-length only. Window/stitch math uses the raw count so leftover + # frames after the 8k+1 snap stay in the original half of the concat. + correct_frame_count(source_frames) + extend_frames = duration_to_extend_frames(params.duration, fps) + requested = params.resolution + content_width, content_height = resolve_home_edit_size( + None if requested is None else requested.width, + None if requested is None else requested.height, + source_width, + source_height, + ) + box = generation_letterbox(content_width, content_height) + # A long 1080p source fills the 505-frame window and 422s on 31 GB. + # Use the longest window that still loads. A new section that is + # already longer than that cannot be saved by more context. + frame_cap = self._pipelines.edit_encode_frame_cap(box.canvas_width, box.canvas_height) + if frame_cap < MAX_INPUT_FRAMES and extend_frames >= frame_cap: + raise CapabilityFailedError( + VIDEO_JOB_TOO_LARGE_MESSAGE, code=VIDEO_JOB_TOO_LARGE + ) + try: + window = window_for_extend( + source_frames=source_frames, + extend_frames=extend_frames, + mode=params.mode, + max_input_frames=frame_cap, + ) + except ValueError as exc: + raise CapabilityFailedError(str(exc), code="INVALID_GENERATION_SPEC") from exc + if ( + abs(content_width - source_width) > 31 + or abs(content_height - source_height) > 31 + ): + logger.info( + "Downscaling source video from %dx%d to %dx%d; queued extend supports up to 1080p", + source_width, + source_height, + content_width, + content_height, + ) + logger.info( + "Extend %s started (%s, source %dx%d → %dx%d canvas %dx%d, %d source frames @ %g fps, %s +%d, encode %d, seed=%d)", + generation.id, + local_model_id, + source_width, + source_height, + content_width, + content_height, + box.canvas_width, + box.canvas_height, + source_frames, + fps, + params.mode, + extend_frames, + window.context_frames, + seed, + ) + return _PreparedExtend( + params=params, + video=video, + pipeline_state=self._pipelines.load_retake_pipeline( + distilled=True, + ltx_model_id=local_model_id, + width=box.canvas_width, + height=box.canvas_height, + frames=window.context_frames + extend_frames, + queued_home=True, + ), + seed=seed, + fps=fps, + content_width=content_width, + content_height=content_height, + canvas_width=box.canvas_width, + canvas_height=box.canvas_height, + window=window, + extend_frames=extend_frames, + dest_path=dest, + windowed_path=windowed_path, + ) + + def generate(self, prepared: _PreparedExtend) -> None: + prepared.pipeline_state.pipeline.extend( + video_path=prepared.video.path, + prompt=prepared.params.prompt, + extend_frames=prepared.extend_frames, + mode=prepared.params.mode, + seed=prepared.seed, + output_path=prepared.windowed_path, + negative_prompt=self._default_negative_prompt, + regenerate_audio=True, + enhance_prompt=False, + distilled=True, + target_width=prepared.canvas_width, + target_height=prepared.canvas_height, + content_width=prepared.content_width, + content_height=prepared.content_height, + target_frames=prepared.window.context_frames, + encode_start_time=prepared.window.start_time(prepared.fps), + encode_max_duration=prepared.window.max_duration(prepared.fps), + ) + + def stitch(self, prepared: _PreparedExtend) -> None: + stitch_extend_output( + source_path=prepared.video.path, + windowed_path=prepared.windowed_path, + dest_path=str(prepared.dest_path), + window=prepared.window, + fps=prepared.fps, + mode=prepared.params.mode, + extend_frames=prepared.extend_frames, + target_width=prepared.content_width, + target_height=prepared.content_height, + ) diff --git a/backend/services/features/video/ic_lora_recipe.py b/backend/services/features/video/ic_lora_recipe.py new file mode 100644 index 000000000..6450c309d --- /dev/null +++ b/backend/services/features/video/ic_lora_recipe.py @@ -0,0 +1,352 @@ +"""Queued Home IC-LoRA recipe. Runs the catalog IC-LoRA path for one recipe row.""" + +from __future__ import annotations + +import subprocess +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Protocol, cast, get_args + +from pydantic import ValidationError + +from api_types import ( + IcLoraRecipeInputs, + IcLoraRecipeStoredParams, + IcLoraGenerateCancelledResponse, + IcLoraGenerateRequest, + IcLoraImageInput, + LTXLocalModelId, + LTXVideoGenAspectRatio, + TargetResolution, +) +from _routes._errors import HTTPError +from runtime_config.ic_lora_local_envelope import fit_ic_lora_stage1 +from runtime_config.ltx_capabilities import budget_pixels, local_caps +from services.media_probe import video_fps, video_frame_count +from services.features.video.alpha_cutout import ( + CUTOUT_OUTPUT_PLANS, + bake_alpha_cutout, + bake_alpha_gif_if_possible, + require_cutout_outputs, +) +from services.features.video.cutout_alignment import ( + conform_matte_to_clip, + fit_clip_to_canvas, + prepare_clip_for_model, +) +from services.features.video.image_to_video import ( + find_closest_aspect_ratio_option, + parse_aspect_ratio, +) +from services.features.video.job_common import ( + AssetLookup, + capability_failed_from_http, + model_from_spec, + require_existing_asset, + resolve_generation_seed, + resolve_job_local_model_id, +) +from services.features.video.text_to_video import ( + VIDEO_OUTPUT_PLAN, + require_supported_contract_version, + require_video_output, +) +from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.records import CapabilityFailedError, GenerationRecord, MediaError + +_ASPECT_MATCH_TOLERANCE = 0.01 + + +class ReservedIcLoraGenerator(Protocol): + def generate_local_reserved( + self, + req: IcLoraGenerateRequest, + *, + generation_id: str, + output_path: Path, + local_model_id: LTXLocalModelId, + seed: int, + explore_generation: bool = True, + explicit_generation_seed: bool = False, + ) -> object: ... + + +def center_crop_box( + width: int, height: int, aspect: str +) -> tuple[int, int, int, int] | None: + """Even crop to ``aspect``, or None when the source is already that ratio.""" + target = parse_aspect_ratio(aspect) + if target is None or height <= 0: + return None + current = width / height + if abs(current - target) / target < _ASPECT_MATCH_TOLERANCE: + return None + if current > target: + crop_w = int(height * target) + crop_w -= crop_w % 2 + crop_h = height - height % 2 + x = (width - crop_w) // 2 + y = 0 + else: + crop_h = int(width / target) + crop_h -= crop_h % 2 + crop_w = width - width % 2 + x = 0 + y = (height - crop_h) // 2 + x -= x % 2 + y -= y % 2 + if crop_w < 2 or crop_h < 2 or (crop_w == width and crop_h == height): + return None + return crop_w, crop_h, x, y + + +def ic_lora_video_filters( + box: tuple[int, int, int, int] | None, output_fps: float | None +) -> str | None: + """ffmpeg -vf chain. ``fps`` picks the nearest source frame, so the file the + catalog path reads is already at the selected rate.""" + filters: list[str] = [] + if output_fps is not None: + filters.append(f"fps={output_fps:g}") + if box is not None: + crop_w, crop_h, x, y = box + filters.append(f"crop={crop_w}:{crop_h}:{x}:{y}") + if not filters: + return None + return ",".join(filters) + + +def center_crop_video( + src: Path, + dest: Path, + width: int, + height: int, + aspect: str, + *, + keep_audio: bool, + output_fps: float | None = None, + crop: bool = True, +) -> Path: + box = center_crop_box(width, height, aspect) if crop else None + video_filter = ic_lora_video_filters(box, output_fps) + if video_filter is None: + return src + args = [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(src), + "-vf", + video_filter, + "-pix_fmt", + "yuv420p", + "-colorspace", + "bt709", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", + "-color_range", + "tv", + ] + # Re-encode. Stream-copy fails when the source audio (WebM Vorbis/Opus) cannot + # live in the mp4 crop. + args += ["-c:a", "aac"] if keep_audio else ["-an"] + args += ["-protocol_whitelist", FFMPEG_PROTOCOL_WHITELIST, str(dest)] + run_ffmpeg(args) + return dest + + +class IcLoraRecipeExecutor: + def __init__( + self, + ic_lora: ReservedIcLoraGenerator, + assets: AssetLookup, + models_dir: Callable[[], Path], + *, + catalog_id: str, + cutout: bool = False, + ) -> None: + self._ic_lora = ic_lora + self._assets = assets + self._models_dir = models_dir + self._catalog_id = catalog_id + self._cutout = cutout + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + try: + model_from_spec(spec, "params", IcLoraRecipeStoredParams) + model_from_spec(spec, "inputs", IcLoraRecipeInputs) + except (ValidationError, ValueError) as exc: + raise CapabilityFailedError( + str(exc), code="INVALID_GENERATION_SPEC" + ) from exc + + def _reference_image_path(self, inputs: IcLoraRecipeInputs) -> str | None: + if inputs.image is None: + return None + image = require_existing_asset( + self._assets, + inputs.image.assetId, + media_kind="image", + unavailable="reference image is no longer available", + ) + return image.path + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + return CUTOUT_OUTPUT_PLANS if self._cutout else (VIDEO_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + params = model_from_spec(generation.spec, "params", IcLoraRecipeStoredParams) + inputs = model_from_spec(generation.spec, "inputs", IcLoraRecipeInputs) + video = require_existing_asset( + self._assets, + inputs.video.assetId, + media_kind="video", + unavailable="video is no longer available", + ) + if video.metadata.mediaType != "video": + raise CapabilityFailedError( + "INVALID_VIDEO_ASSET", code="INVALID_GENERATION_SPEC" + ) + reference_image_path = self._reference_image_path(inputs) + meta = video.metadata.metadata + local_model_id = resolve_job_local_model_id(self._models_dir(), params.model) + seed = resolve_generation_seed(params.seed) + # A cutout recipe keeps the model matte as the second output and bakes the + # WebM with alpha and a GIF from it. Any other recipe writes its one output directly. + cutout_dest: Path | None = None + gif_dest: Path | None = None + if self._cutout: + cutout, matte, gif = require_cutout_outputs(outputs) + cutout_dest = Path(cutout.dest_path) + gif_dest = Path(gif.dest_path) + dest = Path(matte.dest_path) + else: + dest = Path(require_video_output(outputs).dest_path) + source = Path(video.path) + cropped: Path | None = None + padded: Path | None = None + try: + aspect = cast( + LTXVideoGenAspectRatio, + find_closest_aspect_ratio_option( + meta.width, + meta.height, + get_args(LTXVideoGenAspectRatio), + ), + ) + cropped = dest.with_name(f"{dest.stem}-crop.mp4") + source_fps = meta.fps if meta.fps is not None else video_fps(Path(video.path)) + # A selected rate at or above the source is a no-op. 23.976 labelled + # 24 must not be resampled up. + output_fps = params.fps if params.fps + 1e-3 < source_fps else None + source = center_crop_video( + Path(video.path), + cropped, + meta.width, + meta.height, + aspect, + keep_audio=params.audioMode == "source" and meta.audioStreamCount > 0, + output_fps=output_fps, + # A cutout keeps the whole frame. The clip is fitted into the canvas below. + crop=not self._cutout, + ) + # Inside the try so a resolution with no local cell becomes a capability + # failure, the same as image-to-video's pixel lookup. + width, height = budget_pixels( + local_caps(local_model_id), + params.resolution, + aspect, + mode="video", + ) + model_input = source + fit = None + if cutout_dest is not None: + # The model denoises one stage canvas, and the pipeline center-crops the clip + # to fill it. Fit the clip inside that canvas, so the matte covers the same view + # as `source`. Repeat the last frame, so the 8k+1 snap keeps every frame. + fit = fit_clip_to_canvas( + meta.width, meta.height, *fit_ic_lora_stage1(width, height) + ) + padded = dest.with_name(f"{dest.stem}-fit.mp4") + model_input = prepare_clip_for_model( + source, + padded, + fit=fit, + keep_audio=params.audioMode == "source" and meta.audioStreamCount > 0, + ) + request = IcLoraGenerateRequest( + ic_lora_id=self._catalog_id, + input_path=str(model_input), + prompt=params.prompt, + prompt_provenance=params.promptProvenance, + conditioning_type="custom", + resolution=TargetResolution(width=width, height=height), + audio_mode=params.audioMode, + lora_strength=params.loras[0].scale, + variant_id=params.loras[0].variantId, + # No request frame. The handler uses the catalog pin + # (-1 for the Layout look still). + images=( + [IcLoraImageInput(path=reference_image_path)] + if reference_image_path is not None + else [] + ), + ) + result = self._ic_lora.generate_local_reserved( + request, + generation_id=generation.id, + output_path=dest, + local_model_id=local_model_id, + seed=seed, + explicit_generation_seed=params.seed is not None, + ) + if isinstance(result, IcLoraGenerateCancelledResponse): + raise GenerationCancelledError() + if cutout_dest is not None and fit is not None and gif_dest is not None: + conform_matte_to_clip( + dest, frames=video_frame_count(source), fps=video_fps(dest), fit=fit + ) + # `source` is the clip the conformed matte is aligned with. Keep it until here. + bake_alpha_cutout(source, dest, cutout_dest) + bake_alpha_gif_if_possible(source, dest, gif_dest) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, KeyError): + raise CapabilityFailedError( + "INVALID_LOCAL_RESOLUTION", code="INVALID_LOCAL_RESOLUTION" + ) from exc + if isinstance(exc, HTTPError): + raise capability_failed_from_http(exc) from exc + if isinstance(exc, CapabilityFailedError): + raise + if isinstance(exc, MediaError): + raise CapabilityFailedError(str(exc)) from exc + if isinstance(exc, subprocess.CalledProcessError): + raise CapabilityFailedError("crop failed") from exc + raise + finally: + # Unlink the temp path itself. `source` is only reassigned after a + # successful crop, so a failed ffmpeg would otherwise leave the file. + if cropped is not None: + cropped.unlink(missing_ok=True) + if padded is not None: + padded.unlink(missing_ok=True) diff --git a/backend/services/features/video/image_to_video.py b/backend/services/features/video/image_to_video.py new file mode 100644 index 000000000..498d2cdb5 --- /dev/null +++ b/backend/services/features/video/image_to_video.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import Protocol + +from api_types import ( + GenerateVideoCancelledResponse, + GenerateVideoRequest, + ImageToVideoInputs, + ImageToVideoParams, + ImageToVideoRecipeParams, + LoraEntry, +) +from _routes._errors import HTTPError +from services.features.video.job_common import ( + capability_failed_from_http, + model_from_spec, + require_existing_asset, + resolve_job_local_model_id, +) +from services.features.video.text_to_video import ( + ReservedVideoGenerator, + VIDEO_OUTPUT_PLAN, + offering_payload_from_params, + require_video_output, + require_supported_contract_version, +) +from runtime_config.model_download_specs import local_aspect_ratios +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.records import AssetRecord, GenerationRecord + +FEATURE = "image-to-video" +_INPUT_ASSET_UNAVAILABLE = "image input is no longer available" + + +class AssetResolver(Protocol): + def get_asset(self, asset_id: str) -> AssetRecord | None: ... + + +class RebindableAssetResolver: + def __init__(self, assets: AssetResolver) -> None: + self._assets = assets + + def bind(self, assets: AssetResolver) -> None: + self._assets = assets + + def get_asset(self, asset_id: str) -> AssetRecord | None: + return self._assets.get_asset(asset_id) + + +class ImageToVideoExecutor: + def __init__( + self, + video_generation: ReservedVideoGenerator, + assets: AssetResolver, + prompt_wrap: Callable[[str], str] | None = None, + lora_resolver: Callable[[list[LoraEntry]], list[LoraEntry]] | None = None, + ) -> None: + self._video_generation = video_generation + self._assets = assets + # Recipe-scoped: post-enhancement prompt scaffold. None for plain i2v. + self._prompt_wrap = prompt_wrap + # Recipe-scoped: fills the LoRA ref from its catalog id at execution. None for plain i2v. + self._lora_resolver = lora_resolver + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + self._params_from_spec(spec) + _inputs_from_spec(spec) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + return (VIDEO_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.validate_params( + generation.spec, contract_version=generation.contract_version + ) + params = self._params_from_spec(generation.spec) + inputs = _inputs_from_spec(generation.spec) + start = self._resolve_image(inputs.startFrame.assetId, slot="startFrame") + end = ( + None + if inputs.endFrame is None + else self._resolve_image(inputs.endFrame.assetId, slot="endFrame") + ) + request_payload, offering = offering_payload_from_params(params) + request_payload["imagePath"] = start.path + if end is not None: + request_payload["lastImagePath"] = end.path + output = require_video_output(outputs) + try: + # Inside the try so a resolution with no local cell becomes a capability + # failure, the same as generate_local_reserved's pixel lookup. + request_payload["aspectRatio"] = _resolve_aspect_ratio(params, start) + req = GenerateVideoRequest.model_validate(request_payload) + if self._lora_resolver is not None: + # Inside the try so a missing/removed adapter becomes a capability failure. + req = req.model_copy(update={"loras": self._lora_resolver(req.loras)}) + result = self._video_generation.generate_local_reserved( + req, + generation_id=generation.id, + output_path=Path(output.dest_path), + prompt_wrap=self._prompt_wrap, + local_model_id=resolve_job_local_model_id( + self._video_generation.models_dir, offering + ), + ) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, HTTPError): + raise capability_failed_from_http( + exc, unavailable=_INPUT_ASSET_UNAVAILABLE + ) from exc + raise + if isinstance(result, GenerateVideoCancelledResponse): + raise GenerationCancelledError() + + def _params_from_spec( + self, spec: Mapping[str, object] + ) -> ImageToVideoParams | ImageToVideoRecipeParams: + if self._lora_resolver is not None: + return model_from_spec(spec, "params", ImageToVideoRecipeParams) + return model_from_spec(spec, "params", ImageToVideoParams) + + def _resolve_image(self, asset_id: str, *, slot: str) -> AssetRecord: + return require_existing_asset( + self._assets, + asset_id, + media_kind="image", + unavailable=f"{slot} image is no longer available", + ) + + +def find_closest_aspect_ratio_option( + width: int, height: int, options: Sequence[str] +) -> str: + if height <= 0: + raise ValueError("startFrame height must be greater than 0") + target = width / height + closest: str | None = None + closest_diff = float("inf") + for option in options: + ratio = parse_aspect_ratio(option) + if ratio is None: + continue + diff = abs(ratio - target) + if diff < closest_diff: + closest_diff = diff + closest = option + if closest is None: + raise ValueError("no valid aspect ratio options") + return closest + + +def parse_aspect_ratio(option: str) -> float | None: + parts = option.split(":") + if len(parts) != 2: + return None + try: + option_width = float(parts[0]) + option_height = float(parts[1]) + except ValueError: + return None + if option_width <= 0 or option_height <= 0: + return None + return option_width / option_height + + +def _resolve_aspect_ratio( + params: ImageToVideoParams, start: AssetRecord +) -> str: + if params.aspectRatio != "auto": + return params.aspectRatio + metadata = start.metadata + if metadata.mediaType != "image": + raise ValueError("startFrame must have image metadata") + try: + options = local_aspect_ratios(params.resolution, is_a2v=False) + except KeyError as exc: + raise HTTPError(400, "INVALID_LOCAL_RESOLUTION") from exc + return find_closest_aspect_ratio_option( + metadata.metadata.width, + metadata.metadata.height, + options, + ) + + +def _inputs_from_spec(spec: Mapping[str, object]) -> ImageToVideoInputs: + return model_from_spec(spec, "inputs", ImageToVideoInputs) diff --git a/backend/services/features/video/job_common.py b/backend/services/features/video/job_common.py new file mode 100644 index 000000000..4d5a6bd59 --- /dev/null +++ b/backend/services/features/video/job_common.py @@ -0,0 +1,98 @@ +"""Shared queued-video-job helpers (t2v / i2v / a2v / retake / extend).""" + +from __future__ import annotations + +import random +from collections.abc import Mapping +from pathlib import Path +from typing import Protocol, TypeVar + +from pydantic import BaseModel + +from api_types import LTXLocalModelId, OfferingId +from _routes._errors import HTTPError +from runtime_config.ltx_capabilities import LtxCapabilityFeature, local_caps, supports +from runtime_config.offerings import resolve_offering_local_model_id +from services.records import AssetRecord, CapabilityFailedError +from state.app_settings import MAX_GENERATION_SEED + +INPUT_ASSET_NOT_FOUND = "INPUT_ASSET_NOT_FOUND" + +TModel = TypeVar("TModel", bound=BaseModel) + + +class AssetLookup(Protocol): + def get_asset(self, asset_id: str) -> AssetRecord | None: ... + + +def is_existing_file(path: str) -> bool: + try: + return Path(path).is_file() + except OSError: + return False + + +def looks_like_filesystem_path(detail: str) -> bool: + stripped = detail.strip() + if not stripped: + return False + if Path(stripped).is_absolute(): + return True + return "/" in stripped or "\\" in stripped + + +def capability_failed_from_http( + exc: HTTPError, *, unavailable: str = "input media is no longer available" +) -> CapabilityFailedError: + if looks_like_filesystem_path(exc.detail): + return CapabilityFailedError(unavailable, code=INPUT_ASSET_NOT_FOUND) + return CapabilityFailedError(exc.detail, code=exc.code) + + +def model_from_spec( + spec: Mapping[str, object], key: str, model: type[TModel] +) -> TModel: + value = spec.get(key) + if not isinstance(value, dict): + raise ValueError(f"generation spec requires a {key} object") + return model.model_validate(value) + + +def resolve_generation_seed(seed: int | None) -> int: + return seed if seed is not None else random.randint(0, MAX_GENERATION_SEED) + + +def resolve_job_local_model_id( + models_dir: Path, offering: OfferingId +) -> LTXLocalModelId: + resolved = resolve_offering_local_model_id(models_dir, offering) + if resolved is None: + raise HTTPError(409, "LTX_MODEL_NOT_INSTALLED") + return resolved + + +def require_capable_local_model( + models_dir: Path, + offering: OfferingId, + capability: LtxCapabilityFeature, + *, + unsupported_code: str, + unsupported_message: str, +) -> LTXLocalModelId: + local_id = resolve_job_local_model_id(models_dir, offering) + if not supports(local_caps(local_id), capability): + raise CapabilityFailedError(unsupported_message, code=unsupported_code) + return local_id + + +def require_existing_asset( + assets: AssetLookup, + asset_id: str, + *, + media_kind: str, + unavailable: str, +) -> AssetRecord: + asset = assets.get_asset(asset_id) + if asset is None or asset.media_kind != media_kind or not is_existing_file(asset.path): + raise CapabilityFailedError(unavailable, code=INPUT_ASSET_NOT_FOUND) + return asset diff --git a/backend/services/features/video/retake.py b/backend/services/features/video/retake.py new file mode 100644 index 000000000..e2be71e16 --- /dev/null +++ b/backend/services/features/video/retake.py @@ -0,0 +1,214 @@ +from __future__ import annotations + +import logging +from collections.abc import Mapping +from dataclasses import dataclass +from pathlib import Path + +from api_types import LTXLocalModelId, RetakeInputs, RetakeParams +from handlers.video_resolution import ( + correct_frame_count, + generation_letterbox, + read_source_metadata, + resolve_home_edit_size, +) +from runtime_config.video_job_budget import EDIT_JOB_TOO_LARGE_MESSAGE, VIDEO_JOB_TOO_LARGE +from services.features.video.edit_executor import VideoEditExecutor +from services.features.video.job_common import model_from_spec +from services.records import AssetRecord, CapabilityFailedError, GenerationRecord +from services.retake_pipeline.retake_mode import ( + InvalidRetakeModeError, + resolve_retake_mode, +) +from services.retake_pipeline.retake_stitch import stitch_retake_output +from services.retake_pipeline.window import ( + MAX_INPUT_FRAMES, + RetakeEncodeWindow, + feathered_mask_times, + window_for_retake, +) +from state.app_state_types import RetakePipelineState + +FEATURE = "retake" +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class _PreparedRetake: + params: RetakeParams + video: AssetRecord + pipeline_state: RetakePipelineState + seed: int + fps: float + content_width: int + content_height: int + canvas_width: int + canvas_height: int + window: RetakeEncodeWindow + region_start: float + region_end: float + regenerate_video: bool + regenerate_audio: bool + dest_path: Path + windowed_path: str + + +class RetakeExecutor(VideoEditExecutor[RetakeParams, RetakeInputs, _PreparedRetake]): + """Queued Home/Remote retake. 505-frame window, MASK_DELTA, original-pixel stitch.""" + + capability = "retake" + unsupported_code = "UNSUPPORTED_RETAKE" + unsupported_message = "Retake is not supported for the selected LTX model." + heartbeat_label = "retake inference" + + def parse_params(self, spec: Mapping[str, object]) -> RetakeParams: + return model_from_spec(spec, "params", RetakeParams) + + def parse_inputs(self, spec: Mapping[str, object]) -> RetakeInputs: + return model_from_spec(spec, "inputs", RetakeInputs) + + def prepare( + self, + generation: GenerationRecord, + params: RetakeParams, + video: AssetRecord, + local_model_id: LTXLocalModelId, + seed: int, + dest: Path, + windowed_path: str, + ) -> _PreparedRetake: + try: + regenerate_video, regenerate_audio = resolve_retake_mode(params.mode) + except InvalidRetakeModeError as exc: + raise CapabilityFailedError(str(exc), code="INVALID_GENERATION_SPEC") from exc + fps, source_width, source_height, source_frames = read_source_metadata(video.path) + target_frames = correct_frame_count(source_frames) + corrected_duration = target_frames / fps + end_time = min(params.startTime + params.duration, corrected_duration) + if params.startTime >= end_time: + raise CapabilityFailedError( + "Selection is outside the usable video range", + code="INVALID_GENERATION_SPEC", + ) + mask_start_frame = max(0, min(target_frames, round(params.startTime * fps))) + mask_end_frame = max( + mask_start_frame + 1, + min(target_frames, round(end_time * fps)), + ) + requested = params.resolution + content_width, content_height = resolve_home_edit_size( + None if requested is None else requested.width, + None if requested is None else requested.height, + source_width, + source_height, + ) + box = generation_letterbox(content_width, content_height) + frame_cap = self._pipelines.edit_encode_frame_cap(box.canvas_width, box.canvas_height) + try: + window = window_for_retake( + source_frames=target_frames, + mask_start_frame=mask_start_frame, + mask_end_frame=mask_end_frame, + max_input_frames=frame_cap, + fps=fps, + ) + except ValueError as exc: + # A short selection on a long clip used to pad to 505 and 422. + # If the selection itself is larger than the window that fits, + # say so as a resolution limit rather than a mask-size error. + if frame_cap < MAX_INPUT_FRAMES: + raise CapabilityFailedError( + EDIT_JOB_TOO_LARGE_MESSAGE, code=VIDEO_JOB_TOO_LARGE + ) from exc + raise CapabilityFailedError(str(exc), code="INVALID_GENERATION_SPEC") from exc + region_start, region_end = feathered_mask_times(window, fps) + if ( + abs(content_width - source_width) > 31 + or abs(content_height - source_height) > 31 + ): + logger.info( + "Downscaling source video from %dx%d to %dx%d; queued retake supports up to 1080p", + source_width, + source_height, + content_width, + content_height, + ) + logger.info( + "Retake %s started (%s, source %dx%d → %dx%d canvas %dx%d, %d frames @ %g fps, %s %.2fs–%.2fs, encode %d, seed=%d)", + generation.id, + local_model_id, + source_width, + source_height, + content_width, + content_height, + box.canvas_width, + box.canvas_height, + target_frames, + fps, + params.mode, + params.startTime, + end_time, + window.encode_frames, + seed, + ) + return _PreparedRetake( + params=params, + video=video, + pipeline_state=self._pipelines.load_retake_pipeline( + distilled=True, + ltx_model_id=local_model_id, + width=box.canvas_width, + height=box.canvas_height, + frames=window.encode_frames, + queued_home=True, + ), + seed=seed, + fps=fps, + content_width=content_width, + content_height=content_height, + canvas_width=box.canvas_width, + canvas_height=box.canvas_height, + window=window, + region_start=region_start, + region_end=region_end, + regenerate_video=regenerate_video, + regenerate_audio=regenerate_audio, + dest_path=dest, + windowed_path=windowed_path, + ) + + def generate(self, prepared: _PreparedRetake) -> None: + prepared.pipeline_state.pipeline.generate( + video_path=prepared.video.path, + prompt=prepared.params.prompt, + start_time=prepared.region_start, + end_time=prepared.region_end, + seed=prepared.seed, + output_path=prepared.windowed_path, + negative_prompt=self._default_negative_prompt, + num_inference_steps=40, + video_guider_params=None, + audio_guider_params=None, + regenerate_video=prepared.regenerate_video, + regenerate_audio=prepared.regenerate_audio, + enhance_prompt=False, + distilled=True, + target_width=prepared.canvas_width, + target_height=prepared.canvas_height, + content_width=prepared.content_width, + content_height=prepared.content_height, + target_frames=prepared.window.encode_frames, + encode_start_time=prepared.window.encode_start_time(prepared.fps), + encode_max_duration=prepared.window.encode_duration(prepared.fps), + ) + + def stitch(self, prepared: _PreparedRetake) -> None: + stitch_retake_output( + source_path=prepared.video.path, + windowed_path=prepared.windowed_path, + dest_path=str(prepared.dest_path), + window=prepared.window, + fps=prepared.fps, + target_width=prepared.content_width, + target_height=prepared.content_height, + ) diff --git a/backend/services/features/video/text_to_video.py b/backend/services/features/video/text_to_video.py new file mode 100644 index 000000000..c4e13b103 --- /dev/null +++ b/backend/services/features/video/text_to_video.py @@ -0,0 +1,170 @@ +from __future__ import annotations + +from collections.abc import Callable, Mapping +from pathlib import Path +from typing import Protocol + +from pydantic import BaseModel + +from api_types import ( + AudioToVideoParams, + OfferingId, + GenerateVideoCancelledResponse, + GenerateVideoRequest, + GenerateVideoResponse, + LoraEntry, + LTXLocalModelId, + TextToVideoParams, +) +from _routes._errors import HTTPError +from runtime_config.offerings import OFFERING_IDS, local_pipeline_for_offering +from services.features.video.job_common import ( + model_from_spec, + resolve_job_local_model_id, +) +from services.generation_interrupt import GenerationCancelledError, is_cancel_exception +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.records import CapabilityFailedError, GenerationRecord + +FEATURE = "text-to-video" + +VIDEO_OUTPUT_PLAN = OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", +) +_SUPPORTED_CONTRACT_VERSION = 1 + + +class ReservedVideoGenerator(Protocol): + @property + def models_dir(self) -> Path: ... + + def validate_local_a2v_request( + self, params: AudioToVideoParams, audio_duration_ms: int + ) -> None: ... + + def generate_local_reserved( + self, + req: GenerateVideoRequest, + *, + generation_id: str, + output_path: Path | None = None, + prompt_wrap: Callable[[str], str] | None = None, + a2v_num_frames: int | None = None, + a2v_audio_duration_seconds: float | None = None, + local_model_id: LTXLocalModelId, + ) -> GenerateVideoResponse: ... + + +class TextToVideoExecutor: + """Queued text-to-video. v1 drains the local GPU only. + + Always calls ``generate_local_reserved`` (``use_api_specs=False``). It does + not follow ``POST /api/generate``'s LTX API setting. Cancel and progress + for these jobs use the ledger URLs, not ``/api/generate/cancel`` or + ``/api/generation/progress``. + + ``prompt_wrap`` is the recipe-scoped post-enhancement prompt transform. It is + ``None`` for the plain text-to-video feature; a LoRA recipe registers the same + executor with its scaffold wrap so the style scaffold stays out of + ``generate_local_reserved`` and applies only when ``feature`` is that recipe + (and Explore auto-enhance is on, or the user already ran Enhance). + """ + + def __init__( + self, + video_generation: ReservedVideoGenerator, + prompt_wrap: Callable[[str], str] | None = None, + lora_resolver: Callable[[list[LoraEntry]], list[LoraEntry]] | None = None, + ) -> None: + self._video_generation = video_generation + self._prompt_wrap = prompt_wrap + # Recipe-scoped: fills the LoRA ref from its catalog id at execution. None for plain t2v. + self._lora_resolver = lora_resolver + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + params_from_spec(spec) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + self._params(generation) + return (VIDEO_OUTPUT_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + params = self._params(generation) + output = require_video_output(outputs) + try: + req, local_model_id = generate_request_from_offering_params( + params, self._video_generation + ) + if self._lora_resolver is not None: + # Inside the try so a missing/removed adapter becomes a capability failure. + req = req.model_copy(update={"loras": self._lora_resolver(req.loras)}) + result = self._video_generation.generate_local_reserved( + req, + generation_id=generation.id, + output_path=Path(output.dest_path), + prompt_wrap=self._prompt_wrap, + local_model_id=local_model_id, + ) + except Exception as exc: + if is_cancel_exception(exc): + raise GenerationCancelledError() from exc + if isinstance(exc, HTTPError): + raise CapabilityFailedError(exc.detail, code=exc.code) from exc + raise + if isinstance(result, GenerateVideoCancelledResponse): + raise GenerationCancelledError() + + def _params(self, generation: GenerationRecord) -> TextToVideoParams: + require_supported_contract_version(generation.contract_version) + return params_from_spec(generation.spec) + + +def require_supported_contract_version(contract_version: int) -> None: + if contract_version != _SUPPORTED_CONTRACT_VERSION: + raise ValueError( + "text-to-video does not support contract_version " + f"{contract_version}" + ) + + +def params_from_spec(spec: Mapping[str, object]) -> TextToVideoParams: + return model_from_spec(spec, "params", TextToVideoParams) + + +def require_video_output( + outputs: tuple[OutputAllocation, ...], +) -> OutputAllocation: + if len(outputs) != 1 or outputs[0].plan.slot != "output": + raise ValueError("text-to-video requires a single 'output' allocation") + return outputs[0] + + +def offering_payload_from_params( + params: BaseModel, +) -> tuple[dict[str, object], OfferingId]: + payload = params.model_dump(mode="python") + raw_model = payload["model"] + if not isinstance(raw_model, str) or raw_model not in OFFERING_IDS: + raise HTTPError(422, "INVALID_VIDEO_GENERATION_SPEC") + payload["model"] = local_pipeline_for_offering(raw_model) + return payload, raw_model + + +def generate_request_from_offering_params( + params: BaseModel, video_generation: ReservedVideoGenerator +) -> tuple[GenerateVideoRequest, LTXLocalModelId]: + payload, offering = offering_payload_from_params(params) + return ( + GenerateVideoRequest.model_validate(payload), + resolve_job_local_model_id(video_generation.models_dir, offering), + ) diff --git a/backend/services/ffmpeg.py b/backend/services/ffmpeg.py new file mode 100644 index 000000000..fcc4303cb --- /dev/null +++ b/backend/services/ffmpeg.py @@ -0,0 +1,116 @@ +"""ffmpeg invocation shared by audio trim and video stitch.""" + +from __future__ import annotations + +import logging +import subprocess +import time +from collections.abc import Callable + +import imageio_ffmpeg + +from services.records import MediaError + +logger = logging.getLogger(__name__) + +# Local file outputs/inputs only (plus pipe for stdio-style transports). +FFMPEG_PROTOCOL_WHITELIST = "file,pipe" +# Re-encoding a long import can legitimately take tens of seconds. +FFMPEG_TIMEOUT_SECONDS = 120.0 +# Wing re-encode is slower than realtime on CPU. Floor at the shared timeout +# and cap so one long source cannot hold the worker all day. +STITCH_TIMEOUT_PER_SOURCE_SECOND = 8.0 +STITCH_TIMEOUT_CAP_SECONDS = 1800.0 + + +class FfmpegCancelledError(Exception): + """``should_cancel`` turned true and ffmpeg was killed.""" + + +_STDERR_LOG_CHARS = 800 +# How often a cancellable run checks its cancel flag. +_CANCEL_POLL_SECONDS = 0.2 + + +def timeout_for_source_duration(duration_seconds: float) -> float: + """How long a stitch of a source this long may run ffmpeg.""" + scaled = max(0.0, duration_seconds) * STITCH_TIMEOUT_PER_SOURCE_SECOND + return min(STITCH_TIMEOUT_CAP_SECONDS, max(FFMPEG_TIMEOUT_SECONDS, scaled)) + + +def ffmpeg_seconds(value: float) -> str: + """``str(1e-05)`` is scientific notation, which ``-ss``/``-t`` reject.""" + return f"{value:.6f}" + + +def _ffmpeg() -> str: + return str(imageio_ffmpeg.get_ffmpeg_exe()) + + +def _run_until_cancelled( + command: list[str], timeout: float, should_cancel: Callable[[], bool] +) -> subprocess.CompletedProcess[bytes]: + """Like ``subprocess.run``, but kills ffmpeg when ``should_cancel`` turns true.""" + deadline = time.monotonic() + timeout + with subprocess.Popen( + command, stdout=subprocess.PIPE, stderr=subprocess.PIPE + ) as process: + while True: + try: + stdout, stderr = process.communicate(timeout=_CANCEL_POLL_SECONDS) + except subprocess.TimeoutExpired: + if should_cancel(): + process.kill() + process.communicate() + raise FfmpegCancelledError() from None + if time.monotonic() >= deadline: + process.kill() + process.communicate() + raise subprocess.TimeoutExpired(command, timeout) from None + continue + return subprocess.CompletedProcess( + process.args, process.returncode, stdout, stderr + ) + + +def run_ffmpeg( + args: list[str], + *, + ffmpeg_exe: str | list[str] | None = None, + timeout: float = FFMPEG_TIMEOUT_SECONDS, + check: bool = True, + should_cancel: Callable[[], bool] | None = None, +) -> subprocess.CompletedProcess[bytes]: + if ffmpeg_exe is None: + command = [_ffmpeg()] + elif isinstance(ffmpeg_exe, str): + command = [ffmpeg_exe] + else: + command = ffmpeg_exe + full_command = [*command, "-nostdin", *args] + try: + if should_cancel is None: + completed = subprocess.run( + full_command, + check=False, + capture_output=True, + timeout=timeout, + ) + else: + completed = _run_until_cancelled(full_command, timeout, should_cancel) + except subprocess.CalledProcessError as exc: + stderr = exc.stderr.decode("utf-8", "replace") if exc.stderr else "" + # Logged only: stderr carries local paths that must not reach responses. + logger.warning( + "ffmpeg exited %s: %s", exc.returncode, stderr[-_STDERR_LOG_CHARS:] + ) + raise + except FileNotFoundError as exc: + raise MediaError("UNREADABLE_MEDIA", "ffmpeg is not available") from exc + except subprocess.TimeoutExpired as exc: + raise MediaError("UNREADABLE_MEDIA", "ffmpeg timed out") from exc + if check and completed.returncode != 0: + raise subprocess.CalledProcessError( + completed.returncode, completed.args, completed.stdout, completed.stderr + ) + return completed diff --git a/backend/services/generation_queue/__init__.py b/backend/services/generation_queue/__init__.py new file mode 100644 index 000000000..584be65ee --- /dev/null +++ b/backend/services/generation_queue/__init__.py @@ -0,0 +1,27 @@ +from services.generation_queue.control import ( + QueueControl, + NoOpQueueControl, + cancel_queued_generation, + GenerationSlotWaitAborted, + SharedGenerationSlot, +) +from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.runner import QueueRunner +from services.generation_queue.types import ( + GenerationExecutor, + OutputAllocation, + OutputPlan, +) + +__all__ = [ + "ExecutorRegistry", + "GenerationExecutor", + "GenerationSlotWaitAborted", + "OutputAllocation", + "OutputPlan", + "QueueControl", + "QueueRunner", + "NoOpQueueControl", + "SharedGenerationSlot", + "cancel_queued_generation", +] diff --git a/backend/services/generation_queue/control.py b/backend/services/generation_queue/control.py new file mode 100644 index 000000000..a2fed9bf7 --- /dev/null +++ b/backend/services/generation_queue/control.py @@ -0,0 +1,53 @@ +from __future__ import annotations + +from collections.abc import Callable +from contextlib import AbstractContextManager +from threading import Event +from typing import Protocol + +from services.store import Store +from services.records import GenerationRecord + + +class QueueControl(Protocol): + def wake(self) -> None: ... + def interrupt(self, generation_id: str, attempt_count: int) -> None: ... + + +class SharedGenerationSlot(Protocol): + """In-memory GPU/API slot used by the queue runner. + + Implemented by GenerationHandler. Named separately from that class's + GenerationSlot = Literal["gpu", "api"] alias. + """ + + def wait_for_generation_slot( + self, shutdown: Event + ) -> AbstractContextManager[None]: ... + def cancel_generation(self) -> object: ... + + +class GenerationSlotWaitAborted(RuntimeError): + """Expected shutdown while waiting for the shared generation slot.""" + + def __init__(self, message: str = "generation slot wait aborted by shutdown") -> None: + super().__init__(message) + + +class NoOpQueueControl: + def wake(self) -> None: + return None + + def interrupt(self, generation_id: str, attempt_count: int) -> None: + del generation_id, attempt_count + + +def cancel_queued_generation( + db: Store, + generation_id: str, + interrupt: Callable[[str, int], None], +) -> GenerationRecord: + generation = db.request_generation_cancellation(generation_id) + if generation.status == "cancelling": + interrupt(generation.id, generation.attempt_count) + return generation diff --git a/backend/services/generation_queue/finished_tray.py b/backend/services/generation_queue/finished_tray.py new file mode 100644 index 000000000..c1bc3f5a2 --- /dev/null +++ b/backend/services/generation_queue/finished_tray.py @@ -0,0 +1,209 @@ +"""In-memory Done/Failed tray for the generation queue. + +Lives on the desktop process and is merged into the queue snapshot so the +Electron app and the remote app share the same rows. A restart clears it. +Nothing here is written to sqlite. +""" + +from __future__ import annotations + +from collections.abc import Callable +from threading import Lock + +from services.records import GenerationRecord, QueueGenerationRecord, UnavailableError + +FINISHED_TRAY_LIMIT = 20 + + +class FinishedTray: + def __init__(self) -> None: + self._lock = Lock() + self._previous: list[QueueGenerationRecord] = [] + self._has_previous = False + self._done: list[QueueGenerationRecord] = [] + self._failed: list[QueueGenerationRecord] = [] + self._seen: set[str] = set() + self._dismissed: set[str] = set() + + def observe( + self, + live: list[QueueGenerationRecord], + load: Callable[[str], GenerationRecord | None], + ) -> None: + """Record jobs that left the live queue since the previous snapshot.""" + with self._lock: + live_ids = {entry.generation.id for entry in live} + previous_ids = {entry.generation.id for entry in self._previous} + # Only an id that left and came back is a retry. Releasing every id + # in this list undoes a dismiss when the list was read before the + # job finished. + if self._has_previous: + self._release_live(live_ids - previous_ids) + departed = [ + entry + for entry in self._previous + if entry.generation.id not in live_ids + ] + pending: list[QueueGenerationRecord] = [] + loaded: list[tuple[QueueGenerationRecord, GenerationRecord | None]] = [] + for entry in departed: + try: + loaded.append((entry, load(entry.generation.id))) + except UnavailableError: + raise + except Exception: + pending.append(entry) + with self._lock: + for entry, fresh in loaded: + self._remember_locked(entry, fresh) + self._previous = [*pending, *live] + self._has_previous = True + + def release(self, generation_id: str) -> None: + """Drop tray state for a job that is live again. + + Retry must call this itself. A completion can land before the next + queue read, and `remember` ignores ids that are still dismissed. + """ + with self._lock: + self._release_live({generation_id}) + + def remember(self, entry: QueueGenerationRecord) -> None: + """Record a job that just succeeded or failed.""" + with self._lock: + self._remember_locked(entry, entry.generation) + + def lists( + self, + ) -> tuple[list[QueueGenerationRecord], list[QueueGenerationRecord], list[str]]: + with self._lock: + unseen = [ + entry.generation.id + for entry in self._done + if entry.generation.id not in self._seen + ] + return list(self._done), list(self._failed), unseen + + def mark_seen(self, generation_id: str) -> bool: + with self._lock: + if not any(entry.generation.id == generation_id for entry in self._done): + return False + self._seen.add(generation_id) + return True + + def dismiss_done(self, generation_id: str) -> bool: + with self._lock: + if not any(entry.generation.id == generation_id for entry in self._done): + return False + self._done = [ + entry for entry in self._done if entry.generation.id != generation_id + ] + self._seen.discard(generation_id) + self._dismissed.add(generation_id) + return True + + def clear_done( + self, feature_is_allowed: Callable[[str], bool] | None = None + ) -> None: + with self._lock: + self._done = self._dismiss_matching( + self._done, feature_is_allowed, drop_seen=True + ) + + def clear_failed( + self, feature_is_allowed: Callable[[str], bool] | None = None + ) -> None: + with self._lock: + self._failed = self._dismiss_matching( + self._failed, feature_is_allowed, drop_seen=False + ) + + def forget(self, generation_id: str) -> None: + with self._lock: + self._done = [ + entry for entry in self._done if entry.generation.id != generation_id + ] + self._failed = [ + entry + for entry in self._failed + if entry.generation.id != generation_id + ] + self._previous = [ + entry + for entry in self._previous + if entry.generation.id != generation_id + ] + self._seen.discard(generation_id) + self._dismissed.add(generation_id) + + def _release_live(self, live_ids: set[str]) -> None: + self._dismissed.difference_update(live_ids) + self._seen.difference_update(live_ids) + self._done = [ + entry for entry in self._done if entry.generation.id not in live_ids + ] + self._failed = [ + entry for entry in self._failed if entry.generation.id not in live_ids + ] + + def _remember_locked( + self, + previous: QueueGenerationRecord, + fresh: GenerationRecord | None, + ) -> None: + if fresh is None or fresh.id in self._dismissed: + return + if previous.generation.status in {"cancelling", "cancelled"}: + return + if fresh.status not in {"succeeded", "failed"}: + return + record = previous.model_copy(update={"generation": fresh}) + generation_id = fresh.id + if fresh.status == "succeeded": + self._failed = [ + entry + for entry in self._failed + if entry.generation.id != generation_id + ] + self._done = [ + record, + *[ + entry + for entry in self._done + if entry.generation.id != generation_id + ], + ] + del self._done[FINISHED_TRAY_LIMIT:] + return + self._seen.discard(generation_id) + self._done = [ + entry for entry in self._done if entry.generation.id != generation_id + ] + self._failed = [ + record, + *[ + entry + for entry in self._failed + if entry.generation.id != generation_id + ], + ] + del self._failed[FINISHED_TRAY_LIMIT:] + + def _dismiss_matching( + self, + entries: list[QueueGenerationRecord], + feature_is_allowed: Callable[[str], bool] | None, + *, + drop_seen: bool, + ) -> list[QueueGenerationRecord]: + kept: list[QueueGenerationRecord] = [] + for entry in entries: + if feature_is_allowed is None or feature_is_allowed( + entry.generation.feature + ): + self._dismissed.add(entry.generation.id) + if drop_seen: + self._seen.discard(entry.generation.id) + continue + kept.append(entry) + return kept diff --git a/backend/services/generation_queue/output_names.py b/backend/services/generation_queue/output_names.py new file mode 100644 index 000000000..0e3fea41d --- /dev/null +++ b/backend/services/generation_queue/output_names.py @@ -0,0 +1,33 @@ +from __future__ import annotations + +import re +import unicodedata +from datetime import datetime, timezone + +from services.media_probe import extension_for_mime + +_MAX_SLUG = 40 + + +def slug_prompt(prompt: object) -> str: + if not isinstance(prompt, str) or prompt.strip() == "": + return "generation" + normalized = unicodedata.normalize("NFKD", prompt) + ascii_only = normalized.encode("ascii", "ignore").decode("ascii").lower() + slugged = re.sub(r"[^a-z0-9]+", "-", ascii_only) + slugged = re.sub(r"-{2,}", "-", slugged).strip("-")[:_MAX_SLUG].strip("-") + return slugged or "generation" + + +def output_asset_name( + *, + prompt: object, + created_at_ms: int, + asset_id: str, + mime_type: str, +) -> str: + stamp = datetime.fromtimestamp(created_at_ms / 1000, tz=timezone.utc).strftime( + "%Y%m%d-%H%M%S" + ) + ext = extension_for_mime(mime_type).lstrip(".") + return f"{slug_prompt(prompt)}-{stamp}-{asset_id[:6]}.{ext}" diff --git a/backend/services/generation_queue/registry.py b/backend/services/generation_queue/registry.py new file mode 100644 index 000000000..5ebe32ba8 --- /dev/null +++ b/backend/services/generation_queue/registry.py @@ -0,0 +1,21 @@ +from __future__ import annotations + +from collections.abc import Mapping + +from services.generation_queue.types import GenerationExecutor + + +class ExecutorRegistry: + def __init__(self, executors: Mapping[str, GenerationExecutor]) -> None: + self._executors = dict(executors) + + def get(self, feature: str) -> GenerationExecutor: + executor = self._executors.get(feature) + if executor is None: + raise ValueError(f"unknown generation feature: {feature}") + return executor + + def validate_params( + self, feature: str, spec: Mapping[str, object], *, contract_version: int + ) -> None: + self.get(feature).validate_params(spec, contract_version=contract_version) diff --git a/backend/services/generation_queue/runner.py b/backend/services/generation_queue/runner.py new file mode 100644 index 000000000..592b38405 --- /dev/null +++ b/backend/services/generation_queue/runner.py @@ -0,0 +1,450 @@ +from __future__ import annotations + +import logging +from collections.abc import Callable +from dataclasses import dataclass +from pathlib import Path +from threading import Event, Lock, Thread, current_thread +from typing import Literal + +from services.store import Store +from services.records import ( + AttemptError, + CapabilityFailedError, + GenerationErrorCode, + GenerationRecord, + MarkSucceededError, + OutputSpec, + StatusError, + UnavailableError, +) +from logging_policy import log_background_exception +from services.analytics import AnalyticsService, QueuedEnhancement, queued_generation_details +from services.generation_queue.control import ( + GenerationSlotWaitAborted, + SharedGenerationSlot, +) +from services.generation_queue.output_names import output_asset_name +from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.types import OutputAllocation +from services.generation_interrupt import is_cancel_exception + +logger = logging.getLogger(__name__) +_BACKGROUND_TASK_NAME = "generation-queue-runner" +_EXECUTOR_FAILURE_CODE: GenerationErrorCode = "EXECUTOR_FAILED" +_CAPABILITY_FAILURE_CODE: GenerationErrorCode = "CAPABILITY_FAILED" +_LTX_INVALID_API_KEY_CODE: GenerationErrorCode = "LTX_INVALID_API_KEY" +_LTX_API_PROMPT_EMBEDDING_FAILED_CODE: GenerationErrorCode = "LTX_API_PROMPT_EMBEDDING_FAILED" + + +def _capability_error_code(exc: CapabilityFailedError) -> GenerationErrorCode: + if exc.code == _LTX_INVALID_API_KEY_CODE: + return _LTX_INVALID_API_KEY_CODE + if exc.code == _LTX_API_PROMPT_EMBEDDING_FAILED_CODE: + return _LTX_API_PROMPT_EMBEDDING_FAILED_CODE + return _CAPABILITY_FAILURE_CODE + + +@dataclass +class _ActiveGeneration: + generation_id: str + attempt_count: int + + +class QueueRunner: + def __init__( + self, + *, + db: Store, + generation: SharedGenerationSlot, + executors: ExecutorRegistry, + analytics: AnalyticsService | None = None, + enhancement_policy: Callable[[GenerationRecord], QueuedEnhancement] | None = None, + idle_wait_seconds: float = 0.25, + stop_join_timeout_seconds: float = 600.0, + ) -> None: + self._db = db + self._generation = generation + self._executors = executors + self._analytics = analytics + self._enhancement_policy = enhancement_policy + self._idle_wait_seconds = idle_wait_seconds + self._stop_join_timeout_seconds = stop_join_timeout_seconds + + self._shutdown = Event() + self._wake_event = Event() + self._lifecycle_lock = Lock() + self._thread: Thread | None = None + self._active: _ActiveGeneration | None = None + self._finished_listener: Callable[[str], None] | None = None + + def set_finished_listener(self, listener: Callable[[str], None] | None) -> None: + self._finished_listener = listener + + def start(self) -> None: + try: + self._db.has_queued() + except UnavailableError: + return + with self._lifecycle_lock: + if self._thread is not None and self._thread.is_alive(): + return + self._shutdown.clear() + self._wake_event.clear() + self._thread = Thread( + target=self._run, + name="generation-queue-runner", + daemon=True, + ) + self._thread.start() + + def stop(self) -> None: + with self._lifecycle_lock: + thread = self._thread + if thread is None: + return + self._shutdown.set() + self._wake_event.set() + + if thread is not current_thread(): + thread.join(timeout=self._stop_join_timeout_seconds) + + with self._lifecycle_lock: + if self._thread is thread and not thread.is_alive(): + self._thread = None + + def wake(self) -> None: + self._wake_event.set() + + def interrupt(self, generation_id: str, attempt_count: int) -> None: + with self._lifecycle_lock: + active = self._active + if ( + active is None + or active.generation_id != generation_id + or active.attempt_count != attempt_count + ): + return + try: + self._generation.cancel_generation() + except Exception as exc: + logger.warning( + "Generation %s attempt %s interrupt failed: %s", + generation_id, + attempt_count, + exc, + ) + + @property + def is_running(self) -> bool: + with self._lifecycle_lock: + return self._thread is not None and self._thread.is_alive() + + def _run(self) -> None: + while True: + if self._shutdown.is_set(): + return + try: + if not self._db.has_queued(): + self._wake_event.wait(timeout=self._idle_wait_seconds) + self._wake_event.clear() + continue + + with self._generation.wait_for_generation_slot(self._shutdown): + claimed = self._claim_and_register_active() + if claimed is None: + if self._shutdown.is_set(): + return + continue + try: + self._process(claimed) + finally: + self._clear_active(claimed) + except GenerationSlotWaitAborted: + return + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + if self._shutdown.wait(timeout=self._idle_wait_seconds): + return + + def _claim_and_register_active(self) -> GenerationRecord | None: + if self._shutdown.is_set(): + return None + claimed = self._db.claim_next_queued() + if claimed is None: + return None + with self._lifecycle_lock: + self._active = _ActiveGeneration( + generation_id=claimed.id, + attempt_count=claimed.attempt_count, + ) + try: + latest = self._db.get_generation(claimed.id) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + self._clear_active(claimed) + return None + if latest is None or latest.attempt_count != claimed.attempt_count: + self._clear_active(claimed) + return None + if latest.status == "cancelling": + self._send_generation_started(latest) + self._finalize_cancellation_or_unlink(claimed, []) + self._clear_active(claimed) + return None + if latest.status != "running": + self._clear_active(claimed) + return None + self._send_generation_started(latest) + return claimed + + def _process(self, claimed: GenerationRecord) -> None: + allocations: list[OutputAllocation] = [] + partial_paths: list[str] = [] + try: + executor = self._executors.get(claimed.feature) + plans = executor.plan_outputs(claimed) + for plan in plans: + asset_id, dest_path = self._db.allocate_output_path( + plan.media_kind, plan.mime_type + ) + allocations.append( + OutputAllocation( + plan=plan, + asset_id=asset_id, + dest_path=dest_path, + ) + ) + partial_paths.append(dest_path) + executor.execute(claimed, tuple(allocations)) + allocations = [ + allocation + for allocation in allocations + if not allocation.plan.optional or Path(allocation.dest_path).is_file() + ] + except Exception as exc: + if is_cancel_exception(exc): + self._mark_cancelled(claimed, partial_paths) + elif isinstance(exc, CapabilityFailedError): + logger.warning( + "Generation %s attempt %s capability error: %s", + claimed.id, + claimed.attempt_count, + exc.detail, + ) + self._mark_failed(claimed, _capability_error_code(exc), partial_paths) + else: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + self._mark_failed(claimed, _EXECUTOR_FAILURE_CODE, partial_paths) + return + + self._mark_succeeded(claimed, allocations) + + def _mark_succeeded( + self, + claimed: GenerationRecord, + allocations: list[OutputAllocation], + ) -> None: + params = claimed.spec.get("params") + prompt: object = None + if isinstance(params, dict): + prompt = params.get("prompt") + outputs = [ + OutputSpec( + asset_id=allocation.asset_id, + dest_path=allocation.dest_path, + ordinal=index, + mime_type=allocation.plan.mime_type, + name=output_asset_name( + prompt=prompt, + created_at_ms=claimed.created_at, + asset_id=allocation.asset_id, + mime_type=allocation.plan.mime_type, + ), + ) + for index, allocation in enumerate(allocations) + ] + paths = [output.dest_path for output in outputs] + if self._is_cancelling_attempt(claimed): + self._finalize_cancellation_or_unlink(claimed, paths) + return + try: + completed = self._db.mark_succeeded( + claimed.id, + outputs, + attempt_count=claimed.attempt_count, + ) + except MarkSucceededError as exc: + self._mark_failed(claimed, exc.error_code, paths) + except (StatusError, AttemptError): + self._finalize_cancellation_or_unlink(claimed, paths) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + self._unlink_unless_succeeded(claimed.id, paths) + else: + self._notify_finished(claimed.id) + self._send_generation_ended(completed) + + def _is_cancelling_attempt(self, claimed: GenerationRecord) -> bool: + try: + latest = self._db.get_generation(claimed.id) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + return False + return ( + latest is not None + and latest.status == "cancelling" + and latest.attempt_count == claimed.attempt_count + ) + + def _mark_failed( + self, + claimed: GenerationRecord, + error_code: GenerationErrorCode, + partial_paths: list[str], + ) -> None: + wrote = self._cas_or_unlink( + claimed, + partial_paths, + lambda: self._db.mark_failed( + claimed.id, + error_code, + partial_paths, + attempt_count=claimed.attempt_count, + ), + ) + if wrote: + self._notify_finished(claimed.id) + + def _notify_finished(self, generation_id: str) -> None: + listener = self._finished_listener + if listener is None: + return + try: + listener(generation_id) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + + def _mark_cancelled( + self, + claimed: GenerationRecord, + partial_paths: list[str], + ) -> None: + self._cas_or_unlink( + claimed, + partial_paths, + lambda: self._db.mark_cancelled( + claimed.id, + partial_paths, + attempt_count=claimed.attempt_count, + ), + ) + + def _cas_or_unlink( + self, + claimed: GenerationRecord, + paths: list[str], + write: Callable[[], object], + ) -> bool: + try: + completed = write() + except (StatusError, AttemptError): + self._finalize_cancellation_or_unlink(claimed, paths) + return False + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + self._unlink_unless_succeeded(claimed.id, paths) + return False + if isinstance(completed, GenerationRecord): + self._send_generation_ended(completed) + return True + + def _finalize_cancellation_or_unlink( + self, + claimed: GenerationRecord, + paths: list[str], + ) -> None: + try: + completed = self._db.mark_cancelled( + claimed.id, + paths, + attempt_count=claimed.attempt_count, + ) + except (StatusError, AttemptError): + self._unlink_unless_succeeded(claimed.id, paths) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + self._unlink_unless_succeeded(claimed.id, paths) + else: + self._send_generation_ended(completed) + + def _unlink_unless_succeeded(self, generation_id: str, paths: list[str]) -> None: + try: + generation = self._db.get_generation(generation_id) + except Exception as exc: + logger.warning( + "Could not inspect generation %s after a lost finalization; " + "preserving allocated paths: %s", + generation_id, + exc, + ) + return + if generation is None or generation.status != "succeeded": + self._db.unlink_partial_outputs(paths) + + def _enhancement(self, generation: GenerationRecord) -> QueuedEnhancement | None: + if self._enhancement_policy is None: + return None + return self._enhancement_policy(generation) + + def _send_generation_started(self, generation: GenerationRecord) -> None: + if self._analytics is None: + return + try: + details = queued_generation_details( + generation, enhancement=self._enhancement(generation) + ) + if details is not None: + self._analytics.send_generation_started(details) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + + def _send_generation_ended(self, generation: GenerationRecord) -> None: + if ( + self._analytics is None + or generation.started_at is None + or generation.finished_at is None + ): + return + try: + details = queued_generation_details( + generation, enhancement=self._enhancement(generation) + ) + if details is None: + return + outcome: Literal["succeeded", "failed", "cancelled"] + if generation.status == "succeeded": + outcome = "succeeded" + elif generation.status == "failed": + outcome = "failed" + elif generation.status == "cancelled": + outcome = "cancelled" + else: + return + self._analytics.send_generation_ended( + details, + outcome=outcome, + runtime_ms=generation.finished_at - generation.started_at, + error_code=generation.error_code, + ) + except Exception as exc: + log_background_exception(_BACKGROUND_TASK_NAME, exc) + + def _clear_active(self, generation: GenerationRecord) -> None: + with self._lifecycle_lock: + if ( + self._active is not None + and self._active.generation_id == generation.id + and self._active.attempt_count == generation.attempt_count + ): + self._active = None diff --git a/backend/services/generation_queue/types.py b/backend/services/generation_queue/types.py new file mode 100644 index 000000000..581fd48f2 --- /dev/null +++ b/backend/services/generation_queue/types.py @@ -0,0 +1,39 @@ +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +from typing import Protocol + +from api_types import MediaKind +from services.records import GenerationRecord + + +@dataclass(frozen=True) +class OutputPlan: + slot: str + media_kind: MediaKind + mime_type: str + name: str + # An optional output may be missing when the executor returns. It is then left out. + optional: bool = False + + +@dataclass(frozen=True) +class OutputAllocation: + plan: OutputPlan + asset_id: str + dest_path: str + + +class GenerationExecutor(Protocol): + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: ... + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: ... + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: ... diff --git a/backend/services/generation_stats_sql.py b/backend/services/generation_stats_sql.py new file mode 100644 index 000000000..33f80a383 --- /dev/null +++ b/backend/services/generation_stats_sql.py @@ -0,0 +1,79 @@ +"""The generation stats projection. JSON paths for the dashboard live here. + +fps is null unless the JSON value is a number, so a string like "24" cannot +pass for a real frame rate. +""" + +from __future__ import annotations + +from services.features.ic_lora_recipes import queued_ic_lora_recipes + +_IC_LORA_IDS = ", ".join( + f"'{recipe.recipe_id}'" for recipe in queued_ic_lora_recipes() +) +_IC_LORA_GROUP = ( + f"WHEN feature IN ({_IC_LORA_IDS}) THEN 'ic-lora'\n " + if _IC_LORA_IDS + else "" +) + +GENERATION_STATS_CTE = f""" +WITH generation_stats AS ( + SELECT + id, + feature, + status, + error_code, + json_extract(spec, '$.params.model') AS model, + CASE + WHEN json_type(spec, '$.params.resolution') = 'text' + THEN json_extract(spec, '$.params.resolution') + END AS resolution_label, + json_extract(spec, '$.params.aspectRatio') AS aspect_ratio, + CASE + WHEN json_type(spec, '$.params.fps') IN ('integer', 'real') + THEN CAST(json_extract(spec, '$.params.fps') AS INTEGER) + END AS fps, + CASE + {_IC_LORA_GROUP}WHEN feature IN ( + 'text-to-video', + 'image-to-video', + 'audio-to-video', + 'retake', + 'extend' + ) THEN feature + WHEN COALESCE(json_array_length(spec, '$.params.loras'), 0) > 0 THEN 'lora' + ELSE feature + END AS feature_group, + json_extract(spec, '$.params.loras[0].catalogId') AS lora_catalog_id, + json_extract(spec, '$.params.loras[0].displayName') AS lora_name, + CASE + WHEN feature IN ('retake', 'extend') THEN NULL + WHEN feature = 'audio-to-video' + AND json_type(spec, '$.params.fps') IN ('integer', 'real') + AND CAST(json_extract(spec, '$.params.fps') AS INTEGER) > 0 + THEN ROUND(( + CAST(json_extract(spec, '$.params.numFrames') AS REAL) - 1 + ) / CAST(json_extract(spec, '$.params.fps') AS INTEGER)) + ELSE CAST(json_extract(spec, '$.params.duration') AS REAL) + END AS render_duration_s, + CASE + WHEN feature IN ('retake', 'extend') + THEN CAST(json_extract(spec, '$.params.duration') AS REAL) + END AS edited_span_s, + created_at, + started_at, + finished_at, + CASE + WHEN started_at IS NOT NULL AND finished_at IS NOT NULL + THEN finished_at - started_at + END AS run_ms, + deleted_at IS NOT NULL AS is_deleted + FROM generations + WHERE status IN ('succeeded', 'failed', 'cancelled') +) +""" + + +def generation_stats_sql(body: str) -> str: + return GENERATION_STATS_CTE + body diff --git a/backend/services/gpu_info/gpu_info_impl.py b/backend/services/gpu_info/gpu_info_impl.py index 783ecdf9e..36d3028a1 100644 --- a/backend/services/gpu_info/gpu_info_impl.py +++ b/backend/services/gpu_info/gpu_info_impl.py @@ -155,9 +155,11 @@ def get_vram_total_gb(self) -> int | None: return None def get_available_ram_gb(self) -> int | None: - """Free/available system RAM, not total -- used to gate local generation on - Apple Silicon (unified memory shared with the OS/app, so total RAM alone - overstates real headroom).""" + """Free/available system RAM, not total — used for Darwin per-job sizing. + + Local-generation *eligibility* on Apple Silicon uses total RAM + (``get_vram_total_gb``), not this figure. + """ try: return int(psutil.virtual_memory().available // (1024**3)) except Exception: diff --git a/backend/services/ic_lora_pipeline/ic_lora_inference.py b/backend/services/ic_lora_pipeline/ic_lora_inference.py new file mode 100644 index 000000000..5cad69bdb --- /dev/null +++ b/backend/services/ic_lora_pipeline/ic_lora_inference.py @@ -0,0 +1,208 @@ +"""Types, chunk planning and the streamed encode for one IC-LoRA run (see ``ltx_ic_lora_pipeline``).""" + +from __future__ import annotations + +import logging +from collections.abc import Generator, Iterator +from dataclasses import dataclass, replace +from typing import TYPE_CHECKING, TypedDict + +import torch + +from runtime_config.ic_lora_chunking import IC_LORA_CHUNK_CARRY_FRAMES +from services.audio_channels import stereo_waveform +from services.ltx_pipeline_common import encode_video_output, video_chunks_number +from services.services_utils import AudioOrNone, AudioType, PipelineTilingType, TilingConfigType + +if TYPE_CHECKING: + from ltx_pipelines.chunks import ChunkConfig + from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput + +logger = logging.getLogger(__name__) + + +class PipelineKwargs(TypedDict): + """Arguments shared by ``pipeline(...)`` and ``pipeline.stream_chunks(...)``.""" + + prompt: str + seed: int + height: int + width: int + num_frames: int + frame_rate: float + images: list[LtxImageInput] + video_conditioning: list[tuple[str, float]] + tiling_config: PipelineTilingType + skip_stage_2: bool + conditioning_attention_mask: torch.Tensor | None + + +@dataclass(frozen=True, slots=True) +class InferenceResult: + """What one IC-LoRA run hands to the encoder. + + A chunked job streams: ``video`` (and ``audio``, when the model made it) are iterators + that run the windows while the caller reads them. The caller must encode inside the + denoising progress scope. ``audio_sampling_rate`` is set only for that streamed audio. + ``streams`` lists the generators behind a streamed run. Call ``close_streams`` when the + encode ends, also on failure or cancel, so the reference video is released. + """ + + video: torch.Tensor | Iterator[torch.Tensor] + audio: AudioOrNone | Iterator[AudioType] + num_frames: int + tiling_config: TilingConfigType | None + audio_sampling_rate: int | None = None + streams: tuple[Iterator[object], ...] = () + + +def close_streams(result: InferenceResult) -> None: + """Close the generators of a streamed run. A stream already finished closes cleanly.""" + for stream in result.streams: + if isinstance(stream, Generator): + stream.close() + + +def encode_streamed_output( + video: torch.Tensor | Iterator[torch.Tensor], + audio: AudioOrNone | Iterator[AudioType], + audio_sampling_rate: int | None, + *, + fps: int, + output_path: str, +) -> None: + """Encode a chunked job. The windows are one video stream, like the upstream CLI.""" + from ltx_pipelines.utils.media_io import encode_video + + encode_video( + video=video, + fps=fps, + audio=audio, + output_path=output_path, + video_chunks_number=1, + audio_sampling_rate=audio_sampling_rate, + ) + + +def plan_chunks( + chunk_pixel_frames: int | None, + *, + width: int, + height: int, + num_frames: int, + frame_rate: float, +) -> tuple[ChunkConfig | None, int]: + """(chunk config, window count) for the window the job budget chose. + + ``None`` means one pass. The budget decides, so the rule is not run again here.""" + if chunk_pixel_frames is None: + return None, 1 + from ltx_core.types import VideoPixelShape + from ltx_pipelines.chunks import ChunkConfig + from ltx_pipelines.chunks.layout import uniform_chunk_layouts + + config = ChunkConfig( + chunk_pixel_frames=chunk_pixel_frames, next_video_carry_frames=IC_LORA_CHUNK_CARRY_FRAMES + ) + layouts = uniform_chunk_layouts( + target_pixel_shape=VideoPixelShape( + batch=1, frames=num_frames, height=height, width=width, fps=frame_rate + ), + config=config, + ) + return config, len(layouts) + + +def _load_source_audio(path: str, device: torch.device) -> AudioOrNone: + from ltx_pipelines.utils.media_io import decode_audio_from_file + + src = decode_audio_from_file(path, device) + if src is None: + return None + # decode_audio_from_file returns (1, channels, samples), but encode_video's writer + # expects a 2D (channels, samples) tensor with exactly 2 channels. Feeding the 3D + # tensor flattens it in planar order (LL..RR) and it gets misread as interleaved + # stereo (LRLR..) -> the audio plays sped up and loops. Drop the batch dim and + # normalize to stereo. + waveform = stereo_waveform(src.waveform) + if waveform.ndim == 3: + waveform = waveform.squeeze(0) + return replace(src, waveform=waveform) + + +def resolve_output_audio( + result: InferenceResult, + *, + mute_audio: bool, + source_audio_path: str | None, + num_frames: int, + frame_rate: float, + device: torch.device, +) -> tuple[AudioOrNone | Iterator[AudioType], int | None]: + """Audio and sample rate to encode. + + "off" drops it entirely; "source" muxes the input clip's soundtrack and discards the + prompt-synthesized model audio; otherwise keep the generated audio. + """ + if mute_audio: + return None, None + if source_audio_path is None: + return result.audio, result.audio_sampling_rate + audio = _load_source_audio(source_audio_path, device) + if audio is None: + return None, None + v_dur = num_frames / frame_rate + # Trim the source soundtrack to the generated video's length. A longer + # source (e.g. an 8s clip rendered to 5s) would otherwise keep playing + # over a frozen last frame. + max_samples = int(round(v_dur * audio.sampling_rate)) + if audio.waveform.shape[-1] > max_samples: + audio = replace(audio, waveform=audio.waveform[..., :max_samples]) + a_dur = audio.waveform.shape[-1] / audio.sampling_rate + logger.info( + "[ic-lora] source audio: %dHz %dch %.2fs (video %.2fs)%s", + audio.sampling_rate, audio.waveform.shape[0], a_dur, v_dur, + "" if abs(a_dur - v_dur) < 0.1 else " MISMATCH", + ) + return audio, None + + +def encode_result( + result: InferenceResult, + *, + output_path: str, + num_frames: int, + frame_rate: float, + mute_audio: bool, + source_audio_path: str | None, + streamed: bool, + device: torch.device, +) -> None: + """Mux the audio and encode the video. The streams close on success, failure and cancel. + + That releases the reference video, which a temp file delete needs on Windows. + """ + try: + audio, audio_rate = resolve_output_audio( + result, + mute_audio=mute_audio, + source_audio_path=source_audio_path, + num_frames=num_frames, + frame_rate=frame_rate, + device=device, + ) + # round(), not int(): avoids truncating e.g. 23.976 -> 23 (encode_video int()s again). + fps = round(frame_rate) + if streamed: + encode_streamed_output(result.video, audio, audio_rate, fps=fps, output_path=output_path) + else: + assert not isinstance(audio, Iterator) # a one-pass job never streams audio + encode_video_output( + video=result.video, + audio=audio, + fps=fps, + output_path=output_path, + video_chunks_number_value=video_chunks_number(result.num_frames, result.tiling_config), + ) + finally: + close_streams(result) diff --git a/backend/services/ic_lora_pipeline/ic_lora_pipeline.py b/backend/services/ic_lora_pipeline/ic_lora_pipeline.py index bc0afc513..43804811c 100644 --- a/backend/services/ic_lora_pipeline/ic_lora_pipeline.py +++ b/backend/services/ic_lora_pipeline/ic_lora_pipeline.py @@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Protocol from api_types import ImageConditioningInput +from runtime_config.ic_lora_tiling import IcLoraTiling if TYPE_CHECKING: import torch @@ -24,6 +25,8 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + stage_2_ic_lora: bool = False, + tiling: IcLoraTiling | None = None, ) -> "IcLoraPipeline": ... @@ -44,5 +47,6 @@ def generate( source_audio_path: str | None = None, mute_audio: bool = False, conditioning_mask_path: str | None = None, + chunk_pixel_frames: int | None = None, ) -> None: ... diff --git a/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py b/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py index fcd140f3f..0bfc814ba 100644 --- a/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py +++ b/backend/services/ic_lora_pipeline/ltx_ic_lora_pipeline.py @@ -6,22 +6,32 @@ import logging import re import struct -from collections.abc import Iterator +import time +from dataclasses import replace from pathlib import Path +from typing import TYPE_CHECKING import numpy as np import torch from numpy.typing import NDArray from api_types import ImageConditioningInput +from runtime_config.ic_lora_tiling import IC_LORA_TILE_OVERLAP, IcLoraTiling +from services.ic_lora_pipeline.ic_lora_inference import ( + InferenceResult, + PipelineKwargs, + encode_result, + plan_chunks, +) from services.ltx_pipeline_common import ( auto_tiling_config, build_model_paths, - encode_video_output, offload_mode_for_prefetch_count, - video_chunks_number, ) -from services.services_utils import AudioOrNone, PipelineTilingType, TilingConfigType, device_supports_fp8 +from services.services_utils import PipelineTilingType, device_supports_fp8 + +if TYPE_CHECKING: + from ltx_pipelines.chunks import ChunkConfig logger = logging.getLogger(__name__) @@ -40,6 +50,8 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + stage_2_ic_lora: bool = False, + tiling: IcLoraTiling | None = None, ) -> "LTXIcLoraPipeline": return LTXIcLoraPipeline( checkpoint_path=checkpoint_path, @@ -52,6 +64,8 @@ def create( video_vae_path=video_vae_path, audio_vae_path=audio_vae_path, duration_head_path=duration_head_path, + stage_2_ic_lora=stage_2_ic_lora, + tiling=tiling, ) def __init__( @@ -67,20 +81,24 @@ def __init__( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + stage_2_ic_lora: bool = False, + tiling: IcLoraTiling | None = None, ) -> None: from ltx_core.loader.primitives import LoraPathStrengthAndSDOps from ltx_core.loader.sd_ops import LTXV_LORA_COMFY_RENAMING_MAP from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy - from ltx_pipelines.ic_lora import ICLoraPipeline - from ltx_pipelines.utils.types import OffloadMode + from ltx_pipelines.ic_lora import DEFAULT_IC_LORA_STAGES + from services.ic_lora_pipeline.tiled_ic_lora_pipeline import TiledICLoraPipeline self._device = device + self._stage_2_ic_lora = stage_2_ic_lora + self._tiling = tiling self._validate_lora_keys(lora_path) lora_entry = LoraPathStrengthAndSDOps(path=lora_path, strength=lora_strength, sd_ops=LTXV_LORA_COMFY_RENAMING_MAP) self._checkpoint_path = checkpoint_path self._quantization = build_fp8_cast_policy(checkpoint_path) if device_supports_fp8(device) else None offload_mode = offload_mode_for_prefetch_count(streaming_prefetch_count, device) - self.pipeline = ICLoraPipeline( + self.pipeline = TiledICLoraPipeline( model_paths=build_model_paths( checkpoint_path, gemma_root, @@ -93,14 +111,30 @@ def __init__( device=device, quantization=self._quantization, offload_mode=offload_mode, + # Stage 2 keeps the IC-LoRA and the reference. The default recipe drops both. + stages=( + (DEFAULT_IC_LORA_STAGES[0], replace(DEFAULT_IC_LORA_STAGES[1], apply_ic_lora=True)) + if stage_2_ic_lora + else None + ), + ) + + def _tile_stage_1(self, stage_width: int, stage_height: int, tiling: IcLoraTiling) -> None: + """Tile the transformer on stage 1 at the tile size that fits this canvas. + + The tile follows the canvas orientation, which is known only here, so the stage + list is set per job. A pipeline serves one job at a time. + """ + from ltx_pipelines.ic_lora import spatial_tiled_ic_lora_stages + + tile_width, tile_height = tiling.tile_size(stage_width, stage_height) + logger.info("[ic-lora] tiled: %dx%d tiles on %dx%d", tile_width, tile_height, stage_width, stage_height) + self.pipeline.stages = spatial_tiled_ic_lora_stages( + tile_height=tile_height, + tile_width=tile_width, + overlap_fraction=IC_LORA_TILE_OVERLAP, + apply_ic_lora=(True, False), ) - # use_lora_in_stage_2 conditions stage 2 on the full-res reference video (~doubles - # the attention sequence). A fully-resident stage 2 (offload_mode NONE, i.e. no - # streaming_prefetch_count was set) can overflow VRAM even on high-VRAM cards. - # Tracked here so _ensure_stage_2_streams_for_lora can force streaming, once, the - # first time use_lora_in_stage_2 is actually requested -- construction-time, not - # per-call, per services.patches.ic_lora_stage2_lora's note on this. See there. - self._stage_2_streams = offload_mode != OffloadMode.NONE @staticmethod def _validate_lora_keys(lora_path: str) -> None: @@ -144,24 +178,6 @@ def _validate_lora_keys(lora_path: str) -> None: name, len(adapter_keys), len(targeted), ) - def _ensure_stage_2_streams_for_lora(self) -> None: - """Force stage 2 onto the streaming path the first time use_lora_in_stage_2 is - requested, and keep it that way for this pipeline's lifetime (construction-time - override, not a per-call one -- see the note in services.patches.ic_lora_stage2_lora). - No-op if stage 2 already streams (streaming_prefetch_count was already set).""" - if self._stage_2_streams: - return - from ltx_pipelines.utils.blocks import DiffusionStage - - self.pipeline.stage_2 = DiffusionStage.from_checkpoint( # type: ignore[reportUnknownMemberType] - self._checkpoint_path, - self.pipeline.dtype, - self._device, - quantization=self._quantization, - offload_mode=offload_mode_for_prefetch_count(1, self._device), - ) - self._stage_2_streams = True - def _run_inference( self, prompt: str, @@ -175,10 +191,13 @@ def _run_inference( tiling_config: PipelineTilingType, skip_stage_2: bool, conditioning_attention_mask: torch.Tensor | None, - ) -> tuple[torch.Tensor | Iterator[torch.Tensor], AudioOrNone, TilingConfigType | None]: - from ltx_pipelines.utils.args import ImageConditioningInput as _LtxImageInput + chunk_config: ChunkConfig | None = None, + ) -> InferenceResult: + """Run the pipeline. A chunked job streams: ``__call__`` would collect every + decoded window on the GPU first.""" + from ltx_pipelines.utils.types import ImageConditioningInput as _LtxImageInput - video, audio, resolved_tiling = self.pipeline( + kwargs = PipelineKwargs( prompt=prompt, seed=seed, height=height, @@ -191,7 +210,17 @@ def _run_inference( skip_stage_2=skip_stage_2, conditioning_attention_mask=conditioning_attention_mask, ) - return video, audio, resolved_tiling + if chunk_config is None: + result = self.pipeline(**kwargs) + return InferenceResult(result.video, result.audio, result.num_frames, result.tiling_config) + from ltx_pipelines.chunks import split_decoded_chunks + + chunks, resolved_frames, resolved_tiling = self.pipeline.stream_chunks( + **kwargs, chunk_config=chunk_config + ) + video, audio, audio_sampling_rate = split_decoded_chunks(chunks) + streams = (video, chunks) if audio is None else (video, audio, chunks) + return InferenceResult(video, audio, resolved_frames, resolved_tiling, audio_sampling_rate, streams) def _load_mask_tensor(self, path: str, num_frames: int) -> torch.Tensor: """Load an outpaint mask video as a (1, 1, F, H, W) float tensor in [0, 1]. @@ -214,28 +243,6 @@ def _load_mask_tensor(self, path: str, num_frames: int) -> torch.Tensor: single = torch.as_tensor(gray, dtype=torch.float32).to(self._device) # (H, W) return single[None, None, None].expand(1, 1, num_frames, -1, -1) # (1, 1, F, H, W) broadcast view - def _load_source_audio(self, path: str) -> AudioOrNone: - from dataclasses import replace - - from ltx_pipelines.utils.media_io import decode_audio_from_file - - src = decode_audio_from_file(path, self._device) - if src is None: - return None - # decode_audio_from_file returns (1, channels, samples), but encode_video's writer - # expects a 2D (channels, samples) tensor with exactly 2 channels. Feeding the 3D - # tensor flattens it in planar order (LL..RR) and it gets misread as interleaved - # stereo (LRLR..) -> the audio plays sped up and loops. Drop the batch dim and - # normalize to stereo. - waveform = src.waveform - if waveform.ndim == 3: - waveform = waveform.squeeze(0) - if waveform.shape[0] == 1: - waveform = waveform.repeat(2, 1) - elif waveform.shape[0] > 2: - waveform = waveform[:2] - return replace(src, waveform=waveform) - @torch.inference_mode() def generate( self, @@ -254,13 +261,20 @@ def generate( source_audio_path: str | None = None, mute_audio: bool = False, conditioning_mask_path: str | None = None, + chunk_pixel_frames: int | None = None, ) -> None: - # When Stage 2 runs, optionally keep the IC-LoRA active in it (so the - # transformation survives refinement). Honoured by - # services.patches.ic_lora_stage2_lora; a no-op attribute otherwise. if use_lora_in_stage_2: - self._ensure_stage_2_streams_for_lora() - self.pipeline.use_lora_in_stage_2 = use_lora_in_stage_2 # type: ignore[attr-defined] + logger.warning("[ic-lora] use_lora_in_stage_2 is deprecated and ignored (LTXP-514)") + # A still at a negative frame index is an IC-LoRA reference token. A stage + # without the IC-LoRA has no place for it, so fail before any GPU work. + if any(img.frame_idx < 0 for img in images) and not skip_stage_2 and not self._stage_2_ic_lora: + raise ValueError("A reference still at a negative frame index needs the IC-LoRA on stage 2") + if self._tiling is not None: + if not skip_stage_2: + raise ValueError("A tiled IC-LoRA runs a single stage") + if any(img.frame_idx < 0 for img in images): + # Upstream keeps such a token whole in every tile instead of cropping it. + raise ValueError("A tiled IC-LoRA cannot take a reference still") # Stage-1-only outputs height//2 x width//2. Scale the passed canvas by # resolution_factor so the result lands at the desired fraction of native # (2.0 = native target, 1.0 = half). Round to a multiple of 128: stage-1 runs @@ -277,12 +291,28 @@ def generate( if conditioning_mask_path is not None else None ) + if self._tiling is not None: + self._tile_stage_1(width // 2, height // 2, self._tiling) # Stage-1 (the heavy diffusion) runs at half the passed canvas — this is the main # cost driver, so log it to make slow runs explicable. logger.info( "[ic-lora] stage-1 %dx%d, %d frames (skip_stage_2=%s, resolution_factor=%.2f)", width // 2, height // 2, num_frames, skip_stage_2, resolution_factor, ) + chunk_config, chunk_count = plan_chunks( + chunk_pixel_frames, + width=width, + height=height, + num_frames=num_frames, + frame_rate=frame_rate, + ) + if chunk_config is not None: + logger.info( + "[ic-lora] chunked: %d windows of %d frames (carry %d)", + chunk_count, + chunk_config.chunk_pixel_frames, + chunk_config.next_video_carry_frames, + ) cuda = torch.cuda.is_available() and self._device.type == "cuda" base_gb = 0.0 if cuda: @@ -295,57 +325,57 @@ def generate( "reduce frames (shorter clip / lower FPS) or RES FACTOR.", free_gb, ) + started = time.monotonic() try: - video, audio, resolved_tiling = self._run_inference( - prompt=prompt, - seed=seed, - height=height, - width=width, - num_frames=num_frames, - frame_rate=frame_rate, - images=images, - video_conditioning=video_conditioning, - tiling_config=auto_tiling_config(), - skip_stage_2=skip_stage_2, - conditioning_attention_mask=conditioning_attention_mask, - ) - # Audio: "off" drops it entirely; "source" muxes the input clip's soundtrack and - # discards the prompt-synthesized model audio; otherwise keep the generated audio. - if mute_audio: - audio = None - elif source_audio_path is not None: - audio = self._load_source_audio(source_audio_path) - if audio is not None: - from dataclasses import replace + from services.denoising_progress import distilled_total_steps, track_denoising - v_dur = num_frames / frame_rate - # Trim the source soundtrack to the generated video's length. A longer - # source (e.g. an 8s clip rendered to 5s) would otherwise keep playing - # over a frozen last frame. - max_samples = int(round(v_dur * audio.sampling_rate)) - if audio.waveform.shape[-1] > max_samples: - audio = replace(audio, waveform=audio.waveform[..., :max_samples]) - a_dur = audio.waveform.shape[-1] / audio.sampling_rate - logger.info( - "[ic-lora] source audio: %dHz %dch %.2fs (video %.2fs)%s", - audio.sampling_rate, audio.waveform.shape[0], a_dur, v_dur, - "" if abs(a_dur - v_dur) < 0.1 else " MISMATCH", - ) - chunks = video_chunks_number(num_frames, resolved_tiling) - # round(), not int(): avoids truncating e.g. 23.976 -> 23 (encode_video int()s again). - encode_video_output(video=video, audio=audio, fps=round(frame_rate), output_path=output_path, video_chunks_number_value=chunks) + with track_denoising(distilled_total_steps(stage_2=not skip_stage_2) * chunk_count): + result = self._run_inference( + prompt=prompt, + seed=seed, + height=height, + width=width, + num_frames=num_frames, + frame_rate=frame_rate, + images=images, + video_conditioning=video_conditioning, + tiling_config=auto_tiling_config(), + skip_stage_2=skip_stage_2, + conditioning_attention_mask=conditioning_attention_mask, + chunk_config=chunk_config, + ) + encode_result( + result, + output_path=output_path, + num_frames=num_frames, + frame_rate=frame_rate, + mute_audio=mute_audio, + source_audio_path=source_audio_path, + streamed=chunk_config is not None, + device=self._device, + ) except torch.cuda.OutOfMemoryError: logger.error( "[ic-lora] CUDA OOM at stage-1 %dx%d x %d frames — lower RES FACTOR or trim the clip.", width // 2, height // 2, num_frames, ) raise + # The tile and the window count tell a tiled run from a plain one, so run times can be + # compared. This line has no CUDA condition, so a Mac run is measured too. + tile = "none" + if self._tiling is not None: + tile_width, tile_height = self._tiling.tile_size(width // 2, height // 2) + tile = f"{tile_width}x{tile_height}" + logger.info( + "[ic-lora] run time %.0fs (%d frames, tile %s, %d window(s))", + time.monotonic() - started, num_frames, tile, chunk_count, + ) if cuda: peak_alloc = torch.cuda.max_memory_allocated(self._device) / 1e9 peak_resv = torch.cuda.max_memory_reserved(self._device) / 1e9 # base = weights resident at start; (peak_alloc - base) = activation demand; # reserved = what nvidia-smi shows (allocator pool, usually higher than alloc). logger.info( - "[ic-lora] VRAM: base %.1f / peak alloc %.1f / peak reserved %.1f GB", - base_gb, peak_alloc, peak_resv, + "[ic-lora] VRAM: base %.1f / peak alloc %.1f / peak reserved %.1f GB (tile %s, %d window(s))", + base_gb, peak_alloc, peak_resv, tile, chunk_count, ) diff --git a/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py b/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py new file mode 100644 index 000000000..3edad5c4b --- /dev/null +++ b/backend/services/ic_lora_pipeline/tiled_ic_lora_pipeline.py @@ -0,0 +1,159 @@ +"""ICLoraPipeline subclass that tiles the reference-video VAE encode. + +Upstream encodes an untiled stage's guide in one pass (``encode_tiling`` stays +``None`` unless the stage itself uses transformer tiles). Catalog IC-LoRAs +default to ``skip_stage_2`` and do not use those tiles, so a large reference +still OOMs. This override keeps Desktop's rule: ``TileSizeConfig.default()`` +only when the post-downscale encode canvas is larger than one tile. + +Encode size matches ltxv-api tia2v: VAE-align the stage canvas to +``VIDEO_SCALE_FACTORS * downscale``, then the encode is that divided by +``downscale``. Tiling is decided on the post-downscale tensor. + +Stills at a negative ``frame_idx`` (``REFERENCE_STILL_FRAME_IDX``, -1 for Layout To Render) are 1-frame IC-LoRA +reference tokens. Upstream rejects a negative index and would drop it. They are +appended after the reference video, as ``[target | video ref | still]``. +""" + +from __future__ import annotations + +import logging + +from ltx_core.conditioning import ConditioningItem +from ltx_core.model.video_vae import TileSizeConfig, VideoEncoder +from ltx_core.types import VIDEO_SCALE_FACTORS +from ltx_pipelines.chunks import Chunk, MakeVideoConditionings, SequentialVideoFrameSource +from ltx_pipelines.ic_lora import ICLoraPipeline, ICLoraStageConfig, _ICLoraRunContext # pyright: ignore[reportPrivateUsage] +from ltx_pipelines.utils.helpers import combined_image_conditionings + +from api_types import REFERENCE_STILL_FRAME_IDX + +logger = logging.getLogger(__name__) + + +def reference_encode_canvas( + stage1_height: int, stage1_width: int, downscale_factor: int +) -> tuple[int, int]: + """VAE-aligned (height, width) the reference encode is sized from.""" + if downscale_factor < 1: + raise ValueError(f"downscale_factor must be >= 1, got {downscale_factor}") + align_h = VIDEO_SCALE_FACTORS.height * downscale_factor + align_w = VIDEO_SCALE_FACTORS.width * downscale_factor + return stage1_height // align_h * align_h, stage1_width // align_w * align_w + + +def reference_encode_tiling(height: int, width: int, num_frames: int) -> TileSizeConfig | None: + """``None`` when the canvas fits in one default tile; otherwise tile. + + Time stays tiled (80 frames, overlap 24). An untiled 217-frame encode at 1024x576 + spilled a 32 GB RTX 5090 into shared memory in stage 2. The fal CG-aligned worker + untiled time on a B200 after a 1920x1024x201 job collapsed at frame 136. + """ + tile = TileSizeConfig.default() + if ( + num_frames <= tile.frames.tile_size + and height <= tile.height.tile_size + and width <= tile.width.tile_size + ): + return None + return tile + + +def encode_tiling_for_canvas( + height: int, width: int, num_frames: int, downscale_factor: int +) -> TileSizeConfig | None: + """Tile choice for a stage canvas after VAE alignment and reference downscale.""" + pass_height, pass_width = reference_encode_canvas(height, width, downscale_factor) + encode_height = pass_height // downscale_factor + encode_width = pass_width // downscale_factor + return reference_encode_tiling(encode_height, encode_width, num_frames) + + +class TiledICLoraPipeline(ICLoraPipeline): + def _video_conditionings( + self, + ctx: _ICLoraRunContext, + stage_config: ICLoraStageConfig, + frame_sources: dict[str, SequentialVideoFrameSource], + ) -> MakeVideoConditionings: + """Same closure as upstream, with Desktop's reference-encode tiling. + + A stage that runs without the IC-LoRA (stage 2 of the default recipe) attaches no + reference video upstream, so it takes the parent closure and skips the VAE encode. + """ + if not stage_config.apply_ic_lora: + return super()._video_conditionings(ctx, stage_config, frame_sources) + from ltx_pipelines.chunks.conditionings import ( + assert_image_frames_in_clip, + image_conditionings_for_chunk, + reference_video_conditionings_for_chunk, + ) + + frame_images = [img for img in ctx.images if img.frame_idx >= 0] + stills = [img for img in ctx.images if img.frame_idx < 0] + if any(img.frame_idx != REFERENCE_STILL_FRAME_IDX for img in stills): + raise ValueError(f"A reference still must use frame_idx {REFERENCE_STILL_FRAME_IDX}") + if stills and self.reference_downscale_factor != 1: + # A still is placed at full stage size. A LoRA with a reference downscale + # scales reference positions, which this path does not do for stills. + raise ValueError( + "A reference still at a negative frame index needs a LoRA with " + f"reference_downscale_factor 1, got {self.reference_downscale_factor}" + ) + assert_image_frames_in_clip(frame_images, ctx.num_frames) + + def make(chunk: Chunk) -> list[ConditioningItem]: + if chunk.video is None: + return [] + height = int(chunk.video.shape[-2]) * VIDEO_SCALE_FACTORS.height + width = int(chunk.video.shape[-1]) * VIDEO_SCALE_FACTORS.width + dtype = chunk.video.dtype + device = chunk.video.device + count = chunk.layout.pixel_frames + downscale = self.reference_downscale_factor + encode_tiling = encode_tiling_for_canvas(height, width, count, downscale) + logger.info( + "[ic-lora] reference VAE encode tiling %s (stage %dx%d, %d frames, downscale=%d)", + encode_tiling, + height, + width, + count, + downscale, + ) + + def encode(enc: VideoEncoder) -> list[ConditioningItem]: + return [ + *image_conditionings_for_chunk( + chunk, + images=frame_images, + video_encoder=enc, + color_space=ctx.color_space, + ), + *reference_video_conditionings_for_chunk( + chunk, + video_conditioning=ctx.video_conditioning, + video_encoder=enc, + frame_sources=frame_sources, + downscale_factor=downscale, + reference_temporal_scale_factor=self.reference_temporal_scale_factor, + conditioning_attention_strength=ctx.conditioning_attention_strength, + conditioning_attention_mask=ctx.conditioning_attention_mask, + encode_tiling=encode_tiling, + color_space=ctx.color_space, + ), + # frame_idx != 0 becomes a VideoConditionByKeyframeIndex. Its time + # offset puts a -1 still at [-1, 0) / fps, as a 1-frame token. + *combined_image_conditionings( + images=stills, + height=height, + width=width, + video_encoder=enc, + dtype=dtype, + device=device, + color_space=ctx.color_space, + ), + ] + + return self.image_conditioner(encode) + + return make diff --git a/backend/services/ltx_api_client/ltx_api_client.py b/backend/services/ltx_api_client/ltx_api_client.py index b054efbbc..07a7963a2 100644 --- a/backend/services/ltx_api_client/ltx_api_client.py +++ b/backend/services/ltx_api_client/ltx_api_client.py @@ -3,10 +3,14 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Any, Protocol +from typing import Any, Literal, Protocol from api_types import ExtendMode, RetakeMode, VideoCameraMotion +INSUFFICIENT_FUNDS_ERROR_TYPE = "insufficient_funds_error" +PAYMENT_DECLINED_ERROR_TYPE = "payment_declined_error" +CONTENT_FILTERED_ERROR_TYPE = "content_filtered_error" + @dataclass(frozen=True) class LTXRetakeResult: @@ -19,7 +23,7 @@ def __init__( self, status_code: int, detail: str, - stage: str | None = None, + stage: Literal["upload_init", "upload_parse", "upload_put"] | None = None, *, provider_error_type: str | None = None, provider_message: str | None = None, @@ -54,6 +58,7 @@ def generate_text_to_video( fps: float, generate_audio: bool, camera_motion: VideoCameraMotion = "none", + enhance_prompt: bool = True, ) -> bytes: ... @@ -70,6 +75,7 @@ def generate_image_to_video( generate_audio: bool, camera_motion: VideoCameraMotion = "none", last_frame_uri: str | None = None, + enhance_prompt: bool = True, ) -> bytes: ... @@ -83,6 +89,7 @@ def generate_audio_to_video( model: str, resolution: str, last_frame_uri: str | None = None, + enhance_prompt: bool = True, ) -> bytes: ... diff --git a/backend/services/ltx_api_client/ltx_api_client_impl.py b/backend/services/ltx_api_client/ltx_api_client_impl.py index 02b29062e..7b4e6def8 100644 --- a/backend/services/ltx_api_client/ltx_api_client_impl.py +++ b/backend/services/ltx_api_client/ltx_api_client_impl.py @@ -11,7 +11,13 @@ from api_types import ExtendMode, RetakeMode, VideoCameraMotion from pydantic import BaseModel, ConfigDict, ValidationError -from services.ltx_api_client.ltx_api_client import LTXAPIClientError, LTXRetakeResult +from services.ltx_api_client.ltx_api_client import ( + CONTENT_FILTERED_ERROR_TYPE, + INSUFFICIENT_FUNDS_ERROR_TYPE, + LTXAPIClientError, + LTXRetakeResult, + PAYMENT_DECLINED_ERROR_TYPE, +) from services.http_client.http_client import HTTPClient, HttpResponseLike, HttpTransportError from services.services_utils import JSONValue @@ -34,6 +40,37 @@ {"queued", "pending", "processing", "running", "in_progress", "starting", "started"} ) +_JOB_ERROR_TYPE_TO_STATUS = { + INSUFFICIENT_FUNDS_ERROR_TYPE: 402, + PAYMENT_DECLINED_ERROR_TYPE: 402, + CONTENT_FILTERED_ERROR_TYPE: 422, +} + + +def _terminal_job_error( + *, status: _AsyncJobStatusPayload, label: str, rid: str +) -> LTXAPIClientError: + """Error for a terminal (non-completed, non-in-progress) job status.""" + error_type = status.error.type if status.error is not None else None + provider_message = status.error.message if status.error is not None else None + http_status = ( + _JOB_ERROR_TYPE_TO_STATUS.get(error_type, 500) + if error_type is not None + else 500 + ) + if error_type == CONTENT_FILTERED_ERROR_TYPE: + detail = f"Content rejected by safety filters{rid}" + elif provider_message: + detail = f"{provider_message}{rid}" + else: + detail = f"{label} job ended with status '{status.status}'{rid}" + return LTXAPIClientError( + http_status, + detail, + provider_error_type=error_type, + provider_message=provider_message, + ) + def _loggable_payload(payload: dict[str, JSONValue]) -> dict[str, object]: return { @@ -65,21 +102,6 @@ def _loggable_payload(payload: dict[str, JSONValue]) -> dict[str, object]: } -class _RetakeNestedPayload(BaseModel): - model_config = ConfigDict(extra="ignore") - video_url: str | None = None - - -class _RetakeResponsePayload(BaseModel): - model_config = ConfigDict(extra="allow") - video_url: str | None = None - output_video: str | None = None - result: _RetakeNestedPayload | None = None - - def extract_video_url(self) -> str | None: - return self.video_url or self.output_video or (self.result.video_url if self.result is not None else None) - - class _LTXErrorDetailPayload(BaseModel): model_config = ConfigDict(extra="ignore") type: str | None = None @@ -101,13 +123,19 @@ class _AsyncSubmitPayload(BaseModel): class _AsyncJobErrorPayload(BaseModel): model_config = ConfigDict(extra="ignore") + type: str | None = None message: str | None = None +class _AsyncJobResultPayload(BaseModel): + model_config = ConfigDict(extra="ignore") + video_url: str | None = None + + class _AsyncJobStatusPayload(BaseModel): - model_config = ConfigDict(extra="allow") + model_config = ConfigDict(extra="ignore") status: str - result: dict[str, Any] | None = None + result: _AsyncJobResultPayload | None = None error: _AsyncJobErrorPayload | None = None @@ -118,11 +146,12 @@ def __init__( ltx_api_base_url: str, *, poll_interval_s: float = 3.0, - async_max_wait_s: float = 600.0, + async_max_wait_s: float = 1200.0, ) -> None: self._http = http self._base_url = ltx_api_base_url.rstrip("/") - # Async (v2) polling cadence/ceiling; small values injected in tests. + # Async (v2) polling cadence/ceiling; small values injected in tests. Ceiling + # for long Pro clips, which can take up to ~20 minutes. self._poll_interval_s = poll_interval_s self._async_max_wait_s = async_max_wait_s @@ -168,6 +197,7 @@ def generate_text_to_video( fps: float, generate_audio: bool, camera_motion: VideoCameraMotion = "none", + enhance_prompt: bool = True, ) -> bytes: payload: dict[str, JSONValue] = { "prompt": prompt, @@ -176,12 +206,14 @@ def generate_text_to_video( "duration": duration, "fps": fps, "generate_audio": generate_audio, + "enhance_prompt": enhance_prompt, } mapped_camera_motion = self._map_camera_motion(camera_motion) if mapped_camera_motion is not None: payload["camera_motion"] = mapped_camera_motion - response = self._post_json("/v1/text-to-video", api_key=api_key, payload=payload, timeout=1200) - return self._extract_video_bytes(response, api_key) + return self._run_async_job( + api_key=api_key, endpoint="/v2/text-to-video", payload=payload, label="Text-to-video" + ) def generate_image_to_video( self, @@ -196,6 +228,7 @@ def generate_image_to_video( generate_audio: bool, camera_motion: VideoCameraMotion = "none", last_frame_uri: str | None = None, + enhance_prompt: bool = True, ) -> bytes: payload: dict[str, JSONValue] = { "prompt": prompt, @@ -205,14 +238,16 @@ def generate_image_to_video( "duration": duration, "fps": fps, "generate_audio": generate_audio, + "enhance_prompt": enhance_prompt, } mapped_camera_motion = self._map_camera_motion(camera_motion) if mapped_camera_motion is not None: payload["camera_motion"] = mapped_camera_motion if last_frame_uri is not None: payload["last_frame_uri"] = last_frame_uri - response = self._post_json("/v1/image-to-video", api_key=api_key, payload=payload, timeout=1200) - return self._extract_video_bytes(response, api_key) + return self._run_async_job( + api_key=api_key, endpoint="/v2/image-to-video", payload=payload, label="Image-to-video" + ) def generate_audio_to_video( self, @@ -224,19 +259,22 @@ def generate_audio_to_video( model: str, resolution: str, last_frame_uri: str | None = None, + enhance_prompt: bool = True, ) -> bytes: payload: dict[str, JSONValue] = { "prompt": prompt, "audio_uri": audio_uri, "model": model, "resolution": resolution, + "enhance_prompt": enhance_prompt, } if image_uri is not None: payload["image_uri"] = image_uri if last_frame_uri is not None: payload["last_frame_uri"] = last_frame_uri - response = self._post_json("/v1/audio-to-video", api_key=api_key, payload=payload, timeout=1200) - return self._extract_video_bytes(response, api_key) + return self._run_async_job( + api_key=api_key, endpoint="/v2/audio-to-video", payload=payload, label="Audio-to-video" + ) def retake( self, @@ -249,10 +287,10 @@ def retake( mode: RetakeMode, model: str, ) -> LTXRetakeResult: - return self._run_video_edit( + return self._run_async_video_edit( api_key=api_key, video_path=video_path, - endpoint="/v1/retake", + endpoint="/v2/retake", label="Retake", edit_payload={ "start_time": float(start_time), @@ -273,9 +311,6 @@ def extend( mode: ExtendMode, model: str, ) -> LTXRetakeResult: - # Extend uses the async v2 endpoint (submit → poll → download): a 12s Pro extend - # takes minutes, which the sync v1 endpoint can't hold open without the connection - # being reset mid-response. Mirrors ltx-studio's extend path. return self._run_async_video_edit( api_key=api_key, video_path=video_path, @@ -289,10 +324,14 @@ def extend( prompt=prompt, ) - def _upload_source_video(self, *, api_key: str, video_path: str) -> str: + def _upload_source_video(self, *, api_key: str, video_path: str, label: str) -> str: """Upload the source clip, mapping upload-stage failures to friendly messages.""" try: return self.upload_file(api_key=api_key, file_path=video_path) + except HttpTransportError as exc: + # Connection failed/reset/timed out somewhere in the flow — surface as a clean + # retryable error instead of a raw 500. + raise LTXAPIClientError(504, f"{label} request to the LTX API failed; please retry.") from exc except LTXAPIClientError as exc: if exc.stage == "upload_init": err_text = self._extract_error_detail(exc.detail) @@ -304,7 +343,7 @@ def _upload_source_video(self, *, api_key: str, video_path: str) -> str: raise LTXAPIClientError(500, f"Video upload failed: {err_text}") from exc raise - def _run_video_edit( + def _run_async_video_edit( self, *, api_key: str, @@ -314,88 +353,63 @@ def _run_video_edit( edit_payload: dict[str, JSONValue], prompt: str, ) -> LTXRetakeResult: - """Synchronous upload → POST → parse flow for the v1 /retake endpoint. - - Gets back either raw video bytes, a JSON payload with a downloadable URL, or a 422 - safety reject. - """ - storage_uri = self._upload_source_video(api_key=api_key, video_path=video_path) + """Async (v2) flow for retake/extend: upload the source clip, then submit → poll → download.""" + storage_uri = self._upload_source_video(api_key=api_key, video_path=video_path, label=label) payload: dict[str, JSONValue] = {"video_uri": storage_uri, **edit_payload} if prompt: payload["prompt"] = prompt - response = self._post_json(endpoint, api_key=api_key, payload=payload, timeout=600) + video_bytes = self._run_async_job(api_key=api_key, endpoint=endpoint, payload=payload, label=label) + return LTXRetakeResult(video_bytes=video_bytes, result_payload=None) - rid = self._fmt_request_id(response) - if response.status_code == 200: - content_type = str(response.headers.get("Content-Type", "")).lower() - if "video" in content_type or "octet-stream" in content_type: - return LTXRetakeResult(video_bytes=response.content, result_payload=None) - - try: - payload_obj = response.json() - except json.JSONDecodeError as exc: - raise LTXAPIClientError(500, f"Unexpected response format: {response.text[:200]}{rid}") from exc - - try: - parsed_payload = _RetakeResponsePayload.model_validate(payload_obj) - except ValidationError as exc: - raise LTXAPIClientError(500, f"Unexpected response format{rid}") from exc - - video_url = parsed_payload.extract_video_url() - if video_url: - dl_resp = self._http.get(video_url, timeout=120) - if dl_resp.status_code == 200: - return LTXRetakeResult(video_bytes=dl_resp.content, result_payload=None) - raise LTXAPIClientError(500, f"Failed to download {label.lower()} video: {dl_resp.status_code}{rid}") - - response_payload = parsed_payload.model_dump(mode="python") - return LTXRetakeResult(video_bytes=None, result_payload=response_payload) - - if response.status_code == 422: - raise LTXAPIClientError(422, f"Content rejected by safety filters{rid}") - - error_text = response.text[:500] if response.text else "Unknown error" - raise LTXAPIClientError(response.status_code, f"{label} API error: {error_text}{rid}") - - def _run_async_video_edit( + def _run_async_job( self, *, api_key: str, - video_path: str, endpoint: str, + payload: dict[str, JSONValue], label: str, - edit_payload: dict[str, JSONValue], - prompt: str, - ) -> LTXRetakeResult: - """Async (v2) flow: upload → submit job → poll until done → download the result. + ) -> bytes: + """Async (v2) flow: submit job → poll until done → download the result. - The v2 endpoints respond immediately with a job id, so no connection is held open + Shared by generation (t2v/i2v/a2v) and edits (retake/extend). The v2 + endpoints respond immediately with a job id, so no connection is held open for the whole (minutes-long) generation. ``endpoint`` is the submit path (e.g. ``/v2/extend``); polling is ``GET {endpoint}/{id}``. """ try: - storage_uri = self._upload_source_video(api_key=api_key, video_path=video_path) - - payload: dict[str, JSONValue] = {"video_uri": storage_uri, **edit_payload} - if prompt: - payload["prompt"] = prompt - submit = self._post_json(endpoint, api_key=api_key, payload=payload, timeout=120) rid = self._fmt_request_id(submit) if submit.status_code == 422: - raise LTXAPIClientError(422, f"Content rejected by safety filters{rid}") + provider_error_type, provider_message, _ = self._extract_generation_error(submit) + raise LTXAPIClientError( + 422, + f"Content rejected by safety filters{rid}", + provider_error_type=provider_error_type, + provider_message=provider_message, + request_id=self._request_id(submit), + ) if submit.status_code not in (200, 202): - error_text = submit.text[:500] if submit.text else "Unknown error" - raise LTXAPIClientError(submit.status_code, f"{label} API error: {error_text}{rid}") + provider_error_type, provider_message, error_text = self._extract_generation_error(submit) + raise LTXAPIClientError( + submit.status_code, + f"{label} API error: {error_text}{rid}", + provider_error_type=provider_error_type, + provider_message=provider_message, + request_id=self._request_id(submit), + ) try: job = _AsyncSubmitPayload.model_validate(submit.json()) except (json.JSONDecodeError, ValidationError) as exc: - raise LTXAPIClientError(500, f"Unexpected {label.lower()} submit response{rid}") from exc + raise LTXAPIClientError( + 500, f"Unexpected {label.lower()} submit response{rid}", request_id=self._request_id(submit) + ) from exc if not job.id: - raise LTXAPIClientError(500, f"{label} API returned no job id{rid}") + raise LTXAPIClientError( + 500, f"{label} API returned no job id{rid}", request_id=self._request_id(submit) + ) logger.info("LTXV %s job accepted: id=%s%s", label.lower(), job.id, rid) video_url = self._poll_job(api_key=api_key, endpoint=endpoint, job_id=job.id, label=label) @@ -406,8 +420,11 @@ def _run_async_video_edit( dl_resp = self._get_with_retries(video_url, headers=None, timeout=300, label=label) if dl_resp.status_code != 200: raise LTXAPIClientError(500, f"Failed to download {label.lower()} video: {dl_resp.status_code}") - logger.info("LTXV %s complete: %d bytes (job %s)", label.lower(), len(dl_resp.content), job.id) - return LTXRetakeResult(video_bytes=dl_resp.content, result_payload=None) + if not dl_resp.content: + raise LTXAPIClientError(500, f"Downloaded {label.lower()} video is empty") + content = dl_resp.content + logger.info("LTXV %s complete: %d bytes", label.lower(), len(content)) + return content except HttpTransportError as exc: # Connection failed/reset/timed out somewhere in the flow — surface as a clean # retryable error instead of a raw 500. @@ -442,8 +459,23 @@ def _poll_job(self, *, api_key: str, endpoint: str, job_id: str, label: str) -> ) rid = self._fmt_request_id(resp) if resp.status_code != 200: - error_text = resp.text[:500] if resp.text else "Unknown error" - raise LTXAPIClientError(resp.status_code, f"{label} status check failed: {error_text}{rid}") + if resp.status_code == 422: + provider_error_type, provider_message, _ = self._extract_generation_error(resp) + raise LTXAPIClientError( + 422, + f"Content rejected by safety filters{rid}", + provider_error_type=provider_error_type, + provider_message=provider_message, + request_id=self._request_id(resp), + ) + provider_error_type, provider_message, error_text = self._extract_generation_error(resp) + raise LTXAPIClientError( + resp.status_code, + f"{label} status check failed: {error_text}{rid}", + provider_error_type=provider_error_type, + provider_message=provider_message, + request_id=self._request_id(resp), + ) try: status = _AsyncJobStatusPayload.model_validate(resp.json()) except (json.JSONDecodeError, ValidationError) as exc: @@ -454,23 +486,24 @@ def _poll_job(self, *, api_key: str, endpoint: str, job_id: str, label: str) -> logger.debug("LTXV %s job %s status=%s (poll %d, %.0fs)", label.lower(), job_id, status.status, polls, elapsed) if status.status == "completed": - video_url = (status.result or {}).get("video_url") - if not isinstance(video_url, str) or not video_url: + video_url = status.result.video_url if status.result is not None else None + if not video_url: raise LTXAPIClientError(500, f"{label} job completed without a video_url{rid}") logger.info("LTXV %s job %s completed after %.0fs (%d polls)", label.lower(), job_id, elapsed, polls) return video_url if status.status not in _IN_PROGRESS_STATUSES: # failed / error / canceled / rejected / unknown — surface it instead of # polling until the timeout masks the cause behind a 504. - detail = ( - status.error.message - if status.error and status.error.message - else f"{label} job ended with status '{status.status}'" - ) + err = _terminal_job_error(status=status, label=label, rid=rid) logger.warning( - "LTXV %s job %s ended status=%s after %.0fs: %s", label.lower(), job_id, status.status, elapsed, detail + "LTXV %s job %s ended status=%s after %.0fs: %s", + label.lower(), + job_id, + status.status, + elapsed, + err.detail, ) - raise LTXAPIClientError(500, detail) + raise err time.sleep(self._poll_interval_s) @@ -528,55 +561,13 @@ def upload_file(self, *, file_path: str, api_key: str) -> str: logger.info("LTXV source video uploaded in %.1fs", time.monotonic() - put_started) return storage_uri - def _extract_video_bytes(self, response: Any, api_key: str) -> bytes: - rid = self._fmt_request_id(response) - if response.status_code != 200: - provider_error_type, provider_message, err = self._extract_generation_error(response) - raise LTXAPIClientError( - response.status_code, - f"LTX API generation failed ({response.status_code}): {err}{rid}", - stage="generation", - provider_error_type=provider_error_type, - provider_message=provider_message, - request_id=self._request_id(response), - ) - - content_type = str(response.headers.get("Content-Type", "")).lower() - if "video" in content_type or "octet-stream" in content_type: - if not response.content: - raise LTXAPIClientError(500, f"LTX API returned empty video body{rid}", stage="generation") - return response.content - - try: - payload = cast(dict[str, Any], response.json()) - except Exception as exc: - raise LTXAPIClientError(500, f"Unexpected LTX API response format{rid}", stage="generation") from exc - - video_url = self._extract_video_url(payload) - if video_url is not None: - dl_resp = self._http.get( - video_url, - headers={"Authorization": f"Bearer {api_key}"}, - timeout=120, - ) - if dl_resp.status_code != 200: - raise LTXAPIClientError(500, f"Failed to download generated video ({dl_resp.status_code}){rid}", stage="generation") - if not dl_resp.content: - raise LTXAPIClientError(500, f"Downloaded generated video is empty{rid}", stage="generation") - return dl_resp.content - - error_text = payload.get("error") or payload.get("message") or payload.get("detail") - if isinstance(error_text, str) and error_text: - raise LTXAPIClientError(500, f"LTX API returned an error payload: {error_text}{rid}", stage="generation") - raise LTXAPIClientError(500, f"LTX API response did not include a video payload{rid}", stage="generation") - @staticmethod - def _request_id(response: Any) -> str | None: + def _request_id(response: HttpResponseLike) -> str | None: rid = response.headers.get("x-request-id") return str(rid) if rid else None @staticmethod - def _fmt_request_id(response: Any) -> str: + def _fmt_request_id(response: HttpResponseLike) -> str: rid = response.headers.get("x-request-id") return f" [request_id={rid}]" if rid else "" @@ -587,7 +578,7 @@ def _extract_error_detail(detail: str) -> str: return detail.split(":", 1)[1].strip() @staticmethod - def _extract_generation_error(response: Any) -> tuple[str | None, str | None, str]: + def _extract_generation_error(response: HttpResponseLike) -> tuple[str | None, str | None, str]: if response.text: error_text = response.text[:500] else: @@ -612,23 +603,6 @@ def _extract_generation_error(response: Any) -> tuple[str | None, str | None, st error_text = provider_message return provider_error_type, provider_message, error_text - @staticmethod - def _extract_video_url(payload: dict[str, Any]) -> str | None: - direct_keys = ("video_url", "output_video", "output_video_url", "output_url", "url") - for key in direct_keys: - value = payload.get(key) - if isinstance(value, str) and value: - return value - - nested = payload.get("result") - if isinstance(nested, dict): - nested_payload = cast(dict[str, Any], nested) - for key in direct_keys: - value = nested_payload.get(key) - if isinstance(value, str) and value: - return value - return None - @staticmethod def _json_headers(api_key: str) -> dict[str, str]: return { diff --git a/backend/services/ltx_api_client/ltx_api_errors.py b/backend/services/ltx_api_client/ltx_api_errors.py new file mode 100644 index 000000000..20f75b520 --- /dev/null +++ b/backend/services/ltx_api_client/ltx_api_errors.py @@ -0,0 +1,37 @@ +"""Map LTX API auth failures onto one error the generation dialog can act on.""" + +from __future__ import annotations + +from _routes._errors import HTTPError +from services.ltx_api_client.ltx_api_client import INSUFFICIENT_FUNDS_ERROR_TYPE, LTXAPIClientError + +LTX_INVALID_API_KEY = "LTX_INVALID_API_KEY" +LTX_API_KEY_MISSING = "LTX_API_KEY_MISSING" +LTX_API_PROMPT_EMBEDDING_FAILED = "LTX_API_PROMPT_EMBEDDING_FAILED" + +LTX_INVALID_API_KEY_MESSAGE = "This LTX API key isn’t valid." +LTX_API_KEY_MISSING_MESSAGE = "Add an LTX API key to generate." +LTX_API_PROMPT_EMBEDDING_FAILED_MESSAGE = "LTX API text encoding failed." +_LTX_INSUFFICIENT_FUNDS_MESSAGE = ( + "Your LTX API credits are insufficient for this generation. Buy more credits and try again." +) + +_AUTH_REJECTED = frozenset({401, 403}) + + +def missing_ltx_api_key_error() -> HTTPError: + return HTTPError(400, LTX_API_KEY_MISSING_MESSAGE, code=LTX_API_KEY_MISSING) + + +def map_ltx_api_client_error(exc: LTXAPIClientError) -> HTTPError: + """Turn a provider failure into the error the app shows. + + 402 insufficient funds keeps its own code (Buy Credits). 401 and 403 share + one code so the dialog can open Settings on the LTX key. Everything else + stays the provider's status and detail. + """ + if exc.status_code == 402 and exc.provider_error_type == INSUFFICIENT_FUNDS_ERROR_TYPE: + return HTTPError(402, _LTX_INSUFFICIENT_FUNDS_MESSAGE, code="LTX_INSUFFICIENT_FUNDS") + if exc.status_code in _AUTH_REJECTED: + return HTTPError(exc.status_code, LTX_INVALID_API_KEY_MESSAGE, code=LTX_INVALID_API_KEY) + return HTTPError(exc.status_code, exc.detail) diff --git a/backend/services/ltx_pipeline_common.py b/backend/services/ltx_pipeline_common.py index 5b1bff1d2..c6810017b 100644 --- a/backend/services/ltx_pipeline_common.py +++ b/backend/services/ltx_pipeline_common.py @@ -3,12 +3,16 @@ from __future__ import annotations from collections.abc import Iterator +import logging +import platform from typing import TYPE_CHECKING import torch -from api_types import ImageConditioningInput -from services.services_utils import AudioOrNone, PipelineTilingType, TilingConfigType, device_supports_fp8 +from runtime_config.runtime_policy import CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, should_disk_stream_cuda_weights +from services.services_utils import AudioOrNone, PipelineTilingType, TilingConfigType + +logger = logging.getLogger(__name__) if TYPE_CHECKING: from ltx_core.components.guiders import MultiModalGuiderParams @@ -34,6 +38,17 @@ def host_available_bytes() -> int: return int(psutil.virtual_memory().available) +def host_total_gib() -> int | None: + """Total system RAM in GiB, or None if it cannot be queried.""" + try: + import psutil + + return int(psutil.virtual_memory().total // (1024**3)) + except Exception: + logger.warning("Failed to query total system RAM", exc_info=True) + return None + + def diffvae_activation_budget_bytes(device: torch.device | None = None) -> int: """Bytes DiffVAE decode tiling may treat as free activation memory. @@ -129,7 +144,9 @@ def offload_mode_for_prefetch_count(streaming_prefetch_count: int | None, device (an int); which *kind* of streaming depends on the device's memory model: - CUDA: system RAM is separate from VRAM, so OffloadMode.CPU pins the blocks in host - RAM and streams them to the smaller VRAM — the fast streaming path. + RAM and streams them to the smaller VRAM — the fast streaming path. On Linux, + that pin is unswappable and needs ~36 GB host RAM; 32 GB machines (the advertised + local-gen floor) must use OffloadMode.DISK instead (LTX-Desktop#163). - MPS (Apple Silicon): CPU-pinned weights live in the *same* unified RAM as the GPU, so OffloadMode.CPU (which pins every block, ~46 GB for the bf16 transformer) OOMs. OffloadMode.DISK mmaps blocks from the checkpoint through a small pinned buffer @@ -142,6 +159,24 @@ def offload_mode_for_prefetch_count(streaming_prefetch_count: int | None, device return OffloadMode.NONE if device.type == "mps": return OffloadMode.DISK + if device.type == "cuda": + system = platform.system() + ram_gb = host_total_gib() if system == "Linux" else None + if should_disk_stream_cuda_weights(system, ram_gb): + if ram_gb is None: + logger.info( + "Using OffloadMode.DISK on Linux CUDA: host RAM unknown; " + "failing closed below the %s GiB pinned-CPU floor (LTX-Desktop#163).", + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + ) + else: + logger.info( + "Using OffloadMode.DISK on Linux CUDA: host RAM %s GiB is below the " + "%s GiB floor for pinned CPU streaming (LTX-Desktop#163).", + ram_gb, + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + ) + return OffloadMode.DISK return OffloadMode.CPU @@ -161,103 +196,3 @@ def encode_video_output( output_path=output_path, video_chunks_number=video_chunks_number_value, ) - - -class DistilledNativePipeline: - """Fast native pipeline implementation moved from ltx2_server.py.""" - - def __init__( - self, - checkpoint_path: str, - gemma_root: str | None, - device: torch.device | None = None, - fp8transformer: bool = False, - ) -> None: - from ltx_core.quantization.fp8_cast import build_policy as build_fp8_cast_policy - from ltx_pipelines.utils.blocks import ( - AudioDecoder, - DiffusionStage, - ImageConditioner, - PromptEncoder, - VideoDecoder, - ) - from ltx_pipelines.utils.helpers import get_device - - if device is None: - device = get_device() - - self.device = device - self.dtype = torch.bfloat16 - model_paths = build_model_paths(checkpoint_path, gemma_root) - - self.prompt_encoder = PromptEncoder( - model_paths, self.dtype, device, - ) - self.image_conditioner = ImageConditioner( - checkpoint_path, self.dtype, device, - ) - self.stage = DiffusionStage.from_checkpoint( # type: ignore[reportUnknownMemberType] - checkpoint_path, - self.dtype, - device, - quantization=build_fp8_cast_policy(checkpoint_path) if fp8transformer and device_supports_fp8(device) else None, - ) - self.video_decoder = VideoDecoder(checkpoint_path, self.dtype, device) - self.audio_decoder = AudioDecoder(checkpoint_path, self.dtype, device) - - @torch.inference_mode() - def __call__( - self, - prompt: str, - seed: int, - height: int, - width: int, - num_frames: int, - frame_rate: float, - images: list[ImageConditioningInput], - tiling_config: TilingConfigType | None = None, - ) -> tuple[torch.Tensor | Iterator[torch.Tensor], AudioOrNone]: - from ltx_core.components.noisers import GaussianNoiser - from ltx_pipelines.utils.args import ImageConditioningInput as _LtxImageInput - from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES - from ltx_pipelines.utils.denoisers import SimpleDenoiser - from ltx_pipelines.utils.helpers import image_conditionings_by_replacing_latent - from ltx_pipelines.utils.types import ModalitySpec - - generator = torch.Generator(device=self.device).manual_seed(seed) - noiser = GaussianNoiser(generator=generator) - dtype = torch.bfloat16 - - (ctx_p,) = self.prompt_encoder([prompt]) - video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding - - sigmas = torch.Tensor(DISTILLED_SIGMA_VALUES).to(self.device) - - ltx_images = [_LtxImageInput(img.path, img.frame_idx, img.strength) for img in images] - conditionings = self.image_conditioner( - lambda enc: image_conditionings_by_replacing_latent( - images=ltx_images, - height=height, - width=width, - video_encoder=enc, - dtype=dtype, - device=self.device, - ) - ) - - video_state, audio_state = self.stage( - denoiser=SimpleDenoiser(video_context, audio_context), - sigmas=sigmas, - noiser=noiser, - width=width, - height=height, - frames=num_frames, - fps=frame_rate, - video=ModalitySpec(context=video_context, conditionings=conditionings), - audio=ModalitySpec(context=audio_context) if audio_context is not None else None, - ) - - assert video_state is not None - decoded_video = self.video_decoder(video_state.latent, tiling_config) - decoded_audio = self.audio_decoder(audio_state.latent) if audio_state is not None else None - return decoded_video, decoded_audio diff --git a/backend/services/media_probe.py b/backend/services/media_probe.py new file mode 100644 index 000000000..4acc1bf16 --- /dev/null +++ b/backend/services/media_probe.py @@ -0,0 +1,462 @@ +from __future__ import annotations + +import logging +import mimetypes +from collections.abc import Iterator +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path +from typing import TYPE_CHECKING, Literal, assert_never, cast + +import av +from PIL import Image + +from server_utils.oriented_image import open_oriented_image +from services.records import MediaError +from api_types import ( + AudioAssetMetadata, + AudioMeta, + AssetMetadata, + ImageAssetMetadata, + ImageMeta, + MediaKind, + VideoAssetMetadata, + VideoMeta, +) + +if TYPE_CHECKING: + import numpy as np + +ALLOWED_IMAGE_SUFFIXES = frozenset({".png", ".jpg", ".jpeg", ".webp"}) +ALLOWED_VIDEO_SUFFIXES = frozenset({".mp4", ".webm", ".mov"}) +ALLOWED_AUDIO_SUFFIXES = frozenset({".wav", ".mp3", ".m4a"}) +ALLOWED_INGEST_SUFFIXES = ( + ALLOWED_IMAGE_SUFFIXES | ALLOWED_VIDEO_SUFFIXES | ALLOWED_AUDIO_SUFFIXES +) + +MAX_IMAGE_BYTES = 50 * 1024 * 1024 +MAX_AUDIO_BYTES = 100 * 1024 * 1024 +MAX_VIDEO_BYTES = 100 * 1024 * 1024 +MAX_IMAGE_PIXELS = 50_000_000 + +_EXT_BY_MIME = { + "image/png": ".png", + "image/jpeg": ".jpg", + "image/webp": ".webp", + "image/gif": ".gif", + "video/mp4": ".mp4", + "video/webm": ".webm", + "audio/wav": ".wav", + "audio/mpeg": ".mp3", + "audio/mp4": ".m4a", +} + +_IMAGE_FORMAT_MIME = { + "PNG": "image/png", + "JPEG": "image/jpeg", + "WEBP": "image/webp", + # A GIF is only made here, by a cutout recipe. Its suffix is not an allowed upload. + "GIF": "image/gif", +} + +logger = logging.getLogger(__name__) + + +@dataclass(frozen=True) +class _AvProbe: + width: int + height: int + duration_ms: int + audio_stream_count: int + size_bytes: int + fps: float | None = None + + +def extension_for_mime(mime_type: str) -> str: + mapped = _EXT_BY_MIME.get(mime_type) + if mapped is not None: + return mapped + guessed = mimetypes.guess_extension(mime_type) + if guessed is not None: + return guessed + return ".bin" + + +def _as_int(value: object) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"expected int, got {type(value)!r}") + return value + + +def _as_float(value: object) -> float: + if isinstance(value, bool): + raise TypeError(f"expected float, got {type(value)!r}") + if isinstance(value, (int, float)): + return float(value) + if isinstance(value, Fraction): + return float(value) + raise TypeError(f"expected float, got {type(value)!r}") + + +def _duration_ms(container: object, stream: object) -> int: + container_duration = getattr(container, "duration", None) + if container_duration is not None: + seconds = _as_float(container_duration) / 1_000_000 + if seconds > 0: + return round(seconds * 1000) + stream_duration = getattr(stream, "duration", None) + time_base = getattr(stream, "time_base", None) + if stream_duration is not None and time_base is not None: + seconds = _as_float(stream_duration) * _as_float(time_base) + if seconds > 0: + return round(seconds * 1000) + raise ValueError("failed to compute media duration") + + +def _tagged_rotation(raw: object) -> int | None: + if not isinstance(raw, str) or not raw.strip(): + return None + try: + return int(round(float(raw))) % 360 + except ValueError: + return None + + +def _side_data_rotation(container: object, stream: object) -> int | None: + """Display-matrix rotation from the first decoded frame, or None when it cannot be read.""" + decode = getattr(container, "decode", None) + if not callable(decode): + return None + try: + frame = next(cast(Iterator[object], decode(stream)), None) + except Exception: + return None + if frame is None: + return None + rotation = getattr(frame, "rotation", None) + if isinstance(rotation, bool) or not isinstance(rotation, int): + return None + return rotation % 360 + + +def _display_size( + stream: object, container: object, width: int, height: int +) -> tuple[int, int]: + """Coded size swapped for a 90° or 270° display rotation, matching oriented images.""" + metadata = getattr(stream, "metadata", None) + tags = cast("dict[str, object]", metadata) if isinstance(metadata, dict) else {} + rotation = _tagged_rotation(tags.get("rotate")) + if rotation is None: + rotation = _side_data_rotation(container, stream) + if rotation in (90, 270): + return height, width + return width, height + + +def _probe_av(path: Path, *, required_type: Literal["video", "audio"]) -> _AvProbe: + try: + container: object = av.open(str(path)) # type: ignore[reportUnknownMemberType] + except Exception as exc: + logger.warning("unreadable media file %s: %s", path, exc) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + try: + streams_obj = getattr(container, "streams") + streams = list(cast(list[object], streams_obj)) + matched: object | None = None + audio_stream_count = 0 + for stream in streams: + stream_type = str(getattr(stream, "type", "")) + if stream_type == "audio": + audio_stream_count += 1 + if matched is None and stream_type == required_type: + matched = stream + fps: float | None = None + if matched is None: + logger.warning("no %s track in %s", required_type, path) + raise MediaError("UNREADABLE_MEDIA", f"no {required_type} track") + codec_context = getattr(matched, "codec_context", None) + if required_type == "video": + width = _as_int(getattr(codec_context, "width", 0)) + height = _as_int(getattr(codec_context, "height", 0)) + if width <= 0 or height <= 0: + logger.warning( + "invalid video dimensions for %s: %sx%s", path, width, height + ) + raise MediaError( + "UNREADABLE_MEDIA", + f"invalid video dimensions: {width}x{height}", + ) + width, height = _display_size(matched, container, width, height) + fps = _stream_fps(matched) + elif required_type == "audio": + width = 0 + height = 0 + else: + assert_never(required_type) + duration_ms = _duration_ms(container, matched) + if duration_ms < 1: + logger.warning("invalid %s duration for %s", required_type, path) + raise MediaError( + "UNREADABLE_MEDIA", f"invalid {required_type} duration" + ) + return _AvProbe( + width=width, + height=height, + duration_ms=duration_ms, + audio_stream_count=audio_stream_count, + size_bytes=path.stat().st_size, + fps=fps, + ) + finally: + close = getattr(container, "close", None) + if callable(close): + close() + + +def _stream_fps(stream: object) -> float | None: + """None when the container has no usable rate. Ingest stores that and continues.""" + rate = getattr(stream, "average_rate", None) + if rate is None: + return None + try: + fps = _as_float(rate) + except TypeError: + return None + if fps <= 0: + return None + return fps + + +def video_fps(path: Path) -> float: + """Frame rate of the first video stream. Ingest stores this on the asset.""" + try: + container: object = av.open(str(path)) # type: ignore[reportUnknownMemberType] + except Exception as exc: + logger.warning("unreadable media file %s: %s", path, exc) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + try: + streams_obj = getattr(container, "streams") + streams = list(cast(list[object], streams_obj)) + matched: object | None = None + for stream in streams: + if str(getattr(stream, "type", "")) == "video": + matched = stream + break + if matched is None: + raise MediaError("UNREADABLE_MEDIA", "no video track") + fps = _stream_fps(matched) + if fps is None: + raise MediaError("UNREADABLE_MEDIA", "missing frame rate") + return fps + finally: + close = getattr(container, "close", None) + if callable(close): + close() + + +def video_frame_count(path: Path) -> int: + """Frames in the first video stream. Counts packets, so a container with no stored count works.""" + try: + container = av.open(str(path)) # type: ignore[reportUnknownMemberType] + except Exception as exc: + logger.warning("unreadable media file %s: %s", path, exc) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + try: + if not container.streams.video: + raise MediaError("UNREADABLE_MEDIA", "no video track") + stream = container.streams.video[0] + return sum(1 for packet in container.demux(stream) if packet.size > 0) # type: ignore[reportUnknownMemberType, reportUnknownVariableType] + finally: + container.close() + + +def validate_ingest_source(source: Path) -> None: + suffix = source.suffix.lower() + if suffix not in ALLOWED_INGEST_SUFFIXES: + logger.warning("unsupported media type for %s", source) + raise MediaError("UNSUPPORTED_MEDIA", "unsupported media type") + if suffix in ALLOWED_IMAGE_SUFFIXES: + limit = MAX_IMAGE_BYTES + elif suffix in ALLOWED_AUDIO_SUFFIXES: + limit = MAX_AUDIO_BYTES + else: + return + try: + size_bytes = source.stat().st_size + except OSError as exc: + logger.warning("unreadable media file %s: %s", source, exc) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + if size_bytes > limit: + logger.warning( + "file too large %s: %s bytes exceeds %s", source, size_bytes, limit + ) + raise MediaError("FILE_TOO_LARGE", "file too large") + + +def probe_file(path: Path) -> tuple[MediaKind, str, AssetMetadata]: + try: + return _probe_file(path) + except MediaError: + raise + except Exception as exc: + logger.warning("unreadable media file %s: %s", path, exc) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + + +def _probe_file(path: Path) -> tuple[MediaKind, str, AssetMetadata]: + mime = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + suffix = path.suffix.lower() + if mime.startswith("image/") or suffix in ALLOWED_IMAGE_SUFFIXES: + # Header only. exif_transpose decodes the bitmap, and a rotation does + # not change the pixel count, so reject oversized images before that. + with Image.open(path) as raw: + width, height = raw.size + fmt = str(raw.format or "").upper() + mapped = _IMAGE_FORMAT_MIME.get(fmt) + if mapped is None: + logger.warning("unsupported image format %s for %s", fmt, path) + raise MediaError("UNREADABLE_MEDIA", "unsupported image format") + if width <= 0 or height <= 0 or (width * height) > MAX_IMAGE_PIXELS: + logger.warning( + "image dimensions too large %s: %sx%s", path, width, height + ) + raise MediaError( + "IMAGE_DIMENSIONS_TOO_LARGE", + "image dimensions too large", + ) + image = open_oriented_image(path) + width, height = image.size + return ( + "image", + mapped, + ImageAssetMetadata( + mediaType="image", + metadata=ImageMeta(width=width, height=height), + ), + ) + if mime.startswith("video/") or suffix in ALLOWED_VIDEO_SUFFIXES: + mime = mime if mime.startswith("video/") else "video/mp4" + probed = _probe_av(path, required_type="video") + return ( + "video", + mime, + VideoAssetMetadata( + mediaType="video", + metadata=VideoMeta( + width=probed.width, + height=probed.height, + durationMs=probed.duration_ms, + sizeBytes=probed.size_bytes, + audioStreamCount=probed.audio_stream_count, + fps=probed.fps, + ), + ), + ) + if mime.startswith("audio/") or suffix in ALLOWED_AUDIO_SUFFIXES: + mime = mime if mime.startswith("audio/") else "audio/wav" + probed = _probe_av(path, required_type="audio") + bitrate = round((probed.size_bytes * 8) / (probed.duration_ms / 1000)) + if bitrate < 1: + logger.warning("invalid audio bitrate for %s", path) + raise MediaError("UNREADABLE_MEDIA", "invalid audio bitrate") + return ( + "audio", + mime, + AudioAssetMetadata( + mediaType="audio", + metadata=AudioMeta( + durationMs=probed.duration_ms, + bitrate=bitrate, + ), + ), + ) + logger.warning("unsupported media type for %s", path) + raise MediaError("UNSUPPORTED_MEDIA", "unsupported media type") + + +def media_has_audio(path: str) -> bool: + with av.open(path) as container: + return any(stream.type == "audio" for stream in container.streams) + + +def _frame_timestamp(frame: object, time_base: object) -> float | None: + timestamp = cast(float | None, getattr(frame, "time", None)) + if timestamp is None: + pts = getattr(frame, "pts", None) + if pts is not None and time_base is not None: + timestamp = float(pts * time_base) + return timestamp + + +def sample_gray_frames( + path: str, start: float, count: int, width: int, height: int +) -> list[np.ndarray]: + import numpy as np + + try: + container = av.open(path) + except av.FFmpegError: + return [] + try: + stream = container.streams.video[0] + time_base = stream.time_base + if start > 0 and time_base is not None: + try: + container.seek(int(start / time_base), stream=stream) + except av.FFmpegError: + pass + frames: list[np.ndarray] = [] + for frame in container.decode(video=0): + timestamp = _frame_timestamp(frame, time_base) + if timestamp is None or timestamp + 1e-3 < start: + continue + if len(frames) >= count: + break + gray = frame.reformat(width=width, height=height, format="gray") + frames.append(gray.to_ndarray().astype(np.float32)) + return frames + finally: + container.close() + + +def sample_rgb_mean_std( + path: str, + time_range: tuple[float, float], + fps: float, + width: int, + height: int, +) -> tuple[tuple[float, float, float], tuple[float, float, float]] | None: + import numpy as np + + start, end = time_range + chunks: list[np.ndarray] = [] + with av.open(path) as container: + stream = container.streams.video[0] + time_base = stream.time_base + if start > 0 and time_base is not None: + try: + container.seek(int(start / time_base), stream=stream) + except av.FFmpegError: + pass + for frame in container.decode(video=0): + timestamp = _frame_timestamp(frame, time_base) + if timestamp is None or timestamp + 1.0 / fps < start: + continue + if timestamp >= end: + break + pixels = frame.to_ndarray(format="rgb24") + if pixels.shape[1] != width or pixels.shape[0] != height: + pixels = np.asarray( + Image.fromarray(pixels).resize((width, height), Image.Resampling.LANCZOS) + ) + chunks.append(pixels.reshape(-1, 3).astype(np.float64)) + if not chunks: + return None + stacked = np.concatenate(chunks, axis=0) + mean_vals = stacked.mean(axis=0) + std_vals = stacked.std(axis=0) + return ( + (float(mean_vals[0]), float(mean_vals[1]), float(mean_vals[2])), + (float(std_vals[0]), float(std_vals[1]), float(std_vals[2])), + ) + diff --git a/backend/services/media_source.py b/backend/services/media_source.py new file mode 100644 index 000000000..635ff3737 --- /dev/null +++ b/backend/services/media_source.py @@ -0,0 +1,38 @@ +from __future__ import annotations + +import logging +from pathlib import Path + +from api_types import MediaKind +from services.records import AssetRecord, MediaError +from services.store import Store + +logger = logging.getLogger(__name__) + + +def require_source( + store: Store, asset_id: str, expected_kind: MediaKind +) -> tuple[AssetRecord, Path]: + record = store.get_asset(asset_id) + if record is None: + raise FileNotFoundError(asset_id) + if record.media_kind != expected_kind: + raise MediaError( + "UNSUPPORTED_MEDIA", + f"expected {expected_kind} asset, got {record.media_kind}", + ) + try: + source = Path(record.path).resolve() + except OSError as exc: + logger.warning("unreadable media file for asset %s", asset_id) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + try: + is_file = source.is_file() + except OSError: + is_file = False + if not is_file: + logger.warning( + "unreadable media file for asset %s: %s", asset_id, source + ) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") + return record, source diff --git a/backend/services/migrations.py b/backend/services/migrations.py new file mode 100644 index 000000000..e4401ed19 --- /dev/null +++ b/backend/services/migrations.py @@ -0,0 +1,91 @@ +from __future__ import annotations + +import sqlite3 +import time +from pathlib import Path + +MIGRATIONS_DIR = Path(__file__).resolve().parent / "schema" + + +def _sql_statements(script: str) -> list[str]: + statements: list[str] = [] + buffer = "" + for line in script.splitlines(keepends=True): + buffer += line + if not sqlite3.complete_statement(buffer): + continue + stmt = buffer.strip().rstrip(";").strip() + buffer = "" + if stmt: + statements.append(stmt) + leftover = buffer.strip() + if leftover: + raise ValueError(f"incomplete SQL in migration: {leftover[:120]}") + return statements + + +def apply_migrations(conn: sqlite3.Connection, migrations_dir: Path) -> None: + """Apply numbered ``NNNN_*.sql`` files with version > current. + + Each file is applied in a single transaction together with its + ``schema_migrations`` row. ``executescript`` is not used: it autocommits + DDL, so a crash between statements (or before the ledger insert) would + leave the DB unopenable. + + Pre-ship: editing 0001 and deleting the local DB is allowed. After ship, + add 0002+ — do not edit 0001 in place once users have the file. + """ + previous_isolation = conn.isolation_level + conn.isolation_level = None + foreign_keys_row = conn.execute("PRAGMA foreign_keys").fetchone() + restore_foreign_keys = ( + foreign_keys_row is not None and int(foreign_keys_row[0]) == 1 + ) + if restore_foreign_keys: + conn.execute("PRAGMA foreign_keys = OFF") + try: + conn.execute( + """ + CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY, + applied_at INTEGER NOT NULL + ) + """ + ) + row = conn.execute( + "SELECT COALESCE(MAX(version), 0) FROM schema_migrations" + ).fetchone() + current = int(row[0]) if row is not None else 0 + files = sorted(migrations_dir.glob("*.sql")) + for path in files: + prefix = path.name.split("_", 1)[0] + if not prefix.isdigit(): + continue + version = int(prefix) + if version <= current: + continue + statements = _sql_statements(path.read_text(encoding="utf-8")) + conn.execute("BEGIN IMMEDIATE") + try: + for statement in statements: + conn.execute(statement) + foreign_key_violation = conn.execute( + "PRAGMA foreign_key_check" + ).fetchone() + if foreign_key_violation is not None: + raise sqlite3.IntegrityError( + f"foreign key violation in migration {path.name}" + ) + conn.execute( + "INSERT INTO schema_migrations (version, applied_at) VALUES (?, ?)", + (version, int(time.time() * 1000)), + ) + conn.execute("COMMIT") + except Exception: + conn.execute("ROLLBACK") + raise + current = version + finally: + if restore_foreign_keys: + conn.execute("PRAGMA foreign_keys = ON") + conn.isolation_level = previous_isolation diff --git a/backend/services/patches/diffusion_interrupt.py b/backend/services/patches/diffusion_interrupt.py index 66cdff750..d93276285 100644 --- a/backend/services/patches/diffusion_interrupt.py +++ b/backend/services/patches/diffusion_interrupt.py @@ -1,14 +1,24 @@ -"""Monkey-patch: abort denoising between transformer forwards. +"""Monkey-patch: abort denoising between transformer forwards, and count steps. -``ltx_pipelines`` sampler loops have no interrupt callback. Every local video -path (distilled t2v/i2v, A2V, retake, extend, IC-LoRA) goes through +``ltx_pipelines`` sampler loops have no interrupt or progress callback. Every +local video path (distilled t2v/i2v, A2V, retake, extend, IC-LoRA) goes through ``DiffusionStage.__call__`` → ``loop(..., denoiser=...)``. Wrapping that denoiser checks cancel at every denoise call (res2s calls it twice per step). +Wrapping ``loop`` and intercepting ``tqdm`` iterations counts real denoise +steps once per loop iteration (not once per denoiser call). Totals come from +``services.denoising_progress.distilled_total_steps``, which uses the same +sigma schedules the pipelines pass in. Step-based progress reporting was +proposed by Sergio Gil (@jimeneztion). + Raising from the denoiser unwinds ``DiffusionStage.__call__``'s transformer context, so stage 2 / VAE / ffmpeg never run and ``diffusion_stage_cache`` ``_in_use`` drops. GPU weights stay loaded. +Wrap the argument named ``denoiser`` via ``signature.bind``, not ``args[0]``. +A positional reorder still hits the denoiser; a missing name raises at the +``__call__`` (once per stage), not per denoise step. + Remove once ltx-pipelines denoiser/loop accepts an interrupt callback. Usage: @@ -17,8 +27,11 @@ from __future__ import annotations +import functools import inspect -from collections.abc import Callable +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from dataclasses import dataclass from typing import Any, cast from ltx_pipelines.utils.blocks import DiffusionStage @@ -29,27 +42,90 @@ "ltx_pipelines.utils.blocks.DiffusionStage.__call__ missing — re-verify this patch on rev bump" ) _original_call = DiffusionStage.__call__ -assert "denoiser" in inspect.signature(_original_call).parameters, ( - "DiffusionStage.__call__ has no 'denoiser' parameter — re-verify this patch on rev bump" +_call_params = list(inspect.signature(_original_call).parameters) +assert len(_call_params) >= 2 and _call_params[0] == "self" and _call_params[1] == "denoiser", ( + "DiffusionStage.__call__ first positional after self is not 'denoiser' — " + "re-verify this patch on rev bump" ) -_signature_fn: object | None = None -_cached_signature: inspect.Signature | None = None -def _original_signature() -> inspect.Signature: - global _signature_fn, _cached_signature - fn = _original_call - if _signature_fn is not fn or _cached_signature is None: - _cached_signature = inspect.signature(fn) - _signature_fn = fn - return _cached_signature +@dataclass +class _TqdmStepCount: + yielded: int = 0 + counted: int = 0 + + def flush_completed(self) -> None: + """Count iterations the consumer completed but did not resume past. + + ``note_step`` runs after each ``yield``. ``euler_ancestral_denoising_loop`` + ``break``s on the terminal zero-sigma step, so that last resume never + happens even though the denoise ran. Flush only after a normal return — + cancel/exception must not count the aborted iteration. + """ + from services.denoising_progress import note_step + + while self.counted < self.yielded: + self.counted += 1 + note_step() + + +@contextmanager +def _count_tqdm_iterations() -> Iterator[_TqdmStepCount]: + """Count each sampler-loop tqdm iteration as one denoise step.""" + import ltx_pipelines.utils.samplers as samplers + + from services.denoising_progress import note_step + + original_tqdm = samplers.tqdm + state = _TqdmStepCount() + def counting_tqdm(iterable: Any = None, **kwargs: Any) -> Any: + inner = original_tqdm(iterable, **kwargs) + class _CountingTqdm: + def __iter__(self) -> Iterator[Any]: + for item in inner: + state.yielded += 1 + yield item + state.counted += 1 + note_step() + + def __len__(self) -> int: + return len(inner) + + return _CountingTqdm() + + samplers.tqdm = counting_tqdm # type: ignore[misc] + try: + yield state + finally: + samplers.tqdm = original_tqdm # type: ignore[misc] + + +def _loop_with_step_count(loop: Callable[..., Any]) -> Callable[..., Any]: + def wrapped(*args: Any, **kwargs: Any) -> Any: + with _count_tqdm_iterations() as state: + result = loop(*args, **kwargs) + state.flush_completed() + return result + + return wrapped + + +@functools.wraps(_original_call) def _call_with_interrupt(self: DiffusionStage, *args: Any, **kwargs: Any) -> Any: - bound = _original_signature().bind(self, *args, **kwargs) + bound = inspect.signature(_original_call).bind(self, *args, **kwargs) bound.apply_defaults() - original_denoiser = cast(Callable[..., Any], bound.arguments["denoiser"]) - bound.arguments["denoiser"] = wrap_denoiser(original_denoiser) + if "denoiser" not in bound.arguments: + raise TypeError("DiffusionStage.__call__ missing required argument: 'denoiser'") + bound.arguments["denoiser"] = wrap_denoiser(cast(Callable[..., Any], bound.arguments["denoiser"])) + if "loop" in bound.arguments: + loop = bound.arguments["loop"] + if loop is None: + from ltx_pipelines.utils.samplers import euler_denoising_loop + + loop = euler_denoising_loop + bound.arguments["loop"] = _loop_with_step_count(cast(Callable[..., Any], loop)) return _original_call(*bound.args, **bound.kwargs) diff --git a/backend/services/patches/diffusion_stage_cache.py b/backend/services/patches/diffusion_stage_cache.py index 7882b813a..00c15daf4 100644 --- a/backend/services/patches/diffusion_stage_cache.py +++ b/backend/services/patches/diffusion_stage_cache.py @@ -44,19 +44,19 @@ running, so the cache never survives past the generation it was built for. NON-CACHEABLE TRANSITIONS also evict (found live on the same RTX 5090, IC-LoRA -this time): IC-LoRA's ``use_lora_in_stage_2`` forces stage_2 onto the streaming -path (``LTXIcLoraPipeline._ensure_stage_2_streams_for_lora``, a deliberate -existing VRAM-safety mechanism -- streaming halves stage_2's resident -footprint since it conditions on the full-res reference video). That stage_2 -call correctly skips the cache (``_is_streaming`` is True), but skipping the -cache branch also means the cache-key-mismatch eviction below never fires -- -so stage_1's cached transformer stayed resident while stage_2 built its own -streaming transformer AND did its tiled conditioning VAE encode on top of it. -Observed: reserved VRAM climbed to 41.68 GB on the 31.82 GB card and hung -there for 150+ seconds with no progress (denoising loop never started). -Fix: the non-cacheable bypass branch (streaming stages, disabled setting) -evicts unconditionally before delegating to the original method, not just the -cache-hit/miss branch. +this time): a streaming stage_2 correctly skips the cache (``_is_streaming`` is +True), but skipping the cache branch also means the cache-key-mismatch eviction +below never fires -- so stage_1's cached transformer stayed resident while +stage_2 built its own streaming transformer AND did its tiled conditioning VAE +encode on top of it. Observed: reserved VRAM climbed to 41.68 GB on the 31.82 GB +card and hung there for 150+ seconds with no progress (denoising loop never +started). The original repro forced stage 2 onto streaming via Desktop-only +``use_lora_in_stage_2`` (``_ensure_stage_2_streams_for_lora``). That flag is +gone as of 1.3.0 / LTXP-514; IC-LoRA stage 2 is no longer forced onto +streaming. The eviction still matters for any streaming stage (low-VRAM +``streaming_models_loading``) or when the setting is off. Fix: the non-cacheable +bypass branch (streaming stages, disabled setting) evicts unconditionally +before delegating to the original method, not just the cache-hit/miss branch. Single-slot cache: only the most recently built transformer stays resident. Switching to a different checkpoint/LoRA/quantization config (or starting a @@ -111,6 +111,7 @@ from __future__ import annotations import gc +import inspect import logging import os import threading @@ -124,12 +125,25 @@ logger = logging.getLogger(__name__) +# Import-time: Desktop never constructs DiffusionStage with a compilation wrapper. +# If a later revision adds a non-None default, fail at boot like the other re-earn +# patches instead of discovering it mid-generate. +_init_params = inspect.signature(DiffusionStage.__init__).parameters +for _name in ("_model_wrapper", "model_wrapper"): + _param = _init_params.get(_name) + if _param is not None and _param.default not in (None, inspect.Parameter.empty): + raise AssertionError( + f"DiffusionStage.__init__ default {_name}={_param.default!r} — " + "re-verify diffusion_stage_cache against this ltx-pipelines revision" + ) + _CacheKey = tuple[object, ...] _lock = threading.Lock() _enabled = os.environ.get("DIFFUSION_STAGE_CACHE_ENABLED", "1") != "0" _cached_key: _CacheKey | None = None _cached_model: object | None = None +_logged_wrapper_skip = False # >0 while a cached transformer is checked out (yielded to a caller) and possibly # mid-denoise. The single-slot cache is only safe under strict sequentiality; this # counter lets _evict_locked() fail loud if something tries to free a model that is @@ -155,6 +169,20 @@ def set_enabled(value: bool) -> None: def _cacheable(stage: DiffusionStage) -> bool: + # Desktop constructs DiffusionStage with bare CompilationConfig() (capture=False, + # mode=None) and never calls with_model_wrapper. A set _model_wrapper is an + # uncovered cache key — 1.3.0 through 1.4.1 apply it after _transformer_ctx yields. Skip the + # cache (do not raise): a live generate must degrade to uncached, not crash. + # python -O would also strip an assert here and silently reuse wrong weights. + if getattr(stage, "_model_wrapper", None) is not None: + global _logged_wrapper_skip + if not _logged_wrapper_skip: + logger.warning( + "[diffusion-stage-cache] _model_wrapper is set — skipping cache " + "(wrapper is not part of the cache key)" + ) + _logged_wrapper_skip = True + return False return not stage._is_streaming and isinstance(stage._prepared_builder(), SingleGPUModelBuilder) # noqa: SLF001 @@ -200,8 +228,8 @@ def _evict_locked() -> None: # (leak) -- see the module docstring's GENERATION-SCOPED repro. gc.collect() _cached_model.to("meta") # type: ignore[attr-defined] - cleanup_memory() _cached_key, _cached_model = None, None + cleanup_memory() def evict() -> None: @@ -210,9 +238,11 @@ def evict() -> None: Called from ``GenerationHandler.start_generation``/``start_api_generation`` so the cache never survives past the generation it was built for -- see the module docstring's GENERATION-SCOPED section for why that matters. - Safe to call even when nothing is cached (no-op) or when the patch is - disabled (module-level cache is simply always empty). Raises if a cached - transformer is currently in use (see :func:`_evict_locked`). + Always runs ``cleanup_memory()`` so a second job's source encode does not + start against a Windows CUDA allocator that already reports ``free=0`` + (empty cache used to skip that reclaim). + Safe to call even when nothing is cached; raises if a cached transformer + is currently in use (see :func:`_evict_locked`). """ with _lock: _evict_locked() @@ -231,11 +261,10 @@ def _mark_free() -> None: @contextmanager def _cached_transformer_ctx(self: DiffusionStage, **kwargs: object) -> Iterator[object]: if not _enabled or not _cacheable(self): - # A non-cacheable build (e.g. IC-LoRA's use_lora_in_stage_2 forcing stage_2 - # onto the streaming path -- see module docstring's NON-CACHEABLE TRANSITIONS - # section) needs the VRAM a still-resident cached transformer is holding. - # Evicting only on a cache-key mismatch (below) never fires for this case, - # since this path never touches the cache-key branch at all. + # A non-cacheable build (streaming stage, or the patch disabled) needs the + # VRAM a still-resident cached transformer is holding. Evicting only on a + # cache-key mismatch (below) never fires here -- this path never touches + # the cache-key branch. See module docstring NON-CACHEABLE TRANSITIONS. evict() with _orig_transformer_ctx(self, **kwargs) as model: yield model diff --git a/backend/services/patches/diffvae_decode_vram.py b/backend/services/patches/diffvae_decode_vram.py index beaa974e8..3f4fead8f 100644 --- a/backend/services/patches/diffvae_decode_vram.py +++ b/backend/services/patches/diffvae_decode_vram.py @@ -9,14 +9,26 @@ GPU is almost empty (~28 GiB free). Decode then runs after evict with ~6 GiB driver-free — or, after a clean ``empty_cache``, ``mem_get_info`` reports ~30 GiB free. Planning 1024×576 against that 30 GiB budget picks a near-full-frame tile; -the first NA slab then drives ``reserved`` to capacity and hangs. Cap the tile -budget so 540p always splits. +the first NA slab then drives ``reserved`` to capacity and hangs. + +Cap **tile size** (80f × 608px, the 540p layout that used to come from an 8 GiB +``free_bytes`` cap), not the whole job budget. Capping ``free_bytes`` at 8 GiB +left 1080p/10s unable to place a min tile after ~4 GiB of resident stage-4 +features. + +The hang is neighborhood-attention **tile geometry**, not CUDA reserved memory. +A tile larger than 80f × 608px is the layout that never returned on the 5090; +the same max applies on MPS. CUDA still re-resolves AUTO tiles against +``mem_get_info`` after transformer evict, then clamps. MPS has no equivalent +budget call, so it clamps the pipeline's AUTO / untiled config to the same +max. Do not gate the MPS clamp on unified free RAM — that unit-mix is what +wrongly 422'd Darwin jobs against the 5090 stream curve. ``DistilledPipeline`` calls ``VideoDecoder`` only after both denoise stages, so evicting here cannot interrupt a mid-denoise checkout. Remove once ltx-pipelines offloads the transformer before DiffVAE decode and -resolves AUTO_TILING against that post-offload budget. +resolves AUTO_TILING against that post-offload budget with a max-tile constraint. Usage: import services.patches.diffvae_decode_vram # noqa: F401 @@ -29,8 +41,9 @@ import torch from ltx_core.devices import cuda_activation_budget_bytes +from ltx_core.model.video_vae import DimensionSizeConfig, TileSizeConfig from ltx_core.model.video_vae.model_configurator import is_diffusion_video_vae -from ltx_core.types import VideoLatentShape +from ltx_core.types import VIDEO_SCALE_FACTORS, VideoLatentShape from ltx_pipelines.utils.blocks import VideoDecoder from ltx_pipelines.utils.helpers import cleanup_memory, tiling_config_for_vae @@ -38,15 +51,81 @@ logger = logging.getLogger(__name__) -# After evict, Windows ``mem_get_info`` can still report ~30 GiB free. AUTO_TILING -# then covers 540p in one tile. 8 GiB is above the ~2.4 GiB min 540p/5s tile. -_CUDA_DIFFVAE_TILE_BUDGET_CAP_BYTES = 8 * 1024**3 +# 8 GiB-budget 540p layout: temporal 80 (ConvVAE auto too), spatial width 608. +_MAX_DIFFVAE_TILE_FRAMES = 80 +_MAX_DIFFVAE_TILE_SPATIAL = 608 +_DEFAULT_DIFFVAE_FRAME_OVERLAP = 40 +_DEFAULT_DIFFVAE_SPATIAL_OVERLAP = 160 _orig_video_decoder_call = VideoDecoder.__call__ -def _cuda_tile_budget_bytes(measured: int) -> int: - return min(max(int(measured), 0), _CUDA_DIFFVAE_TILE_BUDGET_CAP_BYTES) +def _snap_down(value: int, grid: int) -> int: + return max(grid, (value // grid) * grid) + + +def _clamp_axis( + tile_size: int, + overlap: int, + extent: int, + max_tile: int, + grid: int, + default_overlap: int, +) -> DimensionSizeConfig: + was_untiled = tile_size <= 0 + # Compare against the grid-snapped extent, not the raw one: a tile one cell short of an + # 8k+1 extent would only split off a sub-grid remainder, so it counts as untiled. Explicit + # near-full tiles are dropped on purpose; do not "fix" this to ``>= extent``. + if extent <= max_tile and (was_untiled or tile_size >= _snap_down(extent, grid)): + # Nothing forces a split. Return a truly untiled axis: upstream treats any + # tile_size > 0 as tiled and rejects it unless overlap meets its floor, and + # snapping an 8k+1 extent down to the grid would otherwise tile it by accident. + return DimensionSizeConfig() + size = extent if was_untiled else tile_size + size = min(size, max_tile, extent) + size = _snap_down(size, grid) + if size > extent: + size = _snap_down(extent, grid) + if was_untiled: + overlap = 0 if size >= extent else default_overlap + if overlap >= size: + overlap = _snap_down(size - grid, grid) if size > grid else 0 + if overlap >= size: + overlap = 0 + return DimensionSizeConfig(tile_size=size, overlap=overlap) + + +def _clamp_diffvae_tiles(tiling: Any, height: int, width: int, num_frames: int) -> TileSizeConfig: + """Force NA-safe max tiles. ``tile_size==0`` means the full axis extent.""" + frames = getattr(tiling, "frames", None) + heights = getattr(tiling, "height", None) + widths = getattr(tiling, "width", None) + return TileSizeConfig( + frames=_clamp_axis( + int(getattr(frames, "tile_size", 0) or 0), + int(getattr(frames, "overlap", 0) or 0), + num_frames, + _MAX_DIFFVAE_TILE_FRAMES, + VIDEO_SCALE_FACTORS.time, + _DEFAULT_DIFFVAE_FRAME_OVERLAP, + ), + height=_clamp_axis( + int(getattr(heights, "tile_size", 0) or 0), + int(getattr(heights, "overlap", 0) or 0), + height, + _MAX_DIFFVAE_TILE_SPATIAL, + VIDEO_SCALE_FACTORS.height, + _DEFAULT_DIFFVAE_SPATIAL_OVERLAP, + ), + width=_clamp_axis( + int(getattr(widths, "tile_size", 0) or 0), + int(getattr(widths, "overlap", 0) or 0), + width, + _MAX_DIFFVAE_TILE_SPATIAL, + VIDEO_SCALE_FACTORS.width, + _DEFAULT_DIFFVAE_SPATIAL_OVERLAP, + ), + ) def _release_denoise_weights() -> None: @@ -92,8 +171,8 @@ def _with_post_evict_cuda_tiling( return args, kwargs height, width, num_frames = _pixel_shape_from_latent(latent) - measured = int(cuda_activation_budget_bytes(device)) - budget = _cuda_tile_budget_bytes(measured) + measured = max(int(cuda_activation_budget_bytes(device)), 0) + budget = measured recommend_kwargs: dict[str, Any] = { "height": height, "width": width, @@ -104,7 +183,12 @@ def _with_post_evict_cuda_tiling( optimization = getattr(decoder, "diffvae_optimization", None) if optimization is not None: recommend_kwargs["diffvae_optimization"] = optimization - tiling = tiling_config_for_vae(checkpoint, **recommend_kwargs) + tiling = _clamp_diffvae_tiles( + tiling_config_for_vae(checkpoint, **recommend_kwargs), + height, + width, + num_frames, + ) logger.info( "DiffVAE CUDA tiling after evict: measured=%.1f GiB budget=%.1f GiB " "%sx%sx%s t/h/w tiles=%s/%s/%s", @@ -113,9 +197,49 @@ def _with_post_evict_cuda_tiling( width, height, num_frames, - getattr(getattr(tiling, "frames", None), "tile_size", "?"), - getattr(getattr(tiling, "height", None), "tile_size", "?"), - getattr(getattr(tiling, "width", None), "tile_size", "?"), + tiling.frames.tile_size, + tiling.height.tile_size, + tiling.width.tile_size, + ) + return _replace_tiling_arg(args, kwargs, tiling) + + +def _with_mps_clamped_tiles( + decoder: Any, args: tuple[Any, ...], kwargs: dict[str, Any] +) -> tuple[tuple[Any, ...], dict[str, Any]]: + """Apply the NA-safe max tile on MPS. No CUDA mem_get_info re-resolve. + + Same 80f × 608 clamp as CUDA: NA hang is tile layout, not device VRAM. + """ + device = getattr(decoder, "_device", None) + if not isinstance(device, torch.device) or device.type != "mps": + return args, kwargs + latent = kwargs.get("latent", args[0] if args else None) + if not isinstance(latent, torch.Tensor) or latent.ndim != 5: + return args, kwargs + checkpoint = getattr(decoder, "checkpoint_path", None) + if not isinstance(checkpoint, str): + checkpoint = getattr(decoder, "_checkpoint_path", None) + if not isinstance(checkpoint, str) or not is_diffusion_video_vae(checkpoint): + return args, kwargs + + height, width, num_frames = _pixel_shape_from_latent(latent) + existing = kwargs["tiling_config"] if "tiling_config" in kwargs else (args[1] if len(args) >= 2 else None) + if existing is None or not hasattr(existing, "frames"): + existing = TileSizeConfig( + frames=DimensionSizeConfig(tile_size=0, overlap=0), + height=DimensionSizeConfig(tile_size=0, overlap=0), + width=DimensionSizeConfig(tile_size=0, overlap=0), + ) + tiling = _clamp_diffvae_tiles(existing, height, width, num_frames) + logger.info( + "DiffVAE MPS tiling clamp %sx%sx%s t/h/w tiles=%s/%s/%s", + width, + height, + num_frames, + tiling.frames.tile_size, + tiling.height.tile_size, + tiling.width.tile_size, ) return _replace_tiling_arg(args, kwargs, tiling) @@ -123,6 +247,7 @@ def _with_post_evict_cuda_tiling( def _patched_video_decoder_call(self: VideoDecoder, *args: Any, **kwargs: Any) -> Any: _release_denoise_weights() args, kwargs = _with_post_evict_cuda_tiling(self, args, kwargs) + args, kwargs = _with_mps_clamped_tiles(self, args, kwargs) return _orig_video_decoder_call(self, *args, **kwargs) diff --git a/backend/services/patches/diffvae_mps_tiling_budget.py b/backend/services/patches/diffvae_mps_tiling_budget.py deleted file mode 100644 index 991a2958a..000000000 --- a/backend/services/patches/diffvae_mps_tiling_budget.py +++ /dev/null @@ -1,144 +0,0 @@ -"""Monkey-patch: DiffVAE AUTO_TILING on non-CUDA devices. - -``ltx_pipelines.utils.helpers.tiling_config_for_vae`` (and -``DiffusionVideoDecoder.recommended_tiling_config``) only query the CUDA -allocator. On MPS that yields ``free_bytes=0`` → ``usable_bytes=0`` → -``Cannot fit a DiffVAE decode tile under the memory budget`` before decode -starts. The min tile for a 1024×576×121 job is ~2.4 GiB; the Mac has the RAM, -upstream just never counts it. - -Filling that budget lets AUTO_TILING pick a single full-width stage-5 tile -(1024 on 540p). Eager ``K=11`` neighborhood attention on MPS then silently -zeros the tail frames. After the budget is filled, this patch forces a 2-way -width split when MPS would otherwise decode in one width tile. - -``DistilledPipeline`` resolves ``AUTO_TILING`` internally and never goes through -Desktop's ``resolve_tiling_config``, so callers cannot pass a budget. - -Remove once ltx-pipelines/ltx-core query MPS/unified free memory themselves -and refuse full-width eager NA tiles on MPS. - -Usage: - import services.patches.diffvae_mps_tiling_budget # noqa: F401 -""" - -from __future__ import annotations - -import inspect -import logging -from dataclasses import replace -from typing import Any - -import torch -from ltx_core.model.video_vae.diffusion_video_decoder import DiffusionVideoDecoder -from ltx_core.tiling import DimensionSizeConfig, split_by_size -from ltx_pipelines.utils import helpers - -from services.ltx_pipeline_common import resolve_diffvae_free_bytes - -logger = logging.getLogger(__name__) - -_logged_budget = False -_WIDTH_ALIGN = 32 - - -def _width_tile_count(tile_size: int, overlap: int, width: int) -> int: - if tile_size <= 0 or tile_size >= width or overlap >= tile_size: - return 1 - return len(split_by_size(tile_size, overlap)(width).intervals) - - -def _ensure_mps_width_split(config: Any, *, width: object, device: torch.device) -> Any: - """Force n_w >= 2 on MPS when AUTO_TILING would cover the full frame in one tile.""" - if device.type != "mps" or not isinstance(width, int) or width < 1: - return config - width_axis = getattr(config, "width", None) - if width_axis is None: - return config - current = int(getattr(width_axis, "tile_size", 0) or 0) - overlap = int(getattr(width_axis, "overlap", 0) or 0) - if overlap <= 0: - height_axis = getattr(config, "height", None) - overlap = int(getattr(height_axis, "overlap", 0) or 0) if height_axis is not None else 0 - if overlap <= 0: - return config - n_w = _width_tile_count(current if current > 0 else width, overlap, width) - if n_w >= 2: - return config - min_size = max(overlap + _WIDTH_ALIGN, 2 * overlap) - if width <= min_size: - return config - raw = (width + overlap) // 2 - tile = ((raw + _WIDTH_ALIGN - 1) // _WIDTH_ALIGN) * _WIDTH_ALIGN - tile = min(max(tile, min_size), width - _WIDTH_ALIGN) - if tile <= overlap or tile >= width: - return config - new_n = _width_tile_count(tile, overlap, width) - if new_n < 2: - return config - logger.info("DiffVAE MPS width clamp: %s → %s (n_w %s → %s)", current or width, tile, n_w, new_n) - return replace(config, width=DimensionSizeConfig(tile_size=tile, overlap=overlap)) - - -assert "free_bytes" in inspect.signature(helpers.tiling_config_for_vae).parameters, ( - "tiling_config_for_vae missing free_bytes — patch needs updating." -) -assert hasattr(DiffusionVideoDecoder, "recommended_tiling_config"), ( - "DiffusionVideoDecoder.recommended_tiling_config not found — patch needs updating." -) -assert "free_bytes" in inspect.signature(DiffusionVideoDecoder.recommended_tiling_config).parameters, ( - "recommended_tiling_config missing free_bytes — patch needs updating." -) - -_orig_tiling_config_for_vae = helpers.tiling_config_for_vae -_orig_recommended_tiling_config = DiffusionVideoDecoder.recommended_tiling_config - - -def _maybe_log_injected_budget(device: torch.device, free_bytes: int) -> None: - global _logged_budget - if _logged_budget: - return - _logged_budget = True - logger.info( - "DiffVAE tiling uses available system RAM on %s: %.1f GiB " - "(upstream non-CUDA budget is 0).", - device.type, - free_bytes / (1024**3), - ) - - -def _patched_tiling_config_for_vae(*args: Any, **kwargs: Any) -> Any: - device = kwargs.get("device") - if not isinstance(device, torch.device): - device = helpers.get_device() - kwargs["device"] = device - raw = kwargs.get("free_bytes") - incoming = raw if isinstance(raw, int) else None - filled = resolve_diffvae_free_bytes(device, incoming) - if (incoming is None or incoming == 0) and filled is not None and filled > 0 and device.type != "cuda": - _maybe_log_injected_budget(device, filled) - kwargs["free_bytes"] = filled - return _ensure_mps_width_split( - _orig_tiling_config_for_vae(*args, **kwargs), - width=kwargs.get("width"), - device=device, - ) - - -def _patched_recommended_tiling_config(self: DiffusionVideoDecoder, *args: Any, **kwargs: Any) -> Any: - device = next(self.parameters()).device - raw = kwargs.get("free_bytes") - incoming = raw if isinstance(raw, int) else None - filled = resolve_diffvae_free_bytes(device, incoming) - if (incoming is None or incoming == 0) and filled is not None and filled > 0 and device.type != "cuda": - _maybe_log_injected_budget(device, filled) - kwargs["free_bytes"] = filled - return _ensure_mps_width_split( - _orig_recommended_tiling_config(self, *args, **kwargs), - width=kwargs.get("width"), - device=device, - ) - - -helpers.tiling_config_for_vae = _patched_tiling_config_for_vae -DiffusionVideoDecoder.recommended_tiling_config = _patched_recommended_tiling_config # type: ignore[method-assign] diff --git a/backend/services/patches/disk_streaming_pread.py b/backend/services/patches/disk_streaming_pread.py new file mode 100644 index 000000000..650db447b --- /dev/null +++ b/backend/services/patches/disk_streaming_pread.py @@ -0,0 +1,107 @@ +"""Open disk-streaming checkpoints with safetensors' ``pread`` backend on Darwin. + +``DiskTensorReader`` keeps a ``safe_open`` handle and ``get_tensor``s each block +during every denoise step. With no ``backend`` argument that handle is mmap. +On Apple Silicon mmap is about half the throughput of ``pread`` and varies run +to run once the checkpoint no longer fits in the page cache +(https://github.com/Lightricks/LTX-2/issues/304). + +The same reader is the CUDA disk-streaming path (``OffloadMode.DISK``): Linux +hosts that cannot pin the transformer, and any other machine that streams +blocks from the checkpoint instead of keeping them resident. Pinned and +fully resident loads do not construct ``DiskTensorReader``. ``pread`` does +not shrink the allocation. It only changes the read. On Windows, safetensors +implements it with ``File::seek_read``. + +That Windows read is slower than mmap. Measured on an RTX 5090 / Samsung +9100 PRO NVMe, 63.45 GiB RAM, streamed T2V, DISK forced, Sage on, cold +process (same bytes, same allocation peak): + +- 720p/20s: mmap 232 s, pread 394.82 s (1.70x), 68.1 GiB read, alloc 14.15 GiB +- 1080p/10s: mmap 258 s, pread 420.11 s (1.63x), 74.6 GiB read, alloc 16.37 GiB + +Windows DISK-vs-CPU evidence was measured with mmap (DISK ~0.79x CPU). Under +pread, DISK is ~1.4x slower than that CPU control. Linux DISK is unmeasured, +and the MPS result does not transfer. ``install`` therefore no-ops unless +``sys.platform == "darwin"``. The reader never sees the consuming device, so +the platform check is the scoping we can implement. + +The issue's patch is ``SafetensorsStateDictLoader.load``. Desktop streaming does +not use that loader for the denoise loop, so this wraps ``DiskTensorReader`` +instead. + +Remove once ltx-core passes ``backend="pread"`` from ``DiskTensorReader`` on +Darwin only. An unconditional upstream ``pread`` would regress Windows. + +Usage: + import services.patches.disk_streaming_pread as disk_streaming_pread + disk_streaming_pread.install() +""" + +from __future__ import annotations + +import inspect +import logging +import sys +from typing import Any + +logger = logging.getLogger(__name__) + +_installed = False +_checked = False +_original_init: Any = None + + +def install() -> None: + """Use ``backend="pread"`` for disk-streaming opens on Darwin. Idempotent. + + No-op on every other platform. Does not log. This runs at import time, + before ``logging.basicConfig``, and an info record then is dropped. Call + ``log_status`` once logging exists. + """ + global _installed, _checked, _original_init + if _installed: + return + if sys.platform != "darwin": + _checked = True + return + + import safetensors # noqa: PLC0415 + + from ltx_core.block_streaming.disk import DiskTensorReader # noqa: PLC0415 + + if "backend" not in inspect.signature(safetensors.safe_open).parameters: + _checked = True + return + + _original_init = DiskTensorReader.__init__ + + def _init(self: DiskTensorReader, paths: list[str]) -> None: + original_open = safetensors.safe_open + + def _open(*args: Any, **kwargs: Any) -> Any: + kwargs.setdefault("backend", "pread") + return original_open(*args, **kwargs) + + safetensors.safe_open = _open # type: ignore[assignment] + try: + _original_init(self, paths) + finally: + safetensors.safe_open = original_open + + DiskTensorReader.__init__ = _init # type: ignore[method-assign] + _installed = True + _checked = True + + +def log_status() -> None: + """Report the disk-streaming read backend. Call after logging is configured.""" + if not _checked: + return + if _installed: + logger.info("Disk streaming opens safetensors with backend=pread") + return + if sys.platform != "darwin": + logger.info("Disk streaming keeps mmap; pread is Darwin-only") + return + logger.warning("safetensors.safe_open has no backend=; disk streaming stays on mmap") diff --git a/backend/services/patches/ic_lora_stage2_lora.py b/backend/services/patches/ic_lora_stage2_lora.py deleted file mode 100644 index 89f36d920..000000000 --- a/backend/services/patches/ic_lora_stage2_lora.py +++ /dev/null @@ -1,371 +0,0 @@ -"""Monkey-patch (EXPERIMENTAL): keep the IC-LoRA active in stage 2. - -Ports upstream PR #494's ``use_lora_in_stage_2`` (not yet synced to the public -Lightricks/LTX-2 repo) to the pinned rev. Stock ``ICLoraPipeline`` builds the stage-2 transformer with -``loras=()`` and conditions stage 2 on images only — so refinement pulls the output -back toward the base-model distribution and the IC-LoRA transformation (background -swap / depth / pose / canny / outpaint) blurs out. With the patch, when a pipeline -has ``use_lora_in_stage_2 = True``: - - 1. stage 2 is rebuilt with the same LoRAs as stage 1 (cheap: ``DiffusionStage`` - builds the transformer per call and frees on exit, so this adds only the LoRA - deltas during the stage-2 window — no second resident transformer), and - 2. stage 2's conditionings include the VAE-encoded reference video (via the - existing ``_create_conditionings``) instead of image-only. - -NOT a VRAM fix: stage-2 peak is set by the full output resolution (same as -skip_stage_2 at that res) plus a full-res reference re-encode. That reference encode -(``_create_conditionings`` -> ``VideoEncoder.forward``) is tiled here — scoped to -IC-LoRA pipeline runs only via the thread-local flag below — so it doesn't blow VRAM -(Linux OOM) or crawl on Windows; see -ltx-engine-planning/2026-06-29-ic-lora-resolution-factor-2-hang.md. The real low-VRAM -lever is weight streaming — see -ltx-engine-planning/2026-06-29-ic-lora-vram-auto-clamp-design.md. - -Scoped conditioning-encode tiling: the reference video is VAE-encoded un-tiled by -default; at high resolution_factor (skip_stage_2) or full Stage-2 res -(use_lora_in_stage_2) that working set exceeds VRAM. We wrap ``VideoEncoder.forward`` -to route oversized encodes through the encoder's own ``tiled_encode``, but ONLY while -a thread-local flag is set — and we set it only around this pipeline's reference-encode -steps. The main t2v/i2v pipelines never call ``ICLoraPipeline.__call__``, so their -encodes are untouched (no global ride-along). - -EXPERIMENTAL: pinned to ltx-2 rev a2c3f24 (the ``__call__`` body is copied from the -installed ``ltx_pipelines/ic_lora.py`` with two edits, marked PATCH below). Re-verify -when bumping that rev. Drop once upstream ships PR #494 (and tiles the conditioning -encode itself). - -Stage-2 reference downscale (EXPERIMENTAL, env IC_LORA_STAGE2_REF_DOWNSCALE, default 1=off): -use_lora_in_stage_2 re-conditions Stage 2 on the full-res reference video, which ~doubles the -attention sequence and drives the VRAM spike on long/large clips. Setting the env to e.g. 2 -temporarily raises the LoRA's reference_downscale_factor for the Stage-2 conditioning build, so -the reference is encoded at lower res and contributes ~factor^2 fewer tokens (RoPE positions are -rescaled by downscale_factor to stay aligned with the full-res output — the same mechanism the -model already uses, and the resolution Stage 1 conditions at). Off the LoRA's *trained* ratio, -so the transformation may soften — A/B against the default before relying on it. - -Usage: - import services.patches.ic_lora_stage2_lora # noqa: F401 - pipeline.use_lora_in_stage_2 = True # opt in per pipeline before __call__ -""" - -from __future__ import annotations - -import logging -import os -import threading -from collections.abc import Iterator -from contextlib import contextmanager - -import torch - -from ltx_core.components.noisers import GaussianNoiser -from ltx_core.model.video_vae import AUTO_TILING, AutoTiling, TileSizeConfig, TilingConfig -from ltx_core.model.video_vae.video_vae import VideoEncoder -from ltx_core.types import Audio, VideoPixelShape -from ltx_pipelines.ic_lora import ICLoraPipeline -from ltx_pipelines.utils.args import ImageConditioningInput -from ltx_pipelines.utils.constants import DISTILLED_SIGMAS, STAGE_2_DISTILLED_SIGMAS -from ltx_pipelines.utils.denoisers import SimpleDenoiser -from ltx_pipelines.utils.helpers import assert_resolution, combined_image_conditionings, ensure_tiling_config, tiling_scale_factors_for_vae -from ltx_pipelines.utils.media_io import HDRColorSpace -from ltx_pipelines.utils.types import ModalitySpec -from services.patches import diffusion_stage_cache - -logger = logging.getLogger(__name__) - - -# --- Scoped conditioning-encode tiling (see module docstring) --- -_orig_encoder_forward = VideoEncoder.forward -_encode_state = threading.local() - - -def _should_tile(shape: torch.Size, cfg: TileSizeConfig) -> bool: - """True when ``tiled_encode`` would split this input into more than one tile. - - Below the tile size in every dimension a single tile == the un-tiled forward, so we - skip tiling to keep small encodes (e.g. resolution_factor <= 1.0) exact. ``shape`` is - (B, C, F, H, W). - """ - f, h, w = shape[-3], shape[-2], shape[-1] - if cfg.height.is_tiled() and h > cfg.height.tile_size: - return True - if cfg.width.is_tiled() and w > cfg.width.tile_size: - return True - if cfg.frames.is_tiled() and f > cfg.frames.tile_size: - return True - return False - - -def _scoped_tiling_forward(self: VideoEncoder, sample: torch.Tensor) -> torch.Tensor: - # Off unless an IC-LoRA reference encode opted in; per-tile re-entry (tiled_encode -> - # self.forward) and small inputs pass straight through to the original forward. - if not getattr(_encode_state, "tile", False) or getattr(_encode_state, "in_tiled", False): - return _orig_encoder_forward(self, sample) - cfg = TileSizeConfig.default() - if not _should_tile(sample.shape, cfg): - return _orig_encoder_forward(self, sample) - logger.info( - "[ic-lora] tiling conditioning VAE encode %s (tile %dpx) to avoid VRAM blow-up", - tuple(sample.shape), cfg.height.tile_size, - ) - _encode_state.in_tiled = True - try: - return self.tiled_encode(sample, cfg) - finally: - _encode_state.in_tiled = False - - -VideoEncoder.forward = _scoped_tiling_forward # type: ignore[assignment] - - -@contextmanager -def _tile_ic_lora_encodes() -> Iterator[None]: - """Enable tiling of oversized VAE encodes for the wrapped block (this thread only).""" - prev = getattr(_encode_state, "tile", False) - _encode_state.tile = True - try: - yield - finally: - _encode_state.tile = prev - - -# --- Stage-2 reference downscale (see module docstring) --- -_STAGE2_REF_DOWNSCALE = max(1, int(os.environ.get("IC_LORA_STAGE2_REF_DOWNSCALE", "1"))) - - -@contextmanager -def _stage2_reference_downscale(pipeline: object, extra: int, height: int, width: int) -> Iterator[None]: - """Temporarily raise the pipeline's reference_downscale_factor by ``extra`` so the Stage-2 - reference video is encoded at lower res (~extra^2 fewer conditioning tokens). Restores it - after. No-op when extra <= 1 or the output dims aren't divisible by the effective factor - (which _create_conditionings would otherwise reject).""" - base = int(getattr(pipeline, "reference_downscale_factor", 1)) - eff = base * extra - if extra <= 1 or height % eff != 0 or width % eff != 0: - if extra > 1: - logger.warning( - "[ic-lora] stage-2 ref downscale x%d skipped: output %dx%d not divisible by %d", - extra, width, height, eff, - ) - yield - return - setattr(pipeline, "reference_downscale_factor", eff) - logger.info("[ic-lora] stage-2 reference downscale x%d (downscale_factor %d -> %d) to cut VRAM", extra, base, eff) - try: - yield - finally: - setattr(pipeline, "reference_downscale_factor", base) - - -def _patched_call( # noqa: PLR0913 - self: ICLoraPipeline, - prompt: str, - seed: int, - height: int, - width: int, - num_frames: int, - frame_rate: float, - images: list[ImageConditioningInput], - video_conditioning: list[tuple[str, float]], - enhance_prompt: bool = False, - enhance_static_cache: bool = False, - vae_dtype: torch.dtype | None = None, - tiling_config: TilingConfig | AutoTiling | None = AUTO_TILING, - conditioning_attention_strength: float = 1.0, - skip_stage_2: bool = False, - conditioning_attention_mask: torch.Tensor | None = None, - stage_1_sigmas: torch.Tensor = DISTILLED_SIGMAS, - stage_2_sigmas: torch.Tensor = STAGE_2_DISTILLED_SIGMAS, - color_space: HDRColorSpace | None = None, -) -> tuple[Iterator[torch.Tensor], Audio, TilingConfig | None]: - """Copy of ICLoraPipeline.__call__ (pinned upstream rev) + IC-LoRA-in-stage-2 (PATCH).""" - use_lora_in_stage_2 = getattr(self, "use_lora_in_stage_2", False) - - # PATCH (was): use_lora_in_stage_2 used to force stage 2 onto pinned-RAM streaming per call - # via streaming_prefetch_count, since the full-res reference conditioning roughly doubles the - # attention sequence and can overflow VRAM held resident. ltx_pipelines now fixes weight - # streaming (OffloadMode) at DiffusionStage construction time — LTXIcLoraPipeline.__init__ - # bakes it into self.stage_2 via offload_mode_for_prefetch_count, so it can no longer be - # bumped per call here. If VRAM pressure resurfaces on use_lora_in_stage_2, the fix is a - # construction-time offload_mode override for this pipeline, not a per-call one. - - images = self.image_conditioner.resolve_crf(images) - assert_resolution(height=height, width=width, is_two_stage=True) - if not (0.0 <= conditioning_attention_strength <= 1.0): - raise ValueError( - f"conditioning_attention_strength must be in [0.0, 1.0], got {conditioning_attention_strength}" - ) - - generator = torch.Generator(device=self.device).manual_seed(seed) - noiser = GaussianNoiser(generator=generator) - if vae_dtype is None: - vae_dtype = self.dtype - - (ctx_p,) = self.prompt_encoder( - [prompt], - enhance_first_prompt=enhance_prompt, - enhance_static_cache=enhance_static_cache, - enhance_prompt_image=images[0][0] if len(images) > 0 else None, - enhance_prompt_seed=seed, - ) - video_context, audio_context = ctx_p.video_encoding, ctx_p.audio_encoding - - scale_factors = tiling_scale_factors_for_vae(self.video_decoder.checkpoint_path) - tiling_config = ensure_tiling_config( - tiling_config, - scale_factors=scale_factors, - vae_checkpoint_path=self.video_decoder.checkpoint_path, - video_shape=VideoPixelShape(batch=1, frames=num_frames, height=height, width=width, fps=frame_rate), - diffvae_optimization=self.video_decoder.diffvae_optimization, - device=self.device, - ) - - # Stage 1: Initial low resolution video generation. - stage_1_output_shape = VideoPixelShape( - batch=1, - frames=num_frames, - width=width // 2, - height=height // 2, - fps=frame_rate, - ) - - # PATCH: tile the reference-video VAE encode (oversized at high resolution_factor) — - # scoped to this block so the main pipeline's encodes are unaffected. - with _tile_ic_lora_encodes(): - stage_1_conditionings = self.image_conditioner( - lambda enc: self._create_conditionings( - images=images, - video_conditioning=video_conditioning, - height=stage_1_output_shape.height, - width=stage_1_output_shape.width, - video_encoder=enc, - num_frames=num_frames, - conditioning_attention_strength=conditioning_attention_strength, - conditioning_attention_mask=conditioning_attention_mask, - color_space=color_space, - ) - ) - - stage_1_sigmas = stage_1_sigmas.to(dtype=torch.float32, device=self.device) - - video_state, audio_state = self.stage_1( - denoiser=SimpleDenoiser(video_context, audio_context), - sigmas=stage_1_sigmas, - noiser=noiser, - width=stage_1_output_shape.width, - height=stage_1_output_shape.height, - frames=num_frames, - fps=frame_rate, - video=ModalitySpec( - context=video_context, - conditionings=stage_1_conditionings, - ), - audio=ModalitySpec( - context=audio_context, - ), - ) - - # EXPERIMENTAL: stage_1 and stage_2 never share a diffusion_stage_cache key here -- - # stage_2 either goes streaming (use_lora_in_stage_2, see below) or uses different/ - # empty LoRAs, so a stage_1 cache hit on stage_2 never happens for this pipeline. - # Evict eagerly (costs nothing) so the still-resident stage_1 transformer doesn't - # compete for VRAM with the stage_2 conditioning encode below, which runs before - # stage_2's own DiffusionStage call would otherwise trigger an eviction. Live repro: - # reserved VRAM climbed to ~41GB on a 31.82GB card and hung during that encode. - diffusion_stage_cache.evict() - - if skip_stage_2: - # Skip Stage 2: Decode directly from Stage 1 output at half resolution - logging.info("[IC-LoRA] Skipping Stage 2 (--skip-stage-2 enabled)") - decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype) - decoded_audio = self.audio_decoder(audio_state.latent) - return decoded_video, decoded_audio, tiling_config - - # Stage 2: Upsample and refine the video at higher resolution. - upscaled_video_latent = self.upsampler(video_state.latent[:1]) - - stage_2_sigmas = stage_2_sigmas.to(dtype=torch.float32, device=self.device) - stage_2_output_shape = VideoPixelShape(batch=1, frames=num_frames, width=width, height=height, fps=frame_rate) - - # PATCH: keep stage 2's LoRAs in sync with the flag on EVERY call. DiffusionStage - # builds-on-call, so the builder's LoRAs decide what the next stage_2(...) constructs. - # Set both ways (LoRAs when on, () when off) so a cached pipeline reused with the flag - # flipped off doesn't carry stale LoRAs into a canonical refine. - self.stage_2._transformer_builder = self.stage_2._transformer_builder.with_loras( - self.stage_1._transformer_builder.loras if use_lora_in_stage_2 else () - ) - - if use_lora_in_stage_2: - # Condition stage 2 on the reference video (not image-only) so the IC-LoRA - # transformation survives refinement instead of being repainted from the prompt. - logger.info("[ic-lora] stage 2 running WITH IC-LoRA (use_lora_in_stage_2)") - # PATCH: the full Stage-2-res reference encode/conditioning is the big VRAM spike. Tile - # the encode (scoped), and optionally downscale the reference (IC_LORA_STAGE2_REF_DOWNSCALE) - # so it carries fewer tokens — like Stage 1's half-res reference. See module docstring. - with _tile_ic_lora_encodes(), _stage2_reference_downscale( - self, _STAGE2_REF_DOWNSCALE, stage_2_output_shape.height, stage_2_output_shape.width - ): - stage_2_conditionings = self.image_conditioner( - lambda enc: self._create_conditionings( - images=images, - video_conditioning=video_conditioning, - height=stage_2_output_shape.height, - width=stage_2_output_shape.width, - video_encoder=enc, - num_frames=num_frames, - conditioning_attention_strength=conditioning_attention_strength, - conditioning_attention_mask=conditioning_attention_mask, - color_space=color_space, - ) - ) - else: - stage_2_conditionings = self.image_conditioner( - lambda enc: combined_image_conditionings( - images=images, - height=stage_2_output_shape.height, - width=stage_2_output_shape.width, - video_encoder=enc, - dtype=self.dtype, - device=self.device, - color_space=color_space, - ) - ) - - video_state, audio_state = self.stage_2( - denoiser=SimpleDenoiser(video_context, audio_context), - sigmas=stage_2_sigmas, - noiser=noiser, - width=width, - height=height, - frames=num_frames, - fps=frame_rate, - video=ModalitySpec( - context=video_context, - conditionings=stage_2_conditionings, - noise_scale=stage_2_sigmas[0].item(), - initial_latent=upscaled_video_latent, - ), - audio=ModalitySpec( - context=audio_context, - noise_scale=stage_2_sigmas[0].item(), - initial_latent=audio_state.latent, - ), - ) - - decoded_video = self.video_decoder(video_state.latent, tiling_config, generator, dtype=vae_dtype) - decoded_audio = self.audio_decoder(audio_state.latent) - return decoded_video, decoded_audio, tiling_config - - -ICLoraPipeline.__call__ = _patched_call # type: ignore[method-assign] - - -if __name__ == "__main__": - cfg = TileSizeConfig.default() - sp = cfg.height.tile_size - fr = cfg.frames.tile_size - assert not _should_tile(torch.Size([1, 3, fr, sp, sp]), cfg), "exactly one tile -> no tiling" - assert _should_tile(torch.Size([1, 3, fr, sp, sp + 1]), cfg), "wider than a tile -> tile" - assert _should_tile(torch.Size([1, 3, fr + 1, sp, sp]), cfg), "more frames than a tile -> tile" - print("ic_lora_stage2_lora: tiling gate self-check OK") diff --git a/backend/services/patches/natten_libnatten_gate.py b/backend/services/patches/natten_libnatten_gate.py index 34f9209ad..0c94e2bd4 100644 --- a/backend/services/patches/natten_libnatten_gate.py +++ b/backend/services/patches/natten_libnatten_gate.py @@ -8,6 +8,10 @@ Our Windows GCS wheel has ``HAS_LIBNATTEN=True``. This gate keeps that path and fails closed for Flex-only installs. +1.3.0 through 1.4.1 ``resolve_attention_for_host`` read ``natten_available()`` (this +module's ``_NATTEN_AVAILABLE``). Clearing the flag is the input to that +remap, not a second remap of the same recipe. + Remove once ltx-core's ``natten_available()`` checks ``natten.HAS_LIBNATTEN``. Usage: diff --git a/backend/services/patches/record_stream_fix.py b/backend/services/patches/record_stream_fix.py deleted file mode 100644 index f62b427fc..000000000 --- a/backend/services/patches/record_stream_fix.py +++ /dev/null @@ -1,115 +0,0 @@ -"""Monkey-patch: replace record_stream with manual GPU reference tracking. - -record_stream corrupts the CUDA caching allocator on certain GPU/driver -combinations (observed on RTX 5090 / CUDA 12.8 / PyTorch 2.10), causing -access violations during subsequent safetensors model loads. - -This patch replaces record_stream calls in LayerStreamingWrapper with -explicit Python reference holding + per-layer CUDA events, achieving the -same protection (prevent allocator reuse while compute reads a tensor) -without touching allocator metadata. - -Remove this patch once the upstream ltx-core package includes the fix. - -NOTE: the upstream MPS-support work rewrote the weight-streaming subsystem -(`ltx_core.layer_streaming` -> `ltx_core.block_streaming`). When that module is -absent this patch cleanly no-ops — the CUDA record_stream workaround only ever -applied to the old LayerStreamingWrapper, and it is irrelevant on MPS. Whether -the RTX 5090 allocator issue still needs a workaround under the new -block_streaming path must be re-evaluated on CUDA before shipping there. - -Usage: - import services.patches.record_stream_fix # noqa: F401 -""" - -from __future__ import annotations - -import functools -import itertools -import logging -from typing import Any - -import torch -from torch import nn - -try: - from ltx_core.layer_streaming import LayerStreamingWrapper - - _AVAILABLE = True -except ModuleNotFoundError: - _AVAILABLE = False - logging.getLogger(__name__).info( - "record_stream_fix: ltx_core.layer_streaming absent (streaming subsystem rewritten " - "upstream to block_streaming) — skipping CUDA record_stream patch." - ) - - -def _patched_register_hooks(self: LayerStreamingWrapper) -> None: - idx_map: dict[int, int] = {id(layer): idx for idx, layer in enumerate(self._layers)} - num_layers = len(self._layers) - - compute_stream = torch.cuda.current_stream(self._target_device) - - gpu_refs: dict[int, list[torch.Tensor]] = {} - ref_events: dict[int, torch.cuda.Event] = {} - - def _drain_completed_refs() -> None: - for layer_idx in list(ref_events): - if ref_events[layer_idx].query(): - del gpu_refs[layer_idx] - del ref_events[layer_idx] - - def _pre_hook( - module: nn.Module, - _args: Any, - *, - idx: int, - ) -> None: - self._prefetcher.wait(idx) - if not self._store.is_on_gpu(idx): - self._store.move_to_gpu(idx, module) - - gpu_refs[idx] = [param.data for param in itertools.chain(module.parameters(), module.buffers())] - - _drain_completed_refs() - - for offset in range(1, self._prefetch_count + 1): - self._prefetcher.prefetch((idx + offset) % num_layers) - - def _post_hook( - module: nn.Module, - _args: Any, - _output: Any, - *, - idx: int, - ) -> None: - event = torch.cuda.Event() - event.record(compute_stream) - ref_events[idx] = event - - self._store.evict_to_cpu(idx, module) - - self._gpu_refs = gpu_refs - self._ref_events = ref_events - - for layer in self._layers: - idx = idx_map[id(layer)] - h1 = layer.register_forward_pre_hook(functools.partial(_pre_hook, idx=idx)) - h2 = layer.register_forward_hook(functools.partial(_post_hook, idx=idx)) - self._hooks.extend([h1, h2]) - - -if _AVAILABLE: - _original_teardown = LayerStreamingWrapper.teardown - - def _patched_teardown(self: LayerStreamingWrapper) -> None: - # Clear held GPU references before the original teardown evicts layers. - if hasattr(self, "_gpu_refs"): - torch.cuda.synchronize(device=self._target_device) - self._gpu_refs.clear() - self._ref_events.clear() - _original_teardown(self) - - # Apply patches. - LayerStreamingWrapper._register_hooks = _patched_register_hooks # type: ignore[assignment] - LayerStreamingWrapper.teardown = _patched_teardown # type: ignore[assignment] diff --git a/backend/services/patches/safetensors_loader_fix.py b/backend/services/patches/safetensors_loader_fix.py index 56c6d54aa..2587e0cd1 100644 --- a/backend/services/patches/safetensors_loader_fix.py +++ b/backend/services/patches/safetensors_loader_fix.py @@ -100,7 +100,11 @@ def _patched_load( expected_name = name if sd_ops is None else sd_ops.apply_to_key(name) if expected_name is None: continue - value = value.to(device=device, non_blocking=True, copy=False) + # Async H2D is only ordered against later compute on CUDA + # (same-stream). ltx_core.devices.allow_async_transfer fences the rest. + # Pure transfers like this one happen to be safe on MPS today, but + # blocking costs nothing at load time. + value = value.to(device=device, non_blocking=(device.type == "cuda"), copy=False) key_value_pairs = ((expected_name, value),) if sd_ops is not None: key_value_pairs = sd_ops.apply_to_key_value(expected_name, value) diff --git a/backend/services/prompt_enhancement/resolve_enhance_assets.py b/backend/services/prompt_enhancement/resolve_enhance_assets.py new file mode 100644 index 000000000..c8d0dd40f --- /dev/null +++ b/backend/services/prompt_enhancement/resolve_enhance_assets.py @@ -0,0 +1,30 @@ +"""Resolve Explore asset ids to filesystem paths for EnhancePromptRequest.""" + +from __future__ import annotations + +from _routes._errors import HTTPError +from api_types import EnhancePromptRequest +from handlers.asset_handler import AssetHandler + + +def resolve_enhance_image_assets( + assets: AssetHandler, req: EnhancePromptRequest +) -> EnhancePromptRequest: + """Fill imagePath / lastImagePath from asset ids. No-op when ids are absent.""" + updates: dict[str, str | None] = {} + if req.imageAssetId: + updates["imagePath"] = _image_asset_path(assets, req.imageAssetId) + updates["imageAssetId"] = None + if req.lastImageAssetId: + updates["lastImagePath"] = _image_asset_path(assets, req.lastImageAssetId) + updates["lastImageAssetId"] = None + if not updates: + return req + return req.model_copy(update=updates) + + +def _image_asset_path(assets: AssetHandler, asset_id: str) -> str: + asset = assets.get_asset(asset_id) + if asset.media_kind != "image": + raise HTTPError(400, "ASSET_NOT_IMAGE") + return asset.path diff --git a/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py b/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py index cc75a66fd..3e7de5387 100644 --- a/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py +++ b/backend/services/prompt_enhancer_pipeline/gemini_prompt_enhancer_pipeline.py @@ -8,6 +8,7 @@ from PIL import Image from _routes._errors import HTTPError +from server_utils.oriented_image import open_oriented_image from services.gemini_text_client import apply_gemini_thinking_config, call_gemini_generate_content from services.interfaces import HTTPClient, JSONValue from services.prompt_enhancement import ( @@ -102,16 +103,16 @@ def _inline_image_part(self, image_path: str) -> tuple[JSONValue, int]: # Our own validate_image_file() allows more (GIF/BMP/TIFF, up to 50MB) than Gemini's # inlineData accepts — without this, those pass our gate and only fail once they bounce # off Gemini as an opaque upstream error. - with Image.open(image_path) as img: - fmt = str(img.format or "").upper() - if fmt not in _GEMINI_SUPPORTED_IMAGE_FORMATS: - raise HTTPError( - 400, - f"Image format {fmt or 'unknown'} isn't supported by the Gemini API provider " - "(use Local, or convert the image to PNG/JPEG/WEBP)", - code="GEMINI_UNSUPPORTED_IMAGE_FORMAT", - ) - image = img.convert("RGB") + img = open_oriented_image(image_path) + fmt = str(img.format or "").upper() + if fmt not in _GEMINI_SUPPORTED_IMAGE_FORMATS: + raise HTTPError( + 400, + f"Image format {fmt or 'unknown'} isn't supported by the Gemini API provider " + "(use Local, or convert the image to PNG/JPEG/WEBP)", + code="GEMINI_UNSUPPORTED_IMAGE_FORMAT", + ) + image = img.convert("RGB") image.thumbnail( (_ENHANCE_IMAGE_LONG_EDGE, _ENHANCE_IMAGE_LONG_EDGE), Image.Resampling.LANCZOS, diff --git a/backend/services/records.py b/backend/services/records.py new file mode 100644 index 000000000..c341f8f75 --- /dev/null +++ b/backend/services/records.py @@ -0,0 +1,155 @@ +from __future__ import annotations + +from typing import Literal + +from pydantic import BaseModel, ConfigDict, Field, JsonValue, model_validator + +from api_types import ( + AssetMetadata, + GenerationErrorCode, + GenerationStatus, + MediaKind, + Origin, + require_failed_has_error_code, + require_media_kind_matches_metadata, +) + +Status = GenerationStatus + + +class StatusError(Exception): + def __init__(self, generation_id: str, status: str) -> None: + self.generation_id = generation_id + self.status = status + super().__init__(f"generation {generation_id} is {status}") + + +class AssetInUseError(Exception): + def __init__(self, asset_id: str) -> None: + self.asset_id = asset_id + super().__init__(f"asset {asset_id} is in use") + + +class AttemptError(Exception): + def __init__(self, generation_id: str, expected: int, actual: int) -> None: + self.generation_id = generation_id + self.expected = expected + self.actual = actual + super().__init__( + f"generation {generation_id} attempt mismatch: expected {expected}, actual {actual}" + ) + + +class MarkSucceededError(Exception): + generation_id: str + error_code: GenerationErrorCode + + def __init__(self, generation_id: str, error_code: GenerationErrorCode) -> None: + self.generation_id = generation_id + self.error_code = error_code + super().__init__(error_code) + + +class CapabilityFailedError(Exception): + """Executor could not run this generation with the current local capability.""" + + def __init__(self, detail: str, *, code: str | None = None) -> None: + self.detail = detail + self.code = code + super().__init__(detail) + + +class UnavailableError(Exception): + """Raised when the sqlite store cannot be opened or recovered.""" + + +MediaErrorCode = Literal[ + "UNSUPPORTED_MEDIA", + "FILE_TOO_LARGE", + "NO_AUDIO_STREAM", + "IMAGE_DIMENSIONS_TOO_LARGE", + "UNREADABLE_MEDIA", + "INVALID_TRIM_RANGE", + "TRIM_BUSY", +] + + +class MediaError(Exception): + def __init__(self, code: MediaErrorCode, message: str) -> None: + self.code = code + super().__init__(message) + + +class _RecordModel(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + + +class AssetRecord(_RecordModel): + id: str = Field(min_length=1) + media_kind: MediaKind + origin: Origin + path: str = Field(min_length=1) + thumbnail_path: str | None = None + mime_type: str = Field(min_length=1) + name: str = Field(min_length=1) + metadata: AssetMetadata + created_at: int = Field(ge=0) + + @model_validator(mode="after") + def _media_kind_matches_metadata(self) -> AssetRecord: + require_media_kind_matches_metadata(self.media_kind, self.metadata) + return self + + +class ListedAsset(_RecordModel): + asset: AssetRecord + in_use: bool + + +class AssetListPage(_RecordModel): + items: tuple[ListedAsset, ...] + next_cursor: str | None + + +class OutputSpec(_RecordModel): + asset_id: str = Field(min_length=1) + dest_path: str = Field(min_length=1) + ordinal: int = Field(ge=0) + mime_type: str = Field(min_length=1) + name: str = Field(min_length=1) + + +class PairedDeviceRecord(_RecordModel): + id: str = Field(min_length=1) + name: str = Field(min_length=1) + token_hash: str = Field(min_length=1) + created_at: int = Field(ge=0) + last_seen_at: int = Field(ge=0) + first_seen_ip: str | None = None + first_seen_user_agent: str | None = None + revoked_at: int | None = None + + +class GenerationRecord(_RecordModel): + id: str = Field(min_length=1) + feature: str = Field(min_length=1) + contract_version: int = Field(ge=1) + status: Status + spec: dict[str, JsonValue] + error_code: GenerationErrorCode | None = None + created_at: int = Field(ge=0) + queued_at: int = Field(ge=0) + attempt_count: int = Field(ge=0) + started_at: int | None = None + finished_at: int | None = None + outputs: tuple[AssetRecord, ...] + + @model_validator(mode="after") + def _failed_has_error_code(self) -> GenerationRecord: + require_failed_has_error_code(self.status, self.error_code) + return self + + +class QueueGenerationRecord(_RecordModel): + generation: GenerationRecord + input_assets: tuple[AssetRecord, ...] diff --git a/backend/services/retake_pipeline/extend_stitch.py b/backend/services/retake_pipeline/extend_stitch.py new file mode 100644 index 000000000..f95bbac20 --- /dev/null +++ b/backend/services/retake_pipeline/extend_stitch.py @@ -0,0 +1,222 @@ +"""Put original pixels back so Home/Remote extend is not a VAE round-trip of the source. + +Ports ltxv-api ``stitch_frames`` / ``stitch_audio`` +(``inference/pipelines/src/pipelines/retake/pipeline.py``): RGB ``lerp`` up to +``MAX_FADE_FRAMES``, audio hard-cut at the edit span. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from pathlib import Path + +import numpy as np + +from api_types import ExtendMode +from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg, timeout_for_source_duration +from services.media_probe import media_has_audio +from handlers.video_resolution import SpatialLetterbox, generation_letterbox +from services.retake_pipeline.rgb_stitch import ( + FadeWindow, + blend_fade, + iter_generated, + iter_source, + write_rgb_video, +) +from services.retake_pipeline.stitch_audio import AudioPiece, audio_cut_graph +from services.retake_pipeline.stitch_silence import append_silence_input +from services.retake_pipeline.window import ( + MASK_DELTA_SECONDS, + MAX_FADE_FRAMES, + ExtendEncodeWindow, +) + +_has_audio = media_has_audio + + +def _mask_delta_frames(fps: float, context_frames: int) -> int: + frames = round(MASK_DELTA_SECONDS * fps) + return max(0, min(frames, max(0, context_frames - 1))) + + +def fade_window_for_extend( + window: ExtendEncodeWindow, + *, + mode: ExtendMode, + extend_frames: int, + fps: float, +) -> FadeWindow: + delta = _mask_delta_frames(fps, window.context_frames) + context_end = window.context_frames + extend_frames + if mode == "end": + return FadeWindow(0, context_end, window.context_frames - delta, context_end) + return FadeWindow(0, context_end, 0, extend_frames + delta) + + +def _stitched_frames( + *, + source_path: str, + generated_path: str, + window: ExtendEncodeWindow, + fade: FadeWindow, + mode: ExtendMode, + extend_frames: int, + box: SpatialLetterbox, +) -> Iterator[np.ndarray]: + origin = window.dropped_prefix_frames + if mode == "end": + fade_in = min(MAX_FADE_FRAMES, fade.edit_start - fade.context_start) + fade_in_start = fade.edit_start - fade_in + yield from iter_source(source_path, 0, origin + fade_in_start, box) + yield from blend_fade( + source_path=source_path, + generated_path=generated_path, + source_start=origin + fade_in_start, + generated_start=fade_in_start, + count=fade_in, + fade=fade, + box=box, + ) + yield from iter_generated(generated_path, fade.edit_start, fade.context_end, box) + return + fade_out = min(MAX_FADE_FRAMES, fade.context_end - fade.edit_end) + source_fade_start = fade.edit_end - extend_frames + source_end = ( + window.dropped_prefix_frames + window.context_frames + window.dropped_suffix_frames + ) + yield from iter_generated(generated_path, 0, fade.edit_end, box) + yield from blend_fade( + source_path=source_path, + generated_path=generated_path, + source_start=source_fade_start, + generated_start=fade.edit_end, + count=fade_out, + fade=fade, + box=box, + ) + yield from iter_source(source_path, source_fade_start + fade_out, source_end, box) + + +def _mux_audio( + *, + video_path: str, + source_path: str, + generated_path: str, + dest_path: str, + mode: ExtendMode, + source_cut: float, + generated_cut: float, + silence_original: bool, + timeout: float, +) -> None: + args: list[str] = [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + video_path, + "-i", + source_path, + "-i", + generated_path, + ] + source_audio = "[1:a]" + if silence_original: + append_silence_input(args) + source_audio = "[3:a]" + generated_audio = "[2:a]" + if mode == "end": + graph = audio_cut_graph( + [ + AudioPiece(source_audio, end=source_cut), + AudioPiece(generated_audio, start=generated_cut), + ] + ) + else: + graph = audio_cut_graph( + [ + AudioPiece(generated_audio, end=generated_cut), + AudioPiece(source_audio, start=source_cut), + ] + ) + args.extend( + [ + "-filter_complex", + graph, + "-map", + "0:v", + "-c:v", + "copy", + "-map", + "[a]", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + dest_path, + ] + ) + run_ffmpeg(args, timeout=timeout) + + +def stitch_extend_output( + *, + source_path: str, + windowed_path: str, + dest_path: str, + window: ExtendEncodeWindow, + fps: float, + mode: ExtendMode, + extend_frames: int, + target_width: int, + target_height: int, +) -> None: + box = generation_letterbox(target_width, target_height) + fade = fade_window_for_extend( + window, mode=mode, extend_frames=extend_frames, fps=fps + ) + dest = Path(dest_path) + generated_has_audio = _has_audio(windowed_path) + silence_original = generated_has_audio and not _has_audio(source_path) + video_dest = ( + dest if not generated_has_audio else dest.with_name(f"{dest.stem}.video{dest.suffix}") + ) + write_rgb_video( + video_dest, + _stitched_frames( + source_path=source_path, + generated_path=windowed_path, + window=window, + fade=fade, + mode=mode, + extend_frames=extend_frames, + box=box, + ), + fps=fps, + width=box.content_width, + height=box.content_height, + ) + if not generated_has_audio: + return + if mode == "end": + source_cut = (window.dropped_prefix_frames + fade.edit_start) / fps + generated_cut = fade.edit_start / fps + else: + source_cut = (fade.edit_end - extend_frames) / fps + generated_cut = fade.edit_end / fps + source_frames = ( + window.dropped_prefix_frames + window.context_frames + window.dropped_suffix_frames + ) + try: + _mux_audio( + video_path=str(video_dest), + source_path=source_path, + generated_path=windowed_path, + dest_path=str(dest), + mode=mode, + source_cut=source_cut, + generated_cut=generated_cut, + silence_original=silence_original, + timeout=timeout_for_source_duration((source_frames + extend_frames) / fps), + ) + finally: + if video_dest != dest: + video_dest.unlink(missing_ok=True) diff --git a/backend/services/retake_pipeline/frame_rate.py b/backend/services/retake_pipeline/frame_rate.py new file mode 100644 index 000000000..da021d824 --- /dev/null +++ b/backend/services/retake_pipeline/frame_rate.py @@ -0,0 +1,42 @@ +"""Fix the frame rate the upstream encoder truncates. + +``ltx_pipelines`` ``encode_video`` opens its stream with ``rate=int(fps)``, so a +23.976 fps retake/extend window is written at 23 fps: the video plays ~4% slow +against its audio, and a timestamp seek lands on the wrong frame. Rescaling +the video timestamps by a stream copy puts every frame back at +``index / source_fps`` without re-encoding. +""" + +from __future__ import annotations + +import os +from pathlib import Path + +from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg + +_RATE_TOLERANCE = 1e-6 + + +def restamp_to_source_rate(path: str, *, source_fps: float) -> None: + written_fps = int(source_fps) + if written_fps <= 0 or abs(source_fps - written_fps) < _RATE_TOLERANCE: + return + target = Path(path) + restamped = target.with_name(f"{target.stem}.restamp{target.suffix}") + run_ffmpeg( + [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-itsscale:v", + f"{written_fps / source_fps:.12f}", + "-i", + str(target), + "-map", + "0", + "-c", + "copy", + str(restamped), + ] + ) + os.replace(restamped, target) diff --git a/backend/services/retake_pipeline/letterbox.py b/backend/services/retake_pipeline/letterbox.py new file mode 100644 index 000000000..848aa6416 --- /dev/null +++ b/backend/services/retake_pipeline/letterbox.py @@ -0,0 +1,43 @@ +"""Fit a picture onto the ÷32 canvas, then crop the black bars back off. + +Retake and extend both encode at ``SpatialLetterbox.canvas_*`` and stitch at +``content_*``. Padding keeps source rows on the same rows as the generated +span. A center-crop or a stretch moves them and the seam jumps. The encode and +the stitch both resize through ``resize_rgb`` so they share one kernel. +""" + +from __future__ import annotations + +import numpy as np +from PIL import Image + +from handlers.video_resolution import SpatialLetterbox + + +def resize_rgb(frame: np.ndarray, width: int, height: int) -> np.ndarray: + if frame.shape[1] == width and frame.shape[0] == height: + return frame + return np.asarray(Image.fromarray(frame).resize((width, height), Image.Resampling.LANCZOS)) + + +def fit_and_pad(frame: np.ndarray, box: SpatialLetterbox) -> np.ndarray: + """Resize ``frame`` to the picture, then center it on a black canvas.""" + fitted = resize_rgb(frame, box.content_width, box.content_height) + if box.canvas_width == box.content_width and box.canvas_height == box.content_height: + return fitted + canvas = np.zeros((box.canvas_height, box.canvas_width, frame.shape[2]), dtype=frame.dtype) + canvas[ + box.top : box.top + box.content_height, + box.left : box.left + box.content_width, + ] = fitted + return canvas + + +def crop_letterbox(frame: np.ndarray, box: SpatialLetterbox) -> np.ndarray: + """Drop the bars added by ``fit_and_pad``.""" + if box.top == 0 and box.left == 0 and frame.shape[0] == box.content_height and frame.shape[1] == box.content_width: + return frame + return frame[ + box.top : box.top + box.content_height, + box.left : box.left + box.content_width, + ].copy() diff --git a/backend/services/retake_pipeline/ltx_retake_pipeline.py b/backend/services/retake_pipeline/ltx_retake_pipeline.py index 5a2ba69bc..9527ecb4f 100644 --- a/backend/services/retake_pipeline/ltx_retake_pipeline.py +++ b/backend/services/retake_pipeline/ltx_retake_pipeline.py @@ -6,69 +6,48 @@ * ``@torch.no_grad()`` instead of ``@torch.inference_mode()`` — the transformer checkpoint uses custom autograd functions incompatible with inference-mode tensors. -* Tiled video encoding via ``video_latent_from_file(..., tiling_config)`` - — the original encodes all frames in a single pass which OOMs on most GPUs. +* Tiled video encoding from CPU pixels via ``encode_source_video_latent`` + (assembling the frame tensor on CUDA reserved ~67 GiB on Windows WDDM and + hung the second encode after DiffVAE decode). * Tiled video decoding via ``VideoDecoder(..., tiling_config)`` — the original omits the tiling argument. +* Distilled 2.5 retake and extend use ancestral stage 1 plus a same-resolution + Euler refine (T2V's pair without the 2× upsample). Euler-only on that + 8-step schedule never lets the prompt take. """ from __future__ import annotations +import logging +from dataclasses import replace from collections.abc import Iterator -from functools import partial from typing import Any import torch -from ltx_core.components.diffusion_steps import EulerAncestralDiffusionStep from ltx_core.components.guiders import MultiModalGuiderParams from ltx_core.loader import LoraPathStrengthAndSDOps -from ltx_core.model.video_vae import DimensionSizeConfig, TileSizeConfig, get_video_chunks_number +from ltx_core.model.video_vae import get_video_chunks_number +from ltx_core.loader.registry import DummyRegistry from ltx_core.quantization import QuantizationPolicy -from ltx_core.types import Audio -from ltx_pipelines.distilled import ( - ANCESTRAL_ETA, - ANCESTRAL_NOISE_SEED_OFFSET, - ANCESTRAL_S_NOISE, - should_use_ancestral_sampler, -) +from ltx_core.types import Audio, SpatioTemporalScaleFactors +from ltx_pipelines.distilled import should_use_ancestral_sampler from ltx_pipelines.utils.media_io import encode_video, get_videostream_metadata -from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop +from ltx_pipelines.utils.types import ModalitySpec, VideoAudio from api_types import ExtendMode from services.ltx_pipeline_common import build_model_paths, offload_mode_for_prefetch_count, resolve_tiling_config from services.services_utils import TilingConfigType +from services.retake_pipeline.frame_rate import restamp_to_source_rate from services.retake_pipeline.retake_pipeline import RetakePipeline +from services.retake_pipeline.retake_sampler import resolve_sampler_plan +from services.retake_pipeline.source_encode import ( + encode_source_video_latent, + extend_freeze_pad_frames, + source_encode_tiling, +) +from services.retake_pipeline.window import MASK_DELTA_SECONDS - -# Seam feather for extend: widen the regenerated region this far INTO the kept source so the -# frozen->generated boundary blends instead of cutting hard. Mirrors the cloud gateway's -# MASK_DELTA_SECONDS (ltxv-api retake-edit-window.computePadding). 0 disables the feather. -_EXTEND_MASK_DELTA_SECONDS = 0.5 - - -def distilled_stage_sampler_kwargs( - *, - distilled: bool, - use_ancestral: bool, - seed: int, - dtype: torch.dtype, -) -> dict[str, Any]: - """Optional ``stepper``/``loop`` overrides for :class:`DiffusionStage`. - - Distilled 2.5+ checkpoints need the ancestral sampler; 2.3 and the guided - (non-distilled) path keep DiffusionStage's deterministic defaults. - ``use_ancestral`` is resolved once at pipeline init from checkpoint metadata. - """ - if not distilled or not use_ancestral: - return {} - return { - "stepper": EulerAncestralDiffusionStep(eta=ANCESTRAL_ETA, s_noise=ANCESTRAL_S_NOISE), - "loop": partial( - euler_ancestral_denoising_loop, - noise_seed=seed + ANCESTRAL_NOISE_SEED_OFFSET, - model_dtype=dtype, - ), - } +logger = logging.getLogger(__name__) class LTXRetakePipeline: @@ -140,15 +119,20 @@ def __init__( device, offload_mode=offload_mode, ) + # cache_models shells keep DiffVAE NA workspaces across dispose; the next + # encode then hangs on Windows WDDM with reserved>>device. Do not cache. + vae_registry = DummyRegistry() self.image_conditioner = ImageConditioner( video_vae, self.dtype, device, + registry=vae_registry, ) self.audio_conditioner = AudioConditioner( audio_vae, self.dtype, device, + registry=vae_registry, ) self.stage = DiffusionStage.from_checkpoint( # type: ignore[reportUnknownMemberType] transformer, @@ -162,30 +146,68 @@ def __init__( video_vae, self.dtype, device, + registry=vae_registry, ) self.audio_decoder = AudioDecoder( audio_vae, self.dtype, device, + registry=vae_registry, ) - def _invoke_diffusion_stage( + def _denoise_masked_latents( self, *, distilled: bool, seed: int, - **stage_kwargs: Any, + denoiser: Any, + sigmas: torch.Tensor, + noiser: Any, + video: ModalitySpec, + audio: ModalitySpec | None, ) -> Any: - """Call ``DiffusionStage`` with distilled 2.5 ancestral overrides when needed.""" - return self.stage( - **stage_kwargs, - **distilled_stage_sampler_kwargs( - distilled=distilled, - use_ancestral=self.use_ancestral_sampler, - seed=seed, - dtype=self.dtype, + """Ancestral stage 1 + Euler refine for distilled 2.5; Euler-only otherwise.""" + plan = resolve_sampler_plan( + distilled=distilled, + use_ancestral=self.use_ancestral_sampler, + seed=seed, + dtype=self.dtype, + ) + video_state, audio_state = self.stage( + denoiser=denoiser, + sigmas=sigmas, + noiser=noiser, + modalities=VideoAudio( + video=_pin_frozen_noise(video), + audio=None if audio is None else _pin_frozen_noise(audio), ), + **plan.stage1, ) + video_state, audio_state = _restore_frozen(video_state, video), _restore_frozen(audio_state, audio) + if not plan.two_stage: + return video_state, audio_state + assert video_state is not None + from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMA_VALUES + + stage_2_sigmas = torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES).to( + dtype=torch.float32, device=self.device + ) + noise_scale = float(stage_2_sigmas[0].item()) + video_state, audio_state = self.stage( + denoiser=denoiser, + sigmas=stage_2_sigmas, + noiser=noiser, + modalities=VideoAudio( + video=_with_stage2_latent(video, video_state.latent, noise_scale), + audio=( + None + if audio is None or audio_state is None + else _with_stage2_latent(audio, audio_state.latent, noise_scale) + ), + ), + **plan.refine, + ) + return _restore_frozen(video_state, video), _restore_frozen(audio_state, audio) @torch.no_grad() def _run( # noqa: PLR0913, PLR0915 @@ -209,15 +231,19 @@ def _run( # noqa: PLR0913, PLR0915 target_width: int | None = None, target_height: int | None = None, target_frames: int | None = None, + encode_start_time: float = 0.0, + encode_max_duration: float | None = None, + content_width: int | None = None, + content_height: int | None = None, ) -> tuple[Iterator[torch.Tensor], Audio, TilingConfigType]: from ltx_core.components.guiders import MultiModalGuider from ltx_core.components.noisers import GaussianNoiser from ltx_core.components.schedulers import LTX2Scheduler from ltx_core.conditioning.types.noise_mask_cond import TemporalRegionMask - from ltx_core.types import AudioLatentShape, VideoLatentShape + from ltx_core.types import AudioLatentShape from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES as _distilled_sigmas from ltx_pipelines.utils.denoisers import GuidedDenoiser, SimpleDenoiser - from ltx_pipelines.utils.helpers import audio_latent_from_file, video_latent_from_file + from ltx_pipelines.utils.helpers import audio_latent_from_file from ltx_pipelines.utils.types import ModalitySpec is_extend = extend_frames > 0 @@ -229,38 +255,59 @@ def _run( # noqa: PLR0913, PLR0915 noiser = GaussianNoiser(generator=generator) dtype = self.dtype - # Smaller tiles for source video encoding to reduce peak VRAM allocation - # during the VAE encoder forward pass. - encoding_tiling = TileSizeConfig( - frames=DimensionSizeConfig(tile_size=24, overlap=16), - height=DimensionSizeConfig(tile_size=256, overlap=64), - width=DimensionSizeConfig(tile_size=256, overlap=64), - ) # --- Encode source video (tiled) --- output_shape = get_videostream_metadata(video_path) - # Optional downscale: encode/generate at the requested (already 32-corrected) size. - # video_latent_from_file resizes the source frames to output_shape during encoding. + # Home retake/extend pass a ÷32 canvas plus the picture size. The encode + # letterboxes the picture onto that canvas. Legacy callers omit the + # picture size and keep the center-crop resize. if target_width is not None and target_height is not None: output_shape = output_shape._replace(width=target_width, height=target_height) # Optional frame-count trim: corrected to a valid 8k+1 source length. if target_frames is not None: output_shape = output_shape._replace(frames=target_frames) + encoding_tiling = source_encode_tiling( + self.device, height=output_shape.height, width=output_shape.width + ) + logger.info( + "Encoding source video %dx%d %d frames (tiled, CPU pixels) start=%.2fs duration=%s", + output_shape.width, + output_shape.height, + output_shape.frames, + encode_start_time, + encode_max_duration, + ) + video_encode_shape = output_shape + freeze_pad_frames = 0 + if is_extend: + video_encode_shape = output_shape._replace( + frames=output_shape.frames + extend_frames + ) + freeze_pad_frames = extend_freeze_pad_frames(self.device, extend_frames) + if freeze_pad_frames == 0: + logger.info( + "MPS extend encodes %d source frames and repeats the edge latent for +%d", + output_shape.frames, + extend_frames, + ) initial_video_latent = self.image_conditioner( - lambda enc: video_latent_from_file( - video_encoder=enc, - file_path=video_path, - output_shape=output_shape, + lambda enc: encode_source_video_latent( + enc, + video_path, + video_encode_shape, dtype=dtype, - device=self.device, tiling_config=encoding_tiling, + start_time=encode_start_time, + max_duration=encode_max_duration, + freeze_pad_frames=freeze_pad_frames, + freeze_at=extend_at, + content_width=content_width, + content_height=content_height, ) ) - # --- Encode source audio --- - initial_audio_latent = self.audio_conditioner( lambda enc: audio_latent_from_file( audio_encoder=enc, @@ -268,31 +315,31 @@ def _run( # noqa: PLR0913, PLR0915 output_shape=output_shape, dtype=dtype, device=self.device, + start_time=encode_start_time, + max_duration=encode_max_duration, ) ) # --- Resolve target shape + the temporal region to regenerate --- - # Retake regenerates an interior window [start_time, end_time]; extend grows the - # latent (zeros prepended/appended in latent-frame space, VAE temporal factor 8) - # and regenerates only the new region. The source is frozen by the mask either way. + # Retake regenerates an interior window [start_time, end_time]. Extend + # on CUDA freeze-pads pixels (cloud ``pad_video``) so seam tiles encode + # against a held frame. MPS repeats the edge latent instead. Either + # way only the new region plus MASK_DELTA into the source is denoised. + # Audio still grows in latent space (silence), matching cloud's silent pad. if is_extend: target_shape = output_shape._replace(frames=output_shape.frames + extend_frames) - pad_video_frames = ( - VideoLatentShape.from_pixel_shape(target_shape).frames - - VideoLatentShape.from_pixel_shape(output_shape).frames - ) - if initial_video_latent is not None: - initial_video_latent = self._pad_latent_frames(initial_video_latent, pad_video_frames, extend_at) if initial_audio_latent is not None: pad_audio_frames = ( AudioLatentShape.from_video_pixel_shape(target_shape).frames - AudioLatentShape.from_video_pixel_shape(output_shape).frames ) - initial_audio_latent = self._pad_latent_frames(initial_audio_latent, pad_audio_frames, extend_at) + initial_audio_latent = self._pad_latent_frames( + initial_audio_latent, pad_audio_frames, extend_at + ) # Feather the seam by MASK_DELTA frames INTO the kept source on the side adjacent # to the new region (matches the cloud gateway), so the model regenerates a short # tail/lead of real source and blends the join instead of cutting hard. - mask_delta_frames = round(_EXTEND_MASK_DELTA_SECONDS * output_shape.fps) + mask_delta_frames = round(MASK_DELTA_SECONDS * output_shape.fps) if extend_at == "start": # New content leads; extend the mask forward into the source start. region_start = 0.0 @@ -320,23 +367,28 @@ def _run( # noqa: PLR0913, PLR0915 # --- Build modality specs --- video_modality_spec = ModalitySpec( + latent=initial_video_latent, + conditioning_fps=output_shape.fps, context=v_context_p, conditionings=[TemporalRegionMask(start_time=region_start, end_time=region_end, fps=output_shape.fps)] if regenerate_video else [], - initial_latent=initial_video_latent, frozen=not regenerate_video, ) - audio_modality_spec: ModalitySpec | None = None - if a_context_p is not None: - audio_modality_spec = ModalitySpec( + audio_modality_spec = ( + None + if a_context_p is None + else _audio_modality_spec( + self.stage.video_scale_factors, + source_latent=initial_audio_latent, + video_latent=initial_video_latent, context=a_context_p, - conditionings=[TemporalRegionMask(start_time=region_start, end_time=region_end, fps=output_shape.fps)] - if (initial_audio_latent is not None and regenerate_audio) - else [], - initial_latent=initial_audio_latent, - frozen=initial_audio_latent is not None and not regenerate_audio, + fps=output_shape.fps, + region_start=region_start, + region_end=region_end, + regenerate_audio=regenerate_audio, ) + ) # --- Build denoiser --- if distilled: @@ -355,16 +407,12 @@ def _run( # noqa: PLR0913, PLR0915 ) # --- Run diffusion stage --- - video_state, audio_state = self._invoke_diffusion_stage( + video_state, audio_state = self._denoise_masked_latents( distilled=distilled, seed=effective_seed, denoiser=denoiser, sigmas=sigmas, noiser=noiser, - width=target_shape.width, - height=target_shape.height, - frames=target_shape.frames, - fps=target_shape.fps, video=video_modality_spec, audio=audio_modality_spec, ) @@ -407,28 +455,46 @@ def generate( target_width: int | None = None, target_height: int | None = None, target_frames: int | None = None, + encode_start_time: float = 0.0, + encode_max_duration: float | None = None, + content_width: int | None = None, + content_height: int | None = None, ) -> None: meta = get_videostream_metadata(video_path) fps = meta.fps num_frames = target_frames if target_frames is not None else meta.frames - video_iter, audio, tiling_config = self._run( - video_path=video_path, - prompt=prompt, - start_time=start_time, - end_time=end_time, - seed=seed, - negative_prompt=negative_prompt, - num_inference_steps=num_inference_steps, - video_guider_params=video_guider_params, - audio_guider_params=audio_guider_params, - regenerate_video=regenerate_video, - regenerate_audio=regenerate_audio, - enhance_prompt=enhance_prompt, + from services.denoising_progress import track_denoising + + plan = resolve_sampler_plan( distilled=distilled, - target_width=target_width, - target_height=target_height, - target_frames=target_frames, + use_ancestral=self.use_ancestral_sampler, + seed=seed, + dtype=self.dtype, ) + denoise_steps = plan.total_steps if distilled else num_inference_steps + with track_denoising(denoise_steps): + video_iter, audio, tiling_config = self._run( + video_path=video_path, + prompt=prompt, + start_time=start_time, + end_time=end_time, + seed=seed, + negative_prompt=negative_prompt, + num_inference_steps=num_inference_steps, + video_guider_params=video_guider_params, + audio_guider_params=audio_guider_params, + regenerate_video=regenerate_video, + regenerate_audio=regenerate_audio, + enhance_prompt=enhance_prompt, + distilled=distilled, + target_width=target_width, + target_height=target_height, + target_frames=target_frames, + encode_start_time=encode_start_time, + encode_max_duration=encode_max_duration, + content_width=content_width, + content_height=content_height, + ) audio_out: Audio | None = audio video_chunks = get_video_chunks_number(num_frames, tiling_config) encode_video( @@ -438,6 +504,7 @@ def generate( output_path=output_path, video_chunks_number=video_chunks, ) + restamp_to_source_rate(output_path, source_fps=fps) @torch.no_grad() def extend( @@ -456,30 +523,48 @@ def extend( target_width: int | None = None, target_height: int | None = None, target_frames: int | None = None, + encode_start_time: float = 0.0, + encode_max_duration: float | None = None, + content_width: int | None = None, + content_height: int | None = None, ) -> None: meta = get_videostream_metadata(video_path) fps = meta.fps source_frames = target_frames if target_frames is not None else meta.frames total_frames = source_frames + extend_frames - video_iter, audio, tiling_config = self._run( - video_path=video_path, - prompt=prompt, - start_time=0.0, - end_time=0.0, - seed=seed, - negative_prompt=negative_prompt, - video_guider_params=None, - audio_guider_params=None, - regenerate_video=True, - regenerate_audio=regenerate_audio, - enhance_prompt=enhance_prompt, + from services.denoising_progress import track_denoising + + plan = resolve_sampler_plan( distilled=distilled, - extend_frames=extend_frames, - extend_at=mode, - target_width=target_width, - target_height=target_height, - target_frames=target_frames, + use_ancestral=self.use_ancestral_sampler, + seed=seed, + dtype=self.dtype, ) + denoise_steps = plan.total_steps if distilled else 40 + with track_denoising(denoise_steps): + video_iter, audio, tiling_config = self._run( + video_path=video_path, + prompt=prompt, + start_time=0.0, + end_time=0.0, + seed=seed, + negative_prompt=negative_prompt, + video_guider_params=None, + audio_guider_params=None, + regenerate_video=True, + regenerate_audio=regenerate_audio, + enhance_prompt=enhance_prompt, + distilled=distilled, + extend_frames=extend_frames, + extend_at=mode, + target_width=target_width, + target_height=target_height, + target_frames=target_frames, + encode_start_time=encode_start_time, + encode_max_duration=encode_max_duration, + content_width=content_width, + content_height=content_height, + ) video_chunks = get_video_chunks_number(total_frames, tiling_config) encode_video( video=video_iter, @@ -488,13 +573,84 @@ def extend( output_path=output_path, video_chunks_number=video_chunks, ) + restamp_to_source_rate(output_path, source_fps=fps) @staticmethod - def _pad_latent_frames(latent: torch.Tensor, pad_frames: int, at: ExtendMode) -> torch.Tensor: - """Zero-pad a latent on its temporal axis (dim 2): front for ``start``, back for ``end``.""" + def _pad_latent_frames( + latent: torch.Tensor, + pad_frames: int, + at: ExtendMode, + ) -> torch.Tensor: + """Pad a latent on its temporal axis (dim 2): front for ``start``, back for ``end``. + + Works for 5-D video ``[B, C, T, H, W]`` and 4-D audio ``[B, C, T, F]``. + """ if pad_frames <= 0: return latent pad_shape = list(latent.shape) pad_shape[2] = pad_frames - pad = torch.zeros(pad_shape, device=latent.device, dtype=latent.dtype) - return torch.cat([pad, latent] if at == "start" else [latent, pad], dim=2) + zeros = torch.zeros(pad_shape, device=latent.device, dtype=latent.dtype) + return torch.cat([zeros, latent] if at == "start" else [latent, zeros], dim=2) + + +def _audio_modality_spec( + video_scale_factors: SpatioTemporalScaleFactors, + *, + source_latent: torch.Tensor | None, + video_latent: torch.Tensor, + context: Any, + fps: float, + region_start: float, + region_end: float, + regenerate_audio: bool, +) -> ModalitySpec: + """Audio spec for the stage. + + v1.4 needs the latent up front, so a source with no soundtrack gets a zero latent sized to + the video. That latent is fresh, so it is neither frozen nor masked: only real source + audio can be kept (``frozen``) or partially regenerated (region mask). + """ + from ltx_core.conditioning.types.noise_mask_cond import TemporalRegionMask + from ltx_pipelines.utils.helpers import create_initial_audio_latent + + had_source_audio = source_latent is not None + latent = ( + source_latent + if source_latent is not None + else create_initial_audio_latent( + video_latent, + fps=fps, + # Transformer latent geometry, not the decoder's tiling scale. + video_scale_factors=video_scale_factors, + ) + ) + return ModalitySpec( + latent=latent, + conditioning_fps=fps, + context=context, + conditionings=[TemporalRegionMask(start_time=region_start, end_time=region_end, fps=fps)] + if (had_source_audio and regenerate_audio) + else [], + frozen=had_source_audio and not regenerate_audio, + ) + + +def _pin_frozen_noise(spec: ModalitySpec) -> ModalitySpec: + """A frozen modality is clean conditioning, so it must not be noised. + + ``ModalitySpec.noise_scale`` is applied before ``frozen`` zeroes the denoise mask. Left at the + schedule's scale, the transformer would be fed a (mostly) Gaussian latent that its zero + timestep labels as clean. Upstream's ``denoise_chunks`` pins frozen specs the same way. + """ + return replace(spec, noise_scale=0.0) if spec.frozen else spec + + +def _with_stage2_latent(spec: ModalitySpec, latent: Any, noise_scale: float) -> ModalitySpec: + return _pin_frozen_noise(replace(spec, latent=latent, noise_scale=noise_scale)) + + +def _restore_frozen(state: Any, spec: ModalitySpec | None) -> Any: + """Return the input latent for a frozen modality, not the loop's bf16-drifted copy of it.""" + if state is None or spec is None or not spec.frozen: + return state + return replace(state, latent=spec.latent) diff --git a/backend/services/retake_pipeline/retake_mode.py b/backend/services/retake_pipeline/retake_mode.py new file mode 100644 index 000000000..e6f5f0b5a --- /dev/null +++ b/backend/services/retake_pipeline/retake_mode.py @@ -0,0 +1,20 @@ +"""Canonical retake mode → (regenerate_video, regenerate_audio). Raises on unknown.""" + +from __future__ import annotations + +from api_types import RetakeMode + + +class InvalidRetakeModeError(ValueError): + def __init__(self) -> None: + super().__init__("INVALID_RETAKE_MODE") + + +def resolve_retake_mode(mode: RetakeMode) -> tuple[bool, bool]: + if mode == "replace_audio_and_video": + return True, True + if mode == "replace_video": + return True, False + if mode == "replace_audio": + return False, True + raise InvalidRetakeModeError() diff --git a/backend/services/retake_pipeline/retake_pipeline.py b/backend/services/retake_pipeline/retake_pipeline.py index d97297b8c..87d9d2188 100644 --- a/backend/services/retake_pipeline/retake_pipeline.py +++ b/backend/services/retake_pipeline/retake_pipeline.py @@ -48,6 +48,10 @@ def generate( target_width: int | None = None, target_height: int | None = None, target_frames: int | None = None, + encode_start_time: float = 0.0, + encode_max_duration: float | None = None, + content_width: int | None = None, + content_height: int | None = None, ) -> None: ... def extend( @@ -66,4 +70,8 @@ def extend( target_width: int | None = None, target_height: int | None = None, target_frames: int | None = None, + encode_start_time: float = 0.0, + encode_max_duration: float | None = None, + content_width: int | None = None, + content_height: int | None = None, ) -> None: ... diff --git a/backend/services/retake_pipeline/retake_sampler.py b/backend/services/retake_pipeline/retake_sampler.py new file mode 100644 index 000000000..917554926 --- /dev/null +++ b/backend/services/retake_pipeline/retake_sampler.py @@ -0,0 +1,92 @@ +"""Distilled 2.5 sampler plan for Home/Remote retake and extend. + +T2V 2.5 injects ancestral noise in stage 1 and relies on a short Euler refine +to clean it. The masked region starts at sigma=1 (pure noise), so Euler-only +on that 8-step schedule never lets the prompt take — retake reconstructs the +source, extend morphs the last frame into sludge. Ancestral-only leaves +texture boiling. Both features need the same pair as T2V: ancestral stage 1 +plus a same-resolution Euler refine (no 2× upsample). +""" + +from __future__ import annotations + +from dataclasses import dataclass +from functools import partial +from typing import Any + +import torch + +from ltx_pipelines.distilled import ( + ANCESTRAL_ETA, + ANCESTRAL_NOISE_SEED_OFFSET, + ANCESTRAL_S_NOISE, +) +from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop + +from services.denoising_progress import distilled_total_steps + + +def _distilled_stage_sampler_kwargs( + *, + distilled: bool, + use_ancestral: bool, + seed: int, + dtype: torch.dtype, +) -> dict[str, Any]: + """Optional ``loop`` override for :class:`DiffusionStage`. + + Distilled 2.5+ checkpoints need the ancestral sampler; 2.3 and the guided + (non-distilled) path keep DiffusionStage's deterministic Euler default. + ``eta`` and ``s_noise`` belong on the loop, not on the step constructor. + """ + if not distilled or not use_ancestral: + return {} + return { + "loop": partial( + euler_ancestral_denoising_loop, + noise_seed=seed + ANCESTRAL_NOISE_SEED_OFFSET, + model_dtype=dtype, + eta=ANCESTRAL_ETA, + s_noise=ANCESTRAL_S_NOISE, + ), + } + + +def _retake_uses_two_stage(*, distilled: bool, use_ancestral: bool) -> bool: + return bool(distilled and use_ancestral) + + +def _retake_denoise_steps( + *, distilled: bool, use_ancestral: bool, guided_steps: int = 40 +) -> int: + if not distilled: + return guided_steps + return distilled_total_steps(stage_2=use_ancestral) + + +@dataclass(frozen=True) +class SamplerPlan: + two_stage: bool + total_steps: int + stage1: dict[str, Any] + refine: dict[str, Any] + + +def resolve_sampler_plan( + *, + distilled: bool, + use_ancestral: bool, + seed: int, + dtype: torch.dtype, +) -> SamplerPlan: + two_stage = _retake_uses_two_stage(distilled=distilled, use_ancestral=use_ancestral) + return SamplerPlan( + two_stage=two_stage, + total_steps=_retake_denoise_steps(distilled=distilled, use_ancestral=two_stage), + stage1=_distilled_stage_sampler_kwargs( + distilled=distilled, use_ancestral=two_stage, seed=seed, dtype=dtype + ), + refine=_distilled_stage_sampler_kwargs( + distilled=distilled, use_ancestral=False, seed=seed, dtype=dtype + ), + ) diff --git a/backend/services/retake_pipeline/retake_stitch.py b/backend/services/retake_pipeline/retake_stitch.py new file mode 100644 index 000000000..eaff103d0 --- /dev/null +++ b/backend/services/retake_pipeline/retake_stitch.py @@ -0,0 +1,320 @@ +"""Put original pixels back so Home retake is not a VAE round-trip outside the edit. + +Same stitch as ltxv-api ``stitch_frames`` / ``stitch_audio`` +(``inference/pipelines/src/pipelines/retake/pipeline.py``): original frames +outside a short RGB lerp, generated frames for the user mask, audio cut on +that mask. The lerp is at most ``MAX_FADE_FRAMES`` (16). + +Only that band is re-encoded in Python. The prefix and suffix are frame-trimmed +in ffmpeg. A bitstream copy cannot cut on a frame index, so those wings are +encoded once by that trim, not decoded in Python first. GenSpace +``POST /api/retake`` does not call this. +""" + +from __future__ import annotations + +import shutil +from collections.abc import Iterator +from dataclasses import dataclass +from pathlib import Path + +import numpy as np + +from services.ffmpeg import ( + FFMPEG_PROTOCOL_WHITELIST, + run_ffmpeg, + timeout_for_source_duration, +) +from services.media_probe import media_has_audio +from handlers.video_resolution import SpatialLetterbox, generation_letterbox +from services.retake_pipeline.rgb_stitch import ( + FadeWindow, + blend_fade, + exact_rate, + iter_generated, + write_rgb_video, +) +from services.retake_pipeline.stitch_audio import AudioPiece, audio_cut_graph +from services.retake_pipeline.stitch_silence import append_silence_input +from services.retake_pipeline.window import MAX_FADE_FRAMES, RetakeEncodeWindow + +_has_audio = media_has_audio + + +@dataclass(frozen=True) +class ReencodeSpan: + """Source-absolute prefix/suffix, and the window-relative band Python encodes.""" + + prefix_end: int + suffix_start: int + fade_in_start: int + edit_start: int + edit_end: int + fade_out_end: int + + +def fade_window_for_retake(window: RetakeEncodeWindow) -> FadeWindow: + """User mask in generated-file frames. Context outside it stays original.""" + mask_frames = window.mask_end_frame - window.mask_start_frame + return FadeWindow( + 0, + window.encode_frames, + window.context_before_frames, + window.context_before_frames + mask_frames, + ) + + +def reencode_span(window: RetakeEncodeWindow) -> ReencodeSpan: + fade = fade_window_for_retake(window) + origin = window.encode_start_frame + fade_in = min(MAX_FADE_FRAMES, fade.edit_start - fade.context_start) + fade_out = min(MAX_FADE_FRAMES, fade.context_end - fade.edit_end) + fade_in_start = fade.edit_start - fade_in + fade_out_end = fade.edit_end + fade_out + return ReencodeSpan( + prefix_end=origin + fade_in_start, + suffix_start=origin + fade_out_end, + fade_in_start=fade_in_start, + edit_start=fade.edit_start, + edit_end=fade.edit_end, + fade_out_end=fade_out_end, + ) + + +def retake_audio_graph( + window: RetakeEncodeWindow, fps: float, *, source_label: str, generated_label: str = "[2:a]" +) -> str: + """Hard-cut audio at the user mask. Video fades; audio does not.""" + mask_frames = window.mask_end_frame - window.mask_start_frame + generated_start = window.context_before_frames / fps + pieces: list[AudioPiece] = [] + if window.mask_start_frame > 0: + pieces.append(AudioPiece(source_label, end=window.mask_start_frame / fps)) + pieces.append( + AudioPiece( + generated_label, + start=generated_start, + end=(window.context_before_frames + mask_frames) / fps, + ) + ) + if window.mask_end_frame < window.source_frames: + pieces.append(AudioPiece(source_label, start=window.mask_end_frame / fps)) + return audio_cut_graph(pieces) + + +def _middle_frames( + *, + source_path: str, + generated_path: str, + window: RetakeEncodeWindow, + span: ReencodeSpan, + box: SpatialLetterbox, +) -> Iterator[np.ndarray]: + fade = fade_window_for_retake(window) + yield from blend_fade( + source_path=source_path, + generated_path=generated_path, + source_start=span.prefix_end, + generated_start=span.fade_in_start, + count=span.edit_start - span.fade_in_start, + fade=fade, + box=box, + ) + yield from iter_generated(generated_path, span.edit_start, span.edit_end, box) + yield from blend_fade( + source_path=source_path, + generated_path=generated_path, + source_start=window.encode_start_frame + span.edit_end, + generated_start=span.edit_end, + count=span.fade_out_end - span.edit_end, + fade=fade, + box=box, + ) + + +def _video_filter( + span: ReencodeSpan, window: RetakeEncodeWindow, fps: float, box: SpatialLetterbox +) -> str: + rate = exact_rate(fps) + restamp = f"setpts=N*{rate.denominator}/({rate.numerator}*TB)" + scale = ( + f"scale={box.content_width}:{box.content_height}:flags=lanczos,setsar=1,format=yuv420p" + ) + parts: list[str] = [] + labels: list[str] = [] + if span.prefix_end > 0: + parts.append(f"[0:v]trim=end_frame={span.prefix_end},{restamp},{scale}[vp]") + labels.append("[vp]") + parts.append(f"[1:v]{restamp},{scale}[vm]") + labels.append("[vm]") + if span.suffix_start < window.source_frames: + parts.append(f"[0:v]trim=start_frame={span.suffix_start},{restamp},{scale}[vs]") + labels.append("[vs]") + parts.append(f"{''.join(labels)}concat=n={len(labels)}:v=1:a=0[v]") + return ";".join(parts) + + +def _assemble( + *, + source_path: str, + generated_path: str, + middle_path: str, + dest_path: str, + window: RetakeEncodeWindow, + span: ReencodeSpan, + fps: float, + box: SpatialLetterbox, + generated_has_audio: bool, + silence_original: bool, +) -> None: + rate = exact_rate(fps) + args: list[str] = [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + source_path, + "-i", + middle_path, + ] + source_label = "[0:a]" + graph = _video_filter(span, window, fps, box) + if generated_has_audio: + args.extend(["-i", generated_path]) + if silence_original: + append_silence_input(args) + source_label = "[3:a]" + graph = graph + ";" + retake_audio_graph(window, fps, source_label=source_label) + args.extend( + [ + "-filter_complex", + graph, + "-map", + "[v]", + "-r", + f"{rate.numerator}/{rate.denominator}", + "-pix_fmt", + "yuv420p", + "-colorspace", + "bt709", + "-color_primaries", + "bt709", + "-color_trc", + "bt709", + "-color_range", + "tv", + ] + ) + if generated_has_audio: + args.extend(["-map", "[a]"]) + args.extend(["-protocol_whitelist", FFMPEG_PROTOCOL_WHITELIST, dest_path]) + run_ffmpeg(args, timeout=timeout_for_source_duration(window.source_frames / fps)) + + +def _nothing_to_restore(window: RetakeEncodeWindow) -> bool: + return ( + window.encode_start_frame == 0 + and window.context_before_frames == 0 + and window.context_after_frames == 0 + and window.encode_frames >= window.source_frames + ) + + +def stitch_retake_output( + *, + source_path: str, + windowed_path: str, + dest_path: str, + window: RetakeEncodeWindow, + fps: float, + target_width: int, + target_height: int, +) -> None: + dest = Path(dest_path) + dest.parent.mkdir(parents=True, exist_ok=True) + box = generation_letterbox(target_width, target_height) + if _nothing_to_restore(window): + _place_window(windowed_path, dest, box) + return + span = reencode_span(window) + if span.suffix_start < span.prefix_end: + raise ValueError("retake re-encode span is inverted") + generated_has_audio = _has_audio(windowed_path) + silence_original = generated_has_audio and not _has_audio(source_path) + middle = dest.with_name(f"{dest.stem}.middle{dest.suffix}") + try: + write_rgb_video( + middle, + _checked_middle( + source_path=source_path, + generated_path=windowed_path, + window=window, + span=span, + box=box, + ), + fps=fps, + width=box.content_width, + height=box.content_height, + ) + _assemble( + source_path=source_path, + generated_path=windowed_path, + middle_path=str(middle), + dest_path=str(dest), + window=window, + span=span, + fps=fps, + box=box, + generated_has_audio=generated_has_audio, + silence_original=silence_original, + ) + finally: + middle.unlink(missing_ok=True) + + +def _place_window(windowed_path: str, dest: Path, box: SpatialLetterbox) -> None: + """The whole clip was the encode. Crop the bars, or copy when there are none.""" + if box.canvas_width == box.content_width and box.canvas_height == box.content_height: + shutil.copy2(windowed_path, dest) + return + run_ffmpeg( + [ + "-y", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + windowed_path, + "-vf", + f"crop={box.content_width}:{box.content_height}:{box.left}:{box.top}", + "-pix_fmt", + "yuv420p", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + str(dest), + ] + ) + + +def _checked_middle( + *, + source_path: str, + generated_path: str, + window: RetakeEncodeWindow, + span: ReencodeSpan, + box: SpatialLetterbox, +) -> Iterator[np.ndarray]: + expected = span.fade_out_end - span.fade_in_start + count = 0 + for frame in _middle_frames( + source_path=source_path, + generated_path=generated_path, + window=window, + span=span, + box=box, + ): + yield frame + count += 1 + if count != expected: + raise ValueError( + f"Retake blend produced {count} frames, expected {expected}" + ) diff --git a/backend/services/retake_pipeline/rgb_stitch.py b/backend/services/retake_pipeline/rgb_stitch.py new file mode 100644 index 000000000..4b6508cab --- /dev/null +++ b/backend/services/retake_pipeline/rgb_stitch.py @@ -0,0 +1,225 @@ +"""RGB lerp shared by Home/Remote retake and extend stitches. + +Same control flow as ltxv-api ``stitch_frames`` +(``inference/pipelines/src/pipelines/retake/pipeline.py``): up to +``MAX_FADE_FRAMES`` of ``lerp``, then the generated edit, then the fade back. +ffmpeg ``xfade`` in yuv420p is not that lerp and flashes highlights. +""" + +from __future__ import annotations + +from collections.abc import Iterator +from dataclasses import dataclass +from fractions import Fraction +from pathlib import Path + +import av +import numpy as np + +from handlers.video_resolution import SpatialLetterbox +from services.retake_pipeline.letterbox import crop_letterbox, resize_rgb +from services.retake_pipeline.window import MAX_FADE_FRAMES + + +@dataclass(frozen=True) +class FadeWindow: + """Coordinates on the generated file, which starts at context frame 0.""" + + context_start: int + context_end: int + edit_start: int + edit_end: int + + +def generated_weight(index: int, window: FadeWindow) -> float: + """Weight of the generated frame. 0 = original, 1 = generated.""" + fade_in = min(MAX_FADE_FRAMES, window.edit_start - window.context_start) + fade_out = min(MAX_FADE_FRAMES, window.context_end - window.edit_end) + fade_in_start = window.edit_start - fade_in + fade_out_end = window.edit_end + fade_out + if fade_in > 0 and fade_in_start <= index < window.edit_start: + return (index - fade_in_start) / fade_in + if window.edit_start <= index < window.edit_end: + return 1.0 + if fade_out > 0 and window.edit_end <= index < fade_out_end: + return (fade_out_end - index - 1) / fade_out + return 0.0 + + +def exact_rate(fps: float) -> Fraction: + """24000/1001 for 23.976, 25/1 for 25. The rational the source was mastered at.""" + return Fraction(fps).limit_denominator(1001) + + +def blend_rgb(source: np.ndarray, generated: np.ndarray, weight: float) -> np.ndarray: + if weight <= 0: + return source + if weight >= 1: + return generated + mixed = source.astype(np.float32) * (1.0 - weight) + generated.astype(np.float32) * weight + return np.clip(mixed, 0, 255).astype(np.uint8) + + +# Below this, decoding from frame 0 is cheaper than a keyframe seek and is exact. +_SEEK_MIN_START_FRAME = 48 + + +def _frame_index( + pts: int | None, time_base: Fraction | None, rate: Fraction, origin: int +) -> int | None: + """Decoded-frame index. ``origin`` is the stream start, in ``time_base`` ticks.""" + if pts is None or time_base is None: + return None + return int(round((Fraction(pts) - origin) * time_base * rate)) + + +def _decode_span(path: str, start_frame: int, end_frame: int) -> Iterator[np.ndarray]: + """Frames ``[start_frame, end_frame)`` as decoded. May end short. + + A late span seeks to the previous keyframe and counts forward from the + stream start, not from timestamp zero. If that landing is already past + the span, or the file has no timestamps, decode from frame 0. + """ + if end_frame <= start_frame: + return + with av.open(path) as container: + stream = container.streams.video[0] + rate = stream.average_rate + time_base = stream.time_base + origin = 0 if stream.start_time is None else int(stream.start_time) + index = 0 + first = None + if ( + start_frame >= _SEEK_MIN_START_FRAME + and rate + and time_base is not None + ): + target_pts = origin + int(Fraction(start_frame) / Fraction(rate) / time_base) + try: + container.seek( + max(target_pts, 0), stream=stream, backward=True, any_frame=False + ) + decoded = container.decode(stream) + first = next(decoded, None) + except av.FFmpegError: + container.seek(0, stream=stream, backward=True, any_frame=False) + decoded = container.decode(stream) + first = None + else: + landed = _frame_index( + None if first is None else first.pts, + time_base, + Fraction(rate), + origin, + ) + if first is None or landed is None or landed < 0 or landed > start_frame: + container.seek(0, stream=stream, backward=True, any_frame=False) + decoded = container.decode(stream) + first = None + else: + index = landed + else: + decoded = container.decode(stream) + + if first is not None: + if index >= start_frame: + yield first.to_ndarray(format="rgb24") + index += 1 + for frame in decoded: + if index >= end_frame: + break + if index >= start_frame: + yield frame.to_ndarray(format="rgb24") + index += 1 + + +def iter_span( + path: str, start_frame: int, end_frame: int, width: int, height: int +) -> Iterator[np.ndarray]: + """Frames ``[start_frame, end_frame)`` at ``width`` x ``height``. + + Raises if the file ends early: a short span would desync the audio cut. + """ + count = 0 + for frame in _decode_span(path, start_frame, end_frame): + yield resize_rgb(frame, width, height) + count += 1 + expected = max(0, end_frame - start_frame) + if count != expected: + raise ValueError( + f"Span [{start_frame}, {end_frame}) of {path} has {count} frames, expected {expected}" + ) + + +def iter_source( + path: str, start_frame: int, end_frame: int, box: SpatialLetterbox +) -> Iterator[np.ndarray]: + """Original frames at the picture size.""" + return iter_span(path, start_frame, end_frame, box.content_width, box.content_height) + + +def iter_generated( + path: str, start_frame: int, end_frame: int, box: SpatialLetterbox +) -> Iterator[np.ndarray]: + """Generated frames with the encode's black bars cropped off. + + Resizing the letterboxed encode down to the picture would squash the bars + into the image and shift the seam. + """ + for frame in iter_span(path, start_frame, end_frame, box.canvas_width, box.canvas_height): + yield crop_letterbox(frame, box) + + +def blend_fade( + *, + source_path: str, + generated_path: str, + source_start: int, + generated_start: int, + count: int, + fade: FadeWindow, + box: SpatialLetterbox, +) -> Iterator[np.ndarray]: + """``count`` frames of the lerp between the original and the generated clip.""" + pairs = zip( + iter_source(source_path, source_start, source_start + count, box), + iter_generated(generated_path, generated_start, generated_start + count, box), + strict=True, + ) + for offset, (source_frame, generated_frame) in enumerate(pairs): + yield blend_rgb( + source_frame, generated_frame, generated_weight(generated_start + offset, fade) + ) + + +def write_rgb_video( + dest: Path, + frames: Iterator[np.ndarray], + *, + fps: float, + width: int, + height: int, +) -> None: + dest.parent.mkdir(parents=True, exist_ok=True) + rate = exact_rate(fps) + with av.open(str(dest), mode="w") as container: + stream = container.add_stream("libx264", rate=rate) # type: ignore[reportUnknownMemberType] + stream.width = width + stream.height = height + stream.pix_fmt = "yuv420p" + # yuv420p is limited-range. Tagging these full-range RGB frames as + # JPEG/full makes the decoder skip the limited-to-full expand, so black + # comes back as 16. Limited (MPEG) is the tag that round-trips. + stream.codec_context.colorspace = 1 + stream.codec_context.color_primaries = 1 + stream.codec_context.color_trc = 1 + stream.codec_context.color_range = 1 + pts = 0 + for pixels in frames: + video_frame = av.VideoFrame.from_ndarray(pixels, format="rgb24") + video_frame.pts = pts + pts += 1 + for packet in stream.encode(video_frame): + container.mux(packet) + for packet in stream.encode(): + container.mux(packet) diff --git a/backend/services/retake_pipeline/source_encode.py b/backend/services/retake_pipeline/source_encode.py new file mode 100644 index 000000000..f6ccf98ca --- /dev/null +++ b/backend/services/retake_pipeline/source_encode.py @@ -0,0 +1,181 @@ +"""VAE-encode a source clip without assembling pixels on CUDA. + +``ltx_pipelines.utils.helpers.video_latent_from_file`` decodes every frame onto +the GPU and ``torch.cat``s them. On Windows WDDM that reserved ~67 GiB on a +32 GB 5090 (``free=0``) during retake encode. The first job still returned; the +next encode after DiffVAE neighborhood-attention decode never did. + +``VideoEncoder.tiled_encode`` already copies each tile to the model device, so +the pixel tensor can stay on CPU. Callers pass a probed ``output_shape`` (fps, +size, frame count) and a non-EXR path. +""" + +from __future__ import annotations + +from collections.abc import Iterable + +import torch +from ltx_core.model.video_vae import DimensionSizeConfig, TileSizeConfig, VideoEncoder +from ltx_core.tiling import TileCountConfig +from ltx_core.types import VideoLatentShape, VideoPixelShape +from ltx_pipelines.utils.helpers import decode_video_from_file, video_preprocess +from ltx_pipelines.utils.media_io.range_map import normalize_images + +from handlers.video_resolution import generation_letterbox +from services.retake_pipeline.letterbox import fit_and_pad + + +# CUDA keeps small tiles: one encoder forward must stay small on a 32 GB card. +# MPS uses the library default (80 frames × 768). The 24×256 grid turns one +# 1080p extend into hundreds of forwards. +_CUDA_ENCODE_TILING = TileSizeConfig( + frames=DimensionSizeConfig(tile_size=24, overlap=16), + height=DimensionSizeConfig(tile_size=256, overlap=64), + width=DimensionSizeConfig(tile_size=256, overlap=64), +) +# 540p snaps to 960×512. One spatial tile stayed near 8 GiB on an M4 Pro. +# 720p is 1280 and climbed to 17 GiB, so it keeps the 768 default. A square +# 960×960 has the same long edge and about twice the pixels; that stays on +# the default tiles until it is measured. +_MPS_SINGLE_TILE_MAX_PIXELS = 960 * 512 + + +def source_encode_tiling( + device: torch.device, *, height: int = 0, width: int = 0 +) -> TileSizeConfig: + if device.type != "mps": + return _CUDA_ENCODE_TILING + default = TileSizeConfig.default() + if height <= 0 or width <= 0 or height * width > _MPS_SINGLE_TILE_MAX_PIXELS: + return default + return TileSizeConfig( + frames=default.frames, + height=DimensionSizeConfig( + tile_size=max(default.height.tile_size, height), + overlap=default.height.overlap, + ), + width=DimensionSizeConfig( + tile_size=max(default.width.tile_size, width), + overlap=default.width.overlap, + ), + ) + + +def extend_freeze_pad_frames(device: torch.device, extend_frames: int) -> int: + """How many held frames to VAE-encode beyond the source. + + CUDA pixel-freezes the whole tail (cloud ``pad_video``). Those copies are + cheap there and the seam tiles see a held frame. MPS encodes the source + only and repeats the edge latent: each Mac tile is ~30s, and the new + frames are fully noised at sigma 1. + """ + if device.type == "mps": + return 0 + return extend_frames + + +def _match_latent_length( + latent: torch.Tensor, expected_frames: int, *, at: str = "end" +) -> torch.Tensor: + actual = latent.shape[2] + if actual > expected_frames: + return latent[:, :, :expected_frames] + if actual < expected_frames: + # Repeat the edge rather than zeros: zeros at the source tail sit in the + # extend/retake seam and decode as sludge. Cloud pad_video freezes pixels. + edge = latent[:, :, :1] if at == "start" else latent[:, :, -1:] + extra = edge.repeat(1, 1, expected_frames - actual, *([1] * (latent.ndim - 3))) + return torch.cat([extra, latent] if at == "start" else [latent, extra], dim=2) + return latent + + +def _freeze_pad_pixels( + frames: torch.Tensor, + target_frames: int, + *, + at: str, +) -> torch.Tensor: + """Repeat first/last pixel frame so the VAE encodes a freeze-frame tail/lead.""" + have = frames.shape[2] + if have == target_frames: + return frames + if have > target_frames: + return frames[:, :, :target_frames] + pad = target_frames - have + edge = frames[:, :, :1] if at == "start" else frames[:, :, -1:] + extra = edge.repeat(1, 1, pad, 1, 1) + return torch.cat([extra, frames] if at == "start" else [frames, extra], dim=2) + + +def _letterbox_preprocess( + frames: Iterable[torch.Tensor], + content_width: int, + content_height: int, + canvas_width: int, + canvas_height: int, + dtype: torch.dtype, + device: torch.device, +) -> torch.Tensor: + """Fit each frame to the picture and center it on the black ÷32 canvas. + + ``video_preprocess`` center-crops instead, which shifts rows relative to a + stitch that stretches. The canvas must already be the letterbox of the picture. + """ + box = generation_letterbox(content_width, content_height) + if box.canvas_width != canvas_width or box.canvas_height != canvas_height: + raise ValueError( + f"Encode canvas {canvas_width}x{canvas_height} is not the letterbox of " + f"{content_width}x{content_height} ({box.canvas_width}x{box.canvas_height})" + ) + result: torch.Tensor | None = None + for frame in frames: + canvas = fit_and_pad(frame.reshape(frame.shape[-3:]).numpy(), box) + image = torch.as_tensor(canvas).permute(2, 0, 1).unsqueeze(0).to(torch.float32) + tensor = normalize_images(image.unsqueeze(2), device, dtype) + result = tensor if result is None else torch.cat([result, tensor], dim=2) + if result is None: + raise ValueError("letterbox preprocess received no frames") + return result + + +def encode_source_video_latent( + video_encoder: VideoEncoder, + file_path: str, + output_shape: VideoPixelShape, + *, + dtype: torch.dtype, + tiling_config: TileSizeConfig | TileCountConfig | None, + start_time: float = 0.0, + max_duration: float | None = None, + freeze_pad_frames: int = 0, + freeze_at: str = "end", + content_width: int | None = None, + content_height: int | None = None, +) -> torch.Tensor: + cpu = torch.device("cpu") + fps = output_shape.fps + duration = max_duration or output_shape.frames / fps + frame_gen = decode_video_from_file( + path=file_path, device=cpu, start_time=start_time, max_duration=duration + ) + if content_width is not None and content_height is not None: + frames = _letterbox_preprocess( + frame_gen, + content_width, + content_height, + output_shape.width, + output_shape.height, + dtype, + cpu, + ) + else: + frames = video_preprocess( + frame_gen, output_shape.height, output_shape.width, dtype, cpu + ) + if freeze_pad_frames > 0: + frames = _freeze_pad_pixels(frames, output_shape.frames, at=freeze_at) + latents = video_encoder.tiled_encode(frames, tiling_config) + required_latent_frames = VideoLatentShape.from_pixel_shape( + output_shape, scale_factors=video_encoder.video_scale_factors + ).frames + return _match_latent_length(latents, required_latent_frames, at=freeze_at) diff --git a/backend/services/retake_pipeline/stitch_audio.py b/backend/services/retake_pipeline/stitch_audio.py new file mode 100644 index 000000000..39d24c2c1 --- /dev/null +++ b/backend/services/retake_pipeline/stitch_audio.py @@ -0,0 +1,34 @@ +"""Hard-cut audio for retake and extend stitches. Video fades; audio does not.""" + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import dataclass + +from services.ffmpeg import ffmpeg_seconds + + +@dataclass(frozen=True) +class AudioPiece: + """``label`` between ``start`` and ``end`` seconds. ``None`` runs to that edge.""" + + label: str + start: float | None = None + end: float | None = None + + +def audio_cut_graph(pieces: Sequence[AudioPiece]) -> str: + """Concatenate ``pieces`` in order into ``[a]``.""" + parts: list[str] = [] + outputs: list[str] = [] + for index, piece in enumerate(pieces): + bounds: list[str] = [] + if piece.start is not None: + bounds.append(f"start={ffmpeg_seconds(piece.start)}") + if piece.end is not None: + bounds.append(f"end={ffmpeg_seconds(piece.end)}") + output = f"[p{index}]" + parts.append(f"{piece.label}atrim={':'.join(bounds)},asetpts=PTS-STARTPTS{output}") + outputs.append(output) + parts.append(f"{''.join(outputs)}concat=n={len(outputs)}:v=0:a=1[a]") + return ";".join(parts) diff --git a/backend/services/retake_pipeline/stitch_silence.py b/backend/services/retake_pipeline/stitch_silence.py new file mode 100644 index 000000000..d7ef531a8 --- /dev/null +++ b/backend/services/retake_pipeline/stitch_silence.py @@ -0,0 +1,19 @@ +"""Shared lavfi silence for retake/extend pixel stitch when the source has no audio.""" + +SILENCE_INPUT = "anullsrc=channel_layout=stereo:sample_rate=48000" + + +def append_silence_input(args: list[str]) -> None: + """Add silence as the last input, then end the output with the video. + + ``anullsrc`` never ends. A stitch that keeps its tail (``atrim=start=...``) would + otherwise encode silence forever and ffmpeg would only stop at the timeout, so the + output is cut when the shortest stream (the finite video) ends. ``-shortest`` is an + output option: it must come after every ``-i``, which is why it is added here, after + the last input. + """ + args.extend(["-f", "lavfi", "-i", SILENCE_INPUT, "-shortest"]) + + +def original_audio_ref(silence_original: bool) -> str: + return "[2:a]" if silence_original else "[0:a]" diff --git a/backend/services/retake_pipeline/window.py b/backend/services/retake_pipeline/window.py new file mode 100644 index 000000000..7a87c3298 --- /dev/null +++ b/backend/services/retake_pipeline/window.py @@ -0,0 +1,275 @@ +"""Encode-window math for Home/Remote retake and extend. + +GenSpace callers omit ``max_input_frames`` on extend and never call retake +windowing — they still encode the whole source. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +from api_types import ExtendMode + +MAX_INPUT_FRAMES = 505 +VAE_TEMPORAL_DIVISOR = 8 +MASK_DELTA_SECONDS = 0.5 +RETAKE_BLEND_SECONDS = 0.3 +# ltxv-api ``stitch_frames`` lerp band (``MAX_FADE_FRAMES = 16``). +MAX_FADE_FRAMES = 16 +_BLEND_GUARD_FRAMES = 1 +# The denoise mask covers whole latents, so it spills up to 7 frames past the +# feathered region, and the decoder bleeds about one more latent. The encode +# window keeps that much context so the 16-frame lerp has original frames +# beside the regenerated span. +LATENT_ROUNDING_FRAMES = VAE_TEMPORAL_DIVISOR - 1 +STITCH_GUARD_FRAMES = VAE_TEMPORAL_DIVISOR + + +@dataclass(frozen=True) +class ExtendEncodeWindow: + context_frames: int + encode_start_frame: int + dropped_prefix_frames: int + dropped_suffix_frames: int + + def start_time(self, fps: float) -> float: + return self.encode_start_frame / fps + + def max_duration(self, fps: float) -> float: + return self.context_frames / fps + + +@dataclass(frozen=True) +class RetakeEncodeWindow: + encode_start_frame: int + encode_frames: int + mask_start_frame: int + mask_end_frame: int + context_before_frames: int + context_after_frames: int + source_frames: int + + def encode_start_time(self, fps: float) -> float: + return self.encode_start_frame / fps + + def encode_duration(self, fps: float) -> float: + return self.encode_frames / fps + + def window_mask_start(self, fps: float) -> float: + return (self.mask_start_frame - self.encode_start_frame) / fps + + def window_mask_end(self, fps: float) -> float: + return (self.mask_end_frame - self.encode_start_frame) / fps + + +def vae_align_down(length: int) -> int: + """Largest positive ``8 * k + 1`` that is ``<= length``.""" + if length <= 1: + return 1 + return length - ((length - 1) % VAE_TEMPORAL_DIVISOR) + + +def duration_to_extend_frames(duration: float, fps: float) -> int: + """Snap extend duration up to a multiple of 8 so the padded output stays 8k+1.""" + frames = round(duration * fps) + return ( + (frames + VAE_TEMPORAL_DIVISOR - 1) // VAE_TEMPORAL_DIVISOR + ) * VAE_TEMPORAL_DIVISOR + + +def window_for_extend( + *, + source_frames: int, + extend_frames: int, + mode: ExtendMode, + max_input_frames: int | None = None, +) -> ExtendEncodeWindow: + if source_frames <= 0 or extend_frames <= 0: + raise ValueError("source_frames and extend_frames must be positive") + if max_input_frames is None: + return ExtendEncodeWindow( + context_frames=source_frames, + encode_start_frame=0, + dropped_prefix_frames=0, + dropped_suffix_frames=0, + ) + if extend_frames >= max_input_frames: + raise ValueError( + f"Extend duration ({extend_frames} frames) exceeds limit ({max_input_frames})" + ) + context_budget = max_input_frames - extend_frames + context_frames = vae_align_down(min(source_frames, context_budget)) + if context_frames <= 0: + raise ValueError( + f"Extend duration ({extend_frames} frames) exceeds limit ({max_input_frames})" + ) + dropped = max(0, source_frames - context_frames) + if mode == "end": + return ExtendEncodeWindow( + context_frames=context_frames, + encode_start_frame=dropped, + dropped_prefix_frames=dropped, + dropped_suffix_frames=0, + ) + return ExtendEncodeWindow( + context_frames=context_frames, + encode_start_frame=0, + dropped_prefix_frames=0, + dropped_suffix_frames=dropped, + ) + + +def window_for_retake( + *, + source_frames: int, + mask_start_frame: int, + mask_end_frame: int, + max_input_frames: int | None = MAX_INPUT_FRAMES, + fps: float | None = None, +) -> RetakeEncodeWindow: + if source_frames <= 0: + raise ValueError("source_frames must be positive") + mask_start_frame = max(0, min(source_frames, mask_start_frame)) + mask_end_frame = max(mask_start_frame, min(source_frames, mask_end_frame)) + mask_frames = mask_end_frame - mask_start_frame + if mask_frames <= 0: + raise ValueError("mask region must contain at least one frame") + + cap = source_frames if max_input_frames is None else min(source_frames, max_input_frames) + leftover_source = mask_start_frame > 0 or mask_end_frame < source_frames + if mask_frames > cap or (mask_frames == cap and leftover_source): + raise ValueError( + f"Mask region ({mask_frames} frames) too large for max segment size ({cap} frames)" + ) + + available_before = mask_start_frame + available_after = source_frames - mask_end_frame + if mask_frames >= cap: + return RetakeEncodeWindow( + encode_start_frame=mask_start_frame, + encode_frames=vae_align_down(mask_frames), + mask_start_frame=mask_start_frame, + mask_end_frame=mask_end_frame, + context_before_frames=0, + context_after_frames=0, + source_frames=source_frames, + ) + + per_side = max(0, (cap - mask_frames) // 2) + context_before = min(per_side, available_before) + context_after = min(per_side, available_after) + + if fps is not None and fps > 0: + min_blend = math.ceil((RETAKE_BLEND_SECONDS + MASK_DELTA_SECONDS) * fps) + min_blend += LATENT_ROUNDING_FRAMES + STITCH_GUARD_FRAMES + _BLEND_GUARD_FRAMES + grown_before = context_before + grown_after = context_after + if context_before > 0: + grown_before = max(context_before, min(min_blend, available_before)) + if context_after > 0: + grown_after = max(context_after, min(min_blend, available_after)) + if grown_before + mask_frames + grown_after <= cap: + context_before = grown_before + context_after = grown_after + + leftover = cap - (context_before + mask_frames + context_after) + grow_after = min(leftover, available_after - context_after) + context_after += max(0, grow_after) + leftover -= max(0, grow_after) + grow_before = min(leftover, available_before - context_before) + context_before += max(0, grow_before) + + context_before, context_after = _align_context( + context_before, + mask_frames, + context_after, + available_before, + available_after, + cap, + ) + encode_frames = context_before + mask_frames + context_after + encode_start = mask_start_frame - context_before + return RetakeEncodeWindow( + encode_start_frame=encode_start, + encode_frames=encode_frames, + mask_start_frame=mask_start_frame, + mask_end_frame=mask_end_frame, + context_before_frames=context_before, + context_after_frames=context_after, + source_frames=source_frames, + ) + + +def feathered_mask_times(window: RetakeEncodeWindow, fps: float) -> tuple[float, float]: + """Widen the denoise mask MASK_DELTA into kept context (Home extend seam).""" + start = window.window_mask_start(fps) + end = window.window_mask_end(fps) + duration = window.encode_duration(fps) + if window.context_before_frames > 0: + start = max(0.0, start - MASK_DELTA_SECONDS) + if window.context_after_frames > 0: + end = min(duration, end + MASK_DELTA_SECONDS) + return start, end + + +def _latent_frame_span(latent: int) -> tuple[int, int]: + """Window frames ``[start, end)`` one latent decodes to (causal: latent 0 is frame 0).""" + if latent == 0: + return 0, 1 + return VAE_TEMPORAL_DIVISOR * latent - (VAE_TEMPORAL_DIVISOR - 1), ( + VAE_TEMPORAL_DIVISOR * latent + 1 + ) + + +def denoised_frame_span(window: RetakeEncodeWindow, fps: float) -> tuple[int, int]: + """Window frames ``[start, end)`` the retake actually regenerates. + + ``TemporalRegionMask`` denoises every latent whose frames overlap the + feathered region, so the span snaps outward to latent boundaries. + """ + region_start, region_end = feathered_mask_times(window, fps) + latents = (window.encode_frames - 1) // VAE_TEMPORAL_DIVISOR + 1 + spans = [ + span + for span in map(_latent_frame_span, range(latents)) + if span[1] / fps > region_start and span[0] / fps < region_end + ] + if not spans: + return window.mask_start_frame - window.encode_start_frame, ( + window.mask_end_frame - window.encode_start_frame + ) + return spans[0][0], min(window.encode_frames, spans[-1][1]) + + +def _align_context( + context_before: int, + mask_frames: int, + context_after: int, + available_before: int, + available_after: int, + cap: int, +) -> tuple[int, int]: + total = context_before + mask_frames + context_after + remainder = (total - 1) % VAE_TEMPORAL_DIVISOR + extra = 0 if remainder == 0 else VAE_TEMPORAL_DIVISOR - remainder + for _ in range(extra): + if total >= cap: + break + if context_after < available_after: + context_after += 1 + total += 1 + elif context_before < available_before: + context_before += 1 + total += 1 + else: + break + aligned = vae_align_down(context_before + mask_frames + context_after) + overflow = context_before + mask_frames + context_after - aligned + while overflow > 0 and context_after > 0: + context_after -= 1 + overflow -= 1 + while overflow > 0 and context_before > 0: + context_before -= 1 + overflow -= 1 + return context_before, context_after diff --git a/backend/services/schema/0001_initial_schema.sql b/backend/services/schema/0001_initial_schema.sql new file mode 100644 index 000000000..6fd248ba6 --- /dev/null +++ b/backend/services/schema/0001_initial_schema.sql @@ -0,0 +1,81 @@ +CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY, + applied_at INTEGER NOT NULL +); + +CREATE TABLE IF NOT EXISTS generations ( + id TEXT PRIMARY KEY, + feature TEXT NOT NULL, + contract_version INTEGER NOT NULL CHECK (contract_version > 0), + status TEXT NOT NULL CHECK (status IN ('queued','running','cancelling','succeeded','failed','cancelled')), + spec TEXT NOT NULL CHECK (json_valid(spec)), + error_code TEXT, + created_at INTEGER NOT NULL, + queued_at INTEGER NOT NULL, + queue_rank INTEGER, + attempt_count INTEGER NOT NULL DEFAULT 0 CHECK (attempt_count >= 0), + started_at INTEGER, + finished_at INTEGER, + deleted_at INTEGER, + CHECK ( + (status = 'queued' AND queue_rank IS NOT NULL) + OR (status != 'queued' AND queue_rank IS NULL) + ) +); + +CREATE INDEX IF NOT EXISTS idx_generations_feature_created_at + ON generations(feature, created_at DESC, id DESC) + WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_generations_queue + ON generations(status, queued_at ASC, id ASC) + WHERE deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_generations_pending_queue_rank + ON generations(queue_rank ASC, id ASC) + WHERE status = 'queued' AND deleted_at IS NULL; + +CREATE TABLE IF NOT EXISTS assets ( + id TEXT PRIMARY KEY, + media_kind TEXT NOT NULL CHECK (media_kind IN ('image','video','audio')), + origin TEXT NOT NULL CHECK (origin IN ('uploaded','generated')), + producer_generation_id TEXT REFERENCES generations(id) ON DELETE RESTRICT, + output_ordinal INTEGER CHECK (output_ordinal >= 0), + mime_type TEXT NOT NULL, + name TEXT NOT NULL, + metadata TEXT NOT NULL CHECK (json_valid(metadata)), + thumbnail_path TEXT, + created_at INTEGER NOT NULL, + deleted_at INTEGER, + CHECK ( + ( + origin = 'uploaded' + AND producer_generation_id IS NULL + AND output_ordinal IS NULL + ) + OR + ( + origin = 'generated' + AND producer_generation_id IS NOT NULL + AND output_ordinal IS NOT NULL + ) + ) +); + +CREATE UNIQUE INDEX IF NOT EXISTS idx_assets_producer_ordinal + ON assets(producer_generation_id, output_ordinal) + WHERE producer_generation_id IS NOT NULL AND deleted_at IS NULL; +CREATE INDEX IF NOT EXISTS idx_assets_created_at + ON assets(created_at DESC, id DESC) + WHERE deleted_at IS NULL; + +CREATE TABLE IF NOT EXISTS paired_devices ( + id TEXT PRIMARY KEY, + name TEXT NOT NULL, + token_hash TEXT NOT NULL UNIQUE, + created_at INTEGER NOT NULL, + last_seen_at INTEGER NOT NULL, + first_seen_ip TEXT, + first_seen_user_agent TEXT, + revoked_at INTEGER +); +CREATE INDEX IF NOT EXISTS idx_paired_devices_token_hash + ON paired_devices(token_hash) WHERE revoked_at IS NULL; diff --git a/backend/services/sqlite_store.py b/backend/services/sqlite_store.py new file mode 100644 index 000000000..5da991910 --- /dev/null +++ b/backend/services/sqlite_store.py @@ -0,0 +1,1631 @@ +from __future__ import annotations + +import json +import logging +import shutil +import sqlite3 +import time +import uuid +from collections.abc import Collection +from datetime import datetime +from pathlib import Path +from typing import cast, get_args + +from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter + +from services.dashboard_stats import DashboardSnapshot, DashboardWindow, compute_dashboard +from services.migrations import MIGRATIONS_DIR, apply_migrations +from services.media_probe import ( + extension_for_mime, + probe_file, + validate_ingest_source, +) +from services.records import ( + AssetInUseError, + AssetListPage, + AssetMetadata, + AssetRecord, + AttemptError, + GenerationErrorCode, + GenerationRecord, + ListedAsset, + MarkSucceededError, + MediaError, + MediaKind, + OutputSpec, + PairedDeviceRecord, + QueueGenerationRecord, + StatusError, + UnavailableError, +) +from services.thumbnails import PillowAvThumbnailWriter, ThumbnailWriter + +_RUNNING_STATUSES: set[str] = {"running"} +_CANCELLING_STATUSES: set[str] = {"cancelling"} +_IN_FLIGHT_STATUSES: set[str] = _RUNNING_STATUSES | _CANCELLING_STATUSES +_RETRYABLE_STATUSES: set[str] = {"failed"} +_IN_FLIGHT_DIRNAME = ".in-flight" +_UNLINK_RETRY_ATTEMPTS = 5 +_UNLINK_RETRY_BASE_SECONDS = 0.05 +_QUEUE_RANK_SPACING = 1_000_000 + + +def _unlink_path(path: Path) -> None: + """Unlink ``path``, retrying Windows sharing violations after a brief lock.""" + for attempt in range(_UNLINK_RETRY_ATTEMPTS): + try: + path.unlink(missing_ok=True) + return + except PermissionError: + if attempt == _UNLINK_RETRY_ATTEMPTS - 1: + raise + time.sleep(_UNLINK_RETRY_BASE_SECONDS * (attempt + 1)) + + +_JSON_OBJECT = TypeAdapter(dict[str, JsonValue]) +_ERROR_CODES = frozenset(get_args(GenerationErrorCode)) +logger = logging.getLogger(__name__) + + +class _AssetMetadataHolder(BaseModel): + model_config = ConfigDict(frozen=True, extra="forbid", strict=True) + metadata: AssetMetadata + + +def _parse_json_object(raw: str) -> dict[str, JsonValue]: + parsed: object = json.loads(raw) + return _JSON_OBJECT.validate_python(parsed) + + +def _parse_asset_metadata(raw: str) -> AssetMetadata: + parsed: object = json.loads(raw) + return _AssetMetadataHolder.model_validate({"metadata": parsed}).metadata + + +def _optional_str(value: object) -> str | None: + if value is None: + return None + return str(value) + + +def _optional_int(value: object) -> int | None: + if value is None: + return None + return _require_int(value) + + +def _require_int(value: object) -> int: + if isinstance(value, bool) or not isinstance(value, int): + raise TypeError(f"expected int, got {type(value)!r}") + return value + + +def _is_present_file(path: str) -> bool: + try: + return Path(path).is_file() + except OSError: + return False + + +def collect_asset_ids(value: object) -> list[str]: + """Return unique nested spec values whose key is ``assetId``.""" + found: list[str] = [] + seen: set[str] = set() + + def walk(node: object) -> None: + if isinstance(node, dict): + typed_dict = cast(dict[object, object], node) + raw = typed_dict.get("assetId") + if isinstance(raw, str) and raw != "" and raw not in seen: + seen.add(raw) + found.append(raw) + for child in typed_dict.values(): + walk(child) + return + if isinstance(node, list): + typed_list = cast(list[object], node) + for child in typed_list: + walk(child) + + walk(value) + return found + + +def _derived_path(assets_dir: Path, asset_id: str, mime_type: str) -> Path: + return assets_dir / f"{asset_id}{extension_for_mime(mime_type)}" + + +def _encode_cursor(created_at: int, asset_id: str) -> str: + return f"{created_at}:{asset_id}" + + +def _decode_cursor(cursor: str) -> tuple[int, str]: + created_at_s, asset_id = cursor.split(":", 1) + if asset_id == "": + raise ValueError("invalid cursor") + return int(created_at_s), asset_id + + +def _like_escape(value: str) -> str: + return value.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_") + + +def _fetch_asset_list_rows( + conn: sqlite3.Connection, + *, + media_kind: MediaKind | None, + q: str | None, + descending: bool, + after: tuple[int, str] | None, + fetch_limit: int, +) -> list[sqlite3.Row]: + clauses = ["deleted_at IS NULL", "origin = 'generated'"] + params: list[str | int] = [] + if media_kind is not None: + clauses.append("media_kind = ?") + params.append(media_kind) + if q: + clauses.append("LOWER(name) LIKE '%' || LOWER(?) || '%' ESCAPE '\\'") + params.append(_like_escape(q)) + if after is not None: + if descending: + clauses.append("(created_at, id) < (?, ?)") + else: + clauses.append("(created_at, id) > (?, ?)") + params.append(after[0]) + params.append(after[1]) + order = "DESC" if descending else "ASC" + params.append(fetch_limit) + return conn.execute( + f""" + SELECT * FROM assets + WHERE {" AND ".join(clauses)} + ORDER BY created_at {order}, id {order} + LIMIT ? + """, + params, + ).fetchall() + + +class SqliteStore: + def __init__( + self, + app_data_dir: Path, + thumbnail_writer: ThumbnailWriter | None = None, + ) -> None: + try: + self._assets_dir = app_data_dir / "assets" + self._in_flight_dir = self._assets_dir / _IN_FLIGHT_DIRNAME + self._db_path = app_data_dir / "store.sqlite3" + self._assets_dir.mkdir(parents=True, exist_ok=True) + conn = self._connect() + apply_migrations(conn, MIGRATIONS_DIR) + conn.commit() + conn.close() + self._thumbnail_writer: ThumbnailWriter = ( + thumbnail_writer + if thumbnail_writer is not None + else PillowAvThumbnailWriter() + ) + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + + def _connect(self) -> sqlite3.Connection: + conn = sqlite3.connect(self._db_path, timeout=5.0) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA journal_mode = WAL") + conn.execute("PRAGMA busy_timeout = 5000") + return conn + + def _now_ms(self) -> int: + return int(time.time() * 1000) + + def _new_id(self) -> str: + return str(uuid.uuid4()) + + def _next_queued_at(self, conn: sqlite3.Connection, now: int) -> int: + row = conn.execute( + "SELECT COALESCE(MAX(queued_at), 0) AS latest_queued_at FROM generations" + ).fetchone() + latest = 0 if row is None else _require_int(row["latest_queued_at"]) + return max(now, latest + 1) + + def _next_queue_rank(self, conn: sqlite3.Connection) -> int: + row = conn.execute( + """ + SELECT COALESCE(MAX(queue_rank), 0) AS latest_queue_rank + FROM generations + WHERE status = 'queued' AND deleted_at IS NULL + """ + ).fetchone() + latest = 0 if row is None else _require_int(row["latest_queue_rank"]) + return latest + _QUEUE_RANK_SPACING + + def _rebalance_queued_ranks(self, conn: sqlite3.Connection) -> None: + rows = conn.execute( + """ + SELECT id FROM generations + WHERE status = 'queued' AND deleted_at IS NULL + ORDER BY queue_rank ASC, id ASC + """ + ).fetchall() + conn.executemany( + "UPDATE generations SET queue_rank = ? WHERE id = ?", + [ + (_QUEUE_RANK_SPACING * (index + 1), str(row["id"])) + for index, row in enumerate(rows) + ], + ) + + def _asset_record(self, row: sqlite3.Row) -> AssetRecord: + mime_type = str(row["mime_type"]) + asset_id = str(row["id"]) + raw_thumb = row["thumbnail_path"] + thumbnail_path = None if raw_thumb is None else str(raw_thumb) + return AssetRecord.model_validate( + { + "id": asset_id, + "media_kind": str(row["media_kind"]), + "origin": str(row["origin"]), + "path": str(_derived_path(self._assets_dir, asset_id, mime_type)), + "thumbnail_path": thumbnail_path, + "mime_type": mime_type, + "name": str(row["name"]), + "metadata": _parse_asset_metadata(str(row["metadata"])), + "created_at": _require_int(row["created_at"]), + } + ) + + def ingest_upload(self, source_path: str) -> AssetRecord: + source = Path(source_path).resolve() + try: + is_file = source.is_file() + except OSError: + is_file = False + if not is_file: + raise FileNotFoundError(source) + validate_ingest_source(source) + asset_id = self._new_id() + dest = self._assets_dir / f"{asset_id}{source.suffix}" + created_at = self._now_ms() + name = source.name + try: + shutil.copy2(source, dest) + media_kind, mime_type, metadata = probe_file(dest) + canonical = _derived_path(self._assets_dir, asset_id, mime_type) + if canonical != dest: + dest.replace(canonical) + dest = canonical + conn = self._connect() + try: + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, + output_ordinal, mime_type, name, metadata, created_at, + deleted_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + asset_id, + media_kind, + "uploaded", + None, + None, + mime_type, + name, + json.dumps(metadata.model_dump(mode="json")), + created_at, + None, + ), + ) + conn.commit() + finally: + conn.close() + except MediaError: + dest.unlink(missing_ok=True) + raise + except Exception as exc: + dest.unlink(missing_ok=True) + logger.warning("unreadable media file %s: %s", dest, exc) + raise MediaError("UNREADABLE_MEDIA", "unreadable media file") from exc + return self._persist_thumbnail( + AssetRecord( + id=asset_id, + media_kind=media_kind, + origin="uploaded", + path=str(dest), + thumbnail_path=None, + mime_type=mime_type, + name=name, + metadata=metadata, + created_at=created_at, + ) + ) + + def _persist_thumbnail(self, record: AssetRecord) -> AssetRecord: + try: + written = self._thumbnail_writer.write(record.path, record.media_kind) + except Exception: + logger.warning("thumbnail writer raised for %s", record.id, exc_info=True) + return record + if written is None: + return record + persisted = False + try: + conn = self._connect() + try: + cursor = conn.execute( + "UPDATE assets SET thumbnail_path = ? WHERE id = ? AND deleted_at IS NULL", + (written, record.id), + ) + conn.commit() + persisted = cursor.rowcount == 1 + finally: + conn.close() + except (sqlite3.Error, OSError): + logger.warning( + "thumbnail path persist failed for %s", + record.id, + exc_info=True, + ) + if persisted: + return record.model_copy(update={"thumbnail_path": written}) + try: + _unlink_path(Path(written)) + except OSError: + logger.warning( + "unpersisted thumbnail unlink failed for %s", + record.id, + exc_info=True, + ) + return record + + def get_asset( + self, asset_id: str, *, tombstone_missing: bool = True + ) -> AssetRecord | None: + conn = self._connect() + try: + row = conn.execute( + """ + SELECT * FROM assets + WHERE id = ? AND deleted_at IS NULL + """, + (asset_id,), + ).fetchone() + record = None if row is None else self._asset_record(row) + finally: + conn.close() + if record is None: + return None + if _is_present_file(record.path): + return record + if tombstone_missing: + self._tombstone_missing_assets((record.id,)) + return None + + def list_assets( + self, + *, + media_kind: MediaKind | None = None, + sort: str = "created_at-desc", + q: str | None = None, + cursor: str | None = None, + limit: int = 100, + tombstone_missing: bool = True, + ) -> AssetListPage: + if sort not in ("created_at-desc", "created_at-asc"): + raise ValueError(f"invalid sort: {sort}") + descending = sort == "created_at-desc" + after: tuple[int, str] | None = ( + _decode_cursor(cursor) if cursor is not None else None + ) + conn = self._connect() + try: + in_use_ids = self._live_in_use_ids(conn) + rows = _fetch_asset_list_rows( + conn, + media_kind=media_kind, + q=q, + descending=descending, + after=after, + fetch_limit=limit + 1, + ) + records = [self._asset_record(row) for row in rows] + finally: + conn.close() + window = records[:limit] + missing_ids = tuple( + record.id for record in window if not _is_present_file(record.path) + ) + if tombstone_missing: + self._tombstone_missing_assets(missing_ids) + missing = set(missing_ids) + items = tuple( + ListedAsset(asset=record, in_use=record.id in in_use_ids) + for record in window + if record.id not in missing + ) + next_cursor: str | None = None + if len(records) > limit and window: + last = window[-1] + next_cursor = _encode_cursor(last.created_at, last.id) + return AssetListPage(items=items, next_cursor=next_cursor) + + def _tombstone_missing_assets(self, asset_ids: tuple[str, ...]) -> None: + """Stamp deleted_at only. Skip live inputs. Do not unlink or hide the producer.""" + if not asset_ids: + return + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + in_use_ids = self._live_in_use_ids(conn) + stamped = tuple( + asset_id for asset_id in asset_ids if asset_id not in in_use_ids + ) + if stamped: + now = self._now_ms() + conn.executemany( + """ + UPDATE assets + SET deleted_at = ? + WHERE id = ? AND deleted_at IS NULL + """, + [(now, asset_id) for asset_id in stamped], + ) + conn.commit() + finally: + conn.close() + + def _live_in_use_ids(self, conn: sqlite3.Connection) -> set[str]: + ids: set[str] = set() + for row in conn.execute( + "SELECT spec FROM generations WHERE deleted_at IS NULL" + ): + ids.update(collect_asset_ids(_parse_json_object(str(row["spec"])))) + return ids + + def allocate_output_path( + self, media_kind: MediaKind, mime_type: str + ) -> tuple[str, str]: + if media_kind not in get_args(MediaKind): + raise ValueError(f"invalid media_kind: {media_kind}") + asset_id = self._new_id() + self._in_flight_dir.mkdir(parents=True, exist_ok=True) + dest = _derived_path(self._in_flight_dir, asset_id, mime_type) + return (asset_id, str(dest)) + + def insert_generation( + self, + feature: str, + spec: dict[str, JsonValue], + *, + contract_version: int = 1, + ) -> GenerationRecord: + if contract_version < 1: + raise ValueError("contract_version must be >= 1") + generation_id = self._new_id() + now = self._now_ms() + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + queued_at = self._next_queued_at(conn, now) + queue_rank = self._next_queue_rank(conn) + for asset_id in collect_asset_ids(spec): + row = conn.execute( + "SELECT id FROM assets WHERE id = ? AND deleted_at IS NULL", + (asset_id,), + ).fetchone() + if row is None: + conn.rollback() + raise ValueError(f"unknown input asset: {asset_id}") + conn.execute( + """ + INSERT INTO generations ( + id, feature, contract_version, status, spec, error_code, + created_at, queued_at, queue_rank, attempt_count, started_at, finished_at, + deleted_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + generation_id, + feature, + contract_version, + "queued", + json.dumps(spec), + None, + now, + queued_at, + queue_rank, + 0, + None, + None, + None, + ), + ) + conn.commit() + finally: + conn.close() + record = self.get_generation(generation_id) + if record is None: + raise RuntimeError(f"generation {generation_id} missing after insert") + return record + + def has_queued(self) -> bool: + conn = self._connect() + try: + row = conn.execute( + "SELECT 1 FROM generations WHERE status = 'queued' AND deleted_at IS NULL LIMIT 1" + ).fetchone() + return row is not None + finally: + conn.close() + + def list_queue_generations(self) -> list[QueueGenerationRecord]: + conn = self._connect() + try: + rows = conn.execute( + """ + SELECT * FROM generations + WHERE status IN ('queued', 'running', 'cancelling') + AND deleted_at IS NULL + ORDER BY + CASE WHEN status = 'queued' THEN 1 ELSE 0 END ASC, + started_at ASC, + queue_rank ASC, + id ASC + """ + ).fetchall() + records: list[QueueGenerationRecord] = [] + for row in rows: + generation = self._record_from_generation_row(row, []) + input_ids = collect_asset_ids(generation.spec) + if input_ids: + placeholders = ",".join("?" * len(input_ids)) + asset_rows = conn.execute( + f""" + SELECT * FROM assets + WHERE id IN ({placeholders}) AND deleted_at IS NULL + """, + input_ids, + ).fetchall() + assets_by_id = { + str(asset_row["id"]): self._asset_record(asset_row) + for asset_row in asset_rows + } + input_assets = tuple( + assets_by_id[asset_id] + for asset_id in input_ids + if asset_id in assets_by_id + ) + else: + input_assets = () + records.append( + QueueGenerationRecord( + generation=generation, + input_assets=input_assets, + ) + ) + return records + finally: + conn.close() + + def reorder_queued_generation( + self, generation_id: str, before_generation_id: str | None + ) -> GenerationRecord: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + self._require_status(conn, generation_id, {"queued"}) + if before_generation_id == generation_id: + return self._commit_loaded(conn, generation_id) + if before_generation_id is not None: + self._require_status(conn, before_generation_id, {"queued"}) + + rows = conn.execute( + """ + SELECT id, queue_rank FROM generations + WHERE status = 'queued' AND deleted_at IS NULL AND id != ? + ORDER BY queue_rank ASC, id ASC + """, + (generation_id,), + ).fetchall() + if before_generation_id is None: + previous_rank = ( + _require_int(rows[-1]["queue_rank"]) if rows else 0 + ) + new_rank = previous_rank + _QUEUE_RANK_SPACING + else: + target_index = next( + ( + index + for index, row in enumerate(rows) + if str(row["id"]) == before_generation_id + ), + None, + ) + if target_index is None: + raise RuntimeError("queued reorder target disappeared") + target_rank = _require_int(rows[target_index]["queue_rank"]) + if target_index == 0: + new_rank = target_rank - _QUEUE_RANK_SPACING + else: + previous_rank = _require_int(rows[target_index - 1]["queue_rank"]) + if target_rank - previous_rank <= 1: + self._rebalance_queued_ranks(conn) + rows = conn.execute( + """ + SELECT id, queue_rank FROM generations + WHERE status = 'queued' AND deleted_at IS NULL AND id != ? + ORDER BY queue_rank ASC, id ASC + """, + (generation_id,), + ).fetchall() + target_index = next( + index + for index, row in enumerate(rows) + if str(row["id"]) == before_generation_id + ) + target_rank = _require_int(rows[target_index]["queue_rank"]) + previous_rank = _require_int( + rows[target_index - 1]["queue_rank"] + ) + new_rank = previous_rank + (target_rank - previous_rank) // 2 + + conn.execute( + """ + UPDATE generations SET queue_rank = ? + WHERE id = ? AND status = 'queued' AND deleted_at IS NULL + """, + (new_rank, generation_id), + ) + return self._commit_loaded(conn, generation_id) + except Exception: + conn.rollback() + raise + finally: + conn.close() + + def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + status = self._require_status(conn, generation_id, {"queued", "running"}) + now = self._now_ms() + if status == "queued": + conn.execute( + """ + UPDATE generations + SET status = 'cancelled', queue_rank = NULL, finished_at = ? + WHERE id = ? AND status = 'queued' AND deleted_at IS NULL + """, + (now, generation_id), + ) + else: + conn.execute( + """ + UPDATE generations + SET status = 'cancelling', queue_rank = NULL, finished_at = NULL + WHERE id = ? AND status = 'running' AND deleted_at IS NULL + """, + (generation_id,), + ) + return self._commit_loaded(conn, generation_id) + except Exception: + conn.rollback() + raise + finally: + conn.close() + + def claim_next_queued(self) -> GenerationRecord | None: + while True: + claimed = self._claim_one_queued() + if claimed is None: + return None + if self._has_missing_input(claimed): + self.mark_failed( + claimed.id, + "INPUT_MISSING", + attempt_count=claimed.attempt_count, + ) + continue + return claimed + + def dashboard( + self, + *, + window: DashboardWindow, + tz: str, + now: datetime | None = None, + ) -> DashboardSnapshot: + conn = self._connect() + try: + return compute_dashboard( + conn, + window=window, + tz=tz, + now=now, + ) + finally: + conn.close() + + def _has_missing_input(self, claimed: GenerationRecord) -> bool: + conn = self._connect() + try: + for asset_id in collect_asset_ids(claimed.spec): + row = conn.execute( + """ + SELECT id, mime_type FROM assets + WHERE id = ? AND deleted_at IS NULL + """, + (asset_id,), + ).fetchone() + if row is None: + return True + path = _derived_path( + self._assets_dir, str(row["id"]), str(row["mime_type"]) + ) + if not _is_present_file(str(path)): + return True + return False + finally: + conn.close() + + def _claim_one_queued(self) -> GenerationRecord | None: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + row = conn.execute( + """ + SELECT id + FROM generations + WHERE status = 'queued' AND deleted_at IS NULL + ORDER BY queue_rank ASC, id ASC + LIMIT 1 + """ + ).fetchone() + if row is None: + conn.commit() + return None + + generation_id = str(row["id"]) + now = self._now_ms() + # started_at is this attempt only. Retry clears it, and the next + # claim sets it again, so finished_at - started_at skips earlier + # attempts. Retry also increments attempt_count before this claim + # increments it again. + cursor = conn.execute( + """ + UPDATE generations + SET status = 'running', + queue_rank = NULL, + attempt_count = attempt_count + 1, + started_at = ?, + finished_at = NULL, + error_code = NULL + WHERE id = ? AND status = 'queued' AND deleted_at IS NULL + """, + (now, generation_id), + ) + if cursor.rowcount != 1: + conn.rollback() + return None + return self._commit_loaded(conn, generation_id) + except Exception: + conn.rollback() + raise + finally: + conn.close() + + def retry_generation(self, generation_id: str) -> GenerationRecord: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + self._require_status(conn, generation_id, _RETRYABLE_STATUSES) + generated_paths = self._delete_generated_assets(conn, generation_id) + now = self._now_ms() + queued_at = self._next_queued_at(conn, now) + queue_rank = self._next_queue_rank(conn) + conn.execute( + """ + UPDATE generations + SET status = 'queued', + queued_at = ?, + queue_rank = ?, + error_code = NULL, + started_at = NULL, + finished_at = NULL, + attempt_count = attempt_count + 1 + WHERE id = ? AND status = 'failed' + """, + (queued_at, queue_rank, generation_id), + ) + record = self._commit_loaded(conn, generation_id) + self._unlink_under_assets(generated_paths) + return record + finally: + conn.close() + + def _require_status( + self, conn: sqlite3.Connection, generation_id: str, allowed: set[str] + ) -> str: + row = conn.execute( + """ + SELECT status FROM generations + WHERE id = ? AND deleted_at IS NULL + """, + (generation_id,), + ).fetchone() + if row is None: + raise KeyError(generation_id) + status = str(row["status"]) + if status not in allowed: + raise StatusError(generation_id, status) + return status + + def _require_attempt( + self, + conn: sqlite3.Connection, + generation_id: str, + attempt_count: int, + allowed: set[str], + ) -> None: + self._require_status(conn, generation_id, allowed) + row = conn.execute( + "SELECT attempt_count FROM generations WHERE id = ?", + (generation_id,), + ).fetchone() + if row is None: + raise KeyError(generation_id) + actual = _require_int(row["attempt_count"]) + if actual != attempt_count: + raise AttemptError(generation_id, attempt_count, actual) + + def _load_required( + self, conn: sqlite3.Connection, generation_id: str + ) -> GenerationRecord: + record = self._generation_from_id(conn, generation_id) + if record is None: + raise RuntimeError(f"generation {generation_id} missing after update") + return record + + def _path_under_assets(self, raw: str) -> Path | None: + try: + path = Path(raw).resolve() + except OSError: + return None + assets_dir = self._assets_dir.resolve() + if not path.is_relative_to(assets_dir): + return None + return path + + def _is_under_dir(self, path: Path, directory: Path) -> bool: + try: + return path.resolve().is_relative_to(directory.resolve()) + except OSError: + return False + + def _existing_output_path(self, spec: OutputSpec) -> Path | None: + dest = self._path_under_assets(spec.dest_path) + if dest is None: + return None + if dest.is_file(): + return dest + if not self._is_under_dir(dest, self._in_flight_dir): + return dest + canonical = _derived_path(self._assets_dir, spec.asset_id, spec.mime_type) + if canonical.is_file(): + return canonical + return dest + + def _unlink_partials(self, partial_paths: list[str] | None) -> None: + for raw in partial_paths or []: + try: + path = self._path_under_assets(raw) + if path is None: + continue + _unlink_path(path) + except Exception as exc: + logger.warning( + "Could not remove partial output %s: %s", + raw, + exc, + ) + continue + + def unlink_partial_outputs(self, paths: list[str]) -> None: + self._unlink_partials(paths) + + def _restore_promoted_outputs(self, moved: list[tuple[Path, Path]]) -> None: + for canonical, original in reversed(moved): + try: + if not self._is_under_dir(canonical, self._assets_dir): + continue + if not canonical.is_file(): + continue + if original.exists(): + canonical.unlink(missing_ok=True) + continue + if not self._is_under_dir(original, self._assets_dir): + canonical.unlink(missing_ok=True) + continue + canonical.replace(original) + except OSError as exc: + logger.warning( + "Could not restore promoted output %s to %s: %s", + canonical, + original, + exc, + ) + + def _delete_generated_assets( + self, conn: sqlite3.Connection, generation_id: str + ) -> list[Path]: + rows = conn.execute( + """ + SELECT id, mime_type FROM assets + WHERE producer_generation_id = ? + """, + (generation_id,), + ).fetchall() + conn.execute( + "DELETE FROM assets WHERE producer_generation_id = ?", + (generation_id,), + ) + return [ + _derived_path(self._assets_dir, str(row["id"]), str(row["mime_type"])) + for row in rows + ] + + def _unlink_under_assets(self, paths: list[Path]) -> None: + for path in paths: + if not self._is_under_dir(path, self._assets_dir): + continue + _unlink_path(path) + + def _commit_loaded( + self, conn: sqlite3.Connection, generation_id: str + ) -> GenerationRecord: + record = self._load_required(conn, generation_id) + conn.commit() + return record + + def _require_attempt_unlinking( + self, + conn: sqlite3.Connection, + generation_id: str, + attempt_count: int, + allowed: set[str], + unlink_paths: list[str] | None, + ) -> None: + try: + self._require_attempt(conn, generation_id, attempt_count, allowed) + except (AttemptError, StatusError, KeyError): + conn.rollback() + self._unlink_partials(unlink_paths) + raise + + def _reclaim_in_flight_files(self) -> None: + in_flight_dir = self._in_flight_dir + if not in_flight_dir.is_dir(): + return + assets_dir = self._assets_dir.resolve() + try: + in_flight_resolved = in_flight_dir.resolve() + except OSError: + return + for child in in_flight_dir.iterdir(): + if not child.is_file(): + continue + try: + resolved = child.resolve() + except OSError: + continue + if not resolved.is_relative_to(in_flight_resolved): + continue + if not resolved.is_relative_to(assets_dir): + continue + resolved.unlink(missing_ok=True) + + def _mark_failed_on_conn( + self, + conn: sqlite3.Connection, + generation_id: str, + error_code: GenerationErrorCode, + partial_paths: list[str] | None, + attempt_count: int, + ) -> GenerationRecord: + if error_code not in _ERROR_CODES: + raise ValueError(f"invalid error_code: {error_code}") + generated_paths = self._delete_generated_assets(conn, generation_id) + now = self._now_ms() + conn.execute( + """ + UPDATE generations + SET status = 'failed', error_code = ?, queue_rank = NULL, finished_at = ? + WHERE id = ? AND status = 'running' AND attempt_count = ? + """, + (error_code, now, generation_id, attempt_count), + ) + record = self._commit_loaded(conn, generation_id) + self._unlink_under_assets(generated_paths) + self._unlink_partials(partial_paths) + return record + + def mark_succeeded( + self, + generation_id: str, + outputs: list[OutputSpec], + *, + attempt_count: int, + ) -> GenerationRecord: + if not outputs: + raise ValueError("mark_succeeded requires at least one output") + ordinals = [spec.ordinal for spec in outputs] + if len(ordinals) != len(set(ordinals)): + raise ValueError("mark_succeeded output ordinals must be unique") + resolved_outputs: list[tuple[OutputSpec, Path]] = [] + for spec in outputs: + dest = self._existing_output_path(spec) + if dest is None: + raise ValueError(f"output path is outside assets: {spec.dest_path}") + resolved_outputs.append((spec, dest)) + dest_paths = [spec.dest_path for spec in outputs] + probed: list[tuple[OutputSpec, Path, MediaKind, str, AssetMetadata]] = [] + for spec, dest in resolved_outputs: + if not dest.is_file(): + raise MarkSucceededError(generation_id, "OUTPUT_MISSING") + try: + media_kind, mime_type, metadata = probe_file(dest) + except Exception: + raise MarkSucceededError(generation_id, "OUTPUT_UNREADABLE") from None + probed.append((spec, dest, media_kind, mime_type, metadata)) + conn = self._connect() + moved: list[tuple[Path, Path]] = [] + try: + conn.execute("BEGIN IMMEDIATE") + self._require_attempt_unlinking( + conn, + generation_id, + attempt_count, + _RUNNING_STATUSES, + dest_paths, + ) + now = self._now_ms() + for spec, dest, media_kind, mime_type, metadata in probed: + if not dest.is_file(): + raise MarkSucceededError(generation_id, "OUTPUT_MISSING") + canonical = _derived_path(self._assets_dir, spec.asset_id, mime_type) + if dest.resolve() != canonical.resolve(): + dest.replace(canonical) + moved.append((canonical, dest)) + dest = canonical + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, + output_ordinal, mime_type, name, metadata, created_at, + deleted_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + spec.asset_id, + media_kind, + "generated", + generation_id, + spec.ordinal, + mime_type, + spec.name, + json.dumps(metadata.model_dump(mode="json")), + now, + None, + ), + ) + conn.execute( + """ + UPDATE generations + SET status = 'succeeded', queue_rank = NULL, finished_at = ? + WHERE id = ? AND status = 'running' AND attempt_count = ? + """, + (now, generation_id, attempt_count), + ) + record = self._commit_loaded(conn, generation_id) + except Exception: + try: + conn.rollback() + except sqlite3.Error: + pass + self._restore_promoted_outputs(moved) + raise + finally: + conn.close() + persisted = tuple(self._persist_thumbnail(output) for output in record.outputs) + return record.model_copy(update={"outputs": persisted}) + + def mark_failed( + self, + generation_id: str, + error_code: GenerationErrorCode, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + self._require_attempt_unlinking( + conn, + generation_id, + attempt_count, + _RUNNING_STATUSES, + partial_paths, + ) + return self._mark_failed_on_conn( + conn, + generation_id, + error_code, + partial_paths, + attempt_count, + ) + finally: + conn.close() + + def mark_cancelled( + self, + generation_id: str, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + self._require_attempt_unlinking( + conn, + generation_id, + attempt_count, + _CANCELLING_STATUSES, + partial_paths, + ) + now = self._now_ms() + conn.execute( + """ + UPDATE generations + SET status = 'cancelled', queue_rank = NULL, finished_at = ? + WHERE id = ? AND status = 'cancelling' + AND attempt_count = ? + """, + (now, generation_id, attempt_count), + ) + record = self._commit_loaded(conn, generation_id) + self._unlink_partials(partial_paths) + return record + finally: + conn.close() + + def get_generation(self, generation_id: str) -> GenerationRecord | None: + conn = self._connect() + try: + return self._generation_from_id(conn, generation_id) + finally: + conn.close() + + def list_recent_features( + self, *, limit: int, allowed: Collection[str] | None = None + ) -> list[str]: + """Distinct features, newest generation first. Deleted rows do not count.""" + if limit < 1: + raise ValueError("limit must be >= 1") + if allowed is not None and len(allowed) == 0: + return [] + conn = self._connect() + try: + if allowed is None: + rows = conn.execute( + """ + SELECT feature + FROM generations + WHERE deleted_at IS NULL + GROUP BY feature + ORDER BY MAX(created_at) DESC, feature ASC + LIMIT ? + """, + (limit,), + ).fetchall() + else: + features = tuple(allowed) + placeholders = ",".join("?" * len(features)) + rows = conn.execute( + f""" + SELECT feature + FROM generations + WHERE deleted_at IS NULL + AND feature IN ({placeholders}) + GROUP BY feature + ORDER BY MAX(created_at) DESC, feature ASC + LIMIT ? + """, + (*features, limit), + ).fetchall() + return [str(row["feature"]) for row in rows] + finally: + conn.close() + + def list_generations(self, feature: str) -> list[GenerationRecord]: + conn = self._connect() + try: + gen_rows = conn.execute( + """ + SELECT * + FROM generations + WHERE feature = ? AND deleted_at IS NULL + ORDER BY created_at DESC, id DESC + """, + (feature,), + ).fetchall() + if not gen_rows: + return [] + ids = [str(row["id"]) for row in gen_rows] + placeholders = ",".join("?" * len(ids)) + output_rows = conn.execute( + f""" + SELECT * + FROM assets + WHERE producer_generation_id IN ({placeholders}) + AND deleted_at IS NULL + ORDER BY output_ordinal ASC, id ASC + """, + ids, + ).fetchall() + outputs_by_gen: dict[str, list[sqlite3.Row]] = { + gen_id: [] for gen_id in ids + } + for row in output_rows: + producer = str(row["producer_generation_id"]) + outputs_by_gen[producer].append(row) + return [ + self._record_from_generation_row(row, outputs_by_gen[str(row["id"])]) + for row in gen_rows + ] + finally: + conn.close() + + def _generation_from_id( + self, conn: sqlite3.Connection, generation_id: str + ) -> GenerationRecord | None: + row = conn.execute( + """ + SELECT * FROM generations + WHERE id = ? AND deleted_at IS NULL + """, + (generation_id,), + ).fetchone() + if row is None: + return None + outputs = conn.execute( + """ + SELECT * FROM assets + WHERE producer_generation_id = ? AND deleted_at IS NULL + ORDER BY output_ordinal ASC, id ASC + """, + (generation_id,), + ).fetchall() + return self._record_from_generation_row(row, outputs) + + def _record_from_generation_row( + self, row: sqlite3.Row, output_rows: list[sqlite3.Row] + ) -> GenerationRecord: + outputs: list[AssetRecord] = [] + for output_row in output_rows: + record = self._asset_record(output_row) + if record.origin == "generated" and not _is_present_file(record.path): + continue + outputs.append(record) + return GenerationRecord.model_validate( + { + "id": str(row["id"]), + "feature": str(row["feature"]), + "contract_version": _require_int(row["contract_version"]), + "status": str(row["status"]), + "spec": _parse_json_object(str(row["spec"])), + "error_code": _optional_str(row["error_code"]), + "created_at": _require_int(row["created_at"]), + "queued_at": _require_int(row["queued_at"]), + "attempt_count": _require_int(row["attempt_count"]), + "started_at": _optional_int(row["started_at"]), + "finished_at": _optional_int(row["finished_at"]), + "outputs": tuple(outputs), + } + ) + + def delete_generation(self, generation_id: str) -> bool: + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + row = conn.execute( + """ + SELECT status, deleted_at FROM generations WHERE id = ? + """, + (generation_id,), + ).fetchone() + if row is None or row["deleted_at"] is not None: + conn.commit() + return False + status = str(row["status"]) + if status in _IN_FLIGHT_STATUSES: + raise StatusError(generation_id, status) + now = self._now_ms() + cursor = conn.execute( + """ + UPDATE generations + SET deleted_at = ? + WHERE id = ? AND deleted_at IS NULL + """, + (now, generation_id), + ) + conn.commit() + return cursor.rowcount == 1 + finally: + conn.close() + + def delete_asset(self, asset_id: str) -> bool: + """True if deleted or already deleted. False if the id never existed. + Raises AssetInUseError, StatusError (producer running or cancelling). + Canonical and thumbnail unlinks are best-effort after commit.""" + unlink_paths: list[Path] = [] + conn = self._connect() + try: + conn.execute("BEGIN IMMEDIATE") + row = conn.execute( + "SELECT * FROM assets WHERE id = ?", + (asset_id,), + ).fetchone() + if row is None: + conn.commit() + return False + if row["deleted_at"] is not None: + conn.commit() + return True + if asset_id in self._live_in_use_ids(conn): + raise AssetInUseError(asset_id) + producer_id = _optional_str(row["producer_generation_id"]) + gen_row: sqlite3.Row | None = None + if producer_id is not None: + gen_row = conn.execute( + "SELECT status, deleted_at FROM generations WHERE id = ?", + (producer_id,), + ).fetchone() + if gen_row is not None: + status = str(gen_row["status"]) + if status in _IN_FLIGHT_STATUSES: + raise StatusError(producer_id, status) + now = self._now_ms() + conn.execute( + """ + UPDATE assets + SET deleted_at = ? + WHERE id = ? AND deleted_at IS NULL + """, + (now, asset_id), + ) + if producer_id is not None: + sibling_row = conn.execute( + """ + SELECT COUNT(*) AS n + FROM assets + WHERE producer_generation_id = ? + AND deleted_at IS NULL + AND id != ? + """, + (producer_id, asset_id), + ).fetchone() + n = 0 if sibling_row is None else _require_int(sibling_row["n"]) + if n == 0 and gen_row is not None and gen_row["deleted_at"] is None: + status = str(gen_row["status"]) + if status in _IN_FLIGHT_STATUSES: + raise StatusError(producer_id, status) + conn.execute( + """ + UPDATE generations + SET deleted_at = ? + WHERE id = ? AND deleted_at IS NULL + """, + (now, producer_id), + ) + unlink_paths.append( + _derived_path(self._assets_dir, asset_id, str(row["mime_type"])) + ) + thumbnail_path = _optional_str(row["thumbnail_path"]) + if thumbnail_path is not None: + unlink_paths.append(Path(thumbnail_path)) + conn.commit() + finally: + conn.close() + + try: + self._unlink_under_assets(unlink_paths) + except OSError: + logger.warning( + "asset unlink failed for %s", + asset_id, + exc_info=True, + ) + return True + + def fail_running_on_boot(self) -> int: + now = self._now_ms() + try: + conn = self._connect() + try: + in_flight_ids = [ + str(row["id"]) + for row in conn.execute( + """ + SELECT id FROM generations + WHERE status IN ('running', 'cancelling') AND deleted_at IS NULL + """ + ).fetchall() + ] + generated_paths: list[Path] = [] + for generation_id in in_flight_ids: + generated_paths.extend( + self._delete_generated_assets(conn, generation_id) + ) + failed_cursor = conn.execute( + """ + UPDATE generations + SET status = 'failed', error_code = 'INTERRUPTED', + queue_rank = NULL, finished_at = ? + WHERE status = 'running' AND deleted_at IS NULL + """, + (now,), + ) + cancelled_cursor = conn.execute( + """ + UPDATE generations + SET status = 'cancelled', error_code = NULL, + queue_rank = NULL, finished_at = ? + WHERE status = 'cancelling' AND deleted_at IS NULL + """, + (now,), + ) + conn.commit() + self._unlink_under_assets(generated_paths) + self._reclaim_in_flight_files() + return int(failed_cursor.rowcount) + int(cancelled_cursor.rowcount) + finally: + conn.close() + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + + def insert_paired_device(self, record: PairedDeviceRecord) -> PairedDeviceRecord: + conn = self._connect() + try: + conn.execute( + """ + INSERT INTO paired_devices ( + id, name, token_hash, created_at, last_seen_at, + first_seen_ip, first_seen_user_agent, revoked_at + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?) + """, + ( + record.id, + record.name, + record.token_hash, + record.created_at, + record.last_seen_at, + record.first_seen_ip, + record.first_seen_user_agent, + record.revoked_at, + ), + ) + conn.commit() + return record + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + def get_paired_device_by_token_hash( + self, token_hash: str + ) -> PairedDeviceRecord | None: + return self._get_paired_device("token_hash = ?", (token_hash,)) + + def get_paired_device(self, device_id: str) -> PairedDeviceRecord | None: + return self._get_paired_device("id = ?", (device_id,)) + + def list_paired_devices(self) -> list[PairedDeviceRecord]: + conn = self._connect() + try: + rows = conn.execute( + """ + SELECT id, name, token_hash, created_at, last_seen_at, + first_seen_ip, first_seen_user_agent, revoked_at + FROM paired_devices + ORDER BY created_at DESC, id DESC + """ + ).fetchall() + return [self._paired_device_from_row(row) for row in rows] + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + def revoke_paired_device(self, device_id: str, *, now_ms: int) -> bool: + conn = self._connect() + try: + cursor = conn.execute( + """ + UPDATE paired_devices + SET revoked_at = ? + WHERE id = ? AND revoked_at IS NULL + """, + (now_ms, device_id), + ) + conn.commit() + return cursor.rowcount == 1 + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + def touch_paired_device( + self, + device_id: str, + *, + now_ms: int | None = None, + ip: str | None = None, + user_agent: str | None = None, + ) -> None: + conn = self._connect() + try: + conn.execute( + """ + UPDATE paired_devices + SET last_seen_at = COALESCE(?, last_seen_at), + first_seen_ip = COALESCE(NULLIF(NULLIF(first_seen_ip, ''), 'unknown'), ?), + first_seen_user_agent = COALESCE(NULLIF(first_seen_user_agent, ''), ?) + WHERE id = ? AND revoked_at IS NULL + """, + (now_ms, ip, user_agent, device_id), + ) + conn.commit() + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + def _get_paired_device( + self, where: str, params: tuple[object, ...] + ) -> PairedDeviceRecord | None: + conn = self._connect() + try: + row = conn.execute( + f""" + SELECT id, name, token_hash, created_at, last_seen_at, + first_seen_ip, first_seen_user_agent, revoked_at + FROM paired_devices + WHERE {where} + """, + params, + ).fetchone() + if row is None: + return None + return self._paired_device_from_row(row) + except (sqlite3.Error, OSError) as exc: + raise UnavailableError() from exc + finally: + conn.close() + + def _paired_device_from_row(self, row: sqlite3.Row) -> PairedDeviceRecord: + return PairedDeviceRecord( + id=str(row["id"]), + name=str(row["name"]), + token_hash=str(row["token_hash"]), + created_at=_require_int(row["created_at"]), + last_seen_at=_require_int(row["last_seen_at"]), + first_seen_ip=_optional_str(row["first_seen_ip"]), + first_seen_user_agent=_optional_str(row["first_seen_user_agent"]), + revoked_at=_optional_int(row["revoked_at"]), + ) diff --git a/backend/services/store.py b/backend/services/store.py new file mode 100644 index 000000000..14da7c0f8 --- /dev/null +++ b/backend/services/store.py @@ -0,0 +1,96 @@ +from __future__ import annotations + +from collections.abc import Collection +from datetime import datetime +from typing import Protocol + +from pydantic import JsonValue + +from services.dashboard_stats import DashboardSnapshot, DashboardWindow + +from services.records import ( + AssetListPage, + AssetRecord, + GenerationErrorCode, + GenerationRecord, + MediaKind, + OutputSpec, + QueueGenerationRecord, +) + + +class Store(Protocol): + def ingest_upload(self, source_path: str) -> AssetRecord: ... + def get_asset( + self, asset_id: str, *, tombstone_missing: bool = True + ) -> AssetRecord | None: ... + def list_assets( + self, + *, + media_kind: MediaKind | None = None, + sort: str = "created_at-desc", + q: str | None = None, + cursor: str | None = None, + limit: int = 100, + tombstone_missing: bool = True, + ) -> AssetListPage: ... + def allocate_output_path( + self, media_kind: MediaKind, mime_type: str + ) -> tuple[str, str]: ... + def insert_generation( + self, + feature: str, + spec: dict[str, JsonValue], + *, + contract_version: int = 1, + ) -> GenerationRecord: ... + def has_queued(self) -> bool: ... + def claim_next_queued(self) -> GenerationRecord | None: ... + def dashboard( + self, + *, + window: DashboardWindow, + tz: str, + now: datetime | None = None, + ) -> DashboardSnapshot: ... + def list_queue_generations(self) -> list[QueueGenerationRecord]: ... + def reorder_queued_generation( + self, generation_id: str, before_generation_id: str | None + ) -> GenerationRecord: ... + def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: ... + def retry_generation(self, generation_id: str) -> GenerationRecord: ... + def mark_succeeded( + self, + generation_id: str, + outputs: list[OutputSpec], + *, + attempt_count: int, + ) -> GenerationRecord: ... + def mark_failed( + self, + generation_id: str, + error_code: GenerationErrorCode, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: ... + def mark_cancelled( + self, + generation_id: str, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: ... + def get_generation(self, generation_id: str) -> GenerationRecord | None: ... + def list_generations(self, feature: str) -> list[GenerationRecord]: ... + def list_recent_features( + self, *, limit: int, allowed: Collection[str] | None = None + ) -> list[str]: ... + def delete_generation(self, generation_id: str) -> bool: ... + def delete_asset(self, asset_id: str) -> bool: + """True if deleted or already deleted. False if the id never existed. + Raises AssetInUseError, StatusError (producer running or cancelling). + Canonical and thumbnail unlinks are best-effort after commit.""" + ... + def fail_running_on_boot(self) -> int: ... + def unlink_partial_outputs(self, paths: list[str]) -> None: ... diff --git a/backend/services/text_encoder/ltx_text_encoder.py b/backend/services/text_encoder/ltx_text_encoder.py index 805009a8b..3a548ca7f 100644 --- a/backend/services/text_encoder/ltx_text_encoder.py +++ b/backend/services/text_encoder/ltx_text_encoder.py @@ -11,8 +11,15 @@ import torch +from _routes._errors import HTTPError from runtime_config.ltx_api_text_encoder_ids import LtxApiPromptEmbeddingModel from services.http_client.http_client import HTTPClient +from services.ltx_api_client.ltx_api_errors import ( + LTX_API_PROMPT_EMBEDDING_FAILED, + LTX_API_PROMPT_EMBEDDING_FAILED_MESSAGE, + LTX_INVALID_API_KEY, + LTX_INVALID_API_KEY_MESSAGE, +) from services.services_utils import JSONValue from state.app_state_types import TextEncodingResult @@ -279,9 +286,21 @@ def encode_via_api( timeout=60, ) + # A rejected key opens the API key field. A timeout or other + # non-success opens Text encoding. Local encoding never reaches this method. + if response.status_code in (401, 403): + raise HTTPError( + response.status_code, + LTX_INVALID_API_KEY_MESSAGE, + code=LTX_INVALID_API_KEY, + ) if response.status_code != 200: logger.warning("LTX API error %s: %s", response.status_code, response.text) - return None + raise HTTPError( + response.status_code, + LTX_API_PROMPT_EMBEDDING_FAILED_MESSAGE, + code=LTX_API_PROMPT_EMBEDDING_FAILED, + ) # Map CUDA storages to CPU during unpickling so this works on non-CUDA hosts # (Apple Silicon / CPU-only); the tensors are moved to self.device below. @@ -298,9 +317,15 @@ def encode_via_api( logger.info("Text encoded via API in %.1fs", time.time() - start) return TextEncodingResult(video_context=video_context, audio_context=audio_context) + except HTTPError: + raise except Exception as exc: logger.warning("LTX API encoding failed: %s", exc, exc_info=True) - return None + raise HTTPError( + 504, + LTX_API_PROMPT_EMBEDDING_FAILED_MESSAGE, + code=LTX_API_PROMPT_EMBEDDING_FAILED, + ) from exc class DummyTextEncoder: diff --git a/backend/services/thumbnails.py b/backend/services/thumbnails.py new file mode 100644 index 000000000..5afc44708 --- /dev/null +++ b/backend/services/thumbnails.py @@ -0,0 +1,130 @@ +from __future__ import annotations + +import logging +import tempfile +from pathlib import Path +from typing import Protocol, cast + +import av +from PIL import Image + +from api_types import MediaKind +from server_utils.oriented_image import open_oriented_image +from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, run_ffmpeg + +logger = logging.getLogger(__name__) +_MAX_EDGE = 512 +_JPEG_QUALITY = 85 +# A light-theme transparency grid, close to the design system one (--checkerboard-base / +# --checkerboard-square). The sizes differ from the CSS, and the dark theme has other colors. +_GRID_BASE = (255, 255, 255) +_GRID_SQUARE = (232, 232, 232) +_GRID_SIZE = 16 +_ALPHA_FRAME_TIMEOUT_SECONDS = 30.0 + + +class ThumbnailWriter(Protocol): + def write(self, source_path: str, media_kind: MediaKind) -> str | None: + """JPEG path beside the media, or None (audio / failure). Never raises.""" + ... + + +class PillowAvThumbnailWriter: + def write(self, source_path: str, media_kind: MediaKind) -> str | None: + try: + if media_kind == "audio": + return None + source = Path(source_path) + dest = source.with_name(f"{source.stem}-thumb.jpg") + image = _load_rgb(source, media_kind) + if image is None: + return None + image.thumbnail((_MAX_EDGE, _MAX_EDGE)) + image.save(dest, "JPEG", quality=_JPEG_QUALITY) + return str(dest) + except Exception: + logger.warning("thumbnail write failed for %s", source_path, exc_info=True) + return None + + +def _load_rgb(source: Path, media_kind: MediaKind) -> Image.Image | None: + if media_kind == "image": + image = open_oriented_image(source) + if _has_transparency(image): + # Scale first, so the grid is not drawn at the size of a large import. + rgba = image.convert("RGBA") + rgba.thumbnail((_MAX_EDGE, _MAX_EDGE)) + return _over_grid(rgba) + return image.convert("RGB") + if media_kind == "video": + container = av.open(str(source)) + try: + if _is_vp9_alpha(container): + return _load_alpha_over_grid(source) + for frame in container.decode(video=0): + to_image = getattr(frame, "to_image") + pil_image = cast(Image.Image, to_image()) + return pil_image.convert("RGB") + finally: + container.close() + return None + return None + + +def _has_transparency(image: Image.Image) -> bool: + """An alpha band, or a palette (GIF, PNG8) with a transparent index.""" + return image.mode in ("RGBA", "LA", "PA") or "transparency" in image.info + + +def _is_vp9_alpha(container: object) -> bool: + """A VP9 WebM with an alpha plane, which Matroska flags with ``alpha_mode``.""" + streams = cast(list[object], getattr(getattr(container, "streams", None), "video", [])) + if not streams: + return False + stream = streams[0] + codec_name = getattr(getattr(stream, "codec_context", None), "name", None) + metadata = cast(dict[str, str], getattr(stream, "metadata", {})) + return codec_name == "vp9" and metadata.get("alpha_mode") == "1" + + +def _load_alpha_over_grid(source: Path) -> Image.Image: + """First frame of a VP9 alpha WebM, over the transparency grid. + + PyAV's native VP9 decoder drops the alpha plane, so a cutout would show its + source frame. libvpx-vp9 keeps alpha. A JPEG has none, so the grid shows through. + The frame is scaled before it is written, so a large import stays cheap. + """ + fit = f"scale='min({_MAX_EDGE},iw)':'min({_MAX_EDGE},ih)':force_original_aspect_ratio=decrease" + with tempfile.TemporaryDirectory() as tmp: + frame_path = Path(tmp) / "frame.png" + run_ffmpeg( + [ + "-y", + "-c:v", + "libvpx-vp9", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(source), + "-frames:v", + "1", + "-vf", + fit, + str(frame_path), + ], + timeout=_ALPHA_FRAME_TIMEOUT_SECONDS, + ) + with Image.open(frame_path) as frame: + rgba = frame.convert("RGBA") + return _over_grid(rgba) + + +def _over_grid(rgba: Image.Image) -> Image.Image: + """JPEG has no alpha, so the transparency grid shows where the image is clear.""" + grid = Image.new("RGB", rgba.size, _GRID_BASE) + for top in range(0, rgba.height, _GRID_SIZE): + for left in range(0, rgba.width, _GRID_SIZE): + if (top // _GRID_SIZE + left // _GRID_SIZE) % 2 == 1: + grid.paste(_GRID_SQUARE, (left, top, left + _GRID_SIZE, top + _GRID_SIZE)) + grid.paste(rgba, mask=rgba.getchannel("A")) + return grid diff --git a/backend/services/unavailable_store.py b/backend/services/unavailable_store.py new file mode 100644 index 000000000..8ac6383f3 --- /dev/null +++ b/backend/services/unavailable_store.py @@ -0,0 +1,146 @@ +from __future__ import annotations + +from collections.abc import Collection +from datetime import datetime +from typing import NoReturn + +from pydantic import JsonValue + +from services.dashboard_stats import DashboardSnapshot, DashboardWindow + +from services.records import ( + AssetListPage, + AssetRecord, + GenerationErrorCode, + GenerationRecord, + MediaKind, + OutputSpec, + QueueGenerationRecord, + UnavailableError, +) + + +def _unavailable() -> NoReturn: + raise UnavailableError() + + +class UnavailableStore: + def ingest_upload(self, source_path: str) -> AssetRecord: + _unavailable() + + def get_asset( + self, asset_id: str, *, tombstone_missing: bool = True + ) -> AssetRecord | None: + del asset_id, tombstone_missing + _unavailable() + + def list_assets( + self, + *, + media_kind: MediaKind | None = None, + sort: str = "created_at-desc", + q: str | None = None, + cursor: str | None = None, + limit: int = 100, + tombstone_missing: bool = True, + ) -> AssetListPage: + del media_kind, sort, q, cursor, limit, tombstone_missing + _unavailable() + + def allocate_output_path( + self, media_kind: MediaKind, mime_type: str + ) -> tuple[str, str]: + _unavailable() + + def insert_generation( + self, + feature: str, + spec: dict[str, JsonValue], + *, + contract_version: int = 1, + ) -> GenerationRecord: + _unavailable() + + def has_queued(self) -> bool: + _unavailable() + + def claim_next_queued(self) -> GenerationRecord | None: + _unavailable() + + def dashboard( + self, + *, + window: DashboardWindow, + tz: str, + now: datetime | None = None, + ) -> DashboardSnapshot: + del window, tz, now + _unavailable() + + def list_queue_generations(self) -> list[QueueGenerationRecord]: + _unavailable() + + def reorder_queued_generation( + self, generation_id: str, before_generation_id: str | None + ) -> GenerationRecord: + del generation_id, before_generation_id + _unavailable() + + def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: + del generation_id + _unavailable() + + def retry_generation(self, generation_id: str) -> GenerationRecord: + _unavailable() + + def mark_succeeded( + self, + generation_id: str, + outputs: list[OutputSpec], + *, + attempt_count: int, + ) -> GenerationRecord: + _unavailable() + + def mark_failed( + self, + generation_id: str, + error_code: GenerationErrorCode, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: + _unavailable() + + def mark_cancelled( + self, + generation_id: str, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: + _unavailable() + + def get_generation(self, generation_id: str) -> GenerationRecord | None: + _unavailable() + + def list_generations(self, feature: str) -> list[GenerationRecord]: + _unavailable() + + def list_recent_features( + self, *, limit: int, allowed: Collection[str] | None = None + ) -> list[str]: + del limit, allowed + _unavailable() + + def delete_generation(self, generation_id: str) -> bool: + _unavailable() + + def delete_asset(self, asset_id: str) -> bool: + _unavailable() + + def fail_running_on_boot(self) -> int: + return 0 + + def unlink_partial_outputs(self, paths: list[str]) -> None: + del paths diff --git a/backend/services/video_processor/video_processor_impl.py b/backend/services/video_processor/video_processor_impl.py index dedc21f7d..7ee0e0ed3 100644 --- a/backend/services/video_processor/video_processor_impl.py +++ b/backend/services/video_processor/video_processor_impl.py @@ -5,6 +5,7 @@ import logging from typing import cast +from server_utils.oriented_image import open_oriented_rgb from services.depth_processor_pipeline.depth_processor_pipeline import DepthProcessorPipeline from services.pose_processor_pipeline.pose_processor_pipeline import PoseProcessorPipeline from services.video_processor.video_processor import VideoInfoPayload @@ -43,11 +44,14 @@ def read_frame(self, cap: VideoCaptureLike, frame_idx: int | None = None) -> Fra def read_image(self, path: str) -> FrameArray: import cv2 + import numpy as np + from PIL import UnidentifiedImageError - img = cv2.imread(path) - if img is None: - raise ValueError(f"Could not read image: {path}") - return cast(FrameArray, img) + try: + rgb = np.asarray(open_oriented_rgb(path)) + except (UnidentifiedImageError, OSError) as exc: + raise ValueError(f"Could not read image: {path}") from exc + return cast(FrameArray, cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)) def apply_canny(self, frame: FrameArray) -> FrameArray: import cv2 diff --git a/backend/services/video_trim.py b/backend/services/video_trim.py new file mode 100644 index 000000000..0944a935b --- /dev/null +++ b/backend/services/video_trim.py @@ -0,0 +1,103 @@ +from __future__ import annotations + +import threading +from pathlib import Path + +from services.encoded_media import ( + check_output_size, + derived_file_name, + ingest_encoded, +) +from services.ffmpeg import FFMPEG_PROTOCOL_WHITELIST, ffmpeg_seconds, run_ffmpeg +from services.media_probe import MAX_VIDEO_BYTES +from services.media_source import require_source +from services.records import AssetRecord, MediaError +from services.store import Store + +# Re-encoding up to a minute of 4K source is slower than an audio trim. +VIDEO_TRIM_TIMEOUT_SECONDS = 300.0 + +# Video trims run one at a time so parallel requests (e.g. from a paired +# phone) cannot stack encodes. A queued request gives up after this long +# rather than holding a server worker thread indefinitely. +VIDEO_TRIM_QUEUE_TIMEOUT_SECONDS = 30.0 +_ENCODE_SLOT = threading.Lock() + + +def trim_video_file(src: Path, dest: Path, start_sec: float, end_sec: float) -> None: + run_ffmpeg( + [ + "-y", + # Input-side seek is frame-accurate when re-encoding and does not + # decode everything before the In point of a long source. + "-ss", + ffmpeg_seconds(start_sec), + "-t", + ffmpeg_seconds(end_sec - start_sec), + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-i", + str(src), + "-map", + "0:v:0", + "-map", + "0:a:0?", + # yuv420p + libx264 reject odd dimensions; ingest accepts them. + "-vf", + "scale=trunc(iw/2)*2:trunc(ih/2)*2", + "-c:v", + "libx264", + "-preset", + "veryfast", + "-crf", + "18", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + "-b:a", + "192k", + "-movflags", + "+faststart", + "-protocol_whitelist", + FFMPEG_PROTOCOL_WHITELIST, + "-fs", + str(MAX_VIDEO_BYTES), + str(dest), + ], + timeout=VIDEO_TRIM_TIMEOUT_SECONDS, + ) + + +def trim_video_asset( + store: Store, asset_id: str, start_sec: float, end_sec: float +) -> AssetRecord: + if end_sec <= start_sec: + raise ValueError("endSec must be greater than startSec") + record, source = require_source(store, asset_id, "video") + metadata = record.metadata + # ffmpeg exits 0 with an empty, stream-less file when seeking past the end. + if ( + metadata.mediaType == "video" + and start_sec >= metadata.metadata.durationMs / 1000 + ): + raise MediaError("INVALID_TRIM_RANGE", "startSec is past the end of the video") + + def write(tmp_dir: Path) -> Path: + dest = tmp_dir / derived_file_name(record.name, "trim", ".mp4") + if not _ENCODE_SLOT.acquire(timeout=VIDEO_TRIM_QUEUE_TIMEOUT_SECONDS): + raise MediaError("TRIM_BUSY", "another video trim is in progress") + try: + trim_video_file(source, dest, start_sec, end_sec) + finally: + _ENCODE_SLOT.release() + check_output_size(dest, MAX_VIDEO_BYTES, "video") + return dest + + return ingest_encoded( + store, + write, + prefix="ltx-video-trim-", + label="video", + failure="ffmpeg failed to trim video", + ) diff --git a/backend/state/app_settings.py b/backend/state/app_settings.py index ad56126a0..5037bb7b2 100644 --- a/backend/state/app_settings.py +++ b/backend/state/app_settings.py @@ -3,21 +3,33 @@ from __future__ import annotations import sys -from typing import Any, Literal, TypeGuard, TypeVar, cast, get_args +from typing import Annotated, Any, Literal, TypeGuard, TypeVar, cast, get_args -from pydantic import BaseModel, ConfigDict, Field, create_model, field_validator +from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, StringConstraints, create_model, field_validator from api_types import LTXLocalModelId +RemoteExposure = Literal["off", "lan"] +DashboardRange = Literal["7d", "30d", "all"] +MAX_GENERATION_SEED = 2_147_483_647 -def _to_camel_case(field_name: str) -> str: - special_aliases = { - "prompt_enhancer_enabled_t2v": "promptEnhancerEnabledT2V", - "prompt_enhancer_enabled_i2v": "promptEnhancerEnabledI2V", - } - if field_name in special_aliases: - return special_aliases[field_name] +def _parse_remote_exposure(value: object) -> RemoteExposure: + return "lan" if value == "lan" else "off" + + +RemoteExposureSetting = Annotated[RemoteExposure, BeforeValidator(_parse_remote_exposure)] + + +def _parse_dashboard_range(value: object) -> DashboardRange: + if value == "30d": + return "30d" + if value == "all": + return "all" + return "7d" + + +def _to_camel_case(field_name: str) -> str: head, *tail = field_name.split("_") return head + "".join(part.title() for part in tail) @@ -48,6 +60,33 @@ class SettingsPatchModel(SettingsBaseModel): ) +SelectionValues = list[Annotated[str, StringConstraints(max_length=64)]] + + +class DashboardSelection(SettingsBaseModel): + """Activity Dashboard view. An empty list means Any.""" + + range: DashboardRange = "7d" + models: SelectionValues = Field(default_factory=list, max_length=32) + resolutions: SelectionValues = Field(default_factory=list, max_length=32) + aspect_ratios: SelectionValues = Field(default_factory=list, max_length=32) + fps: SelectionValues = Field(default_factory=list, max_length=32) + + +class GenerationSeed(SettingsBaseModel): + """The seed every generate surface shares. `seed` is the next seed to use.""" + + seed: int = Field(ge=0, le=MAX_GENERATION_SEED) + locked: bool + + +class GenerationSeedUpdate(SettingsBaseModel): + """Partial update: a client can flip the lock without touching the seed.""" + + seed: int | None = Field(default=None, ge=0, le=MAX_GENERATION_SEED) + locked: bool | None = None + + class AppSettings(SettingsBaseModel): use_torch_compile: bool = False diffusion_stage_cache_enabled: bool = False @@ -57,8 +96,11 @@ class AppSettings(SettingsBaseModel): user_prefers_fal_api_image_generations: bool = False use_local_text_encoder: bool = False prompt_cache_size: int = 100 - prompt_enhancer_enabled_t2v: bool = True - prompt_enhancer_enabled_i2v: bool = False + # API enhance_prompt gate. One switch for every conditioning (text, image, keyframes, + # audio) — Settings presents it as one control, so the state behind it is one flag too. + prompt_enhancer_enabled: bool = True + # Home / Remote Explore: automatic prompt rewrite before Generate. Gen Space is unchanged. + explore_auto_enhance_prompts: bool = True # The user's explicit choice, persisted so it survives restarts. None means no active choice # has been made yet — the UI defaults to whichever provider is available, preferring local, # without writing that default back here. Only an explicit user pick (not an automatic @@ -74,6 +116,11 @@ class AppSettings(SettingsBaseModel): active_ltx_model_id: LTXLocalModelId | None = None # None = platform default (Mac on, CUDA/Linux off). An explicit bool is a user override. use_conv_vae: bool | None = None + # Remote client HTTP server. Serving only when this is not off. Default off so a leftover + # settings.json cannot expose the engine after an upgrade. Unknown values (PoC tunnel modes) + # coerce to off. + remote_exposure: RemoteExposureSetting = "off" + activity_dashboard_selections: DashboardSelection = Field(default_factory=DashboardSelection) @field_validator("prompt_cache_size", mode="before") @classmethod @@ -83,7 +130,18 @@ def _clamp_prompt_cache_size(cls, value: Any) -> int: @field_validator("locked_seed", mode="before") @classmethod def _clamp_locked_seed(cls, value: Any) -> int: - return _clamp_int(value, minimum=0, maximum=2_147_483_647, default=42) + return _clamp_int(value, minimum=0, maximum=MAX_GENERATION_SEED, default=42) + + @field_validator("activity_dashboard_selections", mode="before") + @classmethod + def _tolerate_unknown_dashboard_range(cls, value: object) -> object: + """Only a stored file is forgiven an unknown range. The API rejects it.""" + if not isinstance(value, dict): + return value + stored = cast(dict[str, object], value) + if "range" not in stored: + return stored + return {**stored, "range": _parse_dashboard_range(stored["range"])} SettingsModelT = TypeVar("SettingsModelT", bound=SettingsBaseModel) @@ -139,8 +197,8 @@ class SettingsResponse(SettingsBaseModel): user_prefers_fal_api_image_generations: bool = False use_local_text_encoder: bool = False prompt_cache_size: int = 100 - prompt_enhancer_enabled_t2v: bool = True - prompt_enhancer_enabled_i2v: bool = False + prompt_enhancer_enabled: bool = True + explore_auto_enhance_prompts: bool = True prompt_enhancer_provider_preference: Literal["local", "api"] | None = None has_gemini_api_key: bool = False gemini_model: str = "" @@ -149,6 +207,12 @@ class SettingsResponse(SettingsBaseModel): models_dir: str = "" active_ltx_model_id: LTXLocalModelId | None = None use_conv_vae: bool = False + remote_exposure: RemoteExposureSetting = "off" + activity_dashboard_selections: DashboardSelection = Field(default_factory=DashboardSelection) + + +def remote_is_on(exposure: RemoteExposure) -> bool: + return exposure != "off" def resolved_use_conv_vae(settings: AppSettings) -> bool: diff --git a/backend/state/app_state_types.py b/backend/state/app_state_types.py index e2d23bd92..2628c2ba4 100644 --- a/backend/state/app_state_types.py +++ b/backend/state/app_state_types.py @@ -6,6 +6,8 @@ from typing import TYPE_CHECKING, NewType, Protocol from api_types import LTXLocalModelId, ModelCheckpointID +from runtime_config.ic_lora_tiling import IcLoraTiling +from runtime_config.runtime_policy import LocalGenerationMode from state.conditioning_cache import ConditioningCache if TYPE_CHECKING: @@ -101,14 +103,14 @@ def to(self, device: torch.device) -> "CachedTextEncoder": ... -def _new_prompt_cache() -> dict[tuple[str, bool], TextEncodingResult]: +def _new_prompt_cache() -> dict[tuple[str, bool, str], TextEncodingResult]: return {} @dataclass class TextEncoderState: service: TextEncoder - prompt_cache: dict[tuple[str, bool], TextEncodingResult] = field(default_factory=_new_prompt_cache) + prompt_cache: dict[tuple[str, bool, str], TextEncodingResult] = field(default_factory=_new_prompt_cache) api_embeddings: TextEncodingResult | None = None cached_encoder: CachedTextEncoder | None = None @@ -125,6 +127,9 @@ class VideoPipelineState: # Cache key: API text-encode mode leaves gemma_root=None across versions, so without this a # switch (2.5 <-> 2.3) wouldn't rebuild. ltx_model_id: LTXLocalModelId + # Full vs stream for this resident pipeline. A 5s full load must not be reused for + # a 720p/20s job that needs streaming weights. + loading_mode: LocalGenerationMode loras: tuple[tuple[str, float], ...] = field(default_factory=tuple) # gemma_root the pipeline's text encoder was built with. Part of the cache key: switching # text-encoding mode (API<->local) changes it, and a cached pipeline built for the other @@ -149,17 +154,24 @@ class ICLoraState: depth_pipeline: DepthProcessorPipeline | None depth_model_path: str | None ltx_model_id: LTXLocalModelId # cache key — see VideoPipelineState.ltx_model_id + loading_mode: LocalGenerationMode lora_strength: float = 1.0 pose_resources: PoseResources | None = None conditioning_cache: ConditioningCache = field(default_factory=ConditioningCache) gemma_root: str | None = None # cache key — see VideoPipelineState.gemma_root video_vae_path: str | None = None # cache key — see VideoPipelineState.video_vae_path + # Cache key. The stage list is fixed at build, so a one-stage-LoRA pipeline cannot serve it. + stage_2_ic_lora: bool = False + # Cache key: the catalog tiling. The tile size follows the canvas orientation, so the + # pipeline sets the stage list per job. A pipeline built for another tiling cannot serve it. + tiling: IcLoraTiling | None = None @dataclass class A2VPipelineState: pipeline: A2VPipeline ltx_model_id: LTXLocalModelId # cache key — see VideoPipelineState.ltx_model_id + loading_mode: LocalGenerationMode loras: tuple[tuple[str, float], ...] = field(default_factory=tuple) gemma_root: str | None = None # cache key — see VideoPipelineState.gemma_root video_vae_path: str | None = None # cache key — see VideoPipelineState.video_vae_path @@ -171,6 +183,9 @@ class RetakePipelineState: distilled: bool quantized: bool ltx_model_id: LTXLocalModelId # cache key — see VideoPipelineState.ltx_model_id + # Full vs stream for this resident pipeline. A small retake must not be reused + # for a 1080p job that the budget streamed. + loading_mode: LocalGenerationMode gemma_root: str | None = None # cache key — see VideoPipelineState.gemma_root video_vae_path: str | None = None # cache key — see VideoPipelineState.video_vae_path diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index c5b539223..983adf829 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -10,6 +10,7 @@ from app_factory import create_app from app_handler import ServiceBundle +from api_types import AudioToVideoParams, GenerateVideoCompleteResponse, GenerateVideoRequest from runtime_config.model_download_specs import ( DEPTH_PROCESSOR_CP_ID, IMG_GEN_MODEL_CP_ID, @@ -22,8 +23,13 @@ from state import RuntimeConfig, build_initial_state, set_state_service_for_tests from state.app_settings import AppSettings from state.app_state_types import HfAuthenticated +from services.features.ic_lora_recipes import queued_ic_lora_recipes +from services.features.lora_recipes import queued_lora_recipes +from services.features.video import AudioToVideoExecutor from services.gemini_text_client import clear_gemini_models_cache +from services.sqlite_store import SqliteStore from tests.fake_camera_motion_prompts import FAKE_CAMERA_MOTION_PROMPTS +from tests.fakes.generation import FakeGenerationExecutor from tests.fakes.services import FakeServices DEFAULT_NEGATIVE_PROMPT = ( @@ -34,6 +40,34 @@ DEFAULT_APP_SETTINGS = AppSettings() +class _UnusedReservedVideoGenerator: + @property + def models_dir(self) -> Path: + return Path("/unused-reserved-video-generator") + + def validate_local_a2v_request( + self, params: AudioToVideoParams, audio_duration_ms: int + ) -> None: + del params, audio_duration_ms + + def generate_local_reserved( + self, + req: GenerateVideoRequest, + *, + generation_id: str, + output_path: Path | None = None, + prompt_wrap=None, + a2v_num_frames: int | None = None, + a2v_audio_duration_seconds: float | None = None, + local_model_id=None, + ) -> GenerateVideoCompleteResponse: + del req, generation_id, prompt_wrap, a2v_num_frames, a2v_audio_duration_seconds, local_model_id + return GenerateVideoCompleteResponse( + status="complete", + video_path=str(output_path) if output_path is not None else "", + ) + + @pytest.fixture(autouse=True) def _reset_generation_interrupt() -> None: from services.generation_interrupt import clear @@ -43,6 +77,15 @@ def _reset_generation_interrupt() -> None: clear() +@pytest.fixture(autouse=True) +def _reset_denoising_progress() -> None: + from services.denoising_progress import reset + + reset() + yield + reset() + + @pytest.fixture def fake_services() -> FakeServices: return FakeServices() @@ -67,6 +110,7 @@ def test_state(tmp_path: Path, fake_services: FakeServices): settings_file=app_data / "settings.json", ltx_api_base_url="https://api.ltx.video", local_generations_mode="full_models_loading", + vram_gb=31, use_sage_attention=False, camera_motion_prompts=FAKE_CAMERA_MOTION_PROMPTS, default_negative_prompt=DEFAULT_NEGATIVE_PROMPT, @@ -75,6 +119,7 @@ def test_state(tmp_path: Path, fake_services: FakeServices): backend_port=PORT, ) + store = SqliteStore(config.app_data_dir) bundle = ServiceBundle( http=fake_services.http, gpu_cleaner=fake_services.gpu_cleaner, @@ -94,6 +139,27 @@ def test_state(tmp_path: Path, fake_services: FakeServices): a2v_pipeline_class=type(fake_services.a2v_pipeline), retake_pipeline_class=type(fake_services.retake_pipeline), prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), + store=store, + generation_executors={ + "text-to-video": FakeGenerationExecutor(), + "image-to-video": FakeGenerationExecutor(), + # Injecting generation_executors skips AppHandler's real per-recipe + # registration loop, so mirror it from the recipe table — a new recipe + # then can't 422 at validate_params for a missing executor. + **{ + recipe.recipe_id: FakeGenerationExecutor() + for recipe in queued_lora_recipes() + }, + **{ + recipe.recipe_id: FakeGenerationExecutor(feature=recipe.recipe_id) + for recipe in queued_ic_lora_recipes() + }, + "audio-to-video": AudioToVideoExecutor( + _UnusedReservedVideoGenerator(), store + ), + "retake": FakeGenerationExecutor(feature="retake"), + "extend": FakeGenerationExecutor(feature="extend"), + }, ) handler = build_initial_state( @@ -197,7 +263,7 @@ def _create(name: str = "style.safetensors") -> str: return _create -# Built-in depth/canny Union Control IC-LoRA ships with LTX 2.3 only. +# Union Control filenames come from the 2.3 spec; 2.5 reuses the same adapter on disk. _IC_LORA_MODEL_ID = "ltx-2.3-22b-distilled-1.1" diff --git a/backend/tests/fakes/generation.py b/backend/tests/fakes/generation.py new file mode 100644 index 000000000..fc7a61c5b --- /dev/null +++ b/backend/tests/fakes/generation.py @@ -0,0 +1,134 @@ +"""Fake generation executor for queue runner tests.""" + +from __future__ import annotations + +import time +import wave +from collections.abc import Mapping +from pathlib import Path + +import imageio.v2 as imageio +import numpy as np +from PIL import Image + +from api_types import ( + IcLoraRecipeInputs, + IcLoraRecipeStoredParams, + ExtendInputs, + ExtendParams, + ImageToVideoInputs, + ImageToVideoRecipeParams, + RetakeInputs, + RetakeParams, + TextToVideoParams, +) +from services.features.ic_lora_recipes import get_ic_lora_recipe +from services.generation_interrupt import GenerationCancelledError, is_requested +from services.features.video import require_supported_contract_version +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.records import GenerationRecord + +_VIDEO_PLAN = OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", +) + + +def _spec_params(spec: Mapping[str, object]) -> Mapping[str, object]: + params = spec.get("params") + if not isinstance(params, Mapping): + raise ValueError("generation spec requires a params object") + return params + + +def _write_valid_mp4(path: Path) -> None: + writer = imageio.get_writer( + str(path), fps=8, codec="libx264", macro_block_size=None + ) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(8): + writer.append_data(frame) + writer.close() + + +def _write_valid_wav(path: Path) -> None: + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * 800) + + +def _write_valid_output(allocation: OutputAllocation) -> None: + dest = Path(allocation.dest_path) + dest.parent.mkdir(parents=True, exist_ok=True) + match allocation.plan.media_kind: + case "video": + _write_valid_mp4(dest) + case "image": + Image.new("RGB", (16, 16), color=(1, 2, 3)).save(dest) + case "audio": + _write_valid_wav(dest) + + +class FakeGenerationExecutor: + def __init__( + self, + seen_prompts: list[str] | None = None, + error: Exception | None = None, + block: bool = False, + feature: str | None = None, + ) -> None: + self._seen_prompts = seen_prompts + self._error = error + self._block = block + self._feature = feature + + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + require_supported_contract_version(contract_version) + inputs = spec.get("inputs") + params = _spec_params(spec) + if isinstance(inputs, Mapping) and "video" in inputs: + if get_ic_lora_recipe(self._feature or "") is not None: + IcLoraRecipeStoredParams.model_validate(params) + IcLoraRecipeInputs.model_validate(inputs) + elif self._feature == "retake" or ( + self._feature is None and "startTime" in params + ): + RetakeParams.model_validate(params) + RetakeInputs.model_validate(inputs) + else: + ExtendParams.model_validate(params) + ExtendInputs.model_validate(inputs) + elif isinstance(inputs, Mapping) and "startFrame" in inputs: + # Recipe i2v specs carry `loras`; public I2V specs omit them. The + # recipe params model is a superset so one fake covers both. + ImageToVideoRecipeParams.model_validate(params) + ImageToVideoInputs.model_validate(inputs) + else: + TextToVideoParams.model_validate(params) + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + require_supported_contract_version(generation.contract_version) + return (_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + if self._seen_prompts is not None: + prompt = _spec_params(generation.spec).get("prompt") + self._seen_prompts.append(prompt if isinstance(prompt, str) else "") + if self._error is not None: + raise self._error + if self._block: + while not is_requested(): + time.sleep(0.01) + raise GenerationCancelledError() + for allocation in outputs: + _write_valid_output(allocation) diff --git a/backend/tests/fakes/services.py b/backend/tests/fakes/services.py index df00bd1d8..882e9871b 100644 --- a/backend/tests/fakes/services.py +++ b/backend/tests/fakes/services.py @@ -6,6 +6,7 @@ from dataclasses import dataclass, field from pathlib import Path from typing import Any, ClassVar +import shutil import threading import time @@ -27,6 +28,7 @@ RetakeMode, VideoCameraMotion, ) +from runtime_config.ic_lora_tiling import IcLoraTiling from services.interfaces import VideoInfoPayload from services.ltx_api_client.ltx_api_client import LTXRetakeResult from tests.fakes.fake_gpu_info import FakeGpuInfo @@ -36,7 +38,7 @@ def _dl(repo_id: str, filename: str, size_bytes: int = 10) -> DownloadSpec: """Single-checkpoint DownloadSpec (first/only variant = default).""" return DownloadSpec( repo_id=repo_id, - variants=[DownloadVariant(id="default", label="Default", filename=filename, size_bytes=size_bytes)], + variants=[DownloadVariant(id="default", label="Default", filename=filename, size_bytes=size_bytes, base_model="LTX-2.3")], ) @@ -172,6 +174,7 @@ def upload_file( { "api_key": api_key, "file_path": file_path, + "contents": Path(file_path).read_bytes(), } ) if self.raise_on_upload_file is not None: @@ -190,6 +193,7 @@ def generate_text_to_video( fps: float, generate_audio: bool, camera_motion: VideoCameraMotion = "none", + enhance_prompt: bool = True, ) -> bytes: self.text_to_video_calls.append( { @@ -201,6 +205,7 @@ def generate_text_to_video( "fps": fps, "generate_audio": generate_audio, "camera_motion": camera_motion, + "enhance_prompt": enhance_prompt, } ) if self.raise_on_text_to_video is not None: @@ -220,6 +225,7 @@ def generate_image_to_video( generate_audio: bool, camera_motion: VideoCameraMotion = "none", last_frame_uri: str | None = None, + enhance_prompt: bool = True, ) -> bytes: self.image_to_video_calls.append( { @@ -233,6 +239,7 @@ def generate_image_to_video( "fps": fps, "generate_audio": generate_audio, "camera_motion": camera_motion, + "enhance_prompt": enhance_prompt, } ) if self.raise_on_image_to_video is not None: @@ -249,6 +256,7 @@ def generate_audio_to_video( model: str, resolution: str, last_frame_uri: str | None = None, + enhance_prompt: bool = True, ) -> bytes: self.audio_to_video_calls.append( { @@ -259,6 +267,7 @@ def generate_audio_to_video( "last_frame_uri": last_frame_uri, "model": model, "resolution": resolution, + "enhance_prompt": enhance_prompt, } ) if self.raise_on_audio_to_video is not None: @@ -457,9 +466,9 @@ def __init__(self, catalog: LoraCatalogFile | None = None) -> None: requires_hf_login=True, input=InputSpec(kind="image"), preprocessing=[PreprocessingStep(utility="image_to_frames", params={})], - controls=[IcLoraControl(id="duration", label="Duration", default=5, options=[5, 8])], + controls=[IcLoraControl(id="duration", label="Duration", default=5, options=[5, 8, 20])], instructions=[InstructionSection(kind="summary", title="What it does", body="use it")], - default_settings=IcLoraSettings(skip_stage_2=True), + default_settings=IcLoraSettings(skip_stage_2=True, resolution_factor=1.5), ), IcLoraCatalogItem( id="colorize-v1", @@ -470,7 +479,7 @@ def __init__(self, catalog: LoraCatalogFile | None = None) -> None: input=InputSpec(kind="video"), preprocessing=[], instructions=[InstructionSection(kind="summary", title="What it does", body="use it")], - default_settings=IcLoraSettings(skip_stage_2=True), + default_settings=IcLoraSettings(skip_stage_2=True, resolution_factor=1.5), ), IcLoraCatalogItem( id="outpaint-v1", @@ -483,7 +492,7 @@ def __init__(self, catalog: LoraCatalogFile | None = None) -> None: preprocessing=[PreprocessingStep(utility="outpaint_canvas", params={})], controls=[IcLoraControl(id="outpaint_pads", kind="position_canvas", label="Canvas")], instructions=[InstructionSection(kind="summary", title="What it does", body="use it")], - default_settings=IcLoraSettings(skip_stage_2=True), + default_settings=IcLoraSettings(skip_stage_2=True, resolution_factor=1.5), ), IcLoraCatalogItem( id="refimg-v1", @@ -495,7 +504,7 @@ def __init__(self, catalog: LoraCatalogFile | None = None) -> None: input=InputSpec(kind="video"), preprocessing=[], instructions=[InstructionSection(kind="summary", title="What it does", body="use it")], - default_settings=IcLoraSettings(skip_stage_2=True), + default_settings=IcLoraSettings(skip_stage_2=True, resolution_factor=1.5), ), IcLoraCatalogItem( id="multi-v1", @@ -504,15 +513,15 @@ def __init__(self, catalog: LoraCatalogFile | None = None) -> None: download=DownloadSpec( repo_id="org/multi", variants=[ - DownloadVariant(id="strong", label="Strong", filename="strong.safetensors", size_bytes=10), - DownloadVariant(id="light", label="Light", filename="light.safetensors", size_bytes=5), + DownloadVariant(id="strong", label="Strong", filename="strong.safetensors", size_bytes=10, base_model="LTX-2.3"), + DownloadVariant(id="light", label="Light", filename="light.safetensors", size_bytes=5, base_model="LTX-2.3"), ], ), requires_hf_login=False, input=InputSpec(kind="video"), preprocessing=[], instructions=[InstructionSection(kind="summary", title="What it does", body="use it")], - default_settings=IcLoraSettings(skip_stage_2=True), + default_settings=IcLoraSettings(skip_stage_2=True, resolution_factor=1.5), ), ], loras=[ @@ -527,6 +536,155 @@ def __init__(self, catalog: LoraCatalogFile | None = None) -> None: tags=["style"], recommended_strength=1.0, ), + # Matches the real catalog id the "cozy-felt" recipe maps to, so + # create_lora_recipe can resolve + gate it in tests. + LoraCatalogItem( + id="cozy-felt-style", + name="Cozy Felt Style", + description="d", + download=_dl("vrg/felt-style", "CozyFelt.safetensors", size_bytes=20), + requires_hf_login=False, + trigger="F3ltCut0u7", + trigger_placement="anywhere", + tags=["style"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="dolly-in", + name="Dolly In", + description="d", + download=_dl( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In", + "ltx-2-19b-lora-camera-control-dolly-in.safetensors", + size_bytes=20, + ), + requires_hf_login=True, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="claymation-style", + name="Claymation Style", + description="d", + download=_dl("vrg/clay", "Claymation.safetensors", size_bytes=20), + requires_hf_login=False, + tags=["style"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="fantasy-painterly-style", + name="Fantasy Painterly Style", + description="d", + download=_dl("vrg/paint", "Fantasy_Painterly.safetensors", size_bytes=20), + requires_hf_login=False, + tags=["style"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="paper-cutout-style", + name="Paper Cut-Out Style", + description="d", + download=_dl("vrg/paper", "PaperCutOutStyle.safetensors", size_bytes=20), + requires_hf_login=False, + tags=["style"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="cinemagraph-motion", + name="Cinemagraph Motion", + description="d", + download=_dl( + "Lightricks/LTX-2.3-22b-LoRA-Cinemagraph", + "ltx-2.3-22b-lora-cinemagraph-0.9.safetensors", + size_bytes=20, + ), + requires_hf_login=True, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="jib-up", + name="Jib Up", + description="d", + download=_dl( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up", + "ltx-2-19b-lora-camera-control-jib-up.safetensors", + size_bytes=20, + ), + requires_hf_login=True, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="jib-down", + name="Jib Down", + description="d", + download=_dl( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down", + "ltx-2-19b-lora-camera-control-jib-down.safetensors", + size_bytes=20, + ), + requires_hf_login=True, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="dolly-out", + name="Dolly Out", + description="d", + download=_dl( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out", + "ltx-2-19b-lora-camera-control-dolly-out.safetensors", + size_bytes=20, + ), + requires_hf_login=True, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="fpv-motion", + name="FPV Motion", + description="d", + download=_dl("chsengni/fpv", "ltx2.3_fpv_motion.safetensors", size_bytes=20), + requires_hf_login=False, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="openwheel-tcam-style", + name="Open-Wheel Motorsport T-Cam", + description="d", + download=_dl( + "mxturbo/tcam", + "openwheel-t-cam-ltx2.3_000000500.safetensors", + size_bytes=20, + ), + requires_hf_login=False, + tags=["style"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="transition", + name="Transition", + description="d", + download=_dl("joyfox/transition", "ltx2.3-transition.safetensors", size_bytes=20), + requires_hf_login=False, + tags=["motion"], + recommended_strength=1.0, + ), + LoraCatalogItem( + id="vbvr", + name="VBVR", + description="d", + download=_dl( + "LiconStudio/vbvr", + "Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors", + size_bytes=20, + ), + requires_hf_login=False, + tags=["motion"], + recommended_strength=1.0, + ), ], ) @@ -642,6 +800,15 @@ def create_writer(self, path: str, fourcc: str, fps: float, size: tuple[int, int def release(self, cap_or_writer: FakeCapture | FakeWriter) -> None: cap_or_writer.release() + if isinstance(cap_or_writer, FakeWriter) and cap_or_writer.frames: + frame = cap_or_writer.frames[0] + if hasattr(frame, "shape") and len(frame.shape) >= 2: + height, width = int(frame.shape[0]), int(frame.shape[1]) + self.videos[str(cap_or_writer.path)] = FakeCapture( + frames=list(cap_or_writer.frames), + width=width, + height=height, + ) class _FakeVideoPipelineBase: @@ -657,6 +824,8 @@ def __init__(self) -> None: self.step_delay_s = 0.0 self.steps_completed = 0 self.entered_inference = threading.Event() + self.last_streaming_prefetch_count: int | None = None + self.create_count: int = 0 def _record_generate(self, payload: dict[str, Any]) -> None: self.generate_calls.append(payload) @@ -704,7 +873,6 @@ def create( gemma_root, upsampler_path, device, - streaming_prefetch_count, video_vae_path, audio_vae_path, duration_head_path, @@ -712,6 +880,8 @@ def create( pipeline = FakeFastVideoPipeline._singleton if pipeline is None: raise RuntimeError("FakeFastVideoPipeline singleton is not bound") + pipeline.last_streaming_prefetch_count = streaming_prefetch_count + pipeline.create_count += 1 pipeline.create_loras.append(list(loras or [])) return pipeline @@ -727,6 +897,7 @@ def generate( output_path: str, *, guide_all_images: bool = False, + skip_stage_2: bool = False, ) -> None: payload = { "prompt": prompt, @@ -738,6 +909,7 @@ def generate( "images": images, "output_path": output_path, "guide_all_images": guide_all_images, + "skip_stage_2": skip_stage_2, } if self.inference_steps: from services.generation_interrupt import raise_if_requested @@ -896,15 +1068,12 @@ def create( video_vae_path: str | None = None, audio_vae_path: str | None = None, duration_head_path: str | None = None, + stage_2_ic_lora: bool = False, + tiling: IcLoraTiling | None = None, ) -> "FakeIcLoraPipeline": del ( - checkpoint_path, - gemma_root, upsampler_path, - lora_path, device, - streaming_prefetch_count, - lora_strength, video_vae_path, audio_vae_path, duration_head_path, @@ -912,11 +1081,27 @@ def create( pipeline = FakeIcLoraPipeline._singleton if pipeline is None: raise RuntimeError("FakeIcLoraPipeline singleton is not bound") + pipeline.last_checkpoint_path = checkpoint_path + pipeline.last_gemma_root = gemma_root + pipeline.last_lora_path = lora_path + pipeline.last_lora_strength = lora_strength + pipeline.last_stage_2_ic_lora = stage_2_ic_lora + pipeline.last_tiling = tiling + pipeline.last_streaming_prefetch_count = streaming_prefetch_count + pipeline.create_count += 1 return pipeline def __init__(self) -> None: self.generate_calls: list[dict[str, Any]] = [] self.raise_on_generate: Exception | None = None + self.last_streaming_prefetch_count: int | None = None + self.last_checkpoint_path: str | None = None + self.last_gemma_root: str | None = None + self.last_lora_path: str | None = None + self.last_lora_strength: float | None = None + self.last_stage_2_ic_lora: bool | None = None + self.last_tiling: IcLoraTiling | None = None + self.create_count: int = 0 def generate(self, **kwargs: Any) -> None: self.generate_calls.append(kwargs) @@ -1006,7 +1191,6 @@ def create( gemma_root, upsampler_path, device, - streaming_prefetch_count, video_vae_path, audio_vae_path, duration_head_path, @@ -1014,6 +1198,8 @@ def create( pipeline = FakeA2VPipeline._singleton if pipeline is None: raise RuntimeError("FakeA2VPipeline singleton is not bound") + pipeline.last_streaming_prefetch_count = streaming_prefetch_count + pipeline.create_count += 1 pipeline.create_loras.append(list(loras or [])) return pipeline @@ -1021,6 +1207,8 @@ def __init__(self) -> None: self.generate_calls: list[dict[str, Any]] = [] self.create_loras: list[list[tuple[str, float]]] = [] self.raise_on_generate: Exception | None = None + self.last_streaming_prefetch_count: int | None = None + self.create_count: int = 0 def generate(self, **kwargs: Any) -> None: self.generate_calls.append(kwargs) @@ -1052,10 +1240,11 @@ def create( audio_vae_path: str | None = None, duration_head_path: str | None = None, ) -> "FakeRetakePipeline": - del device, streaming_prefetch_count, loras, quantization + del device, loras, quantization pipeline = FakeRetakePipeline._singleton if pipeline is None: raise RuntimeError("FakeRetakePipeline singleton is not bound") + pipeline.last_streaming_prefetch_count = streaming_prefetch_count pipeline.create_calls.append({ "checkpoint_path": checkpoint_path, "gemma_root": gemma_root, @@ -1071,6 +1260,7 @@ def __init__(self) -> None: self.extend_calls: list[dict[str, Any]] = [] self.raise_on_generate: Exception | None = None self.raise_on_extend: Exception | None = None + self.last_streaming_prefetch_count: int | None = None def generate(self, **kwargs: Any) -> None: self.generate_calls.append(kwargs) @@ -1079,7 +1269,11 @@ def generate(self, **kwargs: Any) -> None: output_path = Path(kwargs["output_path"]) output_path.parent.mkdir(parents=True, exist_ok=True) - output_path.write_bytes(b"fake-retake-video") + source = Path(kwargs.get("video_path", "")) + if source.is_file(): + shutil.copy2(source, output_path) + else: + output_path.write_bytes(b"fake-retake-video") def extend(self, **kwargs: Any) -> None: self.extend_calls.append(kwargs) @@ -1088,7 +1282,11 @@ def extend(self, **kwargs: Any) -> None: output_path = Path(kwargs["output_path"]) output_path.parent.mkdir(parents=True, exist_ok=True) - output_path.write_bytes(b"fake-extend-video") + src = Path(str(kwargs.get("video_path") or "")) + if src.is_file(): + shutil.copy2(src, output_path) + else: + output_path.write_bytes(b"fake-extend-video") class FakeTextEncoder: diff --git a/backend/tests/lora_catalog_helpers.py b/backend/tests/lora_catalog_helpers.py new file mode 100644 index 000000000..da77d9115 --- /dev/null +++ b/backend/tests/lora_catalog_helpers.py @@ -0,0 +1,45 @@ +"""Catalog entries the prompt-enhancement tests inject into the fake catalog provider. + +The shipped catalog is real data that changes underneath tests; these build throwaway entries +with only the field under test set, so a test reads as "an IC-LoRA with a trigger" rather than +as a full catalog record. +""" + +from __future__ import annotations + +from api_types import ( + DownloadSpec, + DownloadVariant, + IcLoraCatalogItem, + InputSpec, + LoraCatalogItem, +) + + +def download_spec(filename: str = "x.safetensors") -> DownloadSpec: + return DownloadSpec( + repo_id="org/x", + variants=[DownloadVariant(id="default", label="Default", filename=filename, size_bytes=10, base_model="LTX-2.3")], + ) + + +def add_lora(fake_services, **overrides: object) -> LoraCatalogItem: + defaults: dict[str, object] = dict( + id="test-lora", name="Test Lora", description="d", download=download_spec(), + requires_hf_login=False, + ) + defaults.update(overrides) + lora = LoraCatalogItem(**defaults) + fake_services.lora_catalog_provider._catalog.loras.append(lora) + return lora + + +def add_ic_lora(fake_services, **overrides: object) -> IcLoraCatalogItem: + defaults: dict[str, object] = dict( + id="test-ic-lora", name="Test IC-LoRA", description="d", download=download_spec(), + requires_hf_login=False, input=InputSpec(kind="video"), + ) + defaults.update(overrides) + ic_lora = IcLoraCatalogItem(**defaults) + fake_services.lora_catalog_provider._catalog.ic_loras.append(ic_lora) + return ic_lora diff --git a/backend/tests/test_alpha_cutout.py b/backend/tests/test_alpha_cutout.py new file mode 100644 index 000000000..880bb00ff --- /dev/null +++ b/backend/tests/test_alpha_cutout.py @@ -0,0 +1,471 @@ +"""AlphaGen cutout: the matte and the source become one WebM with a real alpha channel.""" + +from __future__ import annotations + +import re +import shutil +import subprocess +import time +from pathlib import Path + +import imageio.v2 as imageio +import imageio_ffmpeg +import numpy as np +import pytest +from PIL import Image + +from api_types import ( + IcLoraRecipeStoredParams, + LoraEntry, + VideoAssetMetadata, + VideoMeta, +) +from services.features.ic_lora_recipes import IC_LORA_RECIPES +from services.features.video.alpha_cutout import ( + bake_alpha_cutout, + bake_alpha_gif, + bake_alpha_gif_if_possible, +) +from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor +from services.media_probe import video_frame_count +from services.generation_queue.types import OutputAllocation +from services.records import AssetRecord, GenerationRecord + +_SOURCE_RGB = (200, 40, 40) +_MATTE_SIZE = (48, 64) # height, width + + +def _write_mp4(path: Path, frame: np.ndarray, *, frames: int = 9) -> Path: + writer = imageio.get_writer(str(path), fps=24, codec="libx264", macro_block_size=None) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return path + + +def _source(path: Path) -> Path: + frame = np.zeros((60, 80, 3), dtype=np.uint8) + frame[:, :] = _SOURCE_RGB + return _write_mp4(path, frame) + + +def _matte(path: Path) -> Path: + """White left half (subject), black right half (background).""" + frame = np.zeros((*_MATTE_SIZE, 3), dtype=np.uint8) + frame[:, : _MATTE_SIZE[1] // 2] = 255 + return _write_mp4(path, frame) + + +def _first_frame_rgba(webm: Path) -> np.ndarray: + """Decode with libvpx-vp9. The native decoder drops the alpha plane.""" + raw = subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-c:v", "libvpx-vp9", + "-i", str(webm), + "-frames:v", "1", + "-f", "rawvideo", + "-pix_fmt", "rgba", + "-", + ], + capture_output=True, + check=True, + ).stdout + return np.frombuffer(raw, dtype=np.uint8).reshape(*_MATTE_SIZE, 4) + + +def _stream_info(webm: Path) -> str: + return subprocess.run( + [imageio_ffmpeg.get_ffmpeg_exe(), "-i", str(webm)], + capture_output=True, + text=True, + check=False, + ).stderr + + +def _assert_cutout(webm: Path) -> None: + assert "alpha_mode" in _stream_info(webm) + rgba = _first_frame_rgba(webm) + subject = rgba[_MATTE_SIZE[0] // 2, 8] + background = rgba[_MATTE_SIZE[0] // 2, _MATTE_SIZE[1] - 8] + assert subject[3] == 255 + assert background[3] == 0 + # The color is the source color, scaled to the matte size. + assert all(abs(int(a) - b) < 12 for a, b in zip(subject[:3], _SOURCE_RGB)) + + +def test_bake_uses_the_matte_as_alpha_and_the_matte_size(tmp_path: Path) -> None: + dest = tmp_path / "cutout.webm" + bake_alpha_cutout(_source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), dest) + _assert_cutout(dest) + + +def test_bake_keeps_soft_alpha(tmp_path: Path) -> None: + """A faint matte value stays faint. A second range expansion would turn 26 into about 12.""" + frame = np.zeros((*_MATTE_SIZE, 3), dtype=np.uint8) + frame[:, : _MATTE_SIZE[1] // 2] = 128 # half transparent + frame[:, _MATTE_SIZE[1] // 2 :] = 26 # barely visible + dest = tmp_path / "cutout.webm" + bake_alpha_cutout(_source(tmp_path / "source.mp4"), _write_mp4(tmp_path / "matte.mp4", frame), dest) + + rgba = _first_frame_rgba(dest) + half = int(rgba[_MATTE_SIZE[0] // 2, 8][3]) + faint = int(rgba[_MATTE_SIZE[0] // 2, _MATTE_SIZE[1] - 8][3]) + assert abs(half - 128) <= 8 + assert 15 <= faint <= 40 + + +def _gif_frame(gif: Path, index: int = 0) -> Image.Image: + with Image.open(gif) as image: + image.seek(index) + return image.convert("RGBA") + + +def _assert_gif_cutout(gif: Path) -> None: + with Image.open(gif) as image: + assert image.format == "GIF" + assert image.n_frames > 1 + assert image.info.get("loop") == 0 + frame = _gif_frame(gif) + subject = frame.getpixel((8, _MATTE_SIZE[0] // 2)) + background = frame.getpixel((_MATTE_SIZE[1] - 8, _MATTE_SIZE[0] // 2)) + assert subject[3] == 255 + assert background[3] == 0 + assert all(abs(int(a) - b) < 24 for a, b in zip(subject[:3], _SOURCE_RGB)) + + +def test_the_gif_is_the_cutout_with_clear_pixels_and_the_matte_size(tmp_path: Path) -> None: + dest = tmp_path / "cutout.gif" + bake_alpha_gif(_source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), dest) + _assert_gif_cutout(dest) + assert _gif_frame(dest).size == (_MATTE_SIZE[1], _MATTE_SIZE[0]) + + +def test_the_gif_fits_in_720_and_never_grows(tmp_path: Path) -> None: + large = np.zeros((540, 960, 3), dtype=np.uint8) + large[:, :480] = 255 + dest = tmp_path / "large.gif" + bake_alpha_gif( + _source(tmp_path / "source.mp4"), _write_mp4(tmp_path / "matte.mp4", large, frames=3), dest + ) + assert _gif_frame(dest).size == (720, 405) + + +def test_the_gif_is_stored_as_an_image_asset(tmp_path: Path) -> None: + from services.media_probe import probe_file + + dest = tmp_path / "cutout.gif" + bake_alpha_gif(_source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), dest) + kind, mime, metadata = probe_file(dest) + assert (kind, mime) == ("image", "image/gif") + assert metadata.mediaType == "image" + + +def test_a_gif_is_not_an_allowed_upload(tmp_path: Path) -> None: + from services.media_probe import validate_ingest_source + from services.records import MediaError + + gif = tmp_path / "upload.gif" + Image.new("RGB", (4, 4)).save(gif) + with pytest.raises(MediaError): + validate_ingest_source(gif) + + +def _decoded_frames(webm: Path) -> int: + run = subprocess.run( + [imageio_ffmpeg.get_ffmpeg_exe(), "-c:v", "libvpx-vp9", "-i", str(webm), "-f", "null", "-"], + capture_output=True, + text=True, + check=True, + ) + return int(re.findall(r"frame= *(\d+)", run.stderr)[-1]) + + +@pytest.mark.parametrize("frames", [9, 20, 150]) +def test_the_bake_keeps_every_frame_of_the_matte(tmp_path: Path, frames: int) -> None: + """The alpha merge ended one frame early on two streams of the same length.""" + frame = np.full((60, 80, 3), 120, dtype=np.uint8) + dest = tmp_path / "cutout.webm" + bake_alpha_cutout( + _write_mp4(tmp_path / "source.mp4", frame, frames=frames), + _write_mp4(tmp_path / "matte.mp4", np.full((48, 64, 3), 255, dtype=np.uint8), frames=frames), + dest, + ) + + assert _decoded_frames(dest) == frames + + +def test_the_bake_keeps_every_frame_when_the_matte_audio_ends_early(tmp_path: Path) -> None: + """Source audio can end before the video. The audio ends. The video does not.""" + frames = 48 + silent = _write_mp4(tmp_path / "silent.mp4", np.full((48, 64, 3), 255, dtype=np.uint8), frames=frames) + matte = tmp_path / "matte.mp4" + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", "-i", str(silent), + "-f", "lavfi", "-i", "sine=frequency=440:duration=0.5", + "-map", "0:v", "-map", "1:a", + "-c:v", "copy", "-c:a", "aac", + str(matte), + ], + capture_output=True, + check=True, + ) + dest = tmp_path / "cutout.webm" + + bake_alpha_cutout( + _write_mp4(tmp_path / "source.mp4", np.full((60, 80, 3), 120, dtype=np.uint8), frames=frames), + matte, + dest, + ) + + assert _decoded_frames(dest) == frames + + +class _MatteWriter: + """Stands in for the model. It writes a matte where the real one would.""" + + def __init__(self, matte: Path) -> None: + self._matte = matte + + def generate_local_reserved(self, _request: object, **kwargs: object) -> object: + shutil.copyfile(self._matte, Path(str(kwargs["output_path"]))) + return object() + + +def _allocations(tmp_path: Path, executor: IcLoraRecipeExecutor, generation: GenerationRecord): + return tuple( + OutputAllocation(plan=plan, asset_id=plan.slot, dest_path=str(tmp_path / plan.name)) + for plan in executor.plan_outputs(generation) + ) + + +class _GridModel: + """Stands in for the model, with its frame snap. The matte has the shape of the guide clip. + + The pipeline snaps the frame count DOWN to 8k+1. The subject is the left half. + """ + + def generate_local_reserved(self, request: object, **kwargs: object) -> object: + guide = imageio.get_reader(request.input_path) # type: ignore[attr-defined] + try: + frames = guide.count_frames() + height, width = np.asarray(guide.get_data(0)).shape[:2] + finally: + guide.close() + matte = np.zeros((height, width, 3), dtype=np.uint8) + matte[:, : width // 2] = 255 + _write_mp4(Path(str(kwargs["output_path"])), matte, frames=(frames - 1) // 8 * 8 + 1) + return object() + + +def _run_alpha_gen(test_state, tmp_path: Path, model: object, source: Path, *, frames: int): + asset = AssetRecord( + id="clip", + media_kind="video", + origin="uploaded", + path=str(source), + mime_type="video/mp4", + name="clip.mp4", + metadata=VideoAssetMetadata( + mediaType="video", + metadata=VideoMeta( + width=80, + height=60, + durationMs=round(frames / 24 * 1000), + sizeBytes=source.stat().st_size, + audioStreamCount=0, + fps=24, + ), + ), + created_at=0, + ) + params = IcLoraRecipeStoredParams( + prompt="", + model="ltx-2.5-fast", + resolution="540p", + audioMode="off", + fps=24, + loras=[LoraEntry(ref="", scale=1.0, catalogId="alpha-gen")], + ) + generation = GenerationRecord( + id="gen", + feature="alpha-gen", + contract_version=1, + status="running", + spec={ + "params": params.model_dump(mode="json"), + "inputs": {"video": {"assetId": asset.id}}, + }, + created_at=0, + queued_at=0, + attempt_count=1, + started_at=0, + outputs=(), + ) + + class _Clip: + def get_asset(self, asset_id: str) -> AssetRecord | None: + return asset if asset_id == asset.id else None + + executor = IcLoraRecipeExecutor( + model, + _Clip(), + lambda: test_state.config.default_models_dir, + catalog_id="alpha-gen", + cutout=IC_LORA_RECIPES["alpha-gen"].cutout, + ) + outputs = _allocations(tmp_path, executor, generation) + assert [(o.plan.slot, o.plan.mime_type) for o in outputs] == [ + ("output", "video/webm"), + ("matte", "video/mp4"), + ("gif", "image/gif"), + ] + executor.execute(generation, outputs) + return outputs + + +def test_an_alpha_gen_run_stores_the_cutout_the_matte_and_the_gif_in_that_order( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + source = _source(tmp_path / "clip.mp4") + + outputs = _run_alpha_gen( + test_state, tmp_path, _MatteWriter(_matte(tmp_path / "model-matte.mp4")), source, frames=9 + ) + + _assert_cutout(Path(outputs[0].dest_path)) + assert Path(outputs[1].dest_path).exists() + _assert_gif_cutout(Path(outputs[2].dest_path)) + assert not list(tmp_path.glob("*-crop.mp4")) + assert not list(tmp_path.glob("*-fit.mp4")) + + +@pytest.mark.parametrize("frames", [145, 150]) +def test_an_alpha_gen_run_keeps_every_frame_of_the_clip( + test_state, create_fake_model_files, tmp_path: Path, frames: int +) -> None: + """The pipeline snaps down to 8k+1. A 150 frame clip lost 5 frames before the clip was padded.""" + create_fake_model_files() + source = _write_mp4(tmp_path / "clip.mp4", np.full((60, 80, 3), 120, dtype=np.uint8), frames=frames) + + outputs = _run_alpha_gen(test_state, tmp_path, _GridModel(), source, frames=frames) + + assert video_frame_count(Path(outputs[1].dest_path)) == frames + assert video_frame_count(Path(outputs[0].dest_path)) == frames + + +def test_only_alpha_gen_is_a_cutout_recipe() -> None: + assert {recipe_id for recipe_id, recipe in IC_LORA_RECIPES.items() if recipe.cutout} == { + "alpha-gen" + } + + +def test_a_cancel_during_the_bake_stops_ffmpeg(tmp_path: Path) -> None: + """The flag is polled while ffmpeg runs, so a cancel does not wait for the encode.""" + from services.ffmpeg import FfmpegCancelledError, run_ffmpeg + + started = time.monotonic() + with pytest.raises(FfmpegCancelledError): + run_ffmpeg( + ["-f", "lavfi", "-i", "testsrc=duration=600:size=1280x720:rate=30", "-f", "null", "-"], + should_cancel=lambda: True, + ) + assert time.monotonic() - started < 10 + + +def test_a_cancelled_bake_is_a_generation_cancel( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The ffmpeg helper has its own cancel error. The bake maps it to the queue's.""" + from services.ffmpeg import FfmpegCancelledError + from services.generation_interrupt import GenerationCancelledError + + def cancelled(*_args: object, **_kwargs: object) -> None: + raise FfmpegCancelledError() + + monkeypatch.setattr("services.features.video.alpha_cutout.run_ffmpeg", cancelled) + with pytest.raises(GenerationCancelledError): + bake_alpha_cutout( + _source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), tmp_path / "out.webm" + ) + + +def test_a_failed_bake_is_reported_as_a_bake_failure(tmp_path: Path) -> None: + from services.records import MediaError + + with pytest.raises(MediaError, match="alpha cutout failed"): + bake_alpha_cutout(tmp_path / "missing.mp4", _matte(tmp_path / "matte.mp4"), tmp_path / "out.webm") + + +def test_a_cancelled_gif_bake_is_a_generation_cancel( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from services.ffmpeg import FfmpegCancelledError + from services.generation_interrupt import GenerationCancelledError + + def cancelled(*_args: object, **_kwargs: object) -> None: + raise FfmpegCancelledError() + + monkeypatch.setattr("services.features.video.alpha_cutout.run_ffmpeg", cancelled) + with pytest.raises(GenerationCancelledError): + bake_alpha_gif( + _source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), tmp_path / "out.gif" + ) + + +def test_a_failed_gif_bake_is_reported_as_a_bake_failure(tmp_path: Path) -> None: + from services.records import MediaError + + with pytest.raises(MediaError, match="alpha gif failed"): + bake_alpha_gif(tmp_path / "missing.mp4", _matte(tmp_path / "matte.mp4"), tmp_path / "out.gif") + + +def test_a_gif_that_fails_leaves_no_file_and_does_not_raise(tmp_path: Path) -> None: + dest = tmp_path / "out.gif" + dest.write_bytes(b"partial") + + bake_alpha_gif_if_possible(tmp_path / "missing.mp4", _matte(tmp_path / "matte.mp4"), dest) + + assert not dest.exists() + + +def test_a_gif_that_ffmpeg_wrote_but_nothing_can_read_is_dropped( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def write_garbage(*_args: object, **_kwargs: object) -> None: + (tmp_path / "out.gif").write_bytes(b"not a gif") + + monkeypatch.setattr("services.features.video.alpha_cutout.run_ffmpeg", write_garbage) + bake_alpha_gif_if_possible( + _source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), tmp_path / "out.gif" + ) + assert not (tmp_path / "out.gif").exists() + + +def test_a_cancel_during_the_gif_still_cancels_the_run( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from services.ffmpeg import FfmpegCancelledError + from services.generation_interrupt import GenerationCancelledError + + def cancelled(*_args: object, **_kwargs: object) -> None: + raise FfmpegCancelledError() + + monkeypatch.setattr("services.features.video.alpha_cutout.run_ffmpeg", cancelled) + with pytest.raises(GenerationCancelledError): + bake_alpha_gif_if_possible( + _source(tmp_path / "source.mp4"), _matte(tmp_path / "matte.mp4"), tmp_path / "out.gif" + ) + + +def test_the_gif_is_the_only_optional_output() -> None: + from services.features.video.alpha_cutout import CUTOUT_OUTPUT_PLANS + + assert [(plan.slot, plan.optional) for plan in CUTOUT_OUTPUT_PLANS] == [ + ("output", False), + ("matte", False), + ("gif", True), + ] diff --git a/backend/tests/test_analytics.py b/backend/tests/test_analytics.py new file mode 100644 index 000000000..8be0e0c7f --- /dev/null +++ b/backend/tests/test_analytics.py @@ -0,0 +1,387 @@ +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from api_model_specs import video_generation_feature +from handlers.prompt_enhancement_handler import ( + ResolvedGenerationPrompt, + prompt_provenance_label, +) +from services.analytics import ( + ENDED_DETAIL_KEYS, + AnalyticsService, + QueuedEnhancement, + queued_generation_details, +) +from services.records import GenerationRecord +from services.sqlite_store import SqliteStore +from tests.fakes import FakeResponse +from tests.fakes.services import FakeHTTPClient, FakeTaskRunner + + +def _service(http: FakeHTTPClient, *, sink_url: str = "http://127.0.0.1:9/analytics") -> AnalyticsService: + return AnalyticsService( + http=http, + task_runner=FakeTaskRunner(), + sink_url=sink_url, + token="sink-token", + ) + + +def test_missing_sink_does_not_emit() -> None: + http = FakeHTTPClient() + service = _service(http, sink_url="") + + with service.generation({"generation_id": "generation-1"}): + pass + + assert http.calls == [] + + +def test_home_audio_to_video_derives_duration_sec_from_num_frames() -> None: + record = _home_record( + feature="audio-to-video", + params={"model": "ltx-2.5", "numFrames": 121, "fps": 24}, + ) + + details = queued_generation_details(record) + assert details is not None + assert details["duration_sec"] == 5.0 + assert details["fps"] == 24 + + +def test_forwarded_body_is_only_the_event_name_and_details() -> None: + http = FakeHTTPClient() + http.queue("post", FakeResponse()) + service = _service(http) + + service.send_generation_started( + {"generation_id": "generation-1", "prompt": "a fox"} + ) + + assert len(http.calls) == 1 + call = http.calls[0] + assert call.url == "http://127.0.0.1:9/analytics" + assert call.headers is not None + assert call.headers["Authorization"] == "Bearer sink-token" + assert call.json_payload == { + "eventName": "generate_started", + "extraDetails": {"generation_id": "generation-1", "prompt": "a fox"}, + } + assert call.json_payload is not None + assert "events" not in call.json_payload + assert "ltx-desktop.lightricks.com" not in call.url + + +def test_successful_generation_emits_one_matching_start_and_end() -> None: + http = FakeHTTPClient() + http.queue("post", FakeResponse(), FakeResponse()) + service = _service(http) + + with service.generation( + { + "generation_id": "generation-1", + "surface": "genspace", + "feature": "text-to-video", + } + ): + pass + + payloads = [call.json_payload for call in http.calls] + assert [payload["eventName"] for payload in payloads if payload is not None] == [ + "generate_started", + "generate_ended", + ] + start = payloads[0] + end = payloads[1] + assert start is not None and end is not None + start_details = start["extraDetails"] + end_details = end["extraDetails"] + assert isinstance(start_details, dict) + assert isinstance(end_details, dict) + assert start_details["surface"] == "genspace" + assert start_details["feature"] == "text-to-video" + assert set(end_details) == {"generation_id", "outcome", "runtime_ms"} + assert end_details["generation_id"] == start_details["generation_id"] + assert end_details["outcome"] == "succeeded" + assert isinstance(end_details["runtime_ms"], int) + assert end_details["runtime_ms"] >= 0 + + +@pytest.mark.parametrize("outcome", ["failed", "cancelled"]) +def test_terminal_generation_outcome_is_not_reported_as_succeeded(outcome: str) -> None: + http = FakeHTTPClient() + http.queue("post", FakeResponse(), FakeResponse()) + service = _service(http) + + if outcome == "failed": + with pytest.raises(RuntimeError): + with service.generation({"generation_id": "generation-1"}): + raise RuntimeError("generation failed") + else: + with service.generation({"generation_id": "generation-1"}) as tracker: + tracker.finish("cancelled") + + end = http.calls[1].json_payload + assert end is not None + details = end["extraDetails"] + assert isinstance(details, dict) + assert set(details) == {"generation_id", "outcome", "runtime_ms"} + assert details["outcome"] == outcome + + +def test_ended_event_keeps_the_join_key_and_drops_start_fields() -> None: + http = FakeHTTPClient() + http.queue("post", FakeResponse()) + service = _service(http) + + service.send_generation_ended( + { + "generation_id": "generation-1", + "attempt": 2, + "surface": "home", + "feature": "cozy-felt", + "prompt_provenance": "auto-enhanced", + }, + outcome="failed", + runtime_ms=10, + error_code="EXECUTOR_FAILED", + ) + + payload = http.calls[0].json_payload + assert payload is not None + assert payload["extraDetails"] == { + "generation_id": "generation-1", + "attempt": 2, + "outcome": "failed", + "runtime_ms": 10, + "error_code": "EXECUTOR_FAILED", + } + + +def test_prompt_provenance_label_names_the_three_modes() -> None: + manual = ResolvedGenerationPrompt("rewritten", False, False) + via_api = ResolvedGenerationPrompt("a fox", True, False) + via_local = ResolvedGenerationPrompt("a fox", False, True) + untouched = ResolvedGenerationPrompt("a fox", False, False) + + assert prompt_provenance_label("enhanced", manual) == "manually-enhanced" + assert prompt_provenance_label("typed", via_api) == "auto-enhanced" + assert prompt_provenance_label("typed", via_local) == "auto-enhanced" + assert prompt_provenance_label("typed", untouched) == "raw" + + +_LOCAL_ENHANCE = QueuedEnhancement( + explore_auto_enhance_prompts=True, + prompt_enhancer_enabled=True, + use_local_encoding=True, +) +_API_ENHANCE = QueuedEnhancement( + explore_auto_enhance_prompts=True, + prompt_enhancer_enabled=True, + use_local_encoding=False, +) + + +def test_ended_detail_keys_match_the_shared_contract() -> None: + contract_path = Path(__file__).resolve().parents[2] / "shared" / "analytics-ended-details.json" + assert json.loads(contract_path.read_text()) == list(ENDED_DETAIL_KEYS) + + +def test_video_generation_feature_prefers_keyframes_then_audio() -> None: + assert video_generation_feature( + audio_path="clip.wav", + image_path="still.png", + keyframes=[{"imagePath": "opening.png"}], + ) == "multi-keyframe" + assert video_generation_feature( + audio_path="clip.wav", + image_path="still.png", + ) == "audio-to-video" + assert video_generation_feature( + audio_path=None, + image_path=None, + last_image_path="end.png", + ) == "image-to-video" + assert video_generation_feature(audio_path=None, image_path=None) == "text-to-video" + + +def test_home_queue_records_stored_prompt_provenance() -> None: + enhanced = _home_record( + feature="text-to-video", + params={"prompt": "a long caption", "promptProvenance": "enhanced", "model": "ltx-2.5-fast"}, + ) + typed = _home_record( + feature="text-to-video", + params={"prompt": "a fox", "promptProvenance": "typed", "model": "ltx-2.5-fast"}, + ) + retake = _home_record( + feature="retake", + params={"prompt": "a fox", "promptProvenance": "typed"}, + ) + cozy = _home_record( + feature="cozy-felt", + params={"prompt": "a fox", "promptProvenance": "typed", "model": "ltx-2.5-fast"}, + ) + cozy_manual = _home_record( + feature="cozy-felt", + params={"prompt": "a fox", "promptProvenance": "enhanced", "model": "ltx-2.5-fast"}, + ) + + assert "prompt_provenance" not in (queued_generation_details(typed) or {}) + assert queued_generation_details(enhanced, enhancement=_LOCAL_ENHANCE)["prompt_provenance"] == "manually-enhanced" + assert queued_generation_details(typed, enhancement=_LOCAL_ENHANCE)["prompt_provenance"] == "auto-enhanced" + assert queued_generation_details(retake, enhancement=_LOCAL_ENHANCE)["prompt_provenance"] == "raw" + assert queued_generation_details( + typed, + enhancement=QueuedEnhancement( + explore_auto_enhance_prompts=False, + prompt_enhancer_enabled=True, + use_local_encoding=True, + ), + )["prompt_provenance"] == "raw" + # API text encoding plus a recipe wrap sends the typed scene when the local + # enhancer checkpoint is not installed. + assert queued_generation_details(cozy, enhancement=_API_ENHANCE)["prompt_provenance"] == "raw" + assert queued_generation_details( + cozy, + enhancement=QueuedEnhancement( + explore_auto_enhance_prompts=True, + prompt_enhancer_enabled=True, + use_local_encoding=False, + local_enhancer_available=True, + ), + )["prompt_provenance"] == "auto-enhanced" + assert queued_generation_details(cozy, enhancement=_LOCAL_ENHANCE)["prompt_provenance"] == "auto-enhanced" + assert queued_generation_details(cozy_manual, enhancement=_API_ENHANCE)["prompt_provenance"] == "manually-enhanced" + assert queued_generation_details(typed, enhancement=_API_ENHANCE)["prompt_provenance"] == "auto-enhanced" + + +def _home_record(*, feature: str, params: dict[str, object]) -> GenerationRecord: + return GenerationRecord( + id="generation-1", + feature=feature, + contract_version=1, + status="running", + spec={"_analytics": {"client": "desktop"}, "params": params}, + created_at=1, + queued_at=1, + attempt_count=1, + started_at=10, + outputs=(), + ) + + +def test_genspace_preview_records_manual_auto_and_raw(test_state) -> None: + enhancement = test_state.prompt_enhancement + assert enhancement.preview_prompt_provenance( + "a fox", + provenance="enhanced", + explore_generation=False, + ) == "manually-enhanced" + + test_state.state.app_settings.prompt_enhancer_enabled = False + assert enhancement.preview_prompt_provenance( + "a fox", + provenance="typed", + explore_generation=False, + force_api=True, + ) == "raw" + + test_state.state.app_settings.prompt_enhancer_enabled = True + assert enhancement.preview_prompt_provenance( + "a fox", + provenance="typed", + explore_generation=False, + force_api=True, + ) == "auto-enhanced" + + +def test_home_queue_details_stay_local_video_and_omit_prompt() -> None: + record = GenerationRecord( + id="generation-1", + feature="text-to-video", + contract_version=1, + status="running", + spec={ + "_analytics": {"client": "desktop"}, + "params": { + "prompt": "a fox in /tmp/secret.mp4", + "model": "ltx-2.5-fast", + "resolution": "1080p", + "duration": 5, + "fps": 24, + "video_path": "/tmp/in.mp4", + }, + }, + created_at=1, + queued_at=1, + attempt_count=1, + started_at=10, + outputs=(), + ) + + details = queued_generation_details(record) + + assert details is not None + assert details["surface"] == "home" + assert details["kind"] == "video" + assert details["execution"] == "local" + assert details["model"] == "ltx-2.5-fast" + assert details["resolution"] == "1080p" + assert "prompt" not in details + assert "video_path" not in details + + +def test_home_queue_pixel_resolution_is_recorded_as_width_times_height() -> None: + record = GenerationRecord( + id="generation-1", + feature="retake", + contract_version=1, + status="running", + spec={ + "_analytics": {"client": "desktop"}, + "params": { + "prompt": "a fox", + "resolution": {"width": 1920, "height": 1080, "path": "/tmp/in.mp4"}, + }, + }, + created_at=1, + queued_at=1, + attempt_count=1, + started_at=10, + outputs=(), + ) + + details = queued_generation_details(record) + + assert details is not None + assert details["resolution"] == "1920x1080" + assert "path" not in details + assert "prompt" not in details + + +def test_desktop_create_response_omits_internal_analytics(client, test_state) -> None: + response = client.post( + "/api/generations/text-to-video", + json={ + "params": { + "prompt": "a fox in /tmp/secret.mp4", + "model": "ltx-2.5-fast", + } + }, + ) + + assert response.status_code == 200, response.text + body = response.json() + assert "_analytics" not in body["spec"] + assert "a fox" not in str(body["spec"].get("_analytics", "")) + stored = SqliteStore(test_state.config.app_data_dir).get_generation(body["id"]) + assert stored is not None + assert stored.spec["_analytics"] == {"client": "desktop"} + details = queued_generation_details(stored) + assert details is not None + assert "prompt" not in details diff --git a/backend/tests/test_api_calls.py b/backend/tests/test_api_calls.py index 7440df433..2afbb75ac 100644 --- a/backend/tests/test_api_calls.py +++ b/backend/tests/test_api_calls.py @@ -7,6 +7,10 @@ from services.gemini_text_client import DEFAULT_GEMINI_MODEL from services.interfaces import HttpTransportError +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, +) from services.ltx_api_client.ltx_api_client import LTXAPIClientError, LTXRetakeResult from tests.http_error_assertions import assert_http_error from tests.fakes import FakeResponse @@ -261,10 +265,16 @@ def test_video_not_found(self, client, test_state): assert r.status_code == 400 def test_no_api_key(self, client, test_state): + """_force_api means unsupported hardware, which is reported as such, not as a key prompt.""" self._force_api(test_state) video_path = self._make_video(test_state) r = client.post("/api/retake", json=self._base_payload(video_path)) - assert r.status_code == 400 + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) def test_rejects_fast_tier_model(self, client, test_state): # "fast" is not a RetakeExtendModel member, so pydantic rejects it (422) @@ -282,7 +292,12 @@ def test_upload_url_failure(self, client, test_state): test_state.ltx_api_client.raise_on_retake = LTXAPIClientError(401, "Failed to get upload URL: Unauthorized") r = client.post("/api/retake", json=self._base_payload(video_path)) - assert r.status_code == 401 + assert_http_error( + r, + status_code=401, + code="LTX_INVALID_API_KEY", + message="This LTX API key isn’t valid.", + ) def test_video_upload_failure(self, client, test_state): self._force_api(test_state) @@ -338,19 +353,17 @@ def test_local_retake_happy_path(self, client, test_state, create_fake_model_fil assert data["status"] == "complete" assert data["video_path"] - def test_local_retake_rejected_on_2_5(self, client, test_state, create_fake_model_files): + def test_local_retake_happy_path_on_2_5(self, client, test_state, create_fake_model_files): _install_local_2_5(test_state, create_fake_model_files, include_zit=False) test_state.state.app_settings.use_local_text_encoder = True test_state.config.local_generations_mode = "full_models_loading" video_path = self._make_valid_video(test_state) r = client.post("/api/retake", json=self._base_payload(video_path)) - assert_http_error( - r, - status_code=409, - code="UNSUPPORTED_RETAKE", - message="Retake is not supported for the active LTX model.", - ) + assert r.status_code == 200 + data = r.json() + assert data["status"] == "complete" + assert data["video_path"] def test_local_retake_mode_mapping(self, client, test_state, create_fake_model_files, fake_services): _install_local_2_3(test_state, create_fake_model_files, include_zit=False) @@ -543,10 +556,16 @@ def test_nonpositive_resolution_rejected_as_422(self, client, test_state): assert r.status_code == 422 def test_no_api_key(self, client, test_state): + """_force_api means unsupported hardware, which is reported as such, not as a key prompt.""" self._force_api(test_state) video_path = self._make_video(test_state) r = client.post("/api/extend", json=self._base_payload(video_path)) - assert r.status_code == 400 + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) def test_extend_api_422_safety_filter(self, client, test_state): self._force_api(test_state) @@ -588,19 +607,17 @@ def test_local_extend_happy_path(self, client, test_state, create_fake_model_fil assert data["status"] == "complete" assert data["video_path"] - def test_local_extend_rejected_on_2_5(self, client, test_state, create_fake_model_files): + def test_local_extend_happy_path_on_2_5(self, client, test_state, create_fake_model_files): _install_local_2_5(test_state, create_fake_model_files, include_zit=False) test_state.state.app_settings.use_local_text_encoder = True test_state.config.local_generations_mode = "full_models_loading" video_path = self._make_valid_video(test_state) r = client.post("/api/extend", json=self._base_payload(video_path)) - assert_http_error( - r, - status_code=409, - code="UNSUPPORTED_EXTEND", - message="Extend is not supported for the active LTX model.", - ) + assert r.status_code == 200 + data = r.json() + assert data["status"] == "complete" + assert data["video_path"] def test_local_extend_snaps_frames_and_forwards_mode(self, client, test_state, create_fake_model_files, fake_services): _install_local_2_3(test_state, create_fake_model_files, include_zit=False) diff --git a/backend/tests/test_api_cores.py b/backend/tests/test_api_cores.py new file mode 100644 index 000000000..bf3a03066 --- /dev/null +++ b/backend/tests/test_api_cores.py @@ -0,0 +1,363 @@ +"""Desktop and Remote Asset/Generation cores share validation, not filesystem fields.""" + +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from api_types import ( + Asset, + AssetCore, + Generation, + GenerationCore, + ImageAssetMetadata, + ImageMeta, + MediaKind, +) +from remote.dto import ( + RemoteAsset, + RemoteAssetListItem, + RemoteGeneration, + RemoteGenerationSpec, + to_remote_asset, + to_remote_generation, + to_remote_list_item, +) +from remote.media_urls import MediaUrlSigner + +_SIGNER = MediaUrlSigner(b"s" * 32) +_DEVICE_ID = "dev-1" + + +_IMAGE_METADATA = ImageAssetMetadata( + mediaType="image", + metadata=ImageMeta(width=8, height=8), +) +_SECRET_PATH = "/Users/me/secret.png" +_SECRET_THUMB = "/Users/me/secret-thumb.png" + + +def _remote_asset(*, media_kind: MediaKind = "image") -> RemoteAsset: + return RemoteAsset( + id="asset-1", + media_kind=media_kind, + origin="uploaded", + mime_type="image/png", + name="x.png", + metadata=_IMAGE_METADATA, + created_at=1, + bytes_url="/api/assets/asset-1/bytes?exp=1&did=dev-1&sig=abc", + ) + + +def _desktop_asset(*, media_kind: MediaKind = "image") -> Asset: + return Asset( + id="asset-1", + media_kind=media_kind, + origin="uploaded", + path=_SECRET_PATH, + thumbnail_path=_SECRET_THUMB, + mime_type="image/png", + name="x.png", + metadata=_IMAGE_METADATA, + created_at=1, + ) + + +def _desktop_generation(**overrides: object) -> Generation: + values = { + "id": "gen-1", + "feature": "text-to-video", + "contract_version": 1, + "status": "queued", + "error_code": None, + "created_at": 1, + "queued_at": 1, + "attempt_count": 0, + "started_at": None, + "finished_at": None, + "spec": {"params": {"prompt": "fox", "imagePath": _SECRET_PATH}}, + "outputs": [_desktop_asset()], + **overrides, + } + return Generation.model_validate(values) + + +def _remote_generation(**overrides: object) -> RemoteGeneration: + values = { + "id": "gen-1", + "feature": "text-to-video", + "contract_version": 1, + "status": "queued", + "error_code": None, + "created_at": 1, + "queued_at": 1, + "attempt_count": 0, + "started_at": None, + "finished_at": None, + "spec": RemoteGenerationSpec(), + "outputs": [_remote_asset()], + **overrides, + } + return RemoteGeneration.model_validate(values) + + +def test_concrete_models_keep_distinct_spec_output_and_path_fields() -> None: + assert set(Asset.model_fields) - set(AssetCore.model_fields) == { + "path", + "thumbnail_path", + } + assert set(RemoteAsset.model_fields) - set(AssetCore.model_fields) == { + "bytes_url", + "thumbnail_url", + } + assert "path" not in RemoteAsset.model_fields + assert "thumbnail_path" not in RemoteAsset.model_fields + assert set(RemoteAssetListItem.model_fields) - set(RemoteAsset.model_fields) == { + "in_use", + "has_thumbnail", + } + assert "path" not in RemoteAssetListItem.model_fields + assert "thumbnail_path" not in RemoteAssetListItem.model_fields + assert set(Generation.model_fields) - set(GenerationCore.model_fields) == { + "spec", + "outputs", + } + assert set(RemoteGeneration.model_fields) - set(GenerationCore.model_fields) == { + "spec", + "outputs", + } + + +def test_asset_and_remote_asset_reject_media_kind_metadata_mismatch() -> None: + with pytest.raises(ValidationError, match="media_kind"): + _desktop_asset(media_kind="video") + with pytest.raises(ValidationError, match="media_kind"): + _remote_asset(media_kind="video") + assert _desktop_asset().media_kind == "image" + assert _remote_asset().media_kind == "image" + + +def test_generation_and_remote_generation_enforce_failed_error_code() -> None: + with pytest.raises(ValidationError, match="failed generation requires error_code"): + _desktop_generation(status="failed", error_code=None) + with pytest.raises(ValidationError, match="failed generation requires error_code"): + _remote_generation(status="failed", error_code=None) + with pytest.raises(ValidationError, match="error_code is only valid when status is failed"): + _desktop_generation(status="queued", error_code="EXECUTOR_FAILED") + with pytest.raises(ValidationError, match="error_code is only valid when status is failed"): + _remote_generation(status="queued", error_code="EXECUTOR_FAILED") + assert ( + _desktop_generation(status="failed", error_code="EXECUTOR_FAILED").error_code + == "EXECUTOR_FAILED" + ) + assert ( + _remote_generation(status="failed", error_code="EXECUTOR_FAILED").error_code + == "EXECUTOR_FAILED" + ) + + +def test_generation_and_remote_generation_allow_cancelling_status() -> None: + assert _desktop_generation(status="cancelling").status == "cancelling" + assert _remote_generation(status="cancelling").status == "cancelling" + + +def test_desktop_ignores_extra_fields_remote_forbids_them() -> None: + asset_payload = { + "id": "asset-1", + "media_kind": "image", + "origin": "uploaded", + "path": _SECRET_PATH, + "thumbnail_path": None, + "mime_type": "image/png", + "name": "x.png", + "metadata": _IMAGE_METADATA, + "created_at": 1, + "unknown": "x", + } + assert Asset.model_validate(asset_payload).path == _SECRET_PATH + remote_asset_payload = { + key: value + for key, value in asset_payload.items() + if key not in {"path", "thumbnail_path"} + } + remote_asset_payload["bytes_url"] = "/api/assets/asset-1/bytes?exp=1&did=dev-1&sig=abc" + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + RemoteAsset.model_validate(remote_asset_payload) + generation_payload = { + "id": "gen-1", + "feature": "text-to-video", + "contract_version": 1, + "status": "queued", + "spec": {"params": {"prompt": "fox"}}, + "created_at": 1, + "queued_at": 1, + "attempt_count": 0, + "outputs": [asset_payload], + "unknown": "x", + } + assert Generation.model_validate(generation_payload).id == "gen-1" + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + RemoteGeneration.model_validate( + { + "id": "gen-1", + "feature": "text-to-video", + "contract_version": 1, + "status": "queued", + "spec": {"params": {}}, + "created_at": 1, + "queued_at": 1, + "attempt_count": 0, + "outputs": [], + "unknown": "x", + } + ) + + +def test_remote_asset_rejects_filesystem_paths_as_extra_fields() -> None: + payload = { + "id": "asset-1", + "media_kind": "image", + "origin": "uploaded", + "mime_type": "image/png", + "name": "x.png", + "metadata": _IMAGE_METADATA, + "created_at": 1, + "bytes_url": "/api/assets/asset-1/bytes?exp=1&did=dev-1&sig=abc", + } + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + RemoteAsset.model_validate({**payload, "path": _SECRET_PATH}) + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + RemoteAsset.model_validate({**payload, "thumbnail_path": _SECRET_THUMB}) + + +def test_projections_omit_filesystem_paths() -> None: + dumped_asset = to_remote_asset( + _desktop_asset(), signer=_SIGNER, device_id=_DEVICE_ID + ).model_dump() + assert "path" not in dumped_asset + assert "thumbnail_path" not in dumped_asset + assert dumped_asset["bytes_url"].startswith("/api/assets/asset-1/bytes?") + assert dumped_asset["thumbnail_url"].startswith( + "/api/assets/asset-1/thumbnail/bytes?" + ) + assert _SECRET_PATH not in str(dumped_asset) + assert _SECRET_THUMB not in str(dumped_asset) + + dumped_generation = to_remote_generation( + _desktop_generation(), signer=_SIGNER, device_id=_DEVICE_ID + ).model_dump(mode="json") + assert "path" not in dumped_generation + assert dumped_generation["outputs"][0]["id"] == "asset-1" + assert "path" not in dumped_generation["outputs"][0] + assert "thumbnail_path" not in dumped_generation["outputs"][0] + assert _SECRET_PATH not in str(dumped_generation) + assert "imagePath" not in dumped_generation["spec"]["params"] + + +def test_remote_generation_projects_prompt_provenance() -> None: + dumped = to_remote_generation( + _desktop_generation( + spec={ + "params": { + "prompt": "fox", + "promptProvenance": "enhanced", + "imagePath": _SECRET_PATH, + } + } + ), + signer=_SIGNER, + device_id=_DEVICE_ID, + ).model_dump(mode="json") + assert dumped["spec"]["params"]["prompt"] == "fox" + assert dumped["spec"]["params"]["promptProvenance"] == "enhanced" + assert "imagePath" not in dumped["spec"]["params"] + assert _SECRET_PATH not in str(dumped) + + +def test_remote_params_keep_known_modes_and_drop_invalid_values() -> None: + dumped = to_remote_generation( + _desktop_generation( + spec={ + "params": { + "prompt": "fox", + "mode": "replace_video", + "startTime": 1.5, + } + } + ), + signer=_SIGNER, + device_id=_DEVICE_ID, + ).model_dump(mode="json") + assert dumped["spec"]["params"]["mode"] == "replace_video" + assert dumped["spec"]["params"]["startTime"] == 1.5 + + dropped = to_remote_generation( + _desktop_generation( + spec={ + "params": { + "prompt": "fox", + "mode": "not-a-mode", + "startTime": -1, + } + } + ), + signer=_SIGNER, + device_id=_DEVICE_ID, + ).model_dump(mode="json") + assert dropped["spec"]["params"].get("mode") is None + assert dropped["spec"]["params"].get("startTime") is None + + +def test_remote_resolution_keeps_tier_ids_and_target_sizes() -> None: + tier = to_remote_generation( + _desktop_generation(spec={"params": {"prompt": "fox", "resolution": "720p"}}), + signer=_SIGNER, + device_id=_DEVICE_ID, + ).model_dump(mode="json") + assert tier["spec"]["params"]["resolution"] == "720p" + + sized = to_remote_generation( + _desktop_generation( + spec={ + "params": { + "prompt": "fox", + "resolution": {"width": 1280, "height": 720, "path": _SECRET_PATH}, + } + } + ), + signer=_SIGNER, + device_id=_DEVICE_ID, + ).model_dump(mode="json") + assert sized["spec"]["params"]["resolution"] == {"width": 1280, "height": 720} + assert _SECRET_PATH not in str(sized) + + dropped = to_remote_generation( + _desktop_generation( + spec={ + "params": { + "prompt": "fox", + "resolution": {"width": 0, "height": -1}, + } + } + ), + signer=_SIGNER, + device_id=_DEVICE_ID, + ).model_dump(mode="json") + assert dropped["spec"]["params"].get("resolution") is None + + +def test_remote_list_item_omits_paths_and_sets_has_thumbnail() -> None: + dumped = to_remote_list_item( + _desktop_asset(), in_use=True, signer=_SIGNER, device_id=_DEVICE_ID + ).model_dump() + assert dumped["in_use"] is True + assert dumped["has_thumbnail"] is True + assert dumped["bytes_url"].startswith("/api/assets/asset-1/bytes?") + assert dumped["thumbnail_url"].startswith( + "/api/assets/asset-1/thumbnail/bytes?" + ) + assert "path" not in dumped + assert "thumbnail_path" not in dumped + with pytest.raises(ValidationError, match="Extra inputs are not permitted"): + RemoteAssetListItem.model_validate({**dumped, "path": _SECRET_PATH}) diff --git a/backend/tests/test_audio_channels.py b/backend/tests/test_audio_channels.py new file mode 100644 index 000000000..9c08bdf52 --- /dev/null +++ b/backend/tests/test_audio_channels.py @@ -0,0 +1,32 @@ +from __future__ import annotations + +import torch + +from services.audio_channels import stereo_waveform + + +def test_stereo_waveform_upmixes_batched_mono() -> None: + mono = torch.tensor([[[0.1, -0.2, 0.3]]]) + stereo = stereo_waveform(mono) + assert stereo.shape == (1, 2, 3) + assert torch.equal(stereo[0, 0], stereo[0, 1]) + assert torch.equal(stereo[0, 0], mono[0, 0]) + + +def test_stereo_waveform_keeps_batched_stereo() -> None: + original = torch.tensor([[[0.1, 0.2], [0.3, 0.4]]]) + assert torch.equal(stereo_waveform(original), original) + + +def test_stereo_waveform_keeps_first_two_batched_channels() -> None: + multi = torch.arange(12, dtype=torch.float32).reshape(1, 4, 3) + stereo = stereo_waveform(multi) + assert stereo.shape == (1, 2, 3) + assert torch.equal(stereo, multi[:, :2]) + + +def test_stereo_waveform_upmixes_planar_mono() -> None: + mono = torch.tensor([[0.5, -0.5]]) + stereo = stereo_waveform(mono) + assert stereo.shape == (2, 2) + assert torch.equal(stereo[0], stereo[1]) diff --git a/backend/tests/test_audio_trim.py b/backend/tests/test_audio_trim.py new file mode 100644 index 000000000..0973abce1 --- /dev/null +++ b/backend/tests/test_audio_trim.py @@ -0,0 +1,515 @@ +from __future__ import annotations + +import subprocess +import sys +import wave +from pathlib import Path + +import imageio.v2 as imageio +import imageio_ffmpeg +import numpy as np +import pytest +from PIL import Image +from starlette.testclient import TestClient + +from pydantic import ValidationError + +from api_types import TrimMediaRequest +from remote.app import create_remote_app +from services.audio_trim import ( + _write_audio_dest, + extract_audio_file, + trim_audio_file, +) +from services.ffmpeg import FFMPEG_TIMEOUT_SECONDS, run_ffmpeg +from services.media_probe import MAX_AUDIO_BYTES +from services.records import MediaError +from services.sqlite_store import SqliteStore +from tests.http_error_assertions import assert_http_error + +AUTH = {"Authorization": "Bearer pair-token"} + + +def _png(path: Path) -> Path: + Image.new("RGB", (16, 16), color=(1, 2, 3)).save(path) + return path + + +def _wav(path: Path, *, duration_seconds: float = 2.0, sample_rate: int = 8000) -> Path: + frame_count = max(1, int(duration_seconds * sample_rate)) + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(sample_rate) + wav_file.writeframes(b"\x00\x00" * frame_count) + return path + + +def _mp4(path: Path) -> Path: + writer = imageio.get_writer( + str(path), fps=8, codec="libx264", macro_block_size=None + ) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(8): + writer.append_data(frame) + writer.close() + return path + + +def _mp4_with_audio(path: Path) -> Path: + video = _mp4(path.with_name(f"{path.stem}-silent.mp4")) + audio = _wav(path.with_name(f"{path.stem}.wav"), duration_seconds=1.0) + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-i", + str(video), + "-i", + str(audio), + "-c:v", + "copy", + "-c:a", + "aac", + "-shortest", + str(path), + ], + check=True, + capture_output=True, + ) + return path + + +def _store(test_state) -> SqliteStore: + return SqliteStore(test_state.config.app_data_dir) + + +def _ingest_audio(client: TestClient, tmp_path: Path) -> dict[str, object]: + source = _wav(tmp_path / "input.wav") + ingested = client.post("/api/assets", json={"path": str(source)}) + assert ingested.status_code == 200 + payload = ingested.json() + assert isinstance(payload, dict) + return payload + + +def test_trim_audio_creates_new_clip_and_leaves_original( + client, tmp_path: Path +) -> None: + original = _ingest_audio(client, tmp_path) + original_id = original["id"] + original_path = original["path"] + original_duration = original["metadata"]["metadata"]["durationMs"] + assert original_duration == 2000 + + trimmed = client.post( + f"/api/assets/{original_id}/trim-audio", + json={"startSec": 0, "endSec": 1}, + ) + assert trimmed.status_code == 200 + data = trimmed.json() + assert data["id"] != original_id + assert data["media_kind"] == "audio" + assert data["origin"] == "uploaded" + duration_ms = data["metadata"]["metadata"]["durationMs"] + assert 900 <= duration_ms <= 1100 + + fetched = client.get(f"/api/assets/{original_id}") + assert fetched.status_code == 200 + unchanged = fetched.json() + assert unchanged["id"] == original_id + assert unchanged["path"] == original_path + assert unchanged["metadata"]["metadata"]["durationMs"] == original_duration + assert Path(str(original_path)).is_file() + + +def test_trim_audio_rejects_end_not_after_start(client, tmp_path: Path) -> None: + original = _ingest_audio(client, tmp_path) + response = client.post( + f"/api/assets/{original['id']}/trim-audio", + json={"startSec": 1, "endSec": 1}, + ) + assert response.status_code == 422 + + +def test_trim_audio_rejects_image_asset(client, tmp_path: Path) -> None: + ingested = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "still.png"))} + ) + assert ingested.status_code == 200 + response = client.post( + f"/api/assets/{ingested.json()['id']}/trim-audio", + json={"startSec": 0, "endSec": 1}, + ) + assert response.status_code == 422 + + +def test_trim_audio_rejects_missing_asset(client) -> None: + response = client.post( + "/api/assets/missing-asset/trim-audio", + json={"startSec": 0, "endSec": 1}, + ) + assert_http_error(response, status_code=404, code="ASSET_NOT_FOUND") + + +def test_trim_audio_missing_source_file_is_not_found( + client, tmp_path: Path +) -> None: + original = _ingest_audio(client, tmp_path) + Path(str(original["path"])).unlink() + response = client.post( + f"/api/assets/{original['id']}/trim-audio", + json={"startSec": 0, "endSec": 1}, + ) + assert_http_error(response, status_code=404, code="ASSET_NOT_FOUND") + + +def test_missing_ffmpeg_binary_is_unreadable_media(tmp_path: Path) -> None: + missing = tmp_path / "ffmpeg-not-installed" + with pytest.raises(MediaError) as caught: + run_ffmpeg(["-version"], ffmpeg_exe=str(missing)) + assert caught.value.code == "UNREADABLE_MEDIA" + + +def test_hung_ffmpeg_is_unreadable_media_instead_of_blocking() -> None: + """A wedged encoder must not pin the worker thread forever.""" + # A shebang script is not a Win32 PE, so CreateProcess raises WinError 193 + # before the timeout can fire. Python -c sleeps on every platform. + stalling = [sys.executable, "-c", "import time; time.sleep(30)"] + + with pytest.raises(MediaError) as caught: + run_ffmpeg(["-version"], ffmpeg_exe=stalling, timeout=0.2) + + assert caught.value.code == "UNREADABLE_MEDIA" + assert "timed out" in str(caught.value) + + +def test_ffmpeg_timeout_default_is_generous_enough_for_long_audio() -> None: + # 5s is the GPU-probe budget; trimming a long import legitimately exceeds it. + assert FFMPEG_TIMEOUT_SECONDS >= 60.0 + + +def test_extract_audio_from_video_creates_audio_asset( + client, tmp_path: Path +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4_with_audio(tmp_path / "clip.mp4"))} + ) + assert video.status_code == 200 + video_id = video.json()["id"] + video_path = video.json()["path"] + + extracted = client.post(f"/api/assets/{video_id}/extract-audio") + assert extracted.status_code == 200 + data = extracted.json() + assert data["id"] != video_id + assert data["media_kind"] == "audio" + assert data["metadata"]["mediaType"] == "audio" + assert data["metadata"]["metadata"]["durationMs"] >= 1 + + fetched = client.get(f"/api/assets/{video_id}") + assert fetched.status_code == 200 + assert fetched.json()["path"] == video_path + assert fetched.json()["media_kind"] == "video" + + +def test_extract_audio_rejects_video_without_audio_track( + client, tmp_path: Path +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "silent.mp4"))} + ) + assert video.status_code == 200 + response = client.post(f"/api/assets/{video.json()['id']}/extract-audio") + assert_http_error( + response, + status_code=400, + code="NO_AUDIO_STREAM", + message="video has no audio track", + ) + assert "/" not in response.text + assert "\\" not in response.text + + +def test_extract_audio_rejects_image_asset(client, tmp_path: Path) -> None: + ingested = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "still.png"))} + ) + assert ingested.status_code == 200 + response = client.post(f"/api/assets/{ingested.json()['id']}/extract-audio") + assert response.status_code == 422 + + +def test_extract_audio_rejects_missing_asset(client) -> None: + response = client.post("/api/assets/missing-asset/extract-audio") + assert_http_error(response, status_code=404, code="ASSET_NOT_FOUND") + + +def test_phone_trim_and_extract_return_remote_assets_without_paths( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + audio = store.ingest_upload(str(_wav(tmp_path / "line.wav"))) + video = store.ingest_upload(str(_mp4_with_audio(tmp_path / "clip.mp4"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + trimmed = client.post( + f"/api/assets/{audio.id}/trim-audio", + headers=AUTH, + json={"startSec": 0, "endSec": 1}, + ) + extracted = client.post( + f"/api/assets/{video.id}/extract-audio", + headers=AUTH, + ) + missing = client.post( + "/api/assets/missing-asset/trim-audio", + headers=AUTH, + json={"startSec": 0, "endSec": 1}, + ) + + assert trimmed.status_code == 200 + trimmed_asset = trimmed.json() + assert trimmed_asset["media_kind"] == "audio" + assert "path" not in trimmed_asset + assert "thumbnail_path" not in trimmed_asset + assert 900 <= trimmed_asset["metadata"]["metadata"]["durationMs"] <= 1100 + + assert extracted.status_code == 200 + extracted_asset = extracted.json() + assert extracted_asset["media_kind"] == "audio" + assert "path" not in extracted_asset + assert "thumbnail_path" not in extracted_asset + + assert_http_error(missing, status_code=404, code="ASSET_NOT_FOUND") + + +@pytest.mark.parametrize("operation", ["trim-audio", "extract-audio"]) +def test_phone_trim_extract_missing_source_hides_filesystem_path( + test_state, tmp_path: Path, operation: str +) -> None: + store = _store(test_state) + if operation == "trim-audio": + asset = store.ingest_upload(str(_wav(tmp_path / "line.wav"))) + request_json: dict[str, object] | None = {"startSec": 0, "endSec": 1} + else: + asset = store.ingest_upload(str(_mp4_with_audio(tmp_path / "clip.mp4"))) + request_json = None + Path(asset.path).unlink() + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + if request_json is None: + response = client.post( + f"/api/assets/{asset.id}/{operation}", headers=AUTH + ) + else: + response = client.post( + f"/api/assets/{asset.id}/{operation}", + headers=AUTH, + json=request_json, + ) + + assert_http_error(response, status_code=404, code="ASSET_NOT_FOUND") + assert "/" not in response.text + assert "\\" not in response.text + + +def test_trim_audio_rejects_unknown_fields(client, tmp_path: Path) -> None: + original = _ingest_audio(client, tmp_path) + response = client.post( + f"/api/assets/{original['id']}/trim-audio", + json={"startSec": 0, "endSec": 1, "unexpected": 1}, + ) + assert response.status_code == 422 + + +def test_trim_audio_request_rejects_non_finite_and_extra() -> None: + for payload in ( + {"startSec": 0, "endSec": float("inf")}, + {"startSec": 0, "endSec": float("-inf")}, + {"startSec": float("inf"), "endSec": float("inf")}, + {"startSec": 0, "endSec": float("nan")}, + {"startSec": float("nan"), "endSec": 1}, + {"startSec": 0, "endSec": 1, "unexpected": 1}, + ): + with pytest.raises(ValidationError): + TrimMediaRequest.model_validate(payload) + + +@pytest.mark.parametrize( + "raw_json", + [ + '{"startSec": 0, "endSec": Infinity}', + '{"startSec": 0, "endSec": NaN}', + '{"startSec": NaN, "endSec": 1}', + ], +) +def test_trim_audio_rejects_non_finite_at_boundary( + client, tmp_path: Path, raw_json: str +) -> None: + # httpx json= rejects inf/nan client-side; send raw JSON so the FastAPI + # boundary itself must reject the non-finite payload with a clean 422. + original = _ingest_audio(client, tmp_path) + response = client.post( + f"/api/assets/{original['id']}/trim-audio", + content=raw_json, + headers={"Content-Type": "application/json"}, + ) + assert response.status_code == 422 + + +@pytest.mark.parametrize("operation", ["trim-audio", "extract-audio"]) +def test_trim_extract_directory_source_is_not_found( + client, tmp_path: Path, operation: str +) -> None: + if operation == "trim-audio": + original = _ingest_audio(client, tmp_path) + asset_id = str(original["id"]) + asset_path = Path(str(original["path"])) + request_json: dict[str, object] | None = {"startSec": 0, "endSec": 1} + else: + video = client.post( + "/api/assets", json={"path": str(_mp4_with_audio(tmp_path / "clip.mp4"))} + ) + assert video.status_code == 200 + asset_id = str(video.json()["id"]) + asset_path = Path(str(video.json()["path"])) + request_json = None + asset_path.unlink() + asset_path.mkdir() + response = ( + client.post(f"/api/assets/{asset_id}/{operation}") + if request_json is None + else client.post(f"/api/assets/{asset_id}/{operation}", json=request_json) + ) + assert_http_error(response, status_code=404, code="ASSET_NOT_FOUND") + assert "/" not in response.text + assert "\\" not in response.text + + +def test_trim_ffmpeg_args_restrict_protocols_and_cap_output( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + captured: list[list[str]] = [] + + def _capture( + args: list[str], + *, + ffmpeg_exe: str | list[str] | None = None, + timeout: float = FFMPEG_TIMEOUT_SECONDS, + ) -> None: + del ffmpeg_exe, timeout + captured.append(list(args)) + + monkeypatch.setattr("services.audio_trim.run_ffmpeg", _capture) + trim_audio_file(tmp_path / "in.wav", tmp_path / "out.m4a", 0, 1) + extract_audio_file(tmp_path / "in.mp4", tmp_path / "out2.m4a") + + assert len(captured) == 2 + for args in captured: + assert "-protocol_whitelist" in args + whitelist = args[args.index("-protocol_whitelist") + 1] + assert whitelist == "file,pipe" + assert "-fs" in args + assert args[args.index("-fs") + 1] == str(MAX_AUDIO_BYTES) + # Input allowlist must precede the input it constrains; the size cap + # is an output option and must precede the output path. + assert args.index("-protocol_whitelist") < args.index("-i") + assert args.index("-fs") < len(args) - 1 + + +def test_trim_seek_args_are_output_side_for_accuracy( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + captured: list[list[str]] = [] + + def _capture( + args: list[str], + *, + ffmpeg_exe: str | list[str] | None = None, + timeout: float = FFMPEG_TIMEOUT_SECONDS, + ) -> None: + del ffmpeg_exe, timeout + captured.append(list(args)) + + monkeypatch.setattr("services.audio_trim.run_ffmpeg", _capture) + trim_audio_file(tmp_path / "in.wav", tmp_path / "out.m4a", 0.5, 1.5) + + assert len(captured) == 1 + args = captured[0] + input_index = args.index("-i") + # Input allowlist stays immediately before the input it constrains. + assert args[input_index - 2 : input_index] == [ + "-protocol_whitelist", + "file,pipe", + ] + # Output-side seek decodes up to the In point for precise AAC/m4a cuts. + assert args.index("-ss") > input_index + 1 + assert args.index("-t") > input_index + 1 + assert args[args.index("-ss") + 1] == "0.500000" + assert args[args.index("-t") + 1] == "1.000000" + + +def test_write_audio_dest_rejects_oversized_output( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "services.audio_trim.MAX_AUDIO_BYTES", 1024, raising=False + ) + + def _encode(dest: Path) -> None: + dest.write_bytes(b"x" * 2048) + + with pytest.raises(MediaError) as caught: + _write_audio_dest(tmp_path, "input.wav", "trim", _encode) + assert caught.value.code == "FILE_TOO_LARGE" + + +def test_write_audio_dest_fallback_wav_is_bounded( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr( + "services.audio_trim.MAX_AUDIO_BYTES", 1024, raising=False + ) + attempted: list[str] = [] + + def _encode(dest: Path) -> None: + attempted.append(dest.suffix) + if dest.suffix == ".m4a": + raise subprocess.CalledProcessError(1, ["ffmpeg"]) + dest.write_bytes(b"x" * 2048) + + with pytest.raises(MediaError) as caught: + _write_audio_dest(tmp_path, "input.wav", "trim", _encode) + assert caught.value.code == "FILE_TOO_LARGE" + assert attempted == [".m4a", ".wav"] + + +def test_write_audio_dest_fallback_succeeds_when_wav_small(tmp_path: Path) -> None: + def _encode(dest: Path) -> None: + if dest.suffix == ".m4a": + raise subprocess.CalledProcessError(1, ["ffmpeg"]) + dest.write_bytes(b"x" * 16) + + result = _write_audio_dest(tmp_path, "input.wav", "trim", _encode) + assert result.suffix == ".wav" + assert result.is_file() + + +def test_trim_output_cap_surfaces_controlled_error( + client, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + # 1s of silenced AAC is ~895 bytes; cap below that so the post-encode + # size check (not ingest validation) must reject the clip. + monkeypatch.setattr("services.audio_trim.MAX_AUDIO_BYTES", 512, raising=False) + original = _ingest_audio(client, tmp_path) + response = client.post( + f"/api/assets/{original['id']}/trim-audio", + json={"startSec": 0, "endSec": 1}, + ) + assert response.status_code == 400 + body = response.json() + assert body["code"] == "FILE_TOO_LARGE" + assert "/" not in response.text + assert "\\" not in response.text diff --git a/backend/tests/test_automatic_prompt_enhancement.py b/backend/tests/test_automatic_prompt_enhancement.py new file mode 100644 index 000000000..4d32cb23a --- /dev/null +++ b/backend/tests/test_automatic_prompt_enhancement.py @@ -0,0 +1,1399 @@ +"""Automatic, provenance-aware prompt enhancement for local video and IC-LoRA generation. + +Local encoding rewrites on Gen Space (/api/generate) regardless of Explore auto-enhance. +Home/Explore (generate_local_reserved) additionally honors explore_auto_enhance_prompts. +API encoding still honors the T2V/I2V settings toggles for the server-side enhance_prompt +flag, except when Explore auto-enhance is off on the Home path. Home auto-enhance rewrites +locally first when the enhancer checkpoint is installed, even if text embeddings come from +the API; a style-recipe wrap then keeps the API flag off so the scaffold is not rewritten. +Recipe wraps are skipped for typed Explore jobs when auto-enhance is off so the pipeline +sees the prompt as typed. +""" + +from __future__ import annotations + +import logging +import threading +import wave +from dataclasses import dataclass +from pathlib import Path + +import numpy as np +from PIL import Image + +from api_types import ( + GenerateVideoRequest, + IcLoraCatalogItem, + InputSpec, + InstructionSection, + PreprocessingStep, + PromptTemplatePlaceholder, + PromptTemplateSpec, +) +from runtime_config.model_download_specs import get_latest_ltx_model_id, get_ltx_model_spec +from services.features.lora_recipes import get_lora_recipe, make_recipe_prompt_wrap +from services.generation_interrupt import GenerationCancelledError +from tests.fakes import FakeCapture +from tests.lora_catalog_helpers import add_ic_lora, add_lora, download_spec + +# 2.3's gemma3 text encoder doubles as the local prompt enhancer, so a plain bundle is enough to +# make automatic local enhancement runnable (2.5 needs the separate opt-in enhancer download). +_LOCAL_ENHANCER_MODEL_ID = "ltx-2.3-22b-distilled-1.1" + +_T2V_JSON = { + "prompt": "test", + "resolution": "540p", + "model": "fast", + "duration": 5, + "fps": 24, +} + + +@dataclass +class _FakeEncodingResult: + video_context: object = "fake_tensor" + audio_context: object = None + + +def _install_local_enhancer(test_state, create_fake_model_files) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + test_state.state.app_settings.active_ltx_model_id = _LOCAL_ENHANCER_MODEL_ID + test_state.state.app_settings.use_local_text_encoder = True + # Local enhancement is automatic: persisted API opt-out must not suppress it. + test_state.state.app_settings.prompt_enhancer_enabled = False + + +def _install_api_encoding(test_state, fake_services, create_fake_model_files) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + test_state.state.app_settings.active_ltx_model_id = _LOCAL_ENHANCER_MODEL_ID + test_state.state.app_settings.ltx_api_key = "test-key" + test_state.state.app_settings.use_local_text_encoder = False + fake_services.text_encoder.encode_responses.append(_FakeEncodingResult()) + + +def _write_test_wav(path: Path) -> None: + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * 800) + + +def _add_image_ic_lora(fake_services, **overrides: object) -> IcLoraCatalogItem: + """An IC-LoRA driven by a still, which is what every entry built here generates from.""" + return add_ic_lora( + fake_services, + input=InputSpec(kind="image"), + preprocessing=[PreprocessingStep(utility="image_to_frames", params={})], + instructions=[InstructionSection(kind="summary", title="What it does", body="use it")], + **overrides, + ) + + +def _download_ic_lora(client, ic_lora_id: str) -> None: + assert client.post("/api/ic-loras/download", json={"ic_lora_id": ic_lora_id}).status_code == 200 + + +def _write_png(path: Path, size: tuple[int, int] = (64, 64)) -> Path: + Image.new("RGB", size, color=(1, 2, 3)).save(path, format="PNG") + return path + + +def _register_input_video(test_state, name: str = "input.mp4") -> Path: + video_path = test_state.config.outputs_dir / name + video_path.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video(str(video_path), FakeCapture(frames=["frame-a", "frame-b"])) + return video_path + + +def _register_outpaint_source(fake_services, tmp_path: Path) -> Path: + """Real numpy frames so outpaint_canvas can composite onto the larger canvas.""" + src = tmp_path / "in.mp4" + src.write_bytes(b"\x00") + fake_services.video_processor.videos[str(src)] = FakeCapture( + frames=[np.full((96, 96, 3), 0x40, dtype=np.uint8) for _ in range(9)], + width=96, + height=96, + fps=24, + ) + return src + + +class TestLocalVideoAlwaysEnhances: + def test_typed_t2v_prompt_is_enhanced_even_with_the_legacy_toggle_off( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == "test" + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_typed_i2v_prompt_is_enhanced_even_with_the_legacy_toggle_off( + self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post("/api/generate", json={**_T2V_JSON, "imagePath": str(image_path)}) + assert r.status_code == 200 + + assert len(fake_services.prompt_enhancer_pipeline.enhance_i2v_calls) == 1 + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_typed_a2v_prompt_is_enhanced( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + + r = client.post("/api/generate", json={**_T2V_JSON, "audioPath": str(audio_file)}) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == "test" + assert fake_services.a2v_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_typed_keyframe_prompt_is_enhanced( + self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + opening = tmp_path / "opening.png" + closing = tmp_path / "closing.png" + for path in (opening, closing): + path.write_bytes(make_test_image().getvalue()) + + r = client.post( + "/api/generate", + json={ + **_T2V_JSON, + "keyframes": [ + {"imagePath": str(opening), "frameIndex": 0}, + {"imagePath": str(closing), "frameIndex": 80}, + ], + }, + ) + assert r.status_code == 200 + + assert len(fake_services.prompt_enhancer_pipeline.enhance_i2v_calls) == 1 + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_missing_local_enhancer_generates_with_the_prompt_as_typed( + self, client, test_state, fake_services, create_fake_model_files + ): + # 2.5 without its opt-in enhancer download and no 2.3 install to fall back to. + create_fake_model_files(include_prompt_enhancer=False) + test_state.state.app_settings.use_local_text_encoder = True + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "test" + + def test_failing_local_enhancer_generates_with_the_prompt_as_typed( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.raise_on_enhance = RuntimeError("boom") + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "test" + + def test_cancellation_from_local_enhancer_returns_cancelled_response( + self, client, test_state, fake_services, create_fake_model_files, caplog + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.raise_on_enhance = GenerationCancelledError() + caplog.set_level(logging.WARNING, logger="handlers.prompt_enhancement_handler") + + response = client.post("/api/generate", json=_T2V_JSON) + + assert response.status_code == 200 + assert response.json() == {"status": "cancelled"} + assert fake_services.fast_video_pipeline.generate_calls == [] + assert not any( + record.getMessage().startswith("Automatic local enhancement failed") + for record in caplog.records + ) + + def test_success_info_log_reports_lengths_without_prompt_content( + self, client, test_state, fake_services, create_fake_model_files, caplog + ): + _install_local_enhancer(test_state, create_fake_model_files) + prompt = "private typed prompt" + enhanced = "private rewritten prompt" + fake_services.prompt_enhancer_pipeline.enhanced_prompt = enhanced + caplog.set_level(logging.INFO, logger="handlers.prompt_enhancement_handler") + + r = client.post("/api/generate", json={**_T2V_JSON, "prompt": prompt}) + + assert r.status_code == 200 + success_logs = [ + record.getMessage() + for record in caplog.records + if record.getMessage().startswith("Enhanced prompt locally for generation") + ] + assert success_logs == [ + f"Enhanced prompt locally for generation ({len(prompt)} -> {len(enhanced)} chars)" + ] + assert prompt not in success_logs[0] + assert enhanced not in success_logs[0] + + +class TestIcLoraEnhancementCancellation: + def test_catalog_enhancer_cancellation_returns_cancelled_response( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.raise_on_enhance = GenerationCancelledError() + _download_ic_lora(client, "ingredients-v1") + image_path = _write_png(tmp_path / "in.png") + + response = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(image_path), + "control_values": {"duration": 5}, + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + + assert response.status_code == 200 + assert response.json() == {"status": "cancelled"} + assert fake_services.ic_lora_pipeline.generate_calls == [] + + def test_builtin_enhancer_cancellation_returns_cancelled_response( + self, + client, + test_state, + fake_services, + create_fake_model_files, + create_fake_ic_lora_files, + ): + _install_local_enhancer(test_state, create_fake_model_files) + create_fake_ic_lora_files() + fake_services.prompt_enhancer_pipeline.raise_on_enhance = GenerationCancelledError() + video_path = _register_input_video(test_state) + + response = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + }, + ) + + assert response.status_code == 200 + assert response.json() == {"status": "cancelled"} + assert fake_services.ic_lora_pipeline.generate_calls == [] + + +class TestRecommendedEnhancerProvisioning: + """The recommended quality download is exactly what the automatic rewrite looks for. + + 2.5's text encoder can only encode, so on 2.5 the automatic rewrite depends on the separately + recommended enhancer checkpoint. Two contracts meet here — what the recommendation offers and + what the generation path resolves — and nothing else asserts they name the same checkpoint. + """ + + def test_the_checkpoint_first_run_recommends_is_what_makes_generation_enhance_locally( + self, client, test_state, fake_services, create_fake_model_files + ): + spec = get_ltx_model_spec(get_latest_ltx_model_id()) + assert spec.prompt_enhancer_cp is not None + + first_run = client.get("/api/models/ltx-recommendation").json() + assert first_run["status"] == "download" + assert first_run["recommended_quality_cp_ids"] == [spec.prompt_enhancer_cp] + + # Accept the recommendation: the required bundle plus exactly that checkpoint. + create_fake_model_files(include_prompt_enhancer=True) + test_state.state.app_settings.use_local_text_encoder = True + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == "test" + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_skipping_the_recommended_download_still_generates_and_stays_offerable( + self, client, test_state, fake_services, create_fake_model_files + ): + """Skip or download failure is non-blocking: it costs the rewrite, not the generation.""" + spec = get_ltx_model_spec(get_latest_ltx_model_id()) + create_fake_model_files(include_prompt_enhancer=False) + test_state.state.app_settings.use_local_text_encoder = True + + # The required bundle is complete, so the skipped enhancer must not re-open the gate, + # while Settings' own recommendation still offers it as the retry path. + assert client.get("/api/models/ltx-recommendation").json()["status"] == "ok" + settings_offer = client.get("/api/models/text-encoder-recommendation").json() + assert settings_offer["local_enhancer_cp"] == spec.prompt_enhancer_cp + assert settings_offer["local_enhancement_supported"] is False + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "test" + + +class TestPromptProvenance: + def test_enhanced_provenance_is_generated_exactly_as_submitted( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "prompt": "already rewritten", "promptProvenance": "enhanced"}, + ) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.prompt_enhancer_pipeline.enhance_i2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "already rewritten" + + def test_typed_provenance_is_the_default_for_clients_that_omit_it( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_enhanced_provenance_leaves_the_a2v_prompt_alone( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + + r = client.post( + "/api/generate", + json={ + **_T2V_JSON, + "prompt": "already rewritten", + "promptProvenance": "enhanced", + "audioPath": str(audio_file), + }, + ) + assert r.status_code == 200 + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.a2v_pipeline.generate_calls[0]["prompt"] == "already rewritten" + + +def _cozy_felt_wrap(): + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + return make_recipe_prompt_wrap(recipe) + + +def _generate_explore(test_state, json_body: dict | None = None, *, prompt_wrap=None) -> None: + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate(json_body or _T2V_JSON), + generation_id="explore-1", + local_model_id=_LOCAL_ENHANCER_MODEL_ID, + prompt_wrap=prompt_wrap, + ) + + +class TestExploreAutoEnhance: + def test_auto_off_leaves_home_prompt_as_typed( + self, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.explore_auto_enhance_prompts = False + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + + _generate_explore(test_state) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "test" + + def test_resolve_skip_recipe_wrap_only_for_auto_off_typed_home( + self, test_state + ): + test_state.state.app_settings.explore_auto_enhance_prompts = False + typed = test_state.prompt_enhancement.resolve_for_generation( + "mouse in a house", + provenance="typed", + generation_seed=1, + explicit_generation_seed=True, + explore_generation=True, + ) + enhanced = test_state.prompt_enhancement.resolve_for_generation( + "a rewritten scene", + provenance="enhanced", + generation_seed=1, + explicit_generation_seed=True, + explore_generation=True, + ) + gen_space = test_state.prompt_enhancement.resolve_for_generation( + "mouse in a house", + provenance="typed", + generation_seed=1, + explicit_generation_seed=True, + explore_generation=False, + ) + assert typed.skip_recipe_wrap is True + assert enhanced.skip_recipe_wrap is False + assert gen_space.skip_recipe_wrap is False + + def test_auto_off_does_not_skip_gen_space_rewrite( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.explore_auto_enhance_prompts = False + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == "test" + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_auto_on_still_rewrites_home( + self, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + + _generate_explore(test_state) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == "test" + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a long descriptive caption" + + def test_auto_off_drops_home_api_enhance_flag( + self, test_state, fake_services, create_fake_model_files + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.explore_auto_enhance_prompts = False + + _generate_explore(test_state) + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + + def test_auto_off_does_not_drop_gen_space_api_enhance_flag( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.explore_auto_enhance_prompts = False + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True + + def test_auto_off_leaves_typed_recipe_prompt_unwrapped( + self, client, test_state, fake_services, create_fake_model_files + ): + # Cozy Felt's scaffold is a prompt mutation. Auto-off + a typed scene must + # reach the pipeline as typed — the LLM rewrite *and* the felt wrap stay off. + _install_local_enhancer(test_state, create_fake_model_files) + r = client.post("/api/settings", json={"exploreAutoEnhancePrompts": False}) + assert r.status_code == 200 + fake_services.prompt_enhancer_pipeline.enhanced_prompt = ( + "a rewritten felt palace with slow camera moves" + ) + wrap = _cozy_felt_wrap() + scene = "mouse in a house" + + _generate_explore( + test_state, + {**_T2V_JSON, "prompt": scene}, + prompt_wrap=wrap, + ) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == scene + + def test_auto_off_still_wraps_a_manually_enhanced_recipe_prompt( + self, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.explore_auto_enhance_prompts = False + wrap = _cozy_felt_wrap() + rewritten = "a rewritten felt palace with slow camera moves" + + _generate_explore( + test_state, + {**_T2V_JSON, "prompt": rewritten, "promptProvenance": "enhanced"}, + prompt_wrap=wrap, + ) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == wrap(rewritten) + + def test_auto_on_rewrites_then_wraps_recipe_scene( + self, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + rewritten = "a rewritten felt palace with slow camera moves" + fake_services.prompt_enhancer_pipeline.enhanced_prompt = rewritten + wrap = _cozy_felt_wrap() + scene = "mouse in a house" + + _generate_explore( + test_state, + {**_T2V_JSON, "prompt": scene}, + prompt_wrap=wrap, + ) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == scene + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == wrap(rewritten) + + def test_api_text_encoding_still_rewrites_a_recipe_locally_before_the_wrap( + self, test_state, fake_services, create_fake_model_files + ): + # An API key selects API text encoding by default. The recipe wrap then + # turns server-side enhance off so the scaffold survives. Home auto-enhance + # still has to rewrite the scene locally first, or Generate starts immediately + # on the typed prompt. + _install_api_encoding(test_state, fake_services, create_fake_model_files) + rewritten = "a rewritten felt palace with slow camera moves" + fake_services.prompt_enhancer_pipeline.enhanced_prompt = rewritten + wrap = _cozy_felt_wrap() + scene = "mouse in a house" + + _generate_explore( + test_state, + {**_T2V_JSON, "prompt": scene}, + prompt_wrap=wrap, + ) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["prompt"] == scene + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == wrap(rewritten) + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + +class TestApiTextEncodingEnhanceFlag: + def test_typed_prompt_keeps_the_server_side_enhance_flag_on( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True + # API text encoding rewrites server-side; the local enhancer must stay out of it. + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + + def test_enhanced_provenance_turns_the_server_side_enhance_flag_off( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "prompt": "already rewritten", "promptProvenance": "enhanced"}, + ) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + + def test_toggle_off_turns_the_server_side_enhance_flag_off_for_t2v( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.prompt_enhancer_enabled = False + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + + def test_toggle_on_by_default_leaves_the_server_side_flag_on_for_i2v( + self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post("/api/generate", json={**_T2V_JSON, "imagePath": str(image_path)}) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True + + def test_toggle_off_turns_the_server_side_enhance_flag_off_for_i2v( + self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.prompt_enhancer_enabled = False + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post("/api/generate", json={**_T2V_JSON, "imagePath": str(image_path)}) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + def test_toggle_off_turns_the_server_side_enhance_flag_off_for_a2v( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.prompt_enhancer_enabled = False + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + + r = client.post("/api/generate", json={**_T2V_JSON, "audioPath": str(audio_file)}) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + def test_a2v_with_start_frame_follows_the_same_single_toggle( + self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + # Mixed conditioning used to pick between two gates; one switch now covers them all. + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.prompt_enhancer_enabled = False + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "audioPath": str(audio_file), "imagePath": str(image_path)}, + ) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + def test_enhanced_provenance_wins_over_a_toggle_on( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.prompt_enhancer_enabled = True + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "prompt": "already rewritten", "promptProvenance": "enhanced"}, + ) + assert r.status_code == 200 + + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + +class TestLockedSeedAutomaticEnhancement: + """A locked seed has to cover the whole local generation, rewrite included. + + Automatic enhancement is part of what produces the video, so drawing it independently would + leave a "locked" local generation irreproducible: the same seed would still yield a different + prompt, and so a different clip. Manual Enhance is a separate, exploratory action and keeps + its independent draw. + """ + + def test_locked_seed_is_reused_for_the_automatic_local_rewrite( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.seed_locked = True + test_state.state.app_settings.locked_seed = 4242 + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 4242 + assert fake_services.fast_video_pipeline.generate_calls[0]["seed"] == 4242 + + def test_locked_i2v_rewrite_uses_the_generation_seed( + self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.seed_locked = True + test_state.state.app_settings.locked_seed = 4242 + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post("/api/generate", json={**_T2V_JSON, "imagePath": str(image_path)}) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_i2v_calls[0]["seed"] == 4242 + assert fake_services.fast_video_pipeline.generate_calls[0]["seed"] == 4242 + + def test_an_explicit_request_seed_still_wins_and_drives_the_rewrite( + self, client, test_state, fake_services, create_fake_model_files + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.seed_locked = True + test_state.state.app_settings.locked_seed = 4242 + + r = client.post("/api/generate", json={**_T2V_JSON, "seed": 77}) + assert r.status_code == 200 + + assert fake_services.fast_video_pipeline.generate_calls[0]["seed"] == 77 + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 77 + + def test_an_explicit_request_seed_pins_the_rewrite_while_unlocked( + self, client, test_state, fake_services, create_fake_model_files, monkeypatch + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.seed_locked = False + monkeypatch.setattr("handlers.base.random.randint", lambda _start, _end: 909) + + r = client.post("/api/generate", json={**_T2V_JSON, "seed": 77}) + assert r.status_code == 200 + + assert fake_services.fast_video_pipeline.generate_calls[0]["seed"] == 77 + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 77 + + def test_an_unlocked_rewrite_keeps_its_own_random_seed( + self, client, test_state, fake_services, create_fake_model_files, monkeypatch + ): + _install_local_enhancer(test_state, create_fake_model_files) + # Both handlers draw from the one stdlib module, so a single patch covers the generation + # seed (drawn first) and the enhancement seed (drawn second). + draws = iter((101, 909)) + monkeypatch.setattr("handlers.base.random.randint", lambda _start, _end: next(draws)) + + r = client.post("/api/generate", json=_T2V_JSON) + assert r.status_code == 200 + + assert fake_services.fast_video_pipeline.generate_calls[0]["seed"] == 101 + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 909 + + def test_manual_enhance_stays_random_under_a_seed_lock( + self, client, test_state, fake_services, create_fake_model_files, monkeypatch + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.seed_locked = True + test_state.state.app_settings.locked_seed = 4242 + monkeypatch.setattr("handlers.base.random.randint", lambda _start, _end: 909) + + r = client.post("/api/enhance-prompt", json={"prompt": "a cat"}) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 909 + + def test_locked_seed_reaches_the_catalog_ic_lora_rewrite( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + test_state.state.app_settings.seed_locked = True + test_state.state.app_settings.locked_seed = 4242 + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 4242 + assert fake_services.ic_lora_pipeline.generate_calls[-1]["seed"] == 4242 + + def test_locked_seed_reaches_the_builtin_ic_lora_rewrite( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + create_fake_model_files(include_prompt_enhancer=True) + create_fake_ic_lora_files() + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.seed_locked = True + test_state.state.app_settings.locked_seed = 4242 + video_path = _register_input_video(test_state) + + r = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + }, + ) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0]["seed"] == 4242 + assert fake_services.ic_lora_pipeline.generate_calls[-1]["seed"] == 4242 + + +class TestIcLoraRunLogEnhancementField: + """The run log's `enhance=` field names where the rewrite happened, not a request flag.""" + + def _generate_canny(self, client, video_path) -> None: + r = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + }, + ) + assert r.status_code == 200 + + def _run_line(self, caplog) -> str: + lines = [r.getMessage() for r in caplog.records if r.getMessage().startswith("[ic-lora] run:")] + assert len(lines) == 1 + return lines[0] + + def test_a_local_rewrite_is_logged_as_local( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files, caplog + ): + create_fake_model_files(include_prompt_enhancer=True) + create_fake_ic_lora_files() + test_state.state.app_settings.use_local_text_encoder = True + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + video_path = _register_input_video(test_state) + + with caplog.at_level(logging.INFO): + self._generate_canny(client, video_path) + + assert "enhance=local" in self._run_line(caplog) + + def test_a_missing_enhancer_is_logged_as_none( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files, caplog + ): + create_fake_model_files(include_prompt_enhancer=False) + create_fake_ic_lora_files() + test_state.state.app_settings.use_local_text_encoder = True + video_path = _register_input_video(test_state) + + with caplog.at_level(logging.INFO): + self._generate_canny(client, video_path) + + assert "enhance=none" in self._run_line(caplog) + + def test_server_side_enhancement_is_logged_as_api( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files, caplog + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + create_fake_ic_lora_files() + video_path = _register_input_video(test_state) + + with caplog.at_level(logging.INFO): + self._generate_canny(client, video_path) + + assert "enhance=api" in self._run_line(caplog) + + +class TestCatalogIcLoraAutomaticEnhancement: + def _setup(self, test_state, create_fake_model_files) -> None: + _install_local_enhancer(test_state, create_fake_model_files) + + def _generate_trigger_ic_lora(self, client, fake_services, tmp_path) -> str: + _add_image_ic_lora( + fake_services, + id="shave-v1", + name="Instant Shave", + trigger="REMOVEBEARD", + trigger_placement="anywhere", + ) + _download_ic_lora(client, "shave-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "shave-v1", + "input_path": str(img), + "prompt": "shave him", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + return fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] + + def test_prompt_is_enhanced_with_the_catalog_aware_system_prompt( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0] + assert call["prompt"] == "a slow orbit" + assert call["system_prompt"] is not None + assert "Ingredients" in call["system_prompt"] + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "a long descriptive caption" + + def test_enhanced_provenance_is_submitted_as_is( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "already rewritten", + "prompt_provenance": "enhanced", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "already rewritten" + + def test_empty_prompt_is_never_enhanced( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + _download_ic_lora(client, "outpaint-v1") + src = _register_outpaint_source(fake_services, tmp_path) + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "outpaint-v1", + "input_path": str(src), + "prompt": "", + "conditioning_type": "custom", + "outpaint_pads": {"left": 48, "right": 0, "top": 0, "bottom": 0}, + }, + ) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "" + + def test_template_entry_is_filled_automatically( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + _add_image_ic_lora( + fake_services, + id="colorization", + name="Colorization", + prompt_template=PromptTemplateSpec( + template="Reference shows {reference}. COLORIZE {result}.", + placeholders={"reference": PromptTemplatePlaceholder(), "result": PromptTemplatePlaceholder()}, + ), + ) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = ( + '{"reference": "a grey rabbit", "result": "a brown rabbit"}' + ) + _download_ic_lora(client, "colorization") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorization", + "input_path": str(img), + "prompt": "colorize the rabbit", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + assert ( + fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] + == "Reference shows a grey rabbit. COLORIZE a brown rabbit." + ) + + def test_unfillable_template_falls_back_to_the_typed_prompt( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + _add_image_ic_lora( + fake_services, + id="upscale", + name="Upscale", + prompt_template=PromptTemplateSpec(template="upscale", placeholders={}), + ) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "not json" + _download_ic_lora(client, "upscale") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "upscale", + "input_path": str(img), + "prompt": "sharpen it", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "sharpen it" + + def test_trigger_is_enforced_on_the_automatic_rewrite( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a clean shaven man" + assert "REMOVEBEARD" in self._generate_trigger_ic_lora(client, fake_services, tmp_path) + + def test_missing_local_enhancer_fallback_preserves_the_catalog_trigger( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files(include_prompt_enhancer=False) + test_state.state.app_settings.use_local_text_encoder = True + + assert self._generate_trigger_ic_lora(client, fake_services, tmp_path) == "shave him REMOVEBEARD" + + def test_failing_local_enhancer_fallback_preserves_the_catalog_trigger( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.raise_on_enhance = RuntimeError("boom") + + assert self._generate_trigger_ic_lora(client, fake_services, tmp_path) == "shave him REMOVEBEARD" + + def test_blank_local_enhancer_fallback_preserves_the_catalog_trigger( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + self._setup(test_state, create_fake_model_files) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = " " + + assert self._generate_trigger_ic_lora(client, fake_services, tmp_path) == "shave him REMOVEBEARD" + + def test_missing_local_enhancer_falls_back_to_the_typed_prompt( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files(include_prompt_enhancer=False) + test_state.state.app_settings.use_local_text_encoder = True + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "a slow orbit" + + def test_api_text_encoding_keeps_the_server_side_flag_for_a_typed_prompt( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True + + def test_api_text_encoding_drops_the_server_side_flag_for_an_enhanced_prompt( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "already rewritten", + "prompt_provenance": "enhanced", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + def test_api_text_encoding_honors_the_enhance_toggle_off( + self, client, test_state, fake_services, create_fake_model_files, tmp_path + ): + _install_api_encoding(test_state, fake_services, create_fake_model_files) + test_state.state.app_settings.prompt_enhancer_enabled = False + _download_ic_lora(client, "ingredients-v1") + img = _write_png(tmp_path / "in.png") + + r = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "control_values": {"duration": 5}, + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + assert r.status_code == 200 + assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False + + +class TestBuiltinIcLoraAutomaticEnhancement: + def test_conditioning_prompt_is_enhanced_with_the_conditioning_system_prompt( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + create_fake_model_files(include_prompt_enhancer=True) + create_fake_ic_lora_files() + test_state.state.app_settings.use_local_text_encoder = True + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" + video_path = _register_input_video(test_state) + + r = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + }, + ) + assert r.status_code == 200 + + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0] + assert call["prompt"] == "test prompt" + assert call["system_prompt"] is not None + assert "edge" in call["system_prompt"].lower() + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "a long descriptive caption" + + def test_enhanced_provenance_is_submitted_as_is( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + create_fake_model_files(include_prompt_enhancer=True) + create_fake_ic_lora_files() + test_state.state.app_settings.use_local_text_encoder = True + video_path = _register_input_video(test_state) + + r = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "already rewritten", + "prompt_provenance": "enhanced", + "images": [], + }, + ) + assert r.status_code == 200 + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.ic_lora_pipeline.generate_calls[-1]["prompt"] == "already rewritten" + + +class TestCatalogPlainLoraAutomaticEnhancement: + """A catalog LoRA on the normal video picker gets manual Enhance's catalog treatment. + + The generic rewrite has no idea the adapter needs a trigger phrase, so left to itself it + paraphrases the one the user typed away and the LoRA silently does nothing. The automatic + path therefore has to reach the same catalog system prompt and the same deterministic + trigger enforcement the Enhance button already applies — resolved from the catalog id the + request carries, never from the weights' filename. + """ + + _CATALOG_ID = "cozy-felt" + _TRIGGER = "F3ltCut0u7" + + def _add_catalog_lora(self, fake_services, create_fake_lora, *, filename: str = "cozy-felt.safetensors") -> str: + add_lora( + fake_services, + id=self._CATALOG_ID, + name="Cozy Felt", + trigger=self._TRIGGER, + trigger_placement="anywhere", + download=download_spec(filename), + instructions=[InstructionSection(kind="summary", title="What it does", body="Felt look.")], + ) + return create_fake_lora(filename) + + def _generate(self, client, ref: str, *, catalog_id: str | None = _CATALOG_ID, **extra: object): + entry: dict[str, object] = {"ref": ref, "scale": 0.8} + if catalog_id is not None: + entry["catalogId"] = catalog_id + r = client.post( + "/api/generate", + json={**_T2V_JSON, "prompt": "a fox", "loras": [entry], **extra}, + ) + assert r.status_code == 200, r.text + return r + + def test_t2v_prompt_is_enhanced_with_the_catalog_aware_system_prompt( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a felt fox in a garden" + + self._generate(client, ref) + + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0] + assert call["prompt"] == "a fox" + assert call["system_prompt"] is not None + assert "Cozy Felt" in call["system_prompt"] + assert "Felt look." in call["system_prompt"] + assert ( + fake_services.fast_video_pipeline.generate_calls[0]["prompt"] + == f"a felt fox in a garden {self._TRIGGER}" + ) + + def test_i2v_prompt_is_enhanced_with_the_catalog_aware_system_prompt( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora, + make_test_image, tmp_path, + ): + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a felt fox in a garden" + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + self._generate(client, ref, imagePath=str(image_path)) + + call = fake_services.prompt_enhancer_pipeline.enhance_i2v_calls[0] + assert call["system_prompt"] is not None + assert "Cozy Felt" in call["system_prompt"] + assert ( + fake_services.fast_video_pipeline.generate_calls[0]["prompt"] + == f"a felt fox in a garden {self._TRIGGER}" + ) + + def test_a2v_prompt_is_enhanced_with_the_catalog_aware_system_prompt( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora, tmp_path + ): + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a felt fox in a garden" + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + + self._generate(client, ref, audioPath=str(audio_file)) + + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0] + assert call["system_prompt"] is not None + assert "Cozy Felt" in call["system_prompt"] + assert ( + fake_services.a2v_pipeline.generate_calls[0]["prompt"] + == f"a felt fox in a garden {self._TRIGGER}" + ) + + def test_missing_local_enhancer_fallback_preserves_the_catalog_trigger( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + create_fake_model_files(include_prompt_enhancer=False) + test_state.state.app_settings.use_local_text_encoder = True + ref = self._add_catalog_lora(fake_services, create_fake_lora) + + self._generate(client, ref) + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert ( + fake_services.fast_video_pipeline.generate_calls[0]["prompt"] + == f"a fox {self._TRIGGER}" + ) + + def test_failing_local_enhancer_fallback_preserves_the_catalog_trigger( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora) + fake_services.prompt_enhancer_pipeline.raise_on_enhance = RuntimeError("boom") + + self._generate(client, ref) + + assert ( + fake_services.fast_video_pipeline.generate_calls[0]["prompt"] + == f"a fox {self._TRIGGER}" + ) + + def test_blank_local_rewrite_fallback_preserves_the_catalog_trigger( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = " " + + self._generate(client, ref) + + assert ( + fake_services.fast_video_pipeline.generate_calls[0]["prompt"] + == f"a fox {self._TRIGGER}" + ) + + def test_custom_lora_stays_weights_only_even_when_a_catalog_entry_shares_its_filename( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + """No catalog id, no catalog treatment — matching on filename would attach a + stranger's trigger phrase to an unrelated file the user trained themselves. + """ + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora, filename="mine.safetensors") + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a fox in a garden" + + self._generate(client, ref, catalog_id=None) + + call = fake_services.prompt_enhancer_pipeline.enhance_t2v_calls[0] + assert call["system_prompt"] is None + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a fox in a garden" + + def test_a_catalog_id_the_catalog_no_longer_knows_still_generates( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + """Enhancement is a quality step: a stale id costs the catalog treatment, not the run.""" + _install_local_enhancer(test_state, create_fake_model_files) + ref = create_fake_lora("orphan.safetensors") + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a fox in a garden" + + self._generate(client, ref, catalog_id="retired-lora") + + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a fox in a garden" + + def test_enhanced_provenance_is_generated_exactly_as_submitted( + self, client, test_state, fake_services, create_fake_model_files, create_fake_lora + ): + _install_local_enhancer(test_state, create_fake_model_files) + ref = self._add_catalog_lora(fake_services, create_fake_lora) + + self._generate(client, ref, promptProvenance="enhanced") + + assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] + assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "a fox" diff --git a/backend/tests/test_cutout_alignment.py b/backend/tests/test_cutout_alignment.py new file mode 100644 index 000000000..d20104982 --- /dev/null +++ b/backend/tests/test_cutout_alignment.py @@ -0,0 +1,175 @@ +"""A cutout matte must line up with the clip in time and in space.""" + +from __future__ import annotations + +import re +import subprocess +from pathlib import Path + +import imageio.v2 as imageio +import imageio_ffmpeg +import numpy as np +import pytest + +from services.ffmpeg import run_ffmpeg +from services.features.video.cutout_alignment import ( + GRID_PAD_FRAMES, + CanvasFit, + conform_matte_to_clip, + fit_clip_to_canvas, + prepare_clip_for_model, +) +from services.media_probe import video_frame_count + +_FPS = 24 + + +def _write_clip(path: Path, frames: list[np.ndarray]) -> Path: + writer = imageio.get_writer(str(path), fps=_FPS, codec="libx264", macro_block_size=None) + for frame in frames: + writer.append_data(frame) + writer.close() + return path + + +def _solid_clip(path: Path, *, width: int, height: int, frames: int) -> Path: + return _write_clip(path, [np.full((height, width, 3), 90, dtype=np.uint8)] * frames) + + +def _first_frame(path: Path) -> np.ndarray: + reader = imageio.get_reader(str(path)) + try: + return np.asarray(reader.get_data(0)) + finally: + reader.close() + + +def _decoded_frame_count(path: Path) -> int: + """Frames a decoder returns. Packets alone can hide a duplicated or a late frame.""" + run = subprocess.run( + [imageio_ffmpeg.get_ffmpeg_exe(), "-i", str(path), "-f", "null", "-"], + capture_output=True, + text=True, + check=True, + ) + return int(re.findall(r"frame= *(\d+)", run.stderr)[-1]) + + +def _fit(width: int, height: int, canvas_width: int, canvas_height: int) -> CanvasFit: + return fit_clip_to_canvas(width, height, canvas_width, canvas_height) + + +def test_a_wide_clip_is_fitted_inside_a_taller_canvas_with_no_offset_on_the_full_side() -> None: + fit = _fit(640, 360, 512, 256) + + assert (fit.width, fit.height) == (454, 256) + # The clip fills the canvas height, so the vertical offset is 0 and not rounded up. + assert (fit.x, fit.y) == (28, 0) + assert not fit.fills_canvas + + +def test_the_fit_offsets_and_sizes_stay_even_and_inside_the_canvas() -> None: + for clip in [(640, 360), (360, 640), (801, 599), (100, 100)]: + for canvas in [(512, 256), (256, 512), (640, 384), (704, 704)]: + fit = _fit(*clip, *canvas) + assert all(value % 2 == 0 for value in (fit.width, fit.height, fit.x, fit.y)) + assert 0 <= fit.x and fit.x + fit.width <= canvas[0] + assert 0 <= fit.y and fit.y + fit.height <= canvas[1] + + +def test_a_clip_with_the_canvas_shape_fills_the_canvas() -> None: + assert _fit(1024, 512, 512, 256).fills_canvas + + +def test_the_model_clip_is_the_canvas_size_and_repeats_the_last_frame(tmp_path: Path) -> None: + source = _solid_clip(tmp_path / "source.mp4", width=160, height=90, frames=20) + fit = _fit(160, 90, 128, 64) + + model_clip = prepare_clip_for_model(source, tmp_path / "fit.mp4", fit=fit, keep_audio=False) + + assert _first_frame(model_clip).shape[:2] == (64, 128) + assert video_frame_count(model_clip) == 20 + GRID_PAD_FRAMES + + +def test_the_border_of_the_model_clip_repeats_the_edge_pixels(tmp_path: Path) -> None: + frame = np.zeros((90, 160, 3), dtype=np.uint8) + frame[:, :] = (200, 40, 40) + source = _write_clip(tmp_path / "source.mp4", [frame] * 9) + fit = _fit(160, 90, 128, 64) + + pixels = _first_frame(prepare_clip_for_model(source, tmp_path / "fit.mp4", fit=fit, keep_audio=False)) + + # Black padding would read as background to the model. The smear keeps the clip color. + assert abs(int(pixels[32, 1, 0]) - 200) < 20 + assert abs(int(pixels[32, 126, 0]) - 200) < 20 + + +@pytest.mark.parametrize("frames", [9, 20, 25, 145, 150]) +def test_the_matte_is_cut_to_the_clip_frame_count(tmp_path: Path, frames: int) -> None: + """A time cut keeps extra frames on a B-frame stream. The frame count does not.""" + source = _solid_clip(tmp_path / "source.mp4", width=160, height=90, frames=frames) + fit = _fit(160, 90, 128, 64) + model_clip = prepare_clip_for_model(source, tmp_path / "fit.mp4", fit=fit, keep_audio=False) + # The model returns the 8k+1 frames the pipeline snaps down to. + grid = (video_frame_count(model_clip) - 1) // 8 * 8 + 1 + matte = tmp_path / "matte.mp4" + run_ffmpeg(["-y", "-i", str(model_clip), "-frames:v", str(grid), "-c:v", "libx264", str(matte)]) + assert grid >= frames + + conform_matte_to_clip(matte, frames=frames, fps=_FPS, fit=fit) + + assert video_frame_count(matte) == frames + + +def test_a_matte_that_fills_the_canvas_is_cut_to_the_exact_frame_count(tmp_path: Path) -> None: + """With B-frames, a stream copy cut can leave a frame past the cut on some builds.""" + fit = _fit(128, 64, 128, 64) + assert fit.fills_canvas + for total, keep in [(153, 150), (33, 26), (17, 10)]: + matte = _write_clip( + tmp_path / "matte.mp4", + [np.full((64, 128, 3), 10 + index, dtype=np.uint8) for index in range(total)], + ) + + conform_matte_to_clip(matte, frames=keep, fps=_FPS, fit=fit) + + assert video_frame_count(matte) == keep + assert _decoded_frame_count(matte) == keep + + +def test_a_matte_that_needs_no_cut_is_left_as_the_model_wrote_it(tmp_path: Path) -> None: + fit = _fit(128, 64, 128, 64) + matte = _solid_clip(tmp_path / "matte.mp4", width=128, height=64, frames=145) + before = matte.read_bytes() + + conform_matte_to_clip(matte, frames=145, fps=_FPS, fit=fit) + + assert matte.read_bytes() == before + + +def test_the_matte_covers_the_same_view_as_the_clip_after_the_border_is_cut(tmp_path: Path) -> None: + """A 16:9 clip in a 2:1 canvas. A crop would lose the top and the bottom of the clip.""" + width, height = 640, 360 + frame = np.zeros((height, width, 3), dtype=np.uint8) + frame[300:350, 40:120] = 255 # a bright square near the bottom edge + frame[10:60, 520:600] = 255 # a bright square near the top edge + source = _write_clip(tmp_path / "source.mp4", [frame] * 9) + fit = _fit(width, height, 512, 256) + # The model is stood in by the model clip itself: its bright pixels are the matte. + matte = prepare_clip_for_model(source, tmp_path / "matte.mp4", fit=fit, keep_audio=False) + + conform_matte_to_clip(matte, frames=9, fps=_FPS, fit=fit) + + conformed = _first_frame(matte)[:, :, 0] > 128 + assert conformed.shape == (fit.height, fit.width) + scale_x, scale_y = fit.width / width, fit.height / height + for top, bottom, left, right in [(300, 350, 40, 120), (10, 60, 520, 600)]: + rows = slice(int(top * scale_y), int(bottom * scale_y)) + columns = slice(int(left * scale_x), int(right * scale_x)) + expected = np.zeros_like(conformed) + expected[rows, columns] = True + # Compare inside a window around this square, so the other square is not counted. + window = np.zeros_like(conformed) + window[max(0, rows.start - 8) : rows.stop + 8, max(0, columns.start - 8) : columns.stop + 8] = True + overlap = (conformed & expected & window).sum() / (expected | (conformed & window)).sum() + assert overlap > 0.8 diff --git a/backend/tests/test_dashboard_stats.py b/backend/tests/test_dashboard_stats.py new file mode 100644 index 000000000..df7067768 --- /dev/null +++ b/backend/tests/test_dashboard_stats.py @@ -0,0 +1,808 @@ +"""Dashboard aggregates: timezones, percentiles, soft-deletes, and the HTTP route.""" + +from __future__ import annotations + +import json +import logging +import sqlite3 +from datetime import datetime +from pathlib import Path +from zoneinfo import ZoneInfo + +import pytest + +from services.dashboard_stats import percentile +from services.sqlite_store import SqliteStore + +NOW = datetime(2026, 3, 10, 12, 0, tzinfo=ZoneInfo("UTC")) +DAY = datetime(2026, 3, 10, 10, 0, tzinfo=ZoneInfo("UTC")) +OLD = datetime(2026, 3, 1, 10, 0, tzinfo=ZoneInfo("UTC")) + + +def _ms(moment: datetime) -> int: + return int(moment.timestamp() * 1000) + + +def _video_meta(duration_ms: int) -> str: + return json.dumps( + { + "mediaType": "video", + "metadata": { + "width": 1920, + "height": 1080, + "durationMs": duration_ms, + "sizeBytes": 10, + "audioStreamCount": 0, + }, + } + ) + + +def _spec( + *, + duration: float | None = 5, + resolution: str | None = "1080p", + aspect: str | None = "16:9", + fps: int | None = 24, + loras: list[dict[str, object]] | None = None, +) -> str: + params: dict[str, object] = {"model": "ltx-2.3-fast"} + if resolution is not None: + params["resolution"] = resolution + if aspect is not None: + params["aspectRatio"] = aspect + if duration is not None: + params["duration"] = duration + if fps is not None: + params["fps"] = fps + if loras is not None: + params["loras"] = loras + return json.dumps({"params": params, "inputs": {}}) + + +def _insert( + conn: sqlite3.Connection, + *, + generation_id: str, + feature: str, + status: str, + finished: datetime, + run_ms: int, + spec: str, + error_code: str | None = None, + generation_deleted: bool = False, + asset_duration_ms: int | None = None, + asset_deleted: bool = False, +) -> None: + finished_ms = _ms(finished) + conn.execute( + """ + INSERT INTO generations ( + id, feature, contract_version, status, spec, error_code, + created_at, queued_at, queue_rank, attempt_count, + started_at, finished_at, deleted_at + ) VALUES (?, ?, 1, ?, ?, ?, ?, ?, NULL, 1, ?, ?, ?) + """, + ( + generation_id, + feature, + status, + spec, + error_code, + finished_ms - run_ms, + finished_ms - run_ms, + finished_ms - run_ms, + finished_ms, + finished_ms if generation_deleted else None, + ), + ) + if asset_duration_ms is None: + return + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, output_ordinal, + mime_type, name, metadata, created_at, deleted_at + ) VALUES (?, 'video', 'generated', ?, 0, 'video/mp4', ?, ?, ?, ?) + """, + ( + f"asset-{generation_id}", + generation_id, + generation_id, + _video_meta(asset_duration_ms), + finished_ms, + finished_ms if asset_deleted else None, + ), + ) + + +def _seed(conn: sqlite3.Connection) -> None: + standard = _spec() + for index, run_ms in enumerate((60_000, 120_000, 180_000)): + _insert( + conn, + generation_id=f"t2v-{index}", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=run_ms, + spec=standard, + asset_duration_ms=5_000, + asset_deleted=index == 0, + ) + _insert( + conn, + generation_id="t2v-failed", + feature="text-to-video", + status="failed", + finished=DAY, + run_ms=30_000, + spec=standard, + error_code="EXECUTOR_FAILED", + ) + _insert( + conn, + generation_id="t2v-cancelled", + feature="text-to-video", + status="cancelled", + finished=DAY, + run_ms=10_000, + spec=_spec(resolution=None, aspect=None, duration=None, fps=None), + ) + _insert( + conn, + generation_id="retake-1", + feature="retake", + status="succeeded", + finished=DAY, + run_ms=5_000, + spec=json.dumps( + { + "params": {"model": "ltx-2.3-fast", "duration": 2.5}, + "inputs": {"video": {"assetId": "source"}}, + } + ), + asset_duration_ms=20_000, + ) + lora = _spec( + duration=6, + loras=[ + { + "ref": "", + "scale": 1, + "catalogId": "cozy-felt-style", + "displayName": "Cozy Felt Style", + } + ], + ) + _insert( + conn, + generation_id="lora-kept", + feature="cozy-felt", + status="succeeded", + finished=DAY, + run_ms=90_000, + spec=lora, + asset_duration_ms=6_000, + ) + _insert( + conn, + generation_id="lora-dropped", + feature="cozy-felt", + status="succeeded", + finished=DAY, + run_ms=40_000, + spec=lora, + asset_duration_ms=6_000, + asset_deleted=True, + ) + _insert( + conn, + generation_id="t2v-deleted-gen", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=7_000, + spec=standard, + generation_deleted=True, + asset_duration_ms=5_000, + ) + _insert( + conn, + generation_id="t2v-old", + feature="text-to-video", + status="succeeded", + finished=OLD, + run_ms=1_000, + spec=standard, + asset_duration_ms=5_000, + ) + conn.commit() + + +def _open(tmp_path: Path) -> tuple[SqliteStore, sqlite3.Connection]: + store = SqliteStore(tmp_path) + conn = sqlite3.connect(tmp_path / "store.sqlite3") + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + return store, conn + + +def test_lora_panel_includes_the_rows_past_the_preview(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + for index in range(11): + _insert( + conn, + generation_id=f"lora-{index}", + feature=f"recipe-{index}", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec( + loras=[ + { + "ref": "", + "scale": 1, + "catalogId": f"catalog-{index}", + "displayName": f"Style {index}", + } + ] + ), + asset_duration_ms=1_000, + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert len(snapshot.loras.top) == 11 + assert {lora.name for lora in snapshot.loras.top} == {f"Style {index}" for index in range(11)} + + +def test_percentile_interpolates_between_ranks() -> None: + assert percentile([10, 20, 30, 40, 100], 0.5) == 30 + assert percentile([10, 20, 30, 40, 100], 0.9) == 76 + assert percentile([7000, 60000, 120000, 180000], 0.5) == 90_000 + assert percentile([7000, 60000, 120000, 180000], 0.9) == 162_000 + + +def test_seven_day_snapshot_matches_hand_computed_metrics(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + _seed(conn) + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert snapshot.empty is False + assert snapshot.kpis.gpu_ms == 532_000 + assert snapshot.kpis.succeeded == 7 + assert snapshot.kpis.failed == 1 + assert snapshot.kpis.cancelled == 1 + assert snapshot.kpis.success_rate == 7 / 8 + assert snapshot.kpis.content_count == 7 + assert snapshot.kpis.footage_s == 34.5 + assert snapshot.keep_rate.kept == 4 + assert snapshot.keep_rate.total == 7 + assert snapshot.keep_rate.rate == 4 / 7 + assert snapshot.loras.share == 2 / 9 + assert len(snapshot.loras.top) == 1 + assert snapshot.loras.top[0].feature == "cozy-felt" + assert snapshot.loras.top[0].name == "Cozy Felt Style" + assert snapshot.loras.top[0].runs == 2 + assert snapshot.loras.top[0].keep_rate == 0.5 + assert [(row.error_code, row.count) for row in snapshot.failures] == [ + ("EXECUTOR_FAILED", 1) + ] + assert snapshot.usual is not None + assert snapshot.usual.resolution == "1080p" + assert snapshot.usual.aspect_ratio == "16:9" + assert snapshot.usual.duration_s == 5 + assert snapshot.usual.fps == 24 + five_seconds = next(cell for cell in snapshot.render if cell.duration_s == 5) + assert five_seconds.model == "ltx-2.3-fast" + assert five_seconds.resolution == "1080p" + assert five_seconds.aspect_ratio == "16:9" + assert five_seconds.count == 4 + assert five_seconds.median_ms == 90_000 + assert five_seconds.p90_ms == 162_000 + six_seconds = next(cell for cell in snapshot.render if cell.duration_s == 6) + assert six_seconds.aspect_ratio == "16:9" + assert six_seconds.count == 2 + assert [day.day for day in snapshot.activity] == [ + "2026-03-04", + "2026-03-05", + "2026-03-06", + "2026-03-07", + "2026-03-08", + "2026-03-09", + "2026-03-10", + ] + today = snapshot.activity[-1].counts + assert today["text-to-video"] == 6 + assert today["lora"] == 2 + assert today["retake"] == 1 + assert today["image-to-video"] == 0 + + wider = store.dashboard(window="all", tz="UTC", now=NOW) + assert wider.kpis.gpu_ms == 533_000 + assert wider.activity[0].day == "2026-03-01" + assert wider.activity[0].counts["text-to-video"] == 1 + wider_five_seconds = next(cell for cell in wider.render if cell.duration_s == 5) + assert wider_five_seconds.count == 5 + + +def test_render_grid_is_pooled_and_split_by_fps(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + runs = (("slow-24", 24, 60_000), ("fast-24", 24, 120_000), ("only-30", 30, 90_000)) + for generation_id, fps, run_ms in runs: + _insert( + conn, + generation_id=generation_id, + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=run_ms, + spec=_spec(fps=fps), + asset_duration_ms=5_000, + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + pooled = snapshot.render + assert [(cell.aspect_ratio, cell.count) for cell in pooled] == [("16:9", 3)] + assert {(cell.fps, cell.count) for cell in snapshot.render_by_fps} == {(24, 2), (30, 1)} + assert snapshot.fps_values == [24, 30] + + +def test_local_day_follows_the_caller_timezone(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + finished = datetime(2026, 3, 10, 23, 30, tzinfo=ZoneInfo("UTC")) + _insert( + conn, + generation_id="late", + feature="text-to-video", + status="succeeded", + finished=finished, + run_ms=1_000, + spec=_spec(), + ) + conn.commit() + conn.close() + moment = datetime(2026, 3, 10, 23, 45, tzinfo=ZoneInfo("UTC")) + + utc = store.dashboard(window="7d", tz="UTC", now=moment) + tokyo = store.dashboard(window="7d", tz="Asia/Tokyo", now=moment) + + assert utc.activity[-1].day == "2026-03-10" + assert utc.activity[-1].counts["text-to-video"] == 1 + assert tokyo.activity[-1].day == "2026-03-11" + assert tokyo.activity[-1].counts["text-to-video"] == 1 + assert tokyo.activity[-2].counts["text-to-video"] == 0 + + +def test_all_range_skips_empty_days_across_a_huge_gap(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + ancient = datetime(1970, 1, 2, tzinfo=ZoneInfo("UTC")) + _insert( + conn, + generation_id="ancient", + feature="text-to-video", + status="succeeded", + finished=ancient, + run_ms=1_000, + spec=_spec(), + ) + _insert( + conn, + generation_id="recent", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec(), + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="all", tz="UTC", now=NOW) + + assert snapshot.activity[0].day == "1970-01-02" + assert snapshot.activity[0].counts["text-to-video"] == 1 + assert snapshot.activity[1].day != "1970-01-03" + assert snapshot.activity[-1].day == "2026-03-10" + assert len(snapshot.activity) < 1000 + + +def test_one_render_still_shows_and_aspect_ratios_stay_separate(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + _insert( + conn, + generation_id="only", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=10_000, + spec=_spec(resolution="720p", aspect="16:9"), + ) + for aspect in ("4:3", "3:2", "auto"): + _insert( + conn, + generation_id=f"ratio-{aspect}", + feature="cozy-felt", + status="succeeded", + finished=DAY, + run_ms=20_000, + spec=_spec( + resolution="540p", + aspect=aspect, + loras=[ + { + "ref": "", + "scale": 1, + "catalogId": "cozy-felt-style", + "displayName": "Cozy Felt Style", + } + ], + ), + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert [(cell.resolution, cell.aspect_ratio, cell.count) for cell in snapshot.render] == [ + ("540p", "3:2", 1), + ("540p", "4:3", 1), + ("540p", "auto", 1), + ("720p", "16:9", 1), + ] + assert snapshot.aspect_ratios == ["16:9", "3:2", "4:3", "auto"] + + +def test_usual_settings_tie_uses_the_most_recent_run(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + earlier = datetime(2026, 3, 8, 12, tzinfo=ZoneInfo("UTC")) + later = datetime(2026, 3, 9, 12, tzinfo=ZoneInfo("UTC")) + for index, finished in enumerate((earlier, earlier)): + _insert( + conn, + generation_id=f"old-{index}", + feature="text-to-video", + status="succeeded", + finished=finished, + run_ms=1_000, + spec=_spec(resolution="1080p"), + ) + for index, finished in enumerate((later, later)): + _insert( + conn, + generation_id=f"new-{index}", + feature="text-to-video", + status="succeeded", + finished=finished, + run_ms=1_000, + spec=_spec(resolution="720p"), + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert snapshot.usual is not None + assert snapshot.usual.resolution == "720p" + + +def test_dashboard_route_returns_the_snapshot_and_rejects_a_bad_timezone(client) -> None: + ok = client.get("/api/stats/dashboard", params={"range": "7d", "tz": "UTC"}) + assert ok.status_code == 200 + assert ok.json()["empty"] is True + + bad = client.get("/api/stats/dashboard", params={"range": "7d", "tz": "Not/AZone"}) + assert bad.status_code == 422 + assert bad.json()["code"] == "INVALID_TIMEZONE" + for tz in ("/etc/passwd", "../UTC", "a" * 5000): + escaped = client.get("/api/stats/dashboard", params={"range": "7d", "tz": tz}) + assert escaped.status_code == 422 + assert escaped.json()["code"] == "INVALID_TIMEZONE" + + +def test_malformed_rows_leave_the_metrics_that_cannot_read_them( + tmp_path: Path, caplog: pytest.LogCaptureFixture +) -> None: + """provider is not in spec, so its absence drops nothing. A string fps + drops render time and usual settings only. A recipe with no loras array + is not a LoRA run. Text-to-video that also carries loras stays text-to-video. + """ + store, conn = _open(tmp_path) + _insert( + conn, + generation_id="valid", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec(), + ) + string_fps = json.dumps( + { + "params": { + "model": "ltx-2.3-fast", + "resolution": "720p", + "aspectRatio": "16:9", + "duration": 5, + "fps": "24", + }, + "inputs": {}, + } + ) + for index in range(3): + _insert( + conn, + generation_id=f"string-fps-{index}", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=string_fps, + ) + _insert( + conn, + generation_id="recipe-without-loras", + feature="cozy-felt", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec(resolution="540p"), + ) + _insert( + conn, + generation_id="t2v-with-lora", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec( + loras=[ + { + "ref": "", + "scale": 1, + "catalogId": "cozy-felt-style", + "displayName": "Cozy Felt Style", + } + ] + ), + ) + conn.commit() + conn.close() + + with caplog.at_level(logging.INFO, logger="services.dashboard_stats"): + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert snapshot.kpis.succeeded == 6 + assert snapshot.kpis.gpu_ms == 6_000 + assert [(cell.resolution, cell.count) for cell in snapshot.render] == [("1080p", 2)] + assert snapshot.usual is not None + assert snapshot.usual.resolution == "1080p" + assert snapshot.loras.top == [] + assert snapshot.loras.share == 0 + assert snapshot.activity[-1].counts["text-to-video"] == 5 + assert snapshot.activity[-1].counts["lora"] == 0 + assert "dashboard excluded 3 rows from render" in caplog.text + assert "dashboard excluded 3 rows from usual_settings" in caplog.text + assert "dashboard excluded 1 rows from feature_group" in caplog.text + + +def test_fifty_thousand_rows_aggregate(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + finished_ms = _ms(DAY) + spec = _spec() + conn.executemany( + """ + INSERT INTO generations ( + id, feature, contract_version, status, spec, error_code, + created_at, queued_at, queue_rank, attempt_count, + started_at, finished_at, deleted_at + ) VALUES (?, 'text-to-video', 1, 'succeeded', ?, NULL, ?, ?, NULL, 1, ?, ?, NULL) + """, + [ + (f"bulk-{index}", spec, finished_ms, finished_ms, finished_ms - 1000, finished_ms) + for index in range(50_000) + ], + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert snapshot.kpis.succeeded == 50_000 + + +def test_usual_settings_ignore_failed_and_cancelled_runs(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + for index in range(3): + _insert( + conn, + generation_id=f"oom-{index}", + feature="text-to-video", + status="failed", + finished=DAY, + run_ms=1_000, + spec=_spec(resolution="2160p"), + error_code="OOM", + ) + _insert( + conn, + generation_id="cancelled", + feature="text-to-video", + status="cancelled", + finished=DAY, + run_ms=1_000, + spec=_spec(resolution="2160p"), + ) + _insert( + conn, + generation_id="done", + feature="text-to-video", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec(resolution="720p"), + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert snapshot.usual is not None + assert snapshot.usual.resolution == "720p" + + +def test_a_quiet_range_is_empty_but_keeps_its_history(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + _insert( + conn, + generation_id="old", + feature="text-to-video", + status="succeeded", + finished=datetime(2025, 6, 1, 10, 0, tzinfo=ZoneInfo("UTC")), + run_ms=1_000, + spec=_spec(), + ) + conn.commit() + conn.close() + + quiet = store.dashboard(window="7d", tz="UTC", now=NOW) + everything = store.dashboard(window="all", tz="UTC", now=NOW) + + assert quiet.empty is True + assert quiet.has_history is True + assert everything.empty is False + assert everything.has_history is True + + +def test_a_new_install_has_no_history(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert snapshot.empty is True + assert snapshot.has_history is False + + +def test_activity_days_stay_in_date_order_when_a_run_is_dated_after_today(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + for index, day in enumerate((5, 3)): + _insert( + conn, + generation_id=f"future-{index}", + feature="text-to-video", + status="succeeded", + finished=datetime(2026, 3, 10 + day, 10, 0, tzinfo=ZoneInfo("UTC")), + run_ms=1_000, + spec=_spec(), + ) + conn.commit() + conn.close() + + days = [day.day for day in store.dashboard(window="7d", tz="UTC", now=NOW).activity] + + assert days == sorted(days) + + +def test_audio_to_video_lengths_share_one_column_per_second(tmp_path: Path) -> None: + store, conn = _open(tmp_path) + for index, frames in enumerate((121, 129, 137)): + spec = json.dumps( + { + "params": { + "model": "ltx-2.3-fast", + "resolution": "540p", + "aspectRatio": "16:9", + "fps": 24, + "numFrames": frames, + }, + "inputs": {}, + } + ) + _insert( + conn, + generation_id=f"a2v-{index}", + feature="audio-to-video", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=spec, + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert sorted({cell.duration_s for cell in snapshot.render}) == [5.0, 6.0] + + +def test_every_queued_feature_lands_in_a_chart_series(tmp_path: Path) -> None: + from services.features.ic_lora_recipes import IC_LORA_RECIPES + from services.features.queued_features import QUEUED_GENERATION_FEATURES + + store, conn = _open(tmp_path) + plain = { + "text-to-video", + "image-to-video", + "audio-to-video", + "retake", + "extend", + } + for index, feature in enumerate(sorted(QUEUED_GENERATION_FEATURES)): + loras = None if feature in plain else [{"catalogId": feature, "displayName": feature}] + _insert( + conn, + generation_id=f"feature-{index}", + feature=feature, + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec(loras=loras), + ) + conn.commit() + conn.close() + + snapshot = store.dashboard(window="7d", tz="UTC", now=NOW) + + assert sum(snapshot.activity[-1].counts.values()) == len(QUEUED_GENERATION_FEATURES) + # A stored IC-LoRA recipe spec carries loras. It still counts as ic-lora. + assert snapshot.activity[-1].counts["ic-lora"] == len(IC_LORA_RECIPES) + assert set(snapshot.activity[-1].counts) == { + "text-to-video", + "image-to-video", + "audio-to-video", + "lora", + "retake", + "extend", + "ic-lora", + } + + +def test_old_lora_runs_take_their_name_from_the_catalog(tmp_path: Path, fake_services) -> None: + from handlers.dashboard_handler import DashboardHandler + + store, conn = _open(tmp_path) + _insert( + conn, + generation_id="before-names", + feature="cozy-felt", + status="succeeded", + finished=DAY, + run_ms=1_000, + spec=_spec(loras=[{"catalogId": "cozy-felt-style"}]), + ) + conn.commit() + conn.close() + + handler = DashboardHandler(store, fake_services.lora_catalog_provider) + snapshot = handler.get(window="7d", tz="UTC", now=NOW) + + assert [usage.name for usage in snapshot.loras.top] == ["Cozy Felt Style"] diff --git a/backend/tests/test_day_to_night.py b/backend/tests/test_day_to_night.py new file mode 100644 index 000000000..4df0ef459 --- /dev/null +++ b/backend/tests/test_day_to_night.py @@ -0,0 +1,960 @@ +"""Day to Night Home create: stored params, missing weights, and the sized canvas.""" + +from __future__ import annotations + +import json +import sqlite3 +import time +from pathlib import Path + +import av +import numpy as np +import imageio.v2 as imageio +from PIL import Image +from starlette.testclient import TestClient + +from api_types import ( + DownloadSpec, + DownloadVariant, + IcLoraCatalogItem, + IcLoraControl, + IcLoraGenerateCancelledResponse, + IcLoraRecipeStoredParams, + IcLoraSettings, + InputSpec, + LoraEntry, + PreprocessingStep, + PromptTemplatePlaceholder, + PromptTemplateSpec, + VideoAssetMetadata, + VideoMeta, + _HOME_RECIPE_FIELDS, + parse_lora_catalog, +) +from app_factory import create_app +from app_handler import ServiceBundle +from handlers.base import resolve_models_dir +from runtime_config.ltx_capabilities import budget_pixels, local_caps +from runtime_config.model_download_specs import resolve_ic_lora_path +from services.features.ic_lora_recipes import ( + IC_LORA_RECIPES, + ic_lora_fps_choices, + ic_lora_original_fps, +) +from services.features.video.ic_lora_recipe import ic_lora_video_filters +from services.features.video.ic_lora_recipe import IcLoraRecipeExecutor +from services.generation_interrupt import GenerationCancelledError +from services.generation_queue.types import OutputAllocation, OutputPlan +from services.media_probe import _stream_fps, probe_file +from services.records import AssetRecord, CapabilityFailedError, GenerationRecord +from services.sqlite_store import SqliteStore +from state import build_initial_state, set_state_service_for_tests +from tests.conftest import TEST_ADMIN_TOKEN +from tests.fakes.services import FakeCapture +from tests.http_error_assertions import assert_http_error +from tests.lora_catalog_helpers import add_ic_lora, download_spec + +_LOCAL_2_3 = "ltx-2.3-22b-distilled-1.1" +_LOCAL_2_5 = "ltx-2.5-22b-distilled" +_WEIGHTS = "day-to-night.safetensors" + + +def _mp4(path: Path, *, fps: int = 8, seconds: float = 1) -> Path: + writer = imageio.get_writer(str(path), fps=fps, codec="libx264", macro_block_size=None) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(max(1, round(fps * seconds))): + writer.append_data(frame) + writer.close() + return path + + +def _params(**overrides: object) -> dict[str, object]: + params: dict[str, object] = { + "prompt": "turn the street to night", + "model": "ltx-2.5-fast", + "resolution": "540p", + "audioMode": "generated", + "variantId": "default", + } + params.update(overrides) + if params.get("variantId") is None: + del params["variantId"] + return params + + +def _two_variant_spec() -> DownloadSpec: + return DownloadSpec( + repo_id="org/day-23", + variants=[ + DownloadVariant( + id="ltx-2.5__day-to-night", + label="LTX-2.5", + filename="new.safetensors", + size_bytes=10, + base_model="LTX-2.5", + repo_id="org/day-25", + ), + DownloadVariant( + id="default", + label="LTX-2.3", + filename="old.safetensors", + size_bytes=10, + base_model="LTX-2.3", + ), + ], + ) + + +def _install_catalog(fake_services, download=None) -> None: + add_ic_lora( + fake_services, + id="day-to-night", + download=download if download is not None else download_spec(_WEIGHTS), + input={"kind": "video"}, + default_settings=IcLoraSettings( + skip_stage_2=True, resolution_factor=1.5, audio_mode="source" + ), + prompt_template=PromptTemplateSpec( + template=( + "A realistic nighttime scene. {lighting} Only the lighting changes from " + "day to night; identical composition, framing, camera movement and motion." + ), + placeholders={"lighting": PromptTemplatePlaceholder()}, + ), + ) + + +def _write_weights(test_state, filename: str = _WEIGHTS, ic_lora_id: str = "day-to-night") -> None: + models_dir = resolve_models_dir(test_state.state, test_state.config) + path = resolve_ic_lora_path(models_dir, ic_lora_id, filename) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"weights") + + +def test_create_stores_day_to_night_params_and_rejects_a_pipeline_model_id( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + spec = response.json()["spec"] + assert spec["inputs"]["video"]["assetId"] == video["id"] + assert spec["params"]["model"] == "ltx-2.5-fast" + assert spec["params"]["resolution"] == "540p" + assert spec["params"]["audioMode"] == "generated" + assert "scale" not in spec["params"] + assert spec["params"]["loras"] == [ + { + "ref": "", + "scale": 1.0, + "catalogId": "day-to-night", + "displayName": "Test IC-LoRA", + "variantId": "default", + } + ] + + rejected = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(model="fast"), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert rejected.status_code == 422 + + +def test_create_rejects_missing_day_to_night_weights_without_changing_settings( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + create_fake_model_files(model_id=_LOCAL_2_3) + _install_catalog(fake_services) + test_state.state.app_settings.active_ltx_model_id = _LOCAL_2_3 + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(model="ltx-2.5-fast"), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=409, + code="IC_LORA_NOT_DOWNLOADED", + message="IC_LORA_NOT_DOWNLOADED", + ) + assert test_state.state.app_settings.active_ltx_model_id == _LOCAL_2_3 + + +def test_create_rejects_a_2_5_job_for_an_entry_that_supports_only_2_3( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + create_fake_model_files(model_id=_LOCAL_2_3) + _install_catalog(fake_services) + fake_services.lora_catalog_provider._catalog.ic_loras[-1].supported_models = ["LTX-2.3"] + _write_weights(test_state) + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(model="ltx-2.5-fast"), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="IC_LORA_UNSUPPORTED_MODEL", + message="'day-to-night' does not support the selected LTX model", + ) + + +def test_create_fills_omitted_audio_and_scale_from_catalog_defaults( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + fake_services.lora_catalog_provider._catalog.ic_loras[-1].default_settings = IcLoraSettings( + skip_stage_2=True, + resolution_factor=1.5, + audio_mode="generated", + lora_strength=1.5, + ) + _write_weights(test_state) + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": { + "prompt": "turn the street to night", + "model": "ltx-2.5-fast", + "variantId": "default", + }, + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + spec = response.json()["spec"] + assert spec["params"]["audioMode"] == "generated" + assert spec["params"]["loras"][0]["scale"] == 1.5 + assert "scale" not in spec["params"] + + +def test_alpha_gen_create_accepts_a_blank_prompt_and_runs_on_2_5_only( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + """AlphaGen is the shipped catalog row: no prompt, LTX-2.5 weights only.""" + create_fake_model_files() + create_fake_model_files(model_id=_LOCAL_2_3) + catalog_path = Path(__file__).resolve().parents[1] / "runtime_config" / "lora_catalog.json" + item = next( + entry + for entry in parse_lora_catalog(catalog_path.read_text()).ic_loras + if entry.id == "alpha-gen" + ) + fake_services.lora_catalog_provider._catalog.ic_loras.append(item) + models_dir = resolve_models_dir(test_state.state, test_state.config) + weights = resolve_ic_lora_path(models_dir, item.id, item.download.variants[0].filename) + weights.parent.mkdir(parents=True, exist_ok=True) + weights.write_bytes(b"weights") + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + + def create(model: str) -> object: + return client.post( + "/api/generations/ic-lora-recipes/alpha-gen", + json={ + "params": {"prompt": "", "model": model, "resolution": "540p"}, + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + + accepted = create("ltx-2.5-fast") + assert accepted.status_code == 200, accepted.text + params = accepted.json()["spec"]["params"] + assert params["prompt"] == "" + assert params["audioMode"] == "source" + assert params["loras"][0]["scale"] == 1.0 + assert params["loras"][0]["variantId"] == "ltx-2.5__alpha-gen" + assert_http_error( + create("ltx-2.3-fast"), + status_code=422, + code="IC_LORA_UNSUPPORTED_MODEL", + message="'alpha-gen' does not support the selected LTX model", + ) + + +def test_create_rejects_a_clip_longer_than_10_seconds( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "long.mp4", seconds=11))} + ).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="IC_LORA_INPUT_TOO_LONG", + message="This clip is longer than 10s at 8fps. Trim it to continue.", + ) + + +def test_create_accepts_a_10_second_30fps_clip_at_24fps( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + video = client.post( + "/api/assets", + json={"path": str(_mp4(tmp_path / "phone.mp4", fps=30, seconds=10))}, + ).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(fps=24), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + assert response.json()["spec"]["params"]["fps"] == 24 + assert video["metadata"]["metadata"]["fps"] == 30 + + +def test_omitted_fps_stores_the_original_rate_not_24( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + phone = client.post( + "/api/assets", + json={"path": str(_mp4(tmp_path / "phone.mp4", fps=30, seconds=1))}, + ).json() + slow = client.post( + "/api/assets", + json={"path": str(_mp4(tmp_path / "slow.mp4", fps=15, seconds=1))}, + ).json() + + def created(asset_id: str) -> object: + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={"params": _params(), "inputs": {"video": {"assetId": asset_id}}}, + ) + assert response.status_code == 200, response.text + return response.json()["spec"]["params"]["fps"] + + assert created(phone["id"]) == 25 + assert created(slow["id"]) == 15 + + +def test_create_rejects_a_10_second_30fps_clip_when_the_rate_keeps_all_its_frames( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + video = client.post( + "/api/assets", + json={"path": str(_mp4(tmp_path / "phone.mp4", fps=30, seconds=10))}, + ).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(fps=30), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="IC_LORA_INPUT_TOO_LONG", + message="This clip is longer than 8s at 30fps. Trim it to continue.", + ) + + +def test_create_rejects_a_two_stage_catalog_entry( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + fake_services.lora_catalog_provider._catalog.ic_loras[-1].default_settings = IcLoraSettings( + skip_stage_2=False, resolution_factor=1.5, audio_mode="source" + ) + _write_weights(test_state) + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="IC_LORA_UNSUPPORTED_RECIPE", + message="'day-to-night' needs its own form", + ) + + +def test_create_rejects_an_entry_the_home_form_cannot_run( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + item = fake_services.lora_catalog_provider._catalog.ic_loras[-1] + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + + def rejected() -> object: + return client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + + item.controls = [IcLoraControl(id="pads", label="Pads", kind="position_canvas")] + assert_http_error( + rejected(), + status_code=422, + code="IC_LORA_UNSUPPORTED_RECIPE", + message="'day-to-night' needs its own form", + ) + item.controls = [] + item.preprocessing = [PreprocessingStep(utility="canny")] + assert_http_error( + rejected(), + status_code=422, + code="IC_LORA_UNSUPPORTED_RECIPE", + message="'day-to-night' needs its own form", + ) + item.preprocessing = [] + item.allows_reference_image = True + assert_http_error( + rejected(), + status_code=422, + code="IC_LORA_UNSUPPORTED_RECIPE", + message="'day-to-night' needs its own form", + ) + item.allows_reference_image = False + item.input = InputSpec(kind="image") + assert_http_error( + rejected(), + status_code=422, + code="IC_LORA_UNSUPPORTED_RECIPE", + message="'day-to-night' needs its own form", + ) + + +def test_every_ic_lora_recipe_stays_a_home_recipe_until_a_new_field_is_classified() -> None: + catalog_path = Path(__file__).resolve().parents[1] / "runtime_config" / "lora_catalog.json" + catalog = parse_lora_catalog(catalog_path.read_text()) + for recipe in IC_LORA_RECIPES.values(): + item = next(entry for entry in catalog.ic_loras if entry.id == recipe.catalog_id) + assert item.is_home_recipe(), recipe.recipe_id + assert frozenset(IcLoraCatalogItem.model_fields) == _HOME_RECIPE_FIELDS + + +class _Assets: + def get_asset(self, asset_id: str) -> None: + return None + + +class _Generator: + def generate_local_reserved(self, *_args: object, **_kwargs: object) -> None: + raise AssertionError("unused") + + +def test_ic_lora_spec_without_one_catalog_lora_is_a_capability_error() -> None: + executor = IcLoraRecipeExecutor( + _Generator(), + _Assets(), + lambda: Path("."), + catalog_id="day-to-night", + ) + missing = { + "params": {"prompt": "night", "model": "ltx-2.5-fast", "audioMode": "source"}, + "inputs": {"video": {"assetId": "clip"}}, + } + blank = { + "params": { + "prompt": "night", + "model": "ltx-2.5-fast", + "audioMode": "source", + "loras": [{"ref": "", "scale": 1.0, "catalogId": ""}], + }, + "inputs": {"video": {"assetId": "clip"}}, + } + for spec in (missing, blank): + try: + executor.validate_params(spec, contract_version=1) + except CapabilityFailedError as exc: + assert exc.code == "INVALID_GENERATION_SPEC" + else: + raise AssertionError("spec without one catalog LoRA was accepted") + +def test_create_stores_the_requested_variant_and_the_run_loads_that_file( + test_state, fake_services, create_fake_model_files, tmp_path: Path, default_app_settings +) -> None: + create_fake_model_files() + create_fake_model_files(model_id=_LOCAL_2_3) + _install_catalog(fake_services, download=_two_variant_spec()) + _write_weights(test_state, "old.safetensors") + app, _handler = _real_app(test_state, fake_services, default_app_settings) + with TestClient(app) as client: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + fake_services.video_processor.register_video( + video["path"], FakeCapture(frames=["f"] * 9, fps=24, width=16, height=16) + ) + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(scale=0.4, variantId="default"), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + assert response.json()["spec"]["params"]["loras"] == [ + { + "ref": "", + "scale": 0.4, + "catalogId": "day-to-night", + "displayName": "Test IC-LoRA", + "variantId": "default", + } + ] + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.ic_lora_pipeline.last_lora_path: + break + time.sleep(0.01) + assert fake_services.ic_lora_pipeline.last_lora_path is not None + assert fake_services.ic_lora_pipeline.last_lora_path.endswith("old.safetensors") + + +def test_omitted_variant_id_does_not_select_an_installed_file( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services, download=_two_variant_spec()) + _write_weights(test_state, "old.safetensors") + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(variantId=None), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=404, + code="UNKNOWN_DOWNLOAD_VARIANT", + message="UNKNOWN_DOWNLOAD_VARIANT", + ) + + +def test_create_rejects_an_unknown_variant_id( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services, download=_two_variant_spec()) + _write_weights(test_state, "old.safetensors") + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(variantId="nope"), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=404, + code="UNKNOWN_DOWNLOAD_VARIANT", + message="UNKNOWN_DOWNLOAD_VARIANT", + ) + + +def _real_app(test_state, fake_services, default_app_settings): + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=ServiceBundle( + http=fake_services.http, + gpu_cleaner=fake_services.gpu_cleaner, + model_downloader=fake_services.model_downloader, + lora_catalog_provider=fake_services.lora_catalog_provider, + gpu_info=fake_services.gpu_info, + video_processor=fake_services.video_processor, + text_encoder=fake_services.text_encoder, + task_runner=fake_services.task_runner, + ltx_api_client=fake_services.ltx_api_client, + zit_api_client=fake_services.zit_api_client, + fast_video_pipeline_class=type(fake_services.fast_video_pipeline), + image_generation_pipeline_class=type(fake_services.image_generation_pipeline), + ic_lora_pipeline_class=type(fake_services.ic_lora_pipeline), + depth_processor_pipeline_class=type(fake_services.depth_processor_pipeline), + pose_processor_pipeline_class=type(fake_services.pose_processor_pipeline), + a2v_pipeline_class=type(fake_services.a2v_pipeline), + retake_pipeline_class=type(fake_services.retake_pipeline), + prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), + store=SqliteStore(test_state.config.app_data_dir), + ), + ) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.active_ltx_model_id = _LOCAL_2_3 + set_state_service_for_tests(handler) + return create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN), handler + + +def test_day_to_night_explicit_resolution_renders_that_size( + test_state, fake_services, create_fake_model_files, tmp_path: Path, default_app_settings +) -> None: + create_fake_model_files() + create_fake_model_files(model_id=_LOCAL_2_3) + _install_catalog(fake_services) + _write_weights(test_state) + app, handler = _real_app(test_state, fake_services, default_app_settings) + with TestClient(app) as client: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + fake_services.video_processor.register_video( + video["path"], FakeCapture(frames=["f"] * 9, fps=24, width=16, height=16) + ) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = ( + '{"lighting": "Warm amber light spills from the windows."}' + ) + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(resolution="540p", audioMode="source"), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.ic_lora_pipeline.generate_calls: + break + time.sleep(0.01) + assert len(fake_services.ic_lora_pipeline.generate_calls) == 1 + call = fake_services.ic_lora_pipeline.generate_calls[0] + width, height = budget_pixels(local_caps(_LOCAL_2_5), "540p", "1:1", mode="video") + assert (call["width"], call["height"], call["resolution_factor"]) == ( + width * 2, + height * 2, + 1.0, + ) + assert call["width"] != 768 + checkpoint = fake_services.ic_lora_pipeline.last_checkpoint_path or "" + assert "ltx-2.5" in checkpoint + gemma = fake_services.ic_lora_pipeline.last_gemma_root or "" + assert "gemma4" in gemma + assert handler.state.app_settings.active_ltx_model_id == _LOCAL_2_3 + assert fake_services.ic_lora_pipeline.last_lora_strength == 1.0 + assert call["prompt"] == ( + "A realistic nighttime scene. Warm amber light spills from the windows. " + "Only the lighting changes from day to night; identical composition, framing, " + "camera movement and motion." + ) + + +def _install_layout_catalog(fake_services) -> None: + """The Layout to Render shape: stage 2 keeps the IC-LoRA, one required look still at -1.""" + add_ic_lora( + fake_services, + id="layout-to-render", + download=download_spec(_WEIGHTS), + input={"kind": "video"}, + allows_reference_image=True, + reference_image_required=True, + reference_image_frame=-1, + default_settings=IcLoraSettings( + skip_stage_2=False, stage_2_ic_lora=True, resolution_factor=1.0, audio_mode="source" + ), + ) + + +def _png(path: Path) -> Path: + Image.new("RGB", (16, 16), color=(1, 2, 3)).save(path, format="PNG") + return path + + +def test_layout_create_without_the_required_reference_image_is_rejected( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_layout_catalog(fake_services) + _write_weights(test_state, ic_lora_id="layout-to-render") + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/layout-to-render", + json={"params": _params(), "inputs": {"video": {"assetId": video["id"]}}}, + ) + assert_http_error( + response, + status_code=422, + code="INVALID_GENERATION_SPEC", + message="Reference image is required.", + ) + + +def test_create_rejects_a_reference_image_for_a_recipe_that_takes_none( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + image = client.post("/api/assets", json={"path": str(_png(tmp_path / "look.png"))}).json() + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={ + "params": _params(), + "inputs": {"video": {"assetId": video["id"]}, "image": {"assetId": image["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="INVALID_GENERATION_SPEC", + message="'day-to-night' takes no reference image.", + ) + + +def test_layout_run_gives_the_pipeline_the_reference_image_at_the_still_frame( + test_state, fake_services, create_fake_model_files, tmp_path: Path, default_app_settings +) -> None: + create_fake_model_files() + create_fake_model_files(model_id=_LOCAL_2_3) + _install_layout_catalog(fake_services) + _write_weights(test_state, ic_lora_id="layout-to-render") + app, _handler = _real_app(test_state, fake_services, default_app_settings) + with TestClient(app) as client: + video = client.post("/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))}).json() + image = client.post("/api/assets", json={"path": str(_png(tmp_path / "look.png"))}).json() + fake_services.video_processor.register_video( + video["path"], FakeCapture(frames=["f"] * 9, fps=24, width=16, height=16) + ) + response = client.post( + "/api/generations/ic-lora-recipes/layout-to-render", + json={ + "params": _params(), + "inputs": {"video": {"assetId": video["id"]}, "image": {"assetId": image["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.ic_lora_pipeline.generate_calls: + break + time.sleep(0.01) + assert len(fake_services.ic_lora_pipeline.generate_calls) == 1 + call = fake_services.ic_lora_pipeline.generate_calls[0] + assert [(img.path, img.frame_idx) for img in call["images"]] == [(image["path"], -1)] + assert fake_services.ic_lora_pipeline.last_stage_2_ic_lora is True + assert call["skip_stage_2"] is False + + +def test_original_fps_is_the_closest_supported_rate_that_is_not_above_the_source() -> None: + assert ic_lora_fps_choices(60) == (50, 48, 25, 24) + assert ic_lora_fps_choices(30) == (25, 24) + assert ic_lora_fps_choices(29.97) == (25, 24) + assert ic_lora_fps_choices(25) == (25, 24) + assert ic_lora_fps_choices(24) == (24,) + assert ic_lora_fps_choices(23.976) == (24,) + assert ic_lora_fps_choices(15) == (15,) + # 24.5 is equally close to 24 and 25. The higher rate is above the source. + assert ic_lora_original_fps(24.5) == 24 + # 49 is equally close to 48 and 50. + assert ic_lora_original_fps(49) == 48 + + +def test_a_missing_frame_rate_does_not_fail_the_probe(tmp_path: Path) -> None: + assert _stream_fps(object()) is None + kind, _mime, metadata = probe_file(_mp4(tmp_path / "clip.mp4", fps=30)) + assert kind == "video" + assert metadata.mediaType == "video" + assert metadata.metadata.fps == 30 + + +def test_create_rejects_an_unreadable_clip_that_has_no_stored_fps( + client, test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + _install_catalog(fake_services) + _write_weights(test_state) + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + db = test_state.config.app_data_dir / "store.sqlite3" + conn = sqlite3.connect(db) + row = conn.execute( + "SELECT metadata FROM assets WHERE id = ?", (video["id"],) + ).fetchone() + assert row is not None + meta = json.loads(str(row[0])) + del meta["metadata"]["fps"] + conn.execute( + "UPDATE assets SET metadata = ? WHERE id = ?", + (json.dumps(meta), video["id"]), + ) + conn.commit() + conn.close() + Path(str(video["path"])).write_bytes(b"not a video") + response = client.post( + "/api/generations/ic-lora-recipes/day-to-night", + json={"params": _params(), "inputs": {"video": {"assetId": video["id"]}}}, + ) + assert_http_error( + response, + status_code=422, + code="INVALID_GENERATION_SPEC", + message="INVALID_VIDEO_ASSET", + ) + + +class _RecordingGenerator: + def __init__(self) -> None: + self.fps: float | None = None + self.frames: int | None = None + + def generate_local_reserved(self, request: object, **_kwargs: object) -> object: + path = Path(str(getattr(request, "input_path"))) + with av.open(str(path)) as container: + stream = container.streams.video[0] + rate = stream.average_rate + assert rate is not None + self.fps = float(rate) + self.frames = sum(1 for _ in container.decode(stream)) + return IcLoraGenerateCancelledResponse(status="cancelled") + + +def test_a_slower_rate_is_the_file_the_pipeline_receives( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + source = _mp4(tmp_path / "phone.mp4", fps=30, seconds=1) + asset = AssetRecord( + id="clip", + media_kind="video", + origin="uploaded", + path=str(source), + mime_type="video/mp4", + name="phone.mp4", + metadata=VideoAssetMetadata( + mediaType="video", + metadata=VideoMeta( + width=16, + height=16, + durationMs=1000, + sizeBytes=source.stat().st_size, + audioStreamCount=0, + fps=30, + ), + ), + created_at=0, + ) + params = IcLoraRecipeStoredParams( + prompt="night", + model="ltx-2.5-fast", + resolution="540p", + audioMode="off", + fps=25, + loras=[LoraEntry(ref="", scale=1.0, catalogId="day-to-night")], + ) + generation = GenerationRecord( + id="gen", + feature="day-to-night", + contract_version=1, + status="running", + spec={ + "params": params.model_dump(mode="json"), + "inputs": {"video": {"assetId": asset.id}}, + }, + created_at=0, + queued_at=0, + attempt_count=1, + started_at=0, + outputs=(), + ) + generator = _RecordingGenerator() + + class _Clip: + def get_asset(self, asset_id: str) -> AssetRecord | None: + return asset if asset_id == asset.id else None + + executor = IcLoraRecipeExecutor( + generator, + _Clip(), + lambda: test_state.config.default_models_dir, + catalog_id="day-to-night", + ) + try: + executor.execute( + generation, + ( + OutputAllocation( + plan=OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", + ), + asset_id="out", + dest_path=str(tmp_path / "output.mp4"), + ), + ), + ) + except GenerationCancelledError: + pass + else: + raise AssertionError("the reserved call did not return") + assert generator.fps == 25 + assert generator.frames == 25 + + +def test_the_crop_filter_sets_fps_only_when_the_selected_rate_is_slower() -> None: + assert ic_lora_video_filters(None, None) is None + assert ic_lora_video_filters(None, 25) == "fps=25" + assert ic_lora_video_filters((8, 8, 0, 0), 25) == "fps=25,crop=8:8:0:0" + assert ic_lora_video_filters((8, 8, 0, 0), None) == "crop=8:8:0:0" + + +def test_ic_lora_recipe_table_matches_shared_json() -> None: + contract_path = Path(__file__).resolve().parents[2] / "shared" / "ic-lora-recipes.json" + contract = json.loads(contract_path.read_text(encoding="utf-8")) + expected = { + entry["id"]: entry["catalogId"] + for entry in contract + } + actual = { + recipe.recipe_id: recipe.catalog_id for recipe in IC_LORA_RECIPES.values() + } + assert actual == expected diff --git a/backend/tests/test_denoising_progress.py b/backend/tests/test_denoising_progress.py new file mode 100644 index 000000000..b63d9ef65 --- /dev/null +++ b/backend/tests/test_denoising_progress.py @@ -0,0 +1,73 @@ +"""Denoise-step totals and in-flight progress reporting. + +Totals must come from the same sigma schedules the pipelines run, not a guessed +duration or a hardcoded Fast-only step count. +""" + +from __future__ import annotations + +from ltx_pipelines.utils.constants import DISTILLED_SIGMA_VALUES, STAGE_2_DISTILLED_SIGMA_VALUES + +from services.denoising_progress import ( + DISTILLED_STAGE_1_STEPS, + DISTILLED_STAGE_2_STEPS, + DISTILLED_TOTAL_STEPS, + distilled_total_steps, + note_step, + reset, + track_denoising, +) +from state.app_state_types import GpuSlot, VideoPipelineState +from tests.fakes.services import FakeFastVideoPipeline + + +def test_two_stage_distilled_total_matches_sigma_schedules() -> None: + expected = (len(DISTILLED_SIGMA_VALUES) - 1) + (len(STAGE_2_DISTILLED_SIGMA_VALUES) - 1) + assert DISTILLED_STAGE_1_STEPS == 8 + assert DISTILLED_STAGE_2_STEPS == 3 + assert DISTILLED_TOTAL_STEPS == 11 + assert distilled_total_steps() == expected + assert distilled_total_steps() == DISTILLED_TOTAL_STEPS + + +def test_stage_1_only_total_omits_stage_2() -> None: + assert distilled_total_steps(stage_2=False) == DISTILLED_STAGE_1_STEPS + assert distilled_total_steps(stage_2=False) == len(DISTILLED_SIGMA_VALUES) - 1 + assert distilled_total_steps(stage_2=False) == distilled_total_steps() - DISTILLED_STAGE_2_STEPS + + +def test_note_step_reports_current_and_total_to_the_sink() -> None: + seen: list[tuple[int, int]] = [] + from services import denoising_progress + + denoising_progress.configure_sink(lambda current, total: seen.append((current, total))) + total = distilled_total_steps() + with track_denoising(total): + note_step() + note_step() + reset() + assert seen[0] == (0, total) + assert seen[1] == (1, total) + assert seen[2] == (2, total) + + +def test_denoise_steps_fill_generation_progress(test_state) -> None: + pipeline = FakeFastVideoPipeline() + test_state.state.gpu_slot = GpuSlot( + active_pipeline=VideoPipelineState( + pipeline=pipeline, + is_compiled=False, + ltx_model_id="ltx-2.5-22b-distilled", + loading_mode="full_models_loading", + ), + ) + test_state.generation.start_generation("gen-steps") + total = distilled_total_steps() + with track_denoising(total): + note_step() + note_step() + progress = test_state.generation.get_generation_progress() + assert progress.phase == "inference" + assert progress.currentStep == 2 + assert progress.totalSteps == total + assert progress.progress == 15 + int(75 * 2 / total) diff --git a/backend/tests/test_diffusion_interrupt.py b/backend/tests/test_diffusion_interrupt.py index 45b8b7a6e..b24000251 100644 --- a/backend/tests/test_diffusion_interrupt.py +++ b/backend/tests/test_diffusion_interrupt.py @@ -15,6 +15,8 @@ def test_patch_rebinds_diffusion_stage_call() -> None: assert callable(getattr(DiffusionStage, "__call__", None)) assert DiffusionStage.__call__ is diffusion_interrupt._call_with_interrupt assert "denoiser" in inspect.signature(diffusion_interrupt._original_call).parameters + params = list(inspect.signature(diffusion_interrupt._original_call).parameters) + assert params[0] == "self" and params[1] == "denoiser" def test_call_wrap_raises_before_later_denoiser_calls(monkeypatch: pytest.MonkeyPatch) -> None: @@ -36,3 +38,170 @@ def denoiser(latents: object) -> object: with pytest.raises(GenerationCancelledError): diffusion_interrupt._call_with_interrupt(stage, denoiser, latents="step-2") assert calls == ["step-1"] + + +def test_call_wrap_hits_kwargs_denoiser(monkeypatch: pytest.MonkeyPatch) -> None: + def dummy_call(self: object, denoiser: object, latents: object = None) -> object: + del self + return denoiser(latents) # type: ignore[operator] + + monkeypatch.setattr(diffusion_interrupt, "_original_call", dummy_call) + + def denoiser(latents: object) -> object: + return latents + + stage = object() + assert diffusion_interrupt._call_with_interrupt(stage, denoiser=denoiser, latents="kw") == "kw" + request() + with pytest.raises(GenerationCancelledError): + diffusion_interrupt._call_with_interrupt(stage, denoiser=denoiser, latents="kw-2") + + +def test_call_wrap_binds_denoiser_by_name_not_position(monkeypatch: pytest.MonkeyPatch) -> None: + # A leading positional that is not denoiser must not be wrapped. + def dummy_call(self: object, sigmas: object, denoiser: object, latents: object = None) -> object: + del self, sigmas + return denoiser(latents) # type: ignore[operator] + + monkeypatch.setattr(diffusion_interrupt, "_original_call", dummy_call) + + def denoiser(latents: object) -> object: + return latents + + stage = object() + assert diffusion_interrupt._call_with_interrupt(stage, "sigmas", denoiser, latents="pos") == "pos" + request() + with pytest.raises(GenerationCancelledError): + diffusion_interrupt._call_with_interrupt(stage, "sigmas", denoiser, latents="pos-2") + + +def test_loop_tqdm_iterations_count_as_one_step_even_when_denoiser_runs_twice( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """res2s calls the denoiser twice per loop step; the bar must move once per step.""" + from services.denoising_progress import configure_sink, reset, track_denoising + + seen: list[tuple[int, int]] = [] + configure_sink(lambda current, total: seen.append((current, total))) + + def dummy_call( + self: object, + denoiser: object, + sigmas: object, + loop: object = None, + **kwargs: object, + ) -> str: + del self, kwargs + assert loop is not None + loop(sigmas=sigmas, denoiser=denoiser) # type: ignore[operator] + return "ok" + + monkeypatch.setattr(diffusion_interrupt, "_original_call", dummy_call) + + def denoise_loop(*, sigmas: object, denoiser: object, **kwargs: object) -> None: + del kwargs + import ltx_pipelines.utils.samplers as samplers + + for _ in samplers.tqdm(range(len(sigmas) - 1)): # type: ignore[arg-type] + denoiser() # type: ignore[operator] + denoiser() # type: ignore[operator] + + def denoiser() -> None: + return None + + sigmas = list(range(9)) # 8 distilled stage-1 steps + with track_denoising(11): + diffusion_interrupt._call_with_interrupt( + object(), denoiser, sigmas=sigmas, loop=denoise_loop + ) + reset() + step_reports = [pair for pair in seen if pair[0] > 0] + assert len(step_reports) == 8 + assert step_reports[-1] == (8, 11) + + +def _patch_call_to_invoke_loop(monkeypatch: pytest.MonkeyPatch) -> None: + def dummy_call( + self: object, + denoiser: object, + sigmas: object, + loop: object = None, + **kwargs: object, + ) -> str: + del self, kwargs + assert loop is not None + loop(sigmas=sigmas, denoiser=denoiser) # type: ignore[operator] + return "ok" + + monkeypatch.setattr(diffusion_interrupt, "_original_call", dummy_call) + + +def test_ancestral_terminal_break_still_counts_the_last_iteration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """euler_ancestral_denoising_loop breaks when the next sigma is 0, so the + tqdm consumer never resumes after that yield. The completed iteration must + still count when the loop returns normally.""" + from services.denoising_progress import configure_sink, reset, track_denoising + + seen: list[tuple[int, int]] = [] + configure_sink(lambda current, total: seen.append((current, total))) + _patch_call_to_invoke_loop(monkeypatch) + + def ancestral_loop(*, sigmas: object, denoiser: object, **kwargs: object) -> None: + del kwargs + import ltx_pipelines.utils.samplers as samplers + + schedule = list(sigmas) # type: ignore[arg-type] + for step_idx, _ in enumerate(samplers.tqdm(schedule[:-1])): + denoiser() # type: ignore[operator] + if schedule[step_idx + 1] == 0: + break + + sigmas = [1.0, 0.5, 0.25, 0.0] # 3 denoise steps, last is terminal + with track_denoising(3): + diffusion_interrupt._call_with_interrupt( + object(), lambda: None, sigmas=sigmas, loop=ancestral_loop + ) + reset() + step_reports = [pair for pair in seen if pair[0] > 0] + assert len(step_reports) == 3 + assert step_reports[-1] == (3, 3) + + +def test_cancelled_loop_does_not_count_the_aborted_iteration( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from services.denoising_progress import configure_sink, reset, track_denoising + + seen: list[tuple[int, int]] = [] + configure_sink(lambda current, total: seen.append((current, total))) + _patch_call_to_invoke_loop(monkeypatch) + + calls = 0 + + def ancestral_loop(*, sigmas: object, denoiser: object, **kwargs: object) -> None: + del kwargs + import ltx_pipelines.utils.samplers as samplers + + schedule = list(sigmas) # type: ignore[arg-type] + for step_idx, _ in enumerate(samplers.tqdm(schedule[:-1])): + denoiser() # type: ignore[operator] + if schedule[step_idx + 1] == 0: + break + + def denoiser() -> None: + nonlocal calls + calls += 1 + if calls == 2: + raise GenerationCancelledError() + + sigmas = [1.0, 0.5, 0.25, 0.0] + with track_denoising(3): + with pytest.raises(GenerationCancelledError): + diffusion_interrupt._call_with_interrupt( + object(), denoiser, sigmas=sigmas, loop=ancestral_loop + ) + reset() + step_reports = [pair for pair in seen if pair[0] > 0] + assert step_reports == [(1, 3)] diff --git a/backend/tests/test_diffusion_stage_cache.py b/backend/tests/test_diffusion_stage_cache.py index 9f587a82a..aa1e058d7 100644 --- a/backend/tests/test_diffusion_stage_cache.py +++ b/backend/tests/test_diffusion_stage_cache.py @@ -52,6 +52,7 @@ def __init__( self._compilation_config = compilation_config self._dtype = dtype self._device = device + self._model_wrapper = None self._alloc_trim_strategy = AllocatorTrimStrategy.TRIM self.build_count = 0 @@ -125,6 +126,12 @@ def test_cacheable_returns_false_for_a_streaming_stage() -> None: assert dsc._cacheable(streaming_stage) is False +def test_cacheable_skips_when_model_wrapper_is_set() -> None: + stage = _FakeStage(_single_gpu_builder("ckpt.safetensors")) + stage._model_wrapper = object() + assert dsc._cacheable(stage) is False + + class _OtherBuilder: """Stand-in for a non-SingleGPUModelBuilder, non-streaming builder (e.g. a multi-GPU tiled builder).""" @@ -194,6 +201,19 @@ def test_cache_key_self_check() -> None: # --- hardening: dead-reference gc pass + in-use concurrency guard ------------ # +def test_evict_empty_cache_still_cleans_allocator(monkeypatch: pytest.MonkeyPatch) -> None: + """A second Home job starts encode with the cache already empty after DiffVAE evict. + + Skipping cleanup_memory in that case left Windows CUDA at reserved>>device + and free=0; the next tiled encode never reached 'Building transformer'. + """ + cleaned: list[bool] = [] + dsc.evict() + monkeypatch.setattr(dsc, "cleanup_memory", lambda: cleaned.append(True)) + dsc.evict() + assert cleaned == [True] + + def test_evict_runs_gc_collect_before_meta_swap(monkeypatch: pytest.MonkeyPatch) -> None: """The pre-free gc.collect() must run BEFORE .to('meta') (ComfyUI ordering).""" stage = _FakeStage(_single_gpu_builder("ckpt.safetensors")) diff --git a/backend/tests/test_diffvae_decode_vram.py b/backend/tests/test_diffvae_decode_vram.py index 34a657cf1..071d80b20 100644 --- a/backend/tests/test_diffvae_decode_vram.py +++ b/backend/tests/test_diffvae_decode_vram.py @@ -2,15 +2,23 @@ from __future__ import annotations -from types import SimpleNamespace - import pytest import torch +from ltx_core.model.video_vae import DimensionSizeConfig, TileSizeConfig +from ltx_core.tiling import _validate_overlap from services.patches import diffusion_stage_cache as dsc from services.patches import diffvae_decode_vram as patch +def _tiles(*, frames: int, height: int, width: int, overlap_t: int = 40, overlap_hw: int = 160) -> TileSizeConfig: + return TileSizeConfig( + frames=DimensionSizeConfig(tile_size=frames, overlap=overlap_t if frames else 0), + height=DimensionSizeConfig(tile_size=height, overlap=overlap_hw if height else 0), + width=DimensionSizeConfig(tile_size=width, overlap=overlap_hw if width else 0), + ) + + class _FakeModel: def __init__(self) -> None: self.freed_to: str | None = None @@ -80,17 +88,13 @@ def test_pixel_shape_from_5s_latent_is_not_stage4_scale() -> None: def test_cuda_diffvae_reresolves_tiling_after_evict(monkeypatch) -> None: captured: dict[str, object] = {} - sentinel = SimpleNamespace( - frames=SimpleNamespace(tile_size=80), - height=SimpleNamespace(tile_size=576), - width=SimpleNamespace(tile_size=608), - ) + recommended = _tiles(frames=80, height=576, width=608) latent = torch.zeros(1, 4, 61, 18, 32) def _recommend(checkpoint: str, **kwargs: object) -> object: captured["checkpoint"] = checkpoint captured["kwargs"] = kwargs - return sentinel + return recommended monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: True) monkeypatch.setattr(patch, "cuda_activation_budget_bytes", lambda _device: 6 * 1024**3) @@ -102,7 +106,10 @@ def _recommend(checkpoint: str, **kwargs: object) -> object: args, kwargs = patch._patched_video_decoder_call(decoder, latent, old_tiling) assert args[0] is latent - assert args[1] is sentinel + tiling = args[1] + assert tiling.frames.tile_size == 80 + assert tiling.height.tile_size == 0 + assert tiling.width.tile_size == 608 assert kwargs == {} assert captured["checkpoint"] == decoder.checkpoint_path rec = captured["kwargs"] @@ -113,19 +120,15 @@ def _recommend(checkpoint: str, **kwargs: object) -> object: assert rec["device"] == decoder._device -def test_cuda_tile_budget_caps_optimistic_mem_get_info() -> None: - assert patch._cuda_tile_budget_bytes(int(29.5 * 1024**3)) == patch._CUDA_DIFFVAE_TILE_BUDGET_CAP_BYTES - assert patch._cuda_tile_budget_bytes(6 * 1024**3) == 6 * 1024**3 - - -def test_cuda_diffvae_caps_29gib_budget_before_recommend(monkeypatch) -> None: +def test_cuda_diffvae_forwards_29gib_budget_to_recommend(monkeypatch) -> None: captured: dict[str, object] = {} + measured = int(29.5 * 1024**3) monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: True) - monkeypatch.setattr(patch, "cuda_activation_budget_bytes", lambda _device: int(29.5 * 1024**3)) + monkeypatch.setattr(patch, "cuda_activation_budget_bytes", lambda _device: measured) monkeypatch.setattr( patch, "tiling_config_for_vae", - lambda _checkpoint, **kwargs: captured.update(kwargs) or object(), + lambda _checkpoint, **kwargs: captured.update(kwargs) or _tiles(frames=80, height=576, width=608), ) monkeypatch.setattr(patch, "_orig_video_decoder_call", lambda *_args, **_kwargs: "ok") @@ -134,12 +137,120 @@ def test_cuda_diffvae_caps_29gib_budget_before_recommend(monkeypatch) -> None: torch.zeros(1, 128, 61, 18, 32), object(), ) - assert captured["free_bytes"] == patch._CUDA_DIFFVAE_TILE_BUDGET_CAP_BYTES + assert captured["free_bytes"] == measured assert captured["width"] == 1024 assert captured["height"] == 576 assert captured["num_frames"] == 481 +def test_clamp_splits_full_frame_540p_20s() -> None: + clamped = patch._clamp_diffvae_tiles(_tiles(frames=481, height=576, width=1024), 576, 1024, 481) + assert clamped.width.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert clamped.frames.tile_size <= patch._MAX_DIFFVAE_TILE_FRAMES + assert clamped.height.tile_size <= 576 + + +def test_clamp_splits_full_frame_1080p_10s() -> None: + clamped = patch._clamp_diffvae_tiles( + _tiles(frames=241, height=1088, width=1920), 1088, 1920, 241 + ) + assert clamped.width.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert clamped.height.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert clamped.frames.tile_size <= patch._MAX_DIFFVAE_TILE_FRAMES + + +def test_clamp_untiled_axis_is_forced_split() -> None: + clamped = patch._clamp_diffvae_tiles(_tiles(frames=0, height=0, width=0), 576, 1024, 481) + assert clamped.frames.tile_size == patch._MAX_DIFFVAE_TILE_FRAMES + assert clamped.width.tile_size == patch._MAX_DIFFVAE_TILE_SPATIAL + assert clamped.height == DimensionSizeConfig() + assert clamped.frames.overlap == patch._DEFAULT_DIFFVAE_FRAME_OVERLAP + assert clamped.width.overlap == patch._DEFAULT_DIFFVAE_SPATIAL_OVERLAP + + +@pytest.mark.parametrize( + ("frames", "height", "width"), + [ + (9, 256, 512), + (33, 256, 512), + (41, 256, 512), # IC-LoRA output: snapping 41 down to 40 must not tile it + (49, 544, 960), + (81, 576, 1024), + (121, 544, 960), + (481, 576, 1024), + (241, 1088, 1920), + ], +) +@pytest.mark.parametrize("upstream_frames", [0, 48, 80, 481]) +def test_clamp_output_passes_upstream_overlap_floors( + frames: int, height: int, width: int, upstream_frames: int +) -> None: + """ltx_core 1.4.0 rejects any axis with tile_size > 0 whose overlap is below the floor.""" + upstream_tile = upstream_frames if upstream_frames < frames else 0 + upstream = _tiles(frames=upstream_tile, height=0, width=0) + clamped = patch._clamp_diffvae_tiles(upstream, height, width, frames) + _validate_overlap( + clamped, + min_overlap_frames=patch._DEFAULT_DIFFVAE_FRAME_OVERLAP, + min_overlap_pixels=patch._DEFAULT_DIFFVAE_SPATIAL_OVERLAP, + ) + + +@pytest.mark.parametrize("frames", [9, 33, 41, 49, 65, 73, 80]) +def test_clamp_leaves_short_clips_untiled(frames: int) -> None: + clamped = patch._clamp_diffvae_tiles(_tiles(frames=0, height=0, width=0), 256, 512, frames) + assert clamped == TileSizeConfig( + frames=DimensionSizeConfig(), height=DimensionSizeConfig(), width=DimensionSizeConfig() + ) + + +def test_clamp_keeps_smaller_upstream_tiles_when_they_force_a_split() -> None: + clamped = patch._clamp_diffvae_tiles(_tiles(frames=48, height=0, width=0), 256, 512, 121) + assert clamped.frames == DimensionSizeConfig(tile_size=48, overlap=40) + + +def test_cuda_diffvae_clamps_full_frame_recommend_for_540p(monkeypatch) -> None: + monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: True) + monkeypatch.setattr(patch, "cuda_activation_budget_bytes", lambda _device: int(29.5 * 1024**3)) + monkeypatch.setattr( + patch, + "tiling_config_for_vae", + lambda _checkpoint, **_kwargs: _tiles(frames=481, height=576, width=1024), + ) + monkeypatch.setattr(patch, "_orig_video_decoder_call", lambda _self, *args, **kwargs: (args, kwargs)) + + args, _kwargs = patch._patched_video_decoder_call( + _FakeDecoder(torch.device("cuda")), + torch.zeros(1, 128, 61, 18, 32), + object(), + ) + tiling = args[1] + assert tiling.width.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert tiling.frames.tile_size <= patch._MAX_DIFFVAE_TILE_FRAMES + + +def test_cuda_diffvae_clamps_full_frame_recommend_for_1080p_10s(monkeypatch) -> None: + monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: True) + monkeypatch.setattr(patch, "cuda_activation_budget_bytes", lambda _device: int(29.5 * 1024**3)) + monkeypatch.setattr( + patch, + "tiling_config_for_vae", + lambda _checkpoint, **_kwargs: _tiles(frames=241, height=1088, width=1920), + ) + monkeypatch.setattr(patch, "_orig_video_decoder_call", lambda _self, *args, **kwargs: (args, kwargs)) + + # 10s 1080p: 1920×1088×241 → latent 60×34×31 + args, _kwargs = patch._patched_video_decoder_call( + _FakeDecoder(torch.device("cuda")), + torch.zeros(1, 128, 31, 34, 60), + object(), + ) + tiling = args[1] + assert tiling.width.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert tiling.height.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert tiling.frames.tile_size <= patch._MAX_DIFFVAE_TILE_FRAMES + + def test_non_cuda_decoder_keeps_pipeline_tiling(monkeypatch) -> None: monkeypatch.setattr(patch, "tiling_config_for_vae", lambda *_args, **_kwargs: pytest.fail("should not re-resolve")) monkeypatch.setattr(patch, "_orig_video_decoder_call", lambda _self, *args, **kwargs: (args, kwargs)) @@ -149,6 +260,22 @@ def test_non_cuda_decoder_keeps_pipeline_tiling(monkeypatch) -> None: assert args[1] is old_tiling +def test_mps_diffvae_clamps_untiled_1080p_10s(monkeypatch) -> None: + monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: True) + monkeypatch.setattr(patch, "tiling_config_for_vae", lambda *_args, **_kwargs: pytest.fail("should not re-resolve")) + monkeypatch.setattr(patch, "_orig_video_decoder_call", lambda _self, *args, **kwargs: (args, kwargs)) + # 10s 1080p: 1920×1088×241 → latent 60×34×31 + args, _kwargs = patch._patched_video_decoder_call( + _FakeDecoder(torch.device("mps")), + torch.zeros(1, 128, 31, 34, 60), + _tiles(frames=0, height=0, width=0), + ) + tiling = args[1] + assert tiling.width.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert tiling.height.tile_size <= patch._MAX_DIFFVAE_TILE_SPATIAL + assert tiling.frames.tile_size <= patch._MAX_DIFFVAE_TILE_FRAMES + + def test_conv_vae_keeps_pipeline_tiling(monkeypatch) -> None: monkeypatch.setattr(patch, "is_diffusion_video_vae", lambda _path: False) monkeypatch.setattr(patch, "tiling_config_for_vae", lambda *_args, **_kwargs: pytest.fail("should not re-resolve")) diff --git a/backend/tests/test_diffvae_mps_tiling_budget.py b/backend/tests/test_diffvae_mps_tiling_budget.py deleted file mode 100644 index 1709cd2fd..000000000 --- a/backend/tests/test_diffvae_mps_tiling_budget.py +++ /dev/null @@ -1,104 +0,0 @@ -"""DiffVAE MPS tiling budget: upstream treats non-CUDA free_bytes as 0.""" - -from __future__ import annotations - -import torch -from ltx_core.tiling import DimensionSizeConfig, TileSizeConfig, split_by_size - -from services.ltx_pipeline_common import ( - diffvae_activation_budget_bytes, - host_available_bytes, - resolve_diffvae_free_bytes, -) -from services.patches.diffvae_mps_tiling_budget import _ensure_mps_width_split - - -def _size_config(*, width_size: int, width_overlap: int = 160) -> TileSizeConfig: - return TileSizeConfig( - frames=DimensionSizeConfig(tile_size=128, overlap=40), - height=DimensionSizeConfig(tile_size=576, overlap=160), - width=DimensionSizeConfig(tile_size=width_size, overlap=width_overlap), - ) - - -def _width_tiles(config: TileSizeConfig, width: int) -> int: - return len(split_by_size(config.width.tile_size, config.width.overlap)(width).intervals) - - -def test_host_available_bytes_is_positive() -> None: - assert host_available_bytes() > 0 - - -def test_cpu_budget_is_positive() -> None: - assert diffvae_activation_budget_bytes(torch.device("cpu")) > 0 - - -def test_unset_non_cuda_free_bytes_uses_available_ram() -> None: - budget = resolve_diffvae_free_bytes(torch.device("cpu"), None) - assert budget is not None and budget > 0 - - -def test_explicit_free_bytes_are_kept() -> None: - assert resolve_diffvae_free_bytes(torch.device("cpu"), 3 * 1024**3) == 3 * 1024**3 - - -def test_zero_non_cuda_free_bytes_are_replaced() -> None: - # Upstream's MPS path passes 0, which makes usable_bytes=0 and raises before decode. - budget = resolve_diffvae_free_bytes(torch.device("mps"), 0) - assert budget is not None and budget > 0 - - -def test_cuda_unset_budget_stays_none() -> None: - # Let tiling_config_for_vae call cuda_activation_budget_bytes itself. - assert resolve_diffvae_free_bytes(torch.device("cuda"), None) is None - - -def test_patch_rebinds_tiling_config_for_vae() -> None: - import services.patches.diffvae_mps_tiling_budget as patch - from ltx_pipelines.utils import helpers - - assert helpers.tiling_config_for_vae is patch._patched_tiling_config_for_vae - - -def test_mps_full_width_540p_becomes_two_width_tiles() -> None: - original = _size_config(width_size=1024) - clamped = _ensure_mps_width_split(original, width=1024, device=torch.device("mps")) - assert clamped.width.tile_size == 608 - assert clamped.width.overlap == 160 - assert _width_tiles(clamped, 1024) == 2 - assert clamped.height == original.height - assert clamped.frames == original.frames - - -def test_mps_already_split_width_is_unchanged() -> None: - original = _size_config(width_size=608) - clamped = _ensure_mps_width_split(original, width=1024, device=torch.device("mps")) - assert clamped is original - - -def test_cuda_full_width_is_unchanged() -> None: - original = _size_config(width_size=1024) - clamped = _ensure_mps_width_split(original, width=1024, device=torch.device("cuda")) - assert clamped is original - - -def test_mps_too_narrow_to_split_is_unchanged() -> None: - original = _size_config(width_size=320) - clamped = _ensure_mps_width_split(original, width=320, device=torch.device("mps")) - assert clamped is original - - -def test_patched_tiling_config_applies_mps_width_split(monkeypatch) -> None: - import services.patches.diffvae_mps_tiling_budget as patch - - monkeypatch.setattr(patch, "_orig_tiling_config_for_vae", lambda *args, **kwargs: _size_config(width_size=1024)) - config = patch._patched_tiling_config_for_vae( - "unused.safetensors", - height=576, - width=1024, - num_frames=121, - device=torch.device("mps"), - free_bytes=17 * 1024**3, - ) - assert config.width.tile_size == 608 - assert _width_tiles(config, 1024) == 2 diff --git a/backend/tests/test_disk_streaming_pread.py b/backend/tests/test_disk_streaming_pread.py new file mode 100644 index 000000000..3a11bb603 --- /dev/null +++ b/backend/tests/test_disk_streaming_pread.py @@ -0,0 +1,113 @@ +"""Disk streaming opens safetensors with the pread backend on Darwin only.""" + +from __future__ import annotations + +import logging +import sys +from pathlib import Path + +import pytest +import safetensors +import torch +from ltx_core.block_streaming.disk import DiskTensorReader +from safetensors.torch import save_file + +import services.patches.disk_streaming_pread as pread + + +@pytest.fixture(autouse=True) +def _restore_reader() -> None: + original = DiskTensorReader.__init__ + yield + DiskTensorReader.__init__ = original # type: ignore[method-assign] + pread._installed = False + pread._checked = False + pread._original_init = None + + +@pytest.fixture +def on_darwin(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sys, "platform", "darwin") + + +def test_disk_reader_passes_pread(tmp_path: Path, on_darwin: None) -> None: + path = tmp_path / "tiny.safetensors" + save_file({"weight": torch.ones(2, 2)}, str(path)) + pread.install() + seen: list[dict[str, object]] = [] + original_open = safetensors.safe_open + + def _spy(*args: object, **kwargs: object): + seen.append(dict(kwargs)) + return original_open(*args, **kwargs) + + safetensors.safe_open = _spy # type: ignore[assignment] + try: + reader = DiskTensorReader([str(path)]) + try: + torch.testing.assert_close(reader.get_tensor("weight"), torch.ones(2, 2)) + finally: + reader.close() + finally: + safetensors.safe_open = original_open + + assert seen == [{"framework": "pt", "device": "cpu", "backend": "pread"}] + + +def test_install_is_idempotent(on_darwin: None) -> None: + pread.install() + first = DiskTensorReader.__init__ + pread.install() + assert DiskTensorReader.__init__ is first + + +def test_install_leaves_mmap_when_backend_is_unsupported( + monkeypatch: pytest.MonkeyPatch, on_darwin: None +) -> None: + monkeypatch.setattr(pread.inspect, "signature", lambda _fn: type("Sig", (), {"parameters": {}})()) + before = DiskTensorReader.__init__ + pread.install() + assert DiskTensorReader.__init__ is before + assert pread._installed is False + assert pread._checked is True + + +def test_log_status_reports_pread_after_logging_is_configured( + caplog: pytest.LogCaptureFixture, on_darwin: None +) -> None: + pread.install() + with caplog.at_level(logging.INFO, logger=pread.logger.name): + pread.log_status() + assert "Disk streaming opens safetensors with backend=pread" in caplog.text + + +def test_log_status_reports_mmap_when_backend_is_unsupported( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture, on_darwin: None +) -> None: + monkeypatch.setattr(pread.inspect, "signature", lambda _fn: type("Sig", (), {"parameters": {}})()) + pread.install() + with caplog.at_level(logging.WARNING, logger=pread.logger.name): + pread.log_status() + assert "disk streaming stays on mmap" in caplog.text + assert "Darwin-only" not in caplog.text + + +@pytest.mark.parametrize("platform", ["win32", "linux"]) +def test_install_is_noop_off_darwin(platform: str, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(sys, "platform", platform) + before = DiskTensorReader.__init__ + pread.install() + assert DiskTensorReader.__init__ is before + assert pread._installed is False + assert pread._checked is True + + +def test_log_status_reports_darwin_only_skip( + monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setattr(sys, "platform", "win32") + pread.install() + with caplog.at_level(logging.INFO, logger=pread.logger.name): + pread.log_status() + assert "pread is Darwin-only" in caplog.text + assert "safetensors.safe_open has no backend" not in caplog.text diff --git a/backend/tests/test_distilled_a2v_image_crf.py b/backend/tests/test_distilled_a2v_image_crf.py index 75135f666..60d1f9ae3 100644 --- a/backend/tests/test_distilled_a2v_image_crf.py +++ b/backend/tests/test_distilled_a2v_image_crf.py @@ -9,7 +9,7 @@ from collections.abc import Sequence -from ltx_pipelines.utils.args import ImageConditioningInput as LtxImageInput +from ltx_pipelines.utils.types import ImageConditioningInput as LtxImageInput from services.a2v_pipeline.distilled_a2v_pipeline import resolve_image_conditionings _CHECKPOINT_CRF = 29 diff --git a/backend/tests/test_distilled_a2v_stages.py b/backend/tests/test_distilled_a2v_stages.py new file mode 100644 index 000000000..d932c791d --- /dev/null +++ b/backend/tests/test_distilled_a2v_stages.py @@ -0,0 +1,193 @@ +"""Distilled A2V stage flow against the real v1.4 latent and stage-call types. + +A2V has no GPU-free coverage of its two ``DiffusionStage`` calls. This drives +``DistilledA2VPipeline.__call__`` with a recording stage and the real latent +helpers, so a mis-sized latent changes a tensor shape here. + +The stage uses non-default scale factors on purpose. Sizing latents from the +decoder's tiling scale or from the module default would then give a different +shape and fail the assertions. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any, cast + +import pytest +import torch +from ltx_core.types import Audio, SpatioTemporalScaleFactors +from ltx_pipelines.utils.constants import STAGE_2_DISTILLED_SIGMA_VALUES + +from services.a2v_pipeline.distilled_a2v_pipeline import DistilledA2VPipeline + +# Not the module default (8x32x32) and not a 2.5 DiffVAE decoder scale (2x8x8). +_STAGE_SCALE = SpatioTemporalScaleFactors(time=4, height=16, width=16) +_CHANNELS = 128 +_FRAMES = 9 +_HEIGHT, _WIDTH = 576, 1024 +_SAMPLE_RATE = 16000 + + +class _State: + def __init__(self, latent: torch.Tensor) -> None: + self.latent = latent + + +class _Conditioner: + def resolve_crf(self, images): + return list(images) + + def __call__(self, build): + return build(object()) + + +def _pipeline(monkeypatch: pytest.MonkeyPatch) -> tuple[DistilledA2VPipeline, list[dict[str, Any]], list[torch.Tensor]]: + stage_calls: list[dict[str, Any]] = [] + upsampler_inputs: list[torch.Tensor] = [] + + monkeypatch.setattr( + "ltx_pipelines.utils.media_io.decode_audio_from_file", + lambda *_args, **_kwargs: Audio(torch.ones(1, 2, _SAMPLE_RATE * 2), _SAMPLE_RATE), + ) + + def stage(**kwargs: Any) -> tuple[_State, _State]: + stage_calls.append(kwargs) + modalities = kwargs["modalities"] + return _State(modalities.video.latent), _State(modalities.audio.latent) + + stage.video_scale_factors = _STAGE_SCALE # type: ignore[attr-defined] + + def upsampler(latent: torch.Tensor) -> torch.Tensor: + upsampler_inputs.append(latent) + return latent.repeat_interleave(2, dim=-2).repeat_interleave(2, dim=-1) + + def prompt_encoder(prompts: list[str]) -> tuple[Any]: + assert len(prompts) == 1 + return (SimpleNamespace(video_encoding="video-ctx", audio_encoding="audio-ctx"),) + + pipe = cast(DistilledA2VPipeline, object.__new__(DistilledA2VPipeline)) + pipe.device = torch.device("cpu") + pipe.dtype = torch.bfloat16 + pipe.prompt_encoder = prompt_encoder # type: ignore[assignment] + pipe.image_conditioner = _Conditioner() # type: ignore[assignment] + pipe.audio_conditioner = lambda _build: torch.zeros(1, 8, 4, 16) # type: ignore[assignment] + pipe.stage = stage # type: ignore[assignment] + pipe.upsampler = upsampler # type: ignore[assignment] + pipe.video_decoder = lambda latent, _tiling, _generator: latent # type: ignore[assignment] + return pipe, stage_calls, upsampler_inputs + + +def _run(pipe: DistilledA2VPipeline) -> tuple[Any, Audio]: + return pipe( # type: ignore[return-value] + prompt="a clip", + seed=3, + height=_HEIGHT, + width=_WIDTH, + num_frames=_FRAMES, + frame_rate=24.0, + images=[], + audio_path="speech.wav", + ) + + +def test_stage_1_latent_is_half_canvas_in_stage_geometry(monkeypatch: pytest.MonkeyPatch) -> None: + pipe, calls, _ = _pipeline(monkeypatch) + + _run(pipe) + + video = calls[0]["modalities"].video + frames = (_FRAMES - 1) // _STAGE_SCALE.time + 1 + expected = (1, _CHANNELS, frames, _HEIGHT // 2 // _STAGE_SCALE.height, _WIDTH // 2 // _STAGE_SCALE.width) + assert tuple(video.latent.shape) == expected + assert video.conditioning_fps == 24.0 + assert video.context == "video-ctx" + + +def test_stage_2_refines_the_upsampled_latent_at_the_first_stage_2_sigma(monkeypatch: pytest.MonkeyPatch) -> None: + pipe, calls, upsampler_inputs = _pipeline(monkeypatch) + + _run(pipe) + + assert len(calls) == 2 + stage_1_latent = calls[0]["modalities"].video.latent + assert upsampler_inputs[0].shape == stage_1_latent.shape + stage_2 = calls[1]["modalities"].video + assert tuple(stage_2.latent.shape[-2:]) == (stage_1_latent.shape[-2] * 2, stage_1_latent.shape[-1] * 2) + assert stage_2.noise_scale == pytest.approx(STAGE_2_DISTILLED_SIGMA_VALUES[0]) + assert torch.equal(calls[1]["sigmas"].cpu(), torch.tensor(STAGE_2_DISTILLED_SIGMA_VALUES)) + + +def test_audio_stays_frozen_and_unnoised_in_both_stages(monkeypatch: pytest.MonkeyPatch) -> None: + pipe, calls, _ = _pipeline(monkeypatch) + + _run(pipe) + + for call in calls: + audio = call["modalities"].audio + assert audio.frozen is True + assert audio.noise_scale == 0.0 + assert audio.context == "audio-ctx" + # Both stages read the same encoded audio latent. + assert calls[0]["modalities"].audio.latent is calls[1]["modalities"].audio.latent + + +def test_returns_the_source_audio_trimmed_to_the_video_duration(monkeypatch: pytest.MonkeyPatch) -> None: + pipe, _, _ = _pipeline(monkeypatch) + + _, audio = _run(pipe) + + assert audio.sampling_rate == _SAMPLE_RATE + assert audio.waveform.shape[-1] == round(_FRAMES / 24.0 * _SAMPLE_RATE) + assert torch.all(audio.waveform == 1) + + +def _target_audio_frames() -> int: + from ltx_core.types import AudioLatentShape + + return AudioLatentShape.from_duration(batch=1, duration=_FRAMES / 24.0, channels=8, mel_bins=16).frames + + +@pytest.mark.parametrize("delta", [-1, 0, 2], ids=["padded", "exact", "trimmed"]) +def test_audio_latent_is_padded_or_trimmed_to_the_video_duration(monkeypatch: pytest.MonkeyPatch, delta: int) -> None: + target = _target_audio_frames() + encoded_frames = target + delta + assert encoded_frames >= 1 + pipe, calls, _ = _pipeline(monkeypatch) + pipe.audio_conditioner = lambda _build: torch.ones(1, 8, encoded_frames, 16) # type: ignore[assignment] + + _run(pipe) + + latent = calls[0]["modalities"].audio.latent + assert tuple(latent.shape) == (1, 8, target, 16) + kept = min(encoded_frames, target) + assert torch.all(latent[:, :, :kept] == 1) + assert torch.all(latent[:, :, kept:] == 0) + + +def test_audio_window_arguments_reach_the_decoder(monkeypatch: pytest.MonkeyPatch) -> None: + pipe, _, _ = _pipeline(monkeypatch) + seen: list[tuple[Any, ...]] = [] + + def recording_decode(*args: Any, **_kwargs: Any) -> Audio: + seen.append(args) + return Audio(torch.ones(1, 2, _SAMPLE_RATE * 2), _SAMPLE_RATE) + + monkeypatch.setattr("ltx_pipelines.utils.media_io.decode_audio_from_file", recording_decode) + + pipe( + prompt="a clip", + seed=3, + height=_HEIGHT, + width=_WIDTH, + num_frames=_FRAMES, + frame_rate=24.0, + images=[], + audio_path="speech.wav", + audio_start_time=1.5, + audio_max_duration=4.0, + ) + + assert len(seen) == 1 + path, _device, start, max_duration = seen[0] + assert (path, start, max_duration) == ("speech.wav", 1.5, 4.0) diff --git a/backend/tests/test_distilled_keyframe_guiding.py b/backend/tests/test_distilled_keyframe_guiding.py index 1d2f4c186..0131b2e6b 100644 --- a/backend/tests/test_distilled_keyframe_guiding.py +++ b/backend/tests/test_distilled_keyframe_guiding.py @@ -4,22 +4,29 @@ import pytest -import ltx_pipelines.distilled as distilled +import ltx_pipelines.chunks.conditionings as chunk_conditionings +import ltx_pipelines.utils.helpers as helpers from ltx_pipelines.utils.helpers import image_conditionings_by_adding_guiding_latent from services.fast_video_pipeline.distilled_keyframe_guiding import distilled_keyframe_guiding -def test_guiding_context_swaps_distilled_combined_helper() -> None: - original = distilled.combined_image_conditionings +def test_guiding_context_swaps_combined_helper() -> None: + original_helpers = helpers.combined_image_conditionings + original_chunks = chunk_conditionings.combined_image_conditionings with distilled_keyframe_guiding(): - assert distilled.combined_image_conditionings is image_conditionings_by_adding_guiding_latent - assert distilled.combined_image_conditionings is original + assert helpers.combined_image_conditionings is image_conditionings_by_adding_guiding_latent + assert chunk_conditionings.combined_image_conditionings is image_conditionings_by_adding_guiding_latent + assert helpers.combined_image_conditionings is original_helpers + assert chunk_conditionings.combined_image_conditionings is original_chunks def test_guiding_context_restores_helper_after_exception() -> None: - original = distilled.combined_image_conditionings + original_helpers = helpers.combined_image_conditionings + original_chunks = chunk_conditionings.combined_image_conditionings with pytest.raises(RuntimeError, match="swap-failed"): with distilled_keyframe_guiding(): - assert distilled.combined_image_conditionings is image_conditionings_by_adding_guiding_latent + assert helpers.combined_image_conditionings is image_conditionings_by_adding_guiding_latent + assert chunk_conditionings.combined_image_conditionings is image_conditionings_by_adding_guiding_latent raise RuntimeError("swap-failed") - assert distilled.combined_image_conditionings is original + assert helpers.combined_image_conditionings is original_helpers + assert chunk_conditionings.combined_image_conditionings is original_chunks diff --git a/backend/tests/test_distilled_skip_stage_2.py b/backend/tests/test_distilled_skip_stage_2.py new file mode 100644 index 000000000..97536ce54 --- /dev/null +++ b/backend/tests/test_distilled_skip_stage_2.py @@ -0,0 +1,260 @@ +"""Stage-1-only Distilled decode stays at canvas/2 and does not upsample.""" + +from __future__ import annotations + +import inspect + +import pytest +import torch +from ltx_core.types import SpatioTemporalScaleFactors + +import ltx_pipelines.distilled as distilled +from ltx_pipelines.utils.types import PipelineOutput +from services.fast_video_pipeline.distilled_skip_stage_2 import DistilledPipelineWithSkipStage2 + + +class _Encoding: + video_encoding = None + audio_encoding = None + + +class _Conditioner: + def resolve_crf(self, images): + return images + + def __call__(self, build): + return build(object()) + + +class _LatentState: + def __init__(self, latent: torch.Tensor) -> None: + self.latent = latent + + +_DECODER_SCALE = object() +_TRANSFORMER_SCALE = object() + + +def _pipeline(monkeypatch, *, real_latents: bool = False, decoder_scale: object = _DECODER_SCALE, stage_scale: object = _TRANSFORMER_SCALE): + stage_pixels: list[tuple[int, int]] = [] + latent_scales: list[object] = [] + + def fake_combined(**kwargs): + return [] + + def fake_latents(*, width, height, frames, video_scale_factors, **_kwargs): + latent_scales.append(video_scale_factors) + video = torch.zeros(1, 4, frames, height, width) + audio = torch.zeros(1, 8, frames, 16) + return video, audio + + monkeypatch.setattr( + "services.fast_video_pipeline.distilled_skip_stage_2.ltx_helpers.combined_image_conditionings", + fake_combined, + ) + if not real_latents: + monkeypatch.setattr( + "services.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", + fake_latents, + ) + monkeypatch.setattr( + "services.fast_video_pipeline.distilled_skip_stage_2.tiling_scale_factors_for_vae", + lambda _path: decoder_scale, + ) + + pipe = DistilledPipelineWithSkipStage2.__new__(DistilledPipelineWithSkipStage2) + pipe.device = torch.device("cpu") + pipe.dtype = torch.bfloat16 + pipe.use_ancestral_sampler = False + pipe.duration_predictor = None + pipe.image_conditioner = _Conditioner() + + def prompt_encoder(*_args, **_kwargs): + return (_Encoding(),) + + def stage(**kwargs): + video = kwargs["modalities"].video + stage_pixels.append((video.latent.shape[-2], video.latent.shape[-1])) + return _LatentState(video.latent), _LatentState(video.latent.clone()) + + class _Decoder: + checkpoint_path = "unused" + diffvae_optimization = None + + def __call__(self, latent, _tiling, _generator, dtype=None): # noqa: ARG002 + del latent, dtype + height, width = stage_pixels[-1] + return torch.zeros(1, 3, 9, height, width) + + def audio_decoder(latent): # noqa: ARG001 + return None + + stage.video_scale_factors = stage_scale # type: ignore[attr-defined] + pipe.prompt_encoder = prompt_encoder + pipe.stage = stage + pipe.video_decoder = _Decoder() + pipe.audio_decoder = audio_decoder + return pipe, stage_pixels, latent_scales + + +# ltx-pipelines v1.4.x DistilledPipeline.__call__ (unchanged between 1.4.0 and 1.4.1). +_DISTILLED_CALL_PARAMS_V1_4 = ( + "self", + "prompt", + "seed", + "height", + "width", + "frame_rate", + "images", + "num_frames", + "vae_dtype", + "tiling_config", + "enhance_prompt", + "enhance_static_cache", + "stage_1_sigmas", + "stage_2_sigmas", + "color_space", + "generated_keyframes", + "decode_with_keyframes", + "chunk_config", +) + + +def test_distilled_call_signature_is_v1_4() -> None: + params = tuple(inspect.signature(distilled.DistilledPipeline.__call__).parameters) + assert params == _DISTILLED_CALL_PARAMS_V1_4 + + +def test_skip_stage_2_decodes_half_canvas_without_upsampling(monkeypatch) -> None: + pipe, stage_pixels, latent_scales = _pipeline(monkeypatch) + + output = pipe( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[], + num_frames=9, + tiling_config=None, + skip_stage_2=True, + ) + + assert output.num_frames == 9 + assert stage_pixels == [(288, 512)] + # Latents use the transformer's geometry. The decoder's tiling scale is a different + # (smaller) factor on the 2.5 DiffVAE and would allocate an oversized latent. + assert latent_scales == [_TRANSFORMER_SCALE] + + +def test_skip_stage_2_latent_shapes_follow_stage_geometry_not_decoder_geometry(monkeypatch) -> None: + """Real ``create_initial_av_latents``, with a decoder scale unlike the transformer's. + + A 2.5 DiffVAE decoder reports 2x8x8 while the transformer latent is 8x32x32. Sizing from + the decoder value would allocate an oversized latent and change these shapes. + """ + decoder = SpatioTemporalScaleFactors(time=2, height=8, width=8) + stage = SpatioTemporalScaleFactors(time=4, height=16, width=16) + pipe, _, _ = _pipeline(monkeypatch, real_latents=True, decoder_scale=decoder, stage_scale=stage) + seen: list[torch.Tensor] = [] + original_stage = pipe.stage + + def recording_stage(**kwargs): + seen.append(kwargs["modalities"].video.latent) + return original_stage(**kwargs) + + recording_stage.video_scale_factors = stage # type: ignore[attr-defined] + pipe.stage = recording_stage # type: ignore[assignment] + + pipe( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[], + num_frames=9, + tiling_config=None, + skip_stage_2=True, + ) + + # Half canvas is 288x512; (9 - 1) / 4 + 1 = 3 latent frames. + assert tuple(seen[0].shape[-3:]) == (3, 288 // stage.height, 512 // stage.width) + + +@pytest.mark.parametrize(("requested", "expected"), [(9, 9), (12, 9), (17, 17), (24, 17)]) +def test_skip_stage_2_snaps_frames_to_the_vae_grid(monkeypatch, requested: int, expected: int) -> None: + """Auto-duration can yield off-grid counts; upstream snaps them, so this path must too.""" + pipe, _, _ = _pipeline(monkeypatch) + frames_seen: list[int] = [] + + def recording_latents(*, width, height, frames, **_kwargs): + frames_seen.append(frames) + return torch.zeros(1, 4, 1, height, width), torch.zeros(1, 8, 1, 16) + + monkeypatch.setattr( + "services.fast_video_pipeline.distilled_skip_stage_2.create_initial_av_latents", + recording_latents, + ) + + output = pipe( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[], + num_frames=requested, + tiling_config=None, + skip_stage_2=True, + ) + + assert frames_seen == [expected] + assert output.num_frames == expected + + +def test_skip_stage_2_rejects_stage_2_and_chunking_arguments(monkeypatch) -> None: + pipe, _, _ = _pipeline(monkeypatch) + base = dict( + prompt="a clip", + seed=1, + height=576, + width=1024, + frame_rate=24, + images=[], + num_frames=9, + tiling_config=None, + skip_stage_2=True, + ) + + for ignored in ({"stage_2_sigmas": None}, {"decode_with_keyframes": True}, {"chunk_config": None}): + with pytest.raises(TypeError): + pipe(**base, **ignored) + + +def test_skip_stage_2_false_forwards_to_upstream(monkeypatch) -> None: + forwarded: dict[str, object] = {} + + def fake_call(self, *args, **kwargs): # noqa: ARG001 + forwarded["kwargs"] = kwargs + return PipelineOutput(torch.zeros(1, 3, 9, 8, 8), None, 9, None) + + monkeypatch.setattr(distilled.DistilledPipeline, "__call__", fake_call) + pipe = DistilledPipelineWithSkipStage2.__new__(DistilledPipelineWithSkipStage2) + + output = pipe( + prompt="a clip", + seed=1, + height=704, + width=1280, + frame_rate=24, + images=[], + num_frames=9, + tiling_config=None, + skip_stage_2=False, + ) + + assert "skip_stage_2" not in forwarded["kwargs"] + assert forwarded["kwargs"]["prompt"] == "a clip" + assert (forwarded["kwargs"]["height"], forwarded["kwargs"]["width"]) == (704, 1280) + assert tuple(output.video.shape) == (1, 3, 9, 8, 8) diff --git a/backend/tests/test_extend_edit_window.py b/backend/tests/test_extend_edit_window.py new file mode 100644 index 000000000..65f219d80 --- /dev/null +++ b/backend/tests/test_extend_edit_window.py @@ -0,0 +1,94 @@ +"""CPU-only checks for optional Home/Remote extend encode-window math. + +GenSpace keeps the uncapped full-source path. Home/Remote passes +``max_input_frames=505`` so the GPU only encodes a context window. +""" + +from __future__ import annotations + +import pytest + +from services.retake_pipeline.window import ( + MAX_INPUT_FRAMES, + duration_to_extend_frames, + window_for_extend, +) + + +def test_uncapped_window_encodes_the_whole_source() -> None: + window = window_for_extend( + source_frames=241, + extend_frames=96, + mode="end", + ) + assert window.context_frames == 241 + assert window.encode_start_frame == 0 + assert window.dropped_prefix_frames == 0 + assert window.dropped_suffix_frames == 0 + + +def test_end_extend_drops_a_prefix_when_source_plus_pad_exceeds_cap() -> None: + window = window_for_extend( + source_frames=1001, + extend_frames=96, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.context_frames + 96 <= MAX_INPUT_FRAMES + assert (window.context_frames - 1) % 8 == 0 + assert window.dropped_prefix_frames == 1001 - window.context_frames + assert window.encode_start_frame == window.dropped_prefix_frames + assert window.dropped_suffix_frames == 0 + + +def test_start_extend_drops_a_suffix_when_capped() -> None: + window = window_for_extend( + source_frames=1001, + extend_frames=96, + mode="start", + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.encode_start_frame == 0 + assert window.dropped_prefix_frames == 0 + assert window.dropped_suffix_frames == 1001 - window.context_frames + assert window.context_frames + 96 <= MAX_INPUT_FRAMES + + +def test_short_source_under_the_cap_is_not_trimmed() -> None: + window = window_for_extend( + source_frames=97, + extend_frames=96, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.context_frames == 97 + assert window.dropped_prefix_frames == 0 + + +def test_end_extend_keeps_non_8k1_remainder_in_the_dropped_prefix() -> None: + window = window_for_extend( + source_frames=32, + extend_frames=16, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.context_frames == 25 + assert window.dropped_prefix_frames == 7 + assert window.encode_start_frame == 7 + + +def test_extend_that_fills_the_cap_is_rejected() -> None: + with pytest.raises(ValueError, match="exceeds limit"): + window_for_extend( + source_frames=97, + extend_frames=MAX_INPUT_FRAMES, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + + +def test_duration_to_extend_frames_snaps_up_to_multiple_of_8() -> None: + assert duration_to_extend_frames(3.0, 24.0) == 72 + assert duration_to_extend_frames(3.1, 24.0) == 80 + assert duration_to_extend_frames(4.0, 24.0) == 96 + assert duration_to_extend_frames(4.0, 24.0) % 8 == 0 diff --git a/backend/tests/test_extend_frame_math.py b/backend/tests/test_extend_frame_math.py index cf9067c19..c44d72c74 100644 --- a/backend/tests/test_extend_frame_math.py +++ b/backend/tests/test_extend_frame_math.py @@ -1,8 +1,8 @@ """CPU-only checks for the extend latent/frame math. The local extend path runs on CUDA/MPS and isn't exercised by the integration -suite (which uses a fake pipeline). These guard the two pure pieces of logic that -the real wrapper depends on: temporal zero-padding and seconds -> frame snapping. +suite (which uses a fake pipeline). These guard audio latent zero-padding (video +now freeze-pads pixels before the VAE) and seconds -> frame snapping. """ from __future__ import annotations diff --git a/backend/tests/test_extend_stitch.py b/backend/tests/test_extend_stitch.py new file mode 100644 index 000000000..54771e823 --- /dev/null +++ b/backend/tests/test_extend_stitch.py @@ -0,0 +1,174 @@ +"""CPU-only checks for stitching original pixels back onto Home/Remote extend.""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest + +from services.retake_pipeline.window import MAX_FADE_FRAMES, MAX_INPUT_FRAMES, window_for_extend +from services.retake_pipeline.extend_stitch import fade_window_for_extend, stitch_extend_output +from services.retake_pipeline.rgb_stitch import FadeWindow, blend_rgb, generated_weight + + +def test_generated_weight_matches_ltxv_api_full_fade_bands() -> None: + window = FadeWindow(context_start=0, context_end=12, edit_start=5, edit_end=8) + expected = [0, 1 / 5, 2 / 5, 3 / 5, 4 / 5, 1, 1, 1, 3 / 4, 2 / 4, 1 / 4, 0] + assert [generated_weight(index, window) for index in range(12)] == pytest.approx(expected) + + +def test_generated_weight_clamps_when_context_gap_is_smaller_than_max_fade() -> None: + window = FadeWindow(context_start=0, context_end=8, edit_start=2, edit_end=5) + expected = [0, 1 / 2, 1, 1, 1, 2 / 3, 1 / 3, 0] + assert [generated_weight(index, window) for index in range(8)] == pytest.approx(expected) + + +def test_blend_rgb_is_identity_at_the_endpoints() -> None: + source = np.zeros((2, 2, 3), dtype=np.uint8) + generated = np.full((2, 2, 3), 30, dtype=np.uint8) + assert np.array_equal(blend_rgb(source, generated, 0.0), source) + assert np.array_equal(blend_rgb(source, generated, 1.0), generated) + assert blend_rgb(source, generated, 0.5)[0, 0, 0] == 15 + + +def test_end_extend_fade_window_starts_mask_delta_before_the_new_region() -> None: + window = window_for_extend( + source_frames=129, + extend_frames=104, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + fade = fade_window_for_extend(window, mode="end", extend_frames=104, fps=25.0) + assert fade.edit_start == 129 - 12 + assert fade.edit_end == 129 + 104 + assert min(MAX_FADE_FRAMES, fade.edit_start - fade.context_start) == MAX_FADE_FRAMES + + +def test_start_extend_fade_window_has_no_fade_in() -> None: + window = window_for_extend( + source_frames=129, + extend_frames=104, + mode="start", + max_input_frames=MAX_INPUT_FRAMES, + ) + fade = fade_window_for_extend(window, mode="start", extend_frames=104, fps=25.0) + assert fade.edit_start == 0 + assert generated_weight(0, fade) == 1.0 + assert generated_weight(fade.edit_end, fade) < 1.0 + + +def _solid_video(path: Path, *, rgb: tuple[int, int, int], frames: int, fps: int) -> str: + import imageio.v2 as imageio + + writer = imageio.get_writer(str(path), fps=fps, codec="libx264", macro_block_size=None) + frame = np.full((64, 64, 3), rgb, dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return str(path) + + +def test_stitch_extend_output_lerps_in_rgb_not_lutrgb(tmp_path: Path) -> None: + source = _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=25, fps=25) + generated = _solid_video(tmp_path / "generated.mp4", rgb=(30, 30, 30), frames=41, fps=25) + window = window_for_extend( + source_frames=25, + extend_frames=16, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + dest = tmp_path / "out.mp4" + stitch_extend_output( + source_path=source, + windowed_path=generated, + dest_path=str(dest), + window=window, + fps=25.0, + mode="end", + extend_frames=16, + target_width=64, + target_height=64, + ) + fade = fade_window_for_extend(window, mode="end", extend_frames=16, fps=25.0) + fade_in = min(MAX_FADE_FRAMES, fade.edit_start - fade.context_start) + fade_in_start = fade.edit_start - fade_in + with __import__("av").open(str(dest)) as container: + frames = [frame.to_ndarray(format="rgb24") for frame in container.decode(video=0)] + # First fade frame is pure source (weight 0). A later fade frame is in between. + assert frames[fade_in_start].mean() == pytest.approx(0, abs=8) + mid = fade_in_start + fade_in // 2 + assert 8 < frames[mid].mean() < 22 + assert frames[fade.edit_start].mean() == pytest.approx(30, abs=8) + + +def test_start_extend_lerps_after_the_generated_prefix(tmp_path: Path) -> None: + source = _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=25, fps=25) + generated = _solid_video(tmp_path / "generated.mp4", rgb=(30, 30, 30), frames=41, fps=25) + window = window_for_extend( + source_frames=25, + extend_frames=16, + mode="start", + max_input_frames=MAX_INPUT_FRAMES, + ) + dest = tmp_path / "out.mp4" + stitch_extend_output( + source_path=source, + windowed_path=generated, + dest_path=str(dest), + window=window, + fps=25.0, + mode="start", + extend_frames=16, + target_width=64, + target_height=64, + ) + fade = fade_window_for_extend(window, mode="start", extend_frames=16, fps=25.0) + with __import__("av").open(str(dest)) as container: + frames = [frame.to_ndarray(format="rgb24") for frame in container.decode(video=0)] + assert frames[0].mean() == pytest.approx(30, abs=8) + assert frames[fade.edit_end - 1].mean() == pytest.approx(30, abs=8) + assert frames[-1].mean() == pytest.approx(0, abs=8) + + +def test_stitch_extend_output_keeps_generated_audio_when_source_is_silent( + monkeypatch, tmp_path: Path +) -> None: + captured: list[list[str]] = [] + + def _capture(args: list[str], **_kwargs: object) -> None: + captured.append(args) + + monkeypatch.setattr("services.retake_pipeline.extend_stitch.run_ffmpeg", _capture) + monkeypatch.setattr( + "services.retake_pipeline.extend_stitch._has_audio", + lambda path: "generated" in path or "window" in path, + ) + source = _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=25, fps=25) + generated = _solid_video(tmp_path / "window.mp4", rgb=(30, 30, 30), frames=41, fps=25) + window = window_for_extend( + source_frames=25, + extend_frames=16, + mode="end", + max_input_frames=MAX_INPUT_FRAMES, + ) + stitch_extend_output( + source_path=source, + windowed_path=generated, + dest_path=str(tmp_path / "out.mp4"), + window=window, + fps=25.0, + mode="end", + extend_frames=16, + target_width=64, + target_height=64, + ) + assert len(captured) == 1 + args = captured[0] + assert "-c:v" in args and args[args.index("-c:v") + 1] == "copy" + assert "anullsrc=" in args[args.index("-i", args.index("-f")) + 1] + # anullsrc never ends: -shortest is an output option, so it must follow the last -i. + assert args.index("-shortest") > max(i for i, arg in enumerate(args) if arg == "-i") + assert "[3:a]" in args[args.index("-filter_complex") + 1] + assert "lutrgb=" not in args[args.index("-filter_complex") + 1] + assert "xfade=" not in args[args.index("-filter_complex") + 1] diff --git a/backend/tests/test_feature_flags.py b/backend/tests/test_feature_flags.py new file mode 100644 index 000000000..de5b0a178 --- /dev/null +++ b/backend/tests/test_feature_flags.py @@ -0,0 +1,70 @@ +"""Tests for /api/feature-flags on Desktop and Remote.""" + +from __future__ import annotations + +import json + +from starlette.testclient import TestClient + +from api_types import FeatureFlags, FeatureFlagsPatch +from remote.app import create_remote_app + +DEFAULTS = {"customIcLora": False, "advancedIcLoraControls": False} +AUTH = {"Authorization": "Bearer pair-token"} + + +def test_get_returns_defaults_without_file(client, test_state): + response = client.get("/api/feature-flags") + assert response.status_code == 200 + assert response.json() == DEFAULTS + assert not (test_state.config.app_data_dir / "feature_flags.json").exists() + + +def test_patch_merges_and_persists_to_file(client, test_state): + first = client.request("PATCH", "/api/feature-flags", json={"customIcLora": True}) + second = client.request("PATCH", "/api/feature-flags", json={"advancedIcLoraControls": True}) + + expected = {"customIcLora": True, "advancedIcLoraControls": True} + assert first.json() == {**DEFAULTS, "customIcLora": True} + assert second.json() == expected + assert client.get("/api/feature-flags").json() == expected + saved = test_state.config.app_data_dir / "feature_flags.json" + assert json.loads(saved.read_text(encoding="utf-8")) == expected + + +def test_patch_rejects_unknown_flag(client): + response = client.request("PATCH", "/api/feature-flags", json={"nope": True}) + assert response.status_code == 422 + + +def test_patch_null_leaves_flag_unchanged(client): + client.request("PATCH", "/api/feature-flags", json={"customIcLora": True}) + response = client.request("PATCH", "/api/feature-flags", json={"customIcLora": None}) + assert response.status_code == 200 + assert response.json() == {**DEFAULTS, "customIcLora": True} + + +def test_unreadable_file_falls_back_to_defaults(client, test_state): + # A directory at the file path raises OSError (not FileNotFoundError) on read. + (test_state.config.app_data_dir / "feature_flags.json").mkdir() + assert client.get("/api/feature-flags").json() == DEFAULTS + + +def test_corrupt_file_falls_back_to_defaults(client, test_state): + (test_state.config.app_data_dir / "feature_flags.json").write_text("{not json", encoding="utf-8") + assert client.get("/api/feature-flags").json() == DEFAULTS + + +def test_remote_serves_flags_with_bearer_only(test_state): + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + unauth = remote.get("/api/feature-flags") + patched = remote.request("PATCH", "/api/feature-flags", headers=AUTH, json={"customIcLora": True}) + read_back = remote.get("/api/feature-flags", headers=AUTH) + assert unauth.status_code == 401 + assert patched.status_code == 200 + assert read_back.json() == {**DEFAULTS, "customIcLora": True} + + +def test_patch_model_covers_every_flag(): + assert set(FeatureFlagsPatch.model_fields) == set(FeatureFlags.model_fields) diff --git a/backend/tests/test_finished_tray.py b/backend/tests/test_finished_tray.py new file mode 100644 index 000000000..b028cbd79 --- /dev/null +++ b/backend/tests/test_finished_tray.py @@ -0,0 +1,177 @@ +from services.generation_queue.finished_tray import FINISHED_TRAY_LIMIT, FinishedTray +from services.records import GenerationRecord, QueueGenerationRecord + + +def _entry( + generation_id: str, + status: str, + *, + feature: str = "text-to-video", + error_code: str | None = None, +) -> QueueGenerationRecord: + return QueueGenerationRecord( + generation=GenerationRecord( + id=generation_id, + feature=feature, + contract_version=1, + status=status, # type: ignore[arg-type] + spec={"params": {}, "inputs": {}}, + error_code=error_code, # type: ignore[arg-type] + created_at=1, + queued_at=1, + attempt_count=1, + started_at=1, + finished_at=2 if status in {"succeeded", "failed", "cancelled"} else None, + outputs=(), + ), + input_assets=(), + ) + + +def test_first_snapshot_does_not_backfill_history() -> None: + tray = FinishedTray() + tray.observe([_entry("job", "running")], lambda _generation_id: None) + + done, failed, unseen = tray.lists() + assert done == [] + assert failed == [] + assert unseen == [] + + +def test_departed_jobs_split_into_done_and_failed() -> None: + tray = FinishedTray() + running = _entry("job-a", "running") + failing = _entry("job-d", "running") + tray.observe([running, failing], lambda _generation_id: None) + + def load(generation_id: str) -> GenerationRecord: + if generation_id == "job-d": + return _entry("job-d", "failed", error_code="EXECUTOR_FAILED").generation + return _entry(generation_id, "succeeded").generation + + tray.observe([], load) + + done, failed, unseen = tray.lists() + assert [entry.generation.id for entry in done] == ["job-a"] + assert done[0].generation.status == "succeeded" + assert [entry.generation.id for entry in failed] == ["job-d"] + assert failed[0].generation.status == "failed" + assert unseen == ["job-a"] + + +def test_cancelled_and_cancelling_jobs_stay_out() -> None: + tray = FinishedTray() + tray.observe( + [_entry("cancelled", "running"), _entry("cancelling", "cancelling")], + lambda _generation_id: None, + ) + + def load(generation_id: str) -> GenerationRecord: + if generation_id == "cancelled": + return _entry("cancelled", "cancelled").generation + return _entry(generation_id, "succeeded").generation + + tray.observe([], load) + + done, failed, unseen = tray.lists() + assert done == [] + assert failed == [] + assert unseen == [] + + +def test_seen_dismiss_and_clear_are_shared_and_do_not_resurrect() -> None: + tray = FinishedTray() + tray.observe([_entry("job-a", "running")], lambda _generation_id: None) + tray.observe([], lambda _generation_id: _entry("job-a", "succeeded").generation) + assert tray.mark_seen("job-a") is True + assert tray.lists()[2] == [] + + assert tray.dismiss_done("job-a") is True + tray.observe([], lambda _generation_id: _entry("job-a", "succeeded").generation) + assert tray.lists()[0] == [] + assert tray.mark_seen("job-a") is False + assert tray.dismiss_done("job-a") is False + + +def test_clear_keeps_rows_the_caller_cannot_see() -> None: + tray = FinishedTray() + tray.remember(_entry("shown", "succeeded")) + tray.remember(_entry("hidden", "succeeded", feature="desktop-only")) + tray.remember(_entry("broken", "failed", error_code="EXECUTOR_FAILED")) + + tray.clear_done(lambda feature: feature == "text-to-video") + tray.clear_failed(lambda feature: feature == "text-to-video") + + done, failed, unseen = tray.lists() + assert [entry.generation.id for entry in done] == ["hidden"] + assert unseen == ["hidden"] + assert failed == [] + + +def test_retry_returns_to_the_tray_unseen() -> None: + tray = FinishedTray() + running = _entry("job", "running") + tray.observe([running], lambda _generation_id: None) + tray.observe( + [], + lambda _generation_id: _entry( + "job", "failed", error_code="EXECUTOR_FAILED" + ).generation, + ) + + tray.observe([running], lambda _generation_id: None) + assert tray.lists() == ([], [], []) + + tray.observe([], lambda _generation_id: _entry("job", "succeeded").generation) + done, failed, unseen = tray.lists() + assert [entry.generation.id for entry in done] == ["job"] + assert failed == [] + assert unseen == ["job"] + + +def test_stale_live_snapshot_does_not_resurrect_a_dismissed_row() -> None: + tray = FinishedTray() + running = _entry("job", "running") + tray.observe([running], lambda _generation_id: None) + tray.remember(_entry("job", "succeeded")) + assert tray.dismiss_done("job") is True + + tray.observe( + [running], + lambda _generation_id: _entry("job", "succeeded").generation, + ) + tray.observe([], lambda _generation_id: _entry("job", "succeeded").generation) + + assert tray.lists()[0] == [] + + +def test_release_lets_a_retried_completion_return_without_a_live_poll() -> None: + tray = FinishedTray() + tray.remember(_entry("job", "failed", error_code="EXECUTOR_FAILED")) + tray.clear_failed() + assert tray.lists()[1] == [] + + tray.release("job") + tray.remember(_entry("job", "succeeded")) + + done, failed, unseen = tray.lists() + assert [entry.generation.id for entry in done] == ["job"] + assert failed == [] + assert unseen == ["job"] + + +def test_tray_keeps_the_newest_completions() -> None: + tray = FinishedTray() + live = [_entry(f"job-{index}", "running") for index in range(FINISHED_TRAY_LIMIT + 1)] + tray.observe(live, lambda _generation_id: None) + tray.observe( + [], + lambda generation_id: _entry(generation_id, "succeeded").generation, + ) + + done, _failed, unseen = tray.lists() + assert [entry.generation.id for entry in done] == [ + f"job-{index}" for index in range(FINISHED_TRAY_LIMIT, 0, -1) + ] + assert unseen == [entry.generation.id for entry in done] + assert "job-0" not in unseen diff --git a/backend/tests/test_frame_math.py b/backend/tests/test_frame_math.py new file mode 100644 index 000000000..388dfde7b --- /dev/null +++ b/backend/tests/test_frame_math.py @@ -0,0 +1,56 @@ +"""Unit tests for shared video frame-count calculations.""" + +from frame_math import effective_a2v_audio_seconds, num_frames_for_audio_duration + + +def test_audio_duration_10_563_seconds_floors_to_249_frames_under_cap() -> None: + assert num_frames_for_audio_duration(10.563, 24, max_frames=481) == 249 + + +def test_audio_duration_10_563_seconds_reports_over_cap() -> None: + assert num_frames_for_audio_duration(10.563, 24, max_frames=241) is None + + +def test_audio_duration_5_seconds_floors_to_113_frames() -> None: + assert num_frames_for_audio_duration(5.0, 24, max_frames=481) == 113 + + +def test_20s_audio_at_a_10s_cell_keeps_the_opening_10s() -> None: + assert ( + effective_a2v_audio_seconds( + 20.0, + cell_max_seconds=10, + longest_cell_seconds=20, + ) + == 10.0 + ) + + +def test_audio_past_every_cell_stays_rejectable() -> None: + assert ( + effective_a2v_audio_seconds( + 20.1, + cell_max_seconds=10, + longest_cell_seconds=20, + ) + is None + ) + + +def test_audio_inside_the_cell_is_unchanged() -> None: + assert ( + effective_a2v_audio_seconds( + 10.563, + cell_max_seconds=20, + longest_cell_seconds=20, + ) + == 10.563 + ) + + +def test_audio_duration_2_seconds_is_minimum_aligned_grid() -> None: + frames = num_frames_for_audio_duration(2.0, 24, max_frames=481) + + assert frames is not None + assert frames >= 9 + assert (frames - 1) % 8 == 0 diff --git a/backend/tests/test_generate_video_request.py b/backend/tests/test_generate_video_request.py new file mode 100644 index 000000000..1fb6b40ca --- /dev/null +++ b/backend/tests/test_generate_video_request.py @@ -0,0 +1,54 @@ +from __future__ import annotations + +import pytest +from pydantic import ValidationError + +from api_types import GenerateVideoRequest + + +def _payload(**overrides: object) -> dict[str, object]: + payload: dict[str, object] = { + "prompt": "test", + "resolution": "540p", + "model": "fast", + "duration": 5, + "fps": 24, + } + payload.update(overrides) + return payload + + +def test_generate_video_request_strips_whitespace_from_nonblank_prompt() -> None: + req = GenerateVideoRequest.model_validate(_payload(prompt=" fox ")) + assert req.prompt == "fox" + + +def test_generate_video_request_rejects_whitespace_only_prompt_without_image() -> None: + with pytest.raises(ValidationError): + GenerateVideoRequest.model_validate(_payload(prompt=" ")) + + +def test_generate_video_request_rejects_empty_prompt_without_image() -> None: + with pytest.raises(ValidationError): + GenerateVideoRequest.model_validate(_payload(prompt="")) + + +def test_generate_video_request_allows_blank_prompt_with_image() -> None: + req = GenerateVideoRequest.model_validate( + _payload(prompt="", imagePath="/tmp/start.png") + ) + assert req.prompt == "" + + +def test_generate_video_request_normalizes_whitespace_prompt_with_image_to_empty() -> None: + req = GenerateVideoRequest.model_validate( + _payload(prompt=" ", imagePath="/tmp/start.png") + ) + assert req.prompt == "" + + +def test_generate_video_request_strips_padded_prompt_with_image() -> None: + req = GenerateVideoRequest.model_validate( + _payload(prompt=" hello ", imagePath="/tmp/start.png") + ) + assert req.prompt == "hello" diff --git a/backend/tests/test_generation.py b/backend/tests/test_generation.py index d9da81e0f..9677d2fd1 100644 --- a/backend/tests/test_generation.py +++ b/backend/tests/test_generation.py @@ -2,6 +2,7 @@ from __future__ import annotations +import logging import threading from collections.abc import Callable from dataclasses import dataclass @@ -13,6 +14,7 @@ from api_types import ( LOCAL_MULTI_KEYFRAME_MAX_COUNT, GenerateImageRequest, + GenerateVideoCompleteResponse, GenerateVideoRequest, ) from frame_math import AutoDurationSpec, compute_num_frames @@ -23,6 +25,12 @@ from state.app_state_types import GpuSlot, VideoPipelineState from tests.http_error_assertions import assert_http_error from tests.fakes.services import FakeFastVideoPipeline +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + VIDEO_JOB_TOO_LARGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, +) @dataclass @@ -71,6 +79,7 @@ def _fake_running_generation_state(test_state) -> None: pipeline=pipeline, is_compiled=False, ltx_model_id="ltx-2.5-22b-distilled", + loading_mode="full_models_loading", ), ) test_state.generation.start_generation("running") @@ -148,6 +157,206 @@ def test_t2v_happy_path(self, client, test_state, fake_services, create_fake_mod pipeline = fake_services.fast_video_pipeline assert len(pipeline.generate_calls) == 1 + def test_generate_local_reserved_writes_to_caller_output_path( + self, test_state, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + reserved_path = tmp_path / "assets" / "queued.mp4" + reserved_path.parent.mkdir(parents=True) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + result = test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate(_T2V_JSON), + generation_id="reserved-1", + output_path=reserved_path, + local_model_id="ltx-2.5-22b-distilled", + ) + + assert isinstance(result, GenerateVideoCompleteResponse) + assert result.status == "complete" + assert result.video_path == str(reserved_path) + assert reserved_path.exists() + assert not Path(result.video_path).is_relative_to(test_state.config.outputs_dir) + assert fake_services.fast_video_pipeline.generate_calls[0]["output_path"] == str(reserved_path) + + def test_recipe_wrap_is_last_mutation_and_survives_api_encoding( + self, test_state, create_fake_model_files, tmp_path, monkeypatch + ): + # Verifies the recipe scaffold wrap is the *last* text mutation and reaches + # encoding intact on the API text-encoding path: resolve_for_generation + # returns the raw prompt with enhance_via_api=True, and the wrap must both + # prepend the scaffold and force enhance_via_api=False so /prompt-embedding + # can't paraphrase the style lock away. Captures the args that reach + # generate_video (the encoding boundary) and short-circuits there. + from services.features.lora_recipes import ( + get_lora_recipe, + make_recipe_prompt_wrap, + ) + + create_fake_model_files() + monkeypatch.setattr( + test_state.text, + "should_use_local_encoding", + lambda model_id=None: False, + ) + + captured: dict[str, object] = {} + + class _StopAfterCapture(Exception): + pass + + def _capture_generate_video(**kwargs: object) -> str: + captured["prompt"] = kwargs["prompt"] + captured["enhance_via_api"] = kwargs["enhance_via_api"] + raise _StopAfterCapture + + monkeypatch.setattr( + test_state.video_generation, "generate_video", _capture_generate_video + ) + + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + req = GenerateVideoRequest.model_validate(_T2V_JSON) + out = tmp_path / "assets" / "recipe.mp4" + out.parent.mkdir(parents=True) + shutdown = threading.Event() + + # Baseline: without a recipe wrap, the API path keeps enhance_via_api=True. + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(HTTPError): + test_state.video_generation.generate_local_reserved( + req, generation_id="no-wrap", output_path=out, + local_model_id="ltx-2.5-22b-distilled", + ) + assert captured["enhance_via_api"] is True + + captured.clear() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(HTTPError): + test_state.video_generation.generate_local_reserved( + req, + generation_id="with-wrap", + output_path=out, + prompt_wrap=make_recipe_prompt_wrap(recipe), + local_model_id="ltx-2.5-22b-distilled", + ) + prompt = captured["prompt"] + assert isinstance(prompt, str) + assert prompt.startswith("F3ltCut0u7 handcrafted felt") + assert captured["enhance_via_api"] is False + + def test_generate_local_reserved_override_loads_non_active_weights( + self, test_state, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + _enable_local_text_encoding(test_state) + test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + reserved_path = tmp_path / "assets" / "queued.mp4" + reserved_path.parent.mkdir(parents=True) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + result = test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate(_T2V_JSON), + generation_id="reserved-2.3", + output_path=reserved_path, + local_model_id="ltx-2.3-22b-distilled-1.1", + ) + + assert isinstance(result, GenerateVideoCompleteResponse) + assert result.status == "complete" + slot = test_state.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + + def test_generate_local_reserved_2_5_auto_duration_ignores_active_2_3_head( + self, test_state, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + _enable_local_text_encoding(test_state) + test_state.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + reserved_path = tmp_path / "assets" / "queued-auto-2.5.mp4" + reserved_path.parent.mkdir(parents=True) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + result = test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate({**_T2V_JSON, "duration": None}), + generation_id="reserved-2.5-auto", + output_path=reserved_path, + local_model_id="ltx-2.5-22b-distilled", + ) + + assert isinstance(result, GenerateVideoCompleteResponse) + call = fake_services.fast_video_pipeline.generate_calls[0] + assert call["num_frames"] == AutoDurationSpec(min_seconds=2, max_seconds=20) + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.3-22b-distilled-1.1" + + def test_generate_local_reserved_2_5_api_embeddings_ignore_active_2_3( + self, test_state, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + spec = get_ltx_model_spec("ltx-2.5-22b-distilled") + delete_cp_path(test_state.config.default_models_dir, spec.text_encoder_cp) + test_state.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + test_state.state.app_settings.ltx_api_key = "api-key" + test_state.state.app_settings.use_local_text_encoder = False + fake_services.text_encoder.encode_responses.append(_FakeEncodingResult()) + reserved_path = tmp_path / "assets" / "queued-api-2.5.mp4" + reserved_path.parent.mkdir(parents=True) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + result = test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate(_T2V_JSON), + generation_id="reserved-2.5-api", + output_path=reserved_path, + local_model_id="ltx-2.5-22b-distilled", + ) + + assert isinstance(result, GenerateVideoCompleteResponse) + assert fake_services.text_encoder.encode_calls[0]["api_model"] == spec.api_prompt_embedding_model + assert "ltx-2.5-22b-distilled" in fake_services.text_encoder.encode_calls[0]["checkpoint_path"] + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.3-22b-distilled-1.1" + + def test_ordinary_generate_output_path_stays_under_outputs_dir( + self, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + + result = test_state.video_generation.generate( + GenerateVideoRequest.model_validate(_T2V_JSON) + ) + + assert isinstance(result, GenerateVideoCompleteResponse) + assert result.status == "complete" + video_path = Path(result.video_path) + assert video_path.exists() + assert video_path.is_relative_to(test_state.config.outputs_dir) + assert fake_services.fast_video_pipeline.generate_calls[0]["output_path"] == str(video_path) + + def test_local_fast_generates_six_seconds_at_48_fps( + self, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + + result = test_state.video_generation.generate( + GenerateVideoRequest.model_validate({**_T2V_JSON, "duration": 6, "fps": 48}) + ) + + assert isinstance(result, GenerateVideoCompleteResponse) + call = fake_services.fast_video_pipeline.generate_calls[0] + assert call["frame_rate"] == 48 + assert call["num_frames"] == compute_num_frames(6, 48) + def test_t2v_auto_duration_on_2_5_forwards_envelope_range( self, client, test_state, fake_services, create_fake_model_files ): @@ -167,7 +376,30 @@ def test_t2v_auto_duration_on_2_5_forwards_envelope_range( assert r.status_code == 200 call = fake_services.fast_video_pipeline.generate_calls[0] - assert call["num_frames"] == AutoDurationSpec(min_seconds=5, max_seconds=20) + assert call["num_frames"] == AutoDurationSpec(min_seconds=2, max_seconds=20) + + def test_t2v_auto_duration_16gb_720p_caps_at_advertised_max( + self, client, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 16 + test_state.config.local_generations_mode = "streaming_models_loading" + + r = client.post( + "/api/generate", + json={ + "prompt": "A lighthouse keeper climbs the stairs", + "resolution": "720p", + "model": "fast", + "duration": None, + "fps": 24, + }, + ) + + assert r.status_code == 200 + call = fake_services.fast_video_pipeline.generate_calls[0] + assert call["num_frames"] == AutoDurationSpec(min_seconds=2, max_seconds=10) def test_t2v_auto_duration_rejected_on_2_3( self, client, test_state, create_fake_model_files @@ -235,9 +467,14 @@ def test_t2v_loras_forwarded_to_pipeline(self, client, test_state, fake_services def test_same_loras_reuse_loaded_pipeline(self, client, test_state, fake_services, create_fake_model_files, create_fake_lora): _install_local_2_3(test_state, create_fake_model_files) _enable_local_text_encoding(test_state) - test_state.state.app_settings.prompt_enhancer_enabled_t2v = False lora_ref = create_fake_lora("a.safetensors") - body = {**_T2V_JSON, "loras": [{"ref": lora_ref, "scale": 1.0}]} + # An already-enhanced prompt skips the enhancer, which would otherwise evict the + # resident video pipeline to claim its VRAM and defeat the reuse this asserts. + body = { + **_T2V_JSON, + "promptProvenance": "enhanced", + "loras": [{"ref": lora_ref, "scale": 1.0}], + } assert client.post("/api/generate", json=body).status_code == 200 assert client.post("/api/generate", json=body).status_code == 200 @@ -267,7 +504,6 @@ def test_video_vae_path_change_reloads_pipeline( ): create_fake_model_files() _enable_local_text_encoding(test_state) - test_state.state.app_settings.prompt_enhancer_enabled_t2v = False test_state.state.app_settings.use_conv_vae = False assert client.post("/api/generate", json=_T2V_JSON).status_code == 200 @@ -570,8 +806,8 @@ def test_local_resolutions_are_all_on_the_two_stage_grid( test_state.state.app_settings.active_ltx_model_id = model_id _enable_local_text_encoding(test_state) - for resolution in ("540p", "720p", "1080p"): - for aspect_ratio in ("16:9", "9:16"): + for resolution in ("270p", "360p", "540p", "720p", "1080p"): + for aspect_ratio in ("21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16"): fake_services.fast_video_pipeline.generate_calls.clear() r = client.post( "/api/generate", @@ -581,6 +817,7 @@ def test_local_resolutions_are_all_on_the_two_stage_grid( call = fake_services.fast_video_pipeline.generate_calls[0] assert call["width"] % 64 == 0, f"{model_id} {resolution} {aspect_ratio}: width {call['width']}" assert call["height"] % 64 == 0, f"{model_id} {resolution} {aspect_ratio}: height {call['height']}" + assert call["skip_stage_2"] is (resolution in ("270p", "360p")) def test_resolution_mapping_720p(self, client, test_state, fake_services, create_fake_model_files): create_fake_model_files() @@ -597,6 +834,7 @@ def test_resolution_mapping_720p(self, client, test_state, fake_services, create def test_locked_seed(self, client, test_state, fake_services, create_fake_model_files): create_fake_model_files() _enable_local_text_encoding(test_state) + test_state.config.dev_mode = True test_state.state.app_settings.seed_locked = True test_state.state.app_settings.locked_seed = 123 @@ -606,6 +844,24 @@ def test_locked_seed(self, client, test_state, fake_services, create_fake_model_ pipeline = fake_services.fast_video_pipeline assert pipeline.generate_calls[0]["seed"] == 123 + def test_unlocked_seed_is_fresh_for_each_dev_request( + self, client, test_state, fake_services, create_fake_model_files, monkeypatch + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.dev_mode = True + resolved_seeds = iter((101, 202)) + monkeypatch.setattr("handlers.base.random.randint", lambda _start, _end: next(resolved_seeds)) + + first = client.post("/api/generate", json=_T2V_JSON) + second = client.post("/api/generate", json=_T2V_JSON) + + assert first.status_code == 200 + assert second.status_code == 200 + seeds = [call["seed"] for call in fake_services.fast_video_pipeline.generate_calls] + assert len(seeds) == 2 + assert seeds == [101, 202] + def test_error_sets_generation_error(self, client, test_state, fake_services, create_fake_model_files): create_fake_model_files() _enable_local_text_encoding(test_state) @@ -657,8 +913,40 @@ def test_a2v_generation_happy_path(self, client, test_state, fake_services, crea call = pipeline.generate_calls[0] assert call["audio_path"] == str(audio_file) assert call["audio_start_time"] == 0.0 + # Direct /api/generate keeps legacy behavior: only queued A2V + # (persisted numFrames + probed audio metadata) passes a finite cap. assert call["audio_max_duration"] is None + def test_a2v_local_inference_emits_heartbeat_done( + self, client, test_state, create_fake_model_files, tmp_path, caplog + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + caplog.set_level(logging.INFO, logger="server_utils.heartbeat") + + r = client.post( + "/api/generate", + json={ + "prompt": "A music video", + "resolution": "540p", + "model": "fast", + "duration": 5, + "fps": 24, + "audioPath": str(audio_file), + }, + ) + + assert r.status_code == 200 + done_records = [ + record + for record in caplog.records + if record.name == "server_utils.heartbeat" + and "a2v inference done" in record.getMessage() + ] + assert len(done_records) == 1 + def test_a2v_loras_forwarded_to_pipeline(self, client, test_state, fake_services, create_fake_model_files, create_fake_lora, tmp_path): _install_local_2_3(test_state, create_fake_model_files) _enable_local_text_encoding(test_state) @@ -979,6 +1267,8 @@ def test_a2v_uses_resolution_map_on_2_5(self, client, test_state, fake_services, _write_test_wav(audio_file) for resolution, expected_w, expected_h in [ + ("270p", 576, 320), + ("360p", 704, 384), ("540p", 1024, 576), ("720p", 1280, 704), ("1080p", 1920, 1088), @@ -1068,7 +1358,12 @@ def test_a2v_forced_api_missing_key_returns_integrity_error(self, client, test_s }, ) - assert_http_error(r, status_code=400, code="PRO_API_KEY_REQUIRED") + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) def test_a2v_forced_api_cancelled_response(self, client, test_state, fake_services, tmp_path): test_state.config.local_generations_mode = "unsupported" @@ -1158,6 +1453,124 @@ def test_t2v_routes_to_ltx_api(self, client, test_state, fake_services): assert call["fps"] == 50.0 assert call["generate_audio"] is True assert call["camera_motion"] == "dolly_in" + assert call["enhance_prompt"] is True + + def test_t2v_sends_enhance_prompt_false_when_the_toggle_is_off(self, client, test_state, fake_services): + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + test_state.state.app_settings.prompt_enhancer_enabled = False + + r = client.post( + "/api/generate", + json={ + "prompt": "A mountain lake", + "resolution": "1080p", + "model": "pro-2.5", + "duration": 6, + "fps": 24, + }, + ) + + assert r.status_code == 200 + call = fake_services.ltx_api_client.text_to_video_calls[0] + assert call["enhance_prompt"] is False + + def test_t2v_sends_enhance_prompt_false_for_enhanced_provenance(self, client, test_state, fake_services): + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + + r = client.post( + "/api/generate", + json={ + "prompt": "already rewritten", + "promptProvenance": "enhanced", + "resolution": "1080p", + "model": "pro-2.5", + "duration": 6, + "fps": 24, + }, + ) + + assert r.status_code == 200 + call = fake_services.ltx_api_client.text_to_video_calls[0] + assert call["enhance_prompt"] is False + + def test_i2v_sends_enhance_prompt_true_by_default( + self, client, test_state, fake_services, make_test_image, tmp_path + ): + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post( + "/api/generate", + json={ + "prompt": "Animate this frame", + "resolution": "1080p", + "model": "pro-2.5", + "duration": 8, + "fps": 25, + "imagePath": str(image_path), + }, + ) + + assert r.status_code == 200 + call = fake_services.ltx_api_client.image_to_video_calls[0] + assert call["enhance_prompt"] is True + + def test_i2v_sends_enhance_prompt_false_when_the_toggle_is_off( + self, client, test_state, fake_services, make_test_image, tmp_path + ): + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + test_state.state.app_settings.prompt_enhancer_enabled = False + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post( + "/api/generate", + json={ + "prompt": "Animate this frame", + "resolution": "1080p", + "model": "pro-2.5", + "duration": 8, + "fps": 25, + "imagePath": str(image_path), + }, + ) + + assert r.status_code == 200 + call = fake_services.ltx_api_client.image_to_video_calls[0] + assert call["enhance_prompt"] is False + + def test_a2v_with_start_frame_sends_enhance_prompt_from_the_single_toggle( + self, client, test_state, fake_services, make_test_image, tmp_path + ): + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + test_state.state.app_settings.prompt_enhancer_enabled = False + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + image_path = tmp_path / "input.png" + image_path.write_bytes(make_test_image().getvalue()) + + r = client.post( + "/api/generate", + json={ + "prompt": "A music video with a still frame", + "resolution": "1080p", + "model": "pro", + "duration": 6, + "fps": 50, + "audioPath": str(audio_file), + "imagePath": str(image_path), + }, + ) + + assert r.status_code == 200 + call = fake_services.ltx_api_client.audio_to_video_calls[0] + assert call["enhance_prompt"] is False def test_t2v_routes_to_ltx_api_for_ltx_2_5_fast(self, client, test_state, fake_services): test_state.config.local_generations_mode = "unsupported" @@ -1309,6 +1722,7 @@ def test_i2v_routes_to_ltx_api_for_ltx_2_5_pro(self, client, test_state, fake_se assert call["model"] == "ltx-2-5-pro" assert call["resolution"] == "1920x1080" assert call["duration"] == 8.0 + assert call["enhance_prompt"] is True assert call["fps"] == 25.0 assert call["camera_motion"] == "jib_up" @@ -1492,7 +1906,12 @@ def test_missing_api_key_returns_integrity_error(self, client, test_state): }, ) - assert_http_error(r, status_code=400, code="PRO_API_KEY_REQUIRED") + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) def test_invalid_forced_resolution_rejected(self, client, test_state): test_state.config.local_generations_mode = "unsupported" @@ -1637,7 +2056,6 @@ def test_forced_api_surfaces_insufficient_funds_as_custom_402(self, client, test fake_services.ltx_api_client.raise_on_text_to_video = LTXAPIClientError( 402, 'LTX API generation failed (402): {"type":"error","error":{"type":"insufficient_funds_error","message":"Insufficient funds. Required: 36 cents"}}', - stage="generation", provider_error_type="insufficient_funds_error", provider_message="Insufficient funds. Required: 36 cents", request_id="req-123", @@ -1666,6 +2084,33 @@ def test_forced_api_surfaces_insufficient_funds_as_custom_402(self, client, test assert progress.status == "error" assert progress.phase == "error" + def test_forced_api_maps_rejected_key_to_one_code(self, client, test_state, fake_services): + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + fake_services.ltx_api_client.raise_on_text_to_video = LTXAPIClientError( + 401, + "LTX API generation failed (401): unauthorized", + ) + + r = client.post( + "/api/generate", + json={ + "prompt": "A city skyline", + "resolution": "1080p", + "model": "pro", + "duration": 6, + "fps": 25, + "audio": False, + }, + ) + + assert_http_error( + r, + status_code=401, + code="LTX_INVALID_API_KEY", + message="This LTX API key isn’t valid.", + ) + def test_invalid_camera_motion_rejected_with_422(self, client, test_state): test_state.config.local_generations_mode = "unsupported" test_state.state.app_settings.ltx_api_key = "api-key" @@ -2112,6 +2557,346 @@ def test_a2v_forced_api_passes_through_model_and_aspect(self, client, test_state assert call["model"] == "ltx-2-3-pro" +class TestVideoJobLoadMode: + def test_540p_5s_stays_full(self, client, test_state, fake_services, create_fake_model_files): + create_fake_model_files() + _enable_local_text_encoding(test_state) + assert test_state.config.local_generations_mode == "full_models_loading" + + r = client.post("/api/generate", json=_T2V_JSON) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count is None + assert test_state.config.local_generations_mode == "full_models_loading" + + def test_720p_20s_streams_without_flipping_process_mode( + self, client, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "720p", "duration": 20}, + ) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + def test_1080p_10s_streams(self, client, test_state, fake_services, create_fake_model_files): + create_fake_model_files() + _enable_local_text_encoding(test_state) + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "1080p", "duration": 10}, + ) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + def test_stream_only_process_never_full(self, client, test_state, fake_services, create_fake_model_files): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.local_generations_mode = "streaming_models_loading" + test_state.config.vram_gb = 24 + + r = client.post("/api/generate", json=_T2V_JSON) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + + def test_darwin_never_full(self, client, test_state, fake_services, create_fake_model_files): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.darwin_unified_memory = True + test_state.config.available_ram_gb = 128 + + r = client.post("/api/generate", json=_T2V_JSON) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + def test_darwin_m4_48gb_does_not_422_720p_20s( + self, client, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.darwin_unified_memory = True + # Free RAM on a 48 GB Mac, not total. Pre-fix 0.4× CUDA curve 422'd this job. + test_state.config.available_ram_gb = 20 + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "720p", "duration": 20}, + ) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + + def test_darwin_m4_48gb_does_not_422_1080p_10s( + self, client, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.darwin_unified_memory = True + test_state.config.available_ram_gb = 20 + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "1080p", "duration": 10}, + ) + + assert r.status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + + def test_cache_rebuilds_when_job_switches_to_stream( + self, client, test_state, fake_services, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + + assert client.post("/api/generate", json=_T2V_JSON).status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count is None + first_creates = fake_services.fast_video_pipeline.create_count + + assert client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "720p", "duration": 20}, + ).status_code == 200 + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + assert fake_services.fast_video_pipeline.create_count == first_creates + 1 + + def test_a2v_720p_20s_streams(self, client, test_state, fake_services, create_fake_model_files, tmp_path): + create_fake_model_files() + _enable_local_text_encoding(test_state) + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + + r = client.post( + "/api/generate", + json={ + **_T2V_JSON, + "resolution": "720p", + "duration": 20, + "audioPath": str(audio_file), + }, + ) + + assert r.status_code == 200 + assert fake_services.a2v_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + def test_job_too_large_returns_422(self, client, test_state, create_fake_model_files): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 8 + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "720p", "duration": 20}, + ) + assert_http_error( + r, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + + def test_360p_20s_on_8gb_budgets_the_half_canvas( + self, client, test_state, fake_services, create_fake_model_files + ): + # 360p is the 720p canvas with stage 2 skipped. 720p/20s 422s on 8 GB; + # budgeting the parent canvas would 422 this job too. + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 8 + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "360p", "duration": 20}, + ) + + assert r.status_code == 200 + call = fake_services.fast_video_pipeline.generate_calls[0] + assert call["width"] == 1280 + assert call["height"] == 704 + assert call["skip_stage_2"] is True + assert fake_services.fast_video_pipeline.last_streaming_prefetch_count == 2 + + def test_16gb_540p_20s_21_9_returns_422_while_16_9_runs( + self, client, test_state, fake_services, create_fake_model_files + ): + # 1024×576 estimates 14.17 GiB and fits. 1344×576 estimates 17.63 GiB. + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 16 + test_state.config.local_generations_mode = "streaming_models_loading" + + wide = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "540p", "duration": 20, "aspectRatio": "21:9"}, + ) + assert_http_error( + wide, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + assert fake_services.fast_video_pipeline.generate_calls == [] + + landscape = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "540p", "duration": 20, "aspectRatio": "16:9"}, + ) + assert landscape.status_code == 200 + + def test_16gb_720p_20s_returns_422(self, client, test_state, create_fake_model_files): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 16 + test_state.config.local_generations_mode = "streaming_models_loading" + + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "720p", "duration": 20}, + ) + assert_http_error( + r, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + + def test_job_too_large_does_not_run_local_enhance( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 16 + test_state.config.local_generations_mode = "streaming_models_loading" + calls = {"n": 0} + original = test_state.prompt_enhancement.enhance_for_generation + + def spy(*args, **kwargs): + calls["n"] += 1 + return original(*args, **kwargs) + + test_state.prompt_enhancement.enhance_for_generation = spy # type: ignore[method-assign] + r = client.post( + "/api/generate", + json={**_T2V_JSON, "resolution": "720p", "duration": 20}, + ) + assert_http_error( + r, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + assert calls["n"] == 0 + + def test_a2v_job_too_large_does_not_run_local_enhance( + self, client, test_state, create_fake_model_files, tmp_path + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.vram_gb = 16 + test_state.config.local_generations_mode = "streaming_models_loading" + audio_file = tmp_path / "test_audio.wav" + _write_test_wav(audio_file) + calls = {"n": 0} + original = test_state.prompt_enhancement.enhance_for_generation + + def spy(*args, **kwargs): + calls["n"] += 1 + return original(*args, **kwargs) + + test_state.prompt_enhancement.enhance_for_generation = spy # type: ignore[method-assign] + r = client.post( + "/api/generate", + json={ + **_T2V_JSON, + "resolution": "720p", + "duration": 20, + "audioPath": str(audio_file), + }, + ) + assert_http_error( + r, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + assert calls["n"] == 0 + + def test_generate_local_reserved_unsupported_is_not_job_too_large( + self, test_state, create_fake_model_files, tmp_path + ): + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.local_generations_mode = "unsupported" + reserved_path = tmp_path / "assets" / "queued.mp4" + reserved_path.parent.mkdir(parents=True) + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(HTTPError) as exc: + test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate(_T2V_JSON), + generation_id="reserved-unsupported", + output_path=reserved_path, + local_model_id="ltx-2.5-22b-distilled", + ) + assert exc.value.code == LOCAL_GENERATION_UNSUPPORTED + assert exc.value.detail == LOCAL_GENERATION_UNSUPPORTED_MESSAGE + assert "api" not in exc.value.detail.lower() + assert "resolution" not in exc.value.detail.lower() + + def test_generate_local_reserved_auto_duration_unsupported_is_not_a_crash( + self, test_state, create_fake_model_files, tmp_path + ): + """Auto reads the filtered local specs, which unsupported mode empties.""" + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.local_generations_mode = "unsupported" + reserved_path = tmp_path / "assets" / "queued-auto.mp4" + reserved_path.parent.mkdir(parents=True) + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(HTTPError) as exc: + test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate({**_T2V_JSON, "duration": None}), + generation_id="reserved-unsupported-auto", + output_path=reserved_path, + local_model_id="ltx-2.5-22b-distilled", + ) + assert exc.value.status_code == 422 + assert exc.value.code == LOCAL_GENERATION_UNSUPPORTED + + def test_generate_local_reserved_unsupported_is_not_rescued_by_an_ltx_key( + self, test_state, create_fake_model_files, tmp_path + ): + """This entry point never routes to the API, so a key cannot make it viable.""" + create_fake_model_files() + _enable_local_text_encoding(test_state) + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "ltx-key" + reserved_path = tmp_path / "assets" / "queued-keyed.mp4" + reserved_path.parent.mkdir(parents=True) + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(HTTPError) as exc: + test_state.video_generation.generate_local_reserved( + GenerateVideoRequest.model_validate(_T2V_JSON), + generation_id="reserved-unsupported-keyed", + output_path=reserved_path, + local_model_id="ltx-2.5-22b-distilled", + ) + assert exc.value.code == LOCAL_GENERATION_UNSUPPORTED + + class TestGenerateCancel: def test_cancel_active(self, client, test_state): _fake_running_generation_state(test_state) @@ -2221,13 +3006,49 @@ def test_models_specs_endpoint_returns_ordered_backend_specs(self, client): data = r.json() assert [item["pipeline"] for item in data["local_models"]] == ["fast"] assert data["local_models"][0]["spec"]["display_name"] == "LTX 2.5 Fast" - assert list(data["local_models"][0]["spec"]["supported_resolutions_durations"]["540p"]["fps_to_durations"].keys()) == ["24"] + assert data["downloaded_local_models"] == [] + local_t2v = data["local_models"][0]["spec"]["supported_resolutions_durations"] + assert list(local_t2v.keys()) == ["270p", "360p", "540p", "720p", "1080p"] + local_a2v = data["local_models"][0]["spec"]["a2v_supported_resolutions_durations"] + assert list(local_a2v.keys()) == ["270p", "360p", "540p", "720p", "1080p"] + for table in (local_t2v, local_a2v): + for cell in table.values(): + assert list(cell["fps_to_durations"].keys()) == ["24", "25", "48", "50"] + for fps in ("24", "25", "48", "50"): + assert local_t2v["270p"]["fps_to_durations"][fps] == [2, 3, 4, 5, 6, 8, 10, 20] + assert local_t2v["540p"]["fps_to_durations"][fps] == [2, 3, 4, 5, 6, 8, 10, 20] + assert local_a2v["540p"]["fps_to_durations"][fps] == [5, 6, 8, 10, 20] + assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10, 20] + assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 10] + assert local_a2v["1080p"]["fps_to_durations"]["24"] == [5, 10] + assert local_t2v["540p"]["aspect_ratios"] == ["21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16"] + assert local_a2v["540p"]["aspect_ratios"] == ["21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16"] assert [item["pipeline"] for item in data["api_models"]] == ["fast", "pro", "fast-2.5", "pro-2.5"] + api_models_by_pipeline = {item["pipeline"]: item for item in data["api_models"]} + assert api_models_by_pipeline["fast"]["spec"]["supported_resolutions_durations"]["1080p"]["aspect_ratios"] == [ + "16:9", + "9:16", + ] + assert api_models_by_pipeline["fast-2.5"]["spec"]["supported_resolutions_durations"]["1080p"]["aspect_ratios"] == [ + "16:9", + "3:2", + "1:1", + "9:16", + ] + assert api_models_by_pipeline["pro-2.5"]["spec"]["supported_resolutions_durations"]["1080p"]["aspect_ratios"] == [ + "16:9", + "3:2", + "1:1", + "9:16", + ] + assert api_models_by_pipeline["fast-2.5"]["spec"]["a2v_supported_resolutions_durations"]["1080p"]["aspect_ratios"] == [ + "16:9", + "9:16", + ] assert data["api_models"][0]["spec"]["supported_resolutions_durations"]["1080p"]["fps_to_durations"]["24"] == [ 2, 3, 4, 5, 6, 8, 10, 12, 14, 16, 18, 20, ] - api_models_by_pipeline = {item["pipeline"]: item for item in data["api_models"]} # A2V: none on fast; 720p–4K on pro/fast-2.5; 720p+1080p on pro-2.5 (no 48 fps). assert api_models_by_pipeline["fast"]["spec"]["a2v_supported_resolutions_durations"] is None assert list(api_models_by_pipeline["pro"]["spec"]["a2v_supported_resolutions_durations"].keys()) == [ @@ -2258,8 +3079,8 @@ def test_models_specs_endpoint_returns_ordered_backend_specs(self, client): assert local_caps["a2v"] is True assert local_caps["ic_lora"] is True assert local_caps["user_loras"] is True - assert local_caps["retake"] is False - assert local_caps["extend"] is False + assert local_caps["retake"] is True + assert local_caps["extend"] is True assert local_caps["multi_keyframe"] is True # No DurationHead on disk in this fixture — Auto stays off until that file is present. assert local_caps["auto_duration"] is False @@ -2275,6 +3096,51 @@ def test_models_specs_endpoint_returns_ordered_backend_specs(self, client): assert api_models_by_pipeline["pro-2.5"]["spec"]["capabilities"]["multi_keyframe"] is False assert api_models_by_pipeline["pro-2.5"]["spec"]["capabilities"]["auto_duration"] is True + def test_local_fast_16gb_hides_cells_generate_would_reject(self, client, test_state): + test_state.config.vram_gb = 16 + test_state.config.local_generations_mode = "streaming_models_loading" + local_t2v = client.get("/api/generate/models-specs").json()["local_models"][0]["spec"][ + "supported_resolutions_durations" + ] + assert local_t2v["540p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10, 20] + assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10] + assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5] + api_1080 = client.get("/api/generate/models-specs").json()["api_models"][0]["spec"][ + "supported_resolutions_durations" + ]["1080p"]["fps_to_durations"]["24"] + assert 20 in api_1080 + + def test_local_fast_24gb_keeps_1080p_10s(self, client, test_state): + test_state.config.vram_gb = 24 + test_state.config.local_generations_mode = "streaming_models_loading" + local_t2v = client.get("/api/generate/models-specs").json()["local_models"][0]["spec"][ + "supported_resolutions_durations" + ] + assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 10] + assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10, 20] + + def test_local_fast_darwin_20gib_keeps_ceiling(self, client, test_state): + test_state.config.darwin_unified_memory = True + test_state.config.available_ram_gb = 20 + test_state.config.local_generations_mode = "streaming_models_loading" + local_t2v = client.get("/api/generate/models-specs").json()["local_models"][0]["spec"][ + "supported_resolutions_durations" + ] + assert local_t2v["720p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 6, 8, 10, 20] + assert local_t2v["1080p"]["fps_to_durations"]["24"] == [2, 3, 4, 5, 10] + + def test_local_fast_unsupported_is_empty(self, client, test_state): + test_state.config.local_generations_mode = "unsupported" + spec = client.get("/api/generate/models-specs").json()["local_models"][0]["spec"] + assert spec["supported_resolutions_durations"] == {} + assert spec["a2v_supported_resolutions_durations"] == {} + + def test_local_fast_never_advertises_1080p_20s(self, client): + local_t2v = client.get("/api/generate/models-specs").json()["local_models"][0]["spec"][ + "supported_resolutions_durations" + ] + assert 20 not in local_t2v["1080p"]["fps_to_durations"]["24"] + def test_local_auto_duration_requires_duration_head_on_disk(self, client, create_fake_model_files): create_fake_model_files() r = client.get("/api/generate/models-specs") @@ -2445,7 +3311,12 @@ def test_generate_image_missing_fal_key(self, client, test_state, fake_services) r = client.post("/api/generate-image", json={"prompt": "A cat"}) - assert_http_error(r, status_code=500, code="FAL_API_KEY_NOT_CONFIGURED") + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) def test_generate_image_cancelled(self, client, test_state, fake_services): test_state.config.local_generations_mode = "unsupported" @@ -2496,7 +3367,11 @@ def test_missing_image_prompt_rejected(self, client): class TestEnhancePromptFlag: - """Verify enhance_prompt is passed correctly to the text encoder API.""" + """Verify enhance_prompt is passed correctly to the text encoder API. + + Typed T2V prompts carry the flag by default (T2V toggle on). Provenance and the + T2V/I2V settings live in test_automatic_prompt_enhancement.py. + """ def _setup_api_encoding(self, test_state, fake_services, create_fake_model_files): create_fake_model_files(model_id=_API_ENCODING_MODEL_ID) @@ -2505,9 +3380,8 @@ def _setup_api_encoding(self, test_state, fake_services, create_fake_model_files test_state.state.app_settings.use_local_text_encoder = False fake_services.text_encoder.encode_responses.append(_FakeEncodingResult()) - def test_t2v_enhance_enabled(self, client, test_state, fake_services, create_fake_model_files): + def test_t2v_enhances_server_side(self, client, test_state, fake_services, create_fake_model_files): self._setup_api_encoding(test_state, fake_services, create_fake_model_files) - test_state.state.app_settings.prompt_enhancer_enabled_t2v = True r = client.post("/api/generate", json=_T2V_JSON) assert r.status_code == 200 @@ -2515,16 +3389,6 @@ def test_t2v_enhance_enabled(self, client, test_state, fake_services, create_fak assert len(fake_services.text_encoder.encode_calls) == 1 assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True - def test_t2v_enhance_disabled(self, client, test_state, fake_services, create_fake_model_files): - self._setup_api_encoding(test_state, fake_services, create_fake_model_files) - test_state.state.app_settings.prompt_enhancer_enabled_t2v = False - - r = client.post("/api/generate", json=_T2V_JSON) - assert r.status_code == 200 - - assert len(fake_services.text_encoder.encode_calls) == 1 - assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False - def test_empty_prompt_api_encoding_uses_placeholder( self, test_state, fake_services, create_fake_model_files ): @@ -2540,9 +3404,8 @@ def test_empty_prompt_api_encoding_uses_placeholder( assert fake_services.text_encoder.encode_calls[0]["prompt"] == " " # placeholder, not "" assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False # nothing to enhance - def test_i2v_enhance_enabled(self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path): + def test_i2v_enhances_server_side(self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path): self._setup_api_encoding(test_state, fake_services, create_fake_model_files) - test_state.state.app_settings.prompt_enhancer_enabled_i2v = True image_path = tmp_path / "input.png" image_path.write_bytes(make_test_image().getvalue()) @@ -2552,21 +3415,8 @@ def test_i2v_enhance_enabled(self, client, test_state, fake_services, create_fak assert len(fake_services.text_encoder.encode_calls) == 1 assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True - def test_i2v_enhance_disabled(self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path): + def test_a2v_without_image_enhances_server_side(self, client, test_state, fake_services, create_fake_model_files, tmp_path): self._setup_api_encoding(test_state, fake_services, create_fake_model_files) - test_state.state.app_settings.prompt_enhancer_enabled_i2v = False - image_path = tmp_path / "input.png" - image_path.write_bytes(make_test_image().getvalue()) - - r = client.post("/api/generate", json={**_T2V_JSON, "imagePath": str(image_path)}) - assert r.status_code == 200 - - assert len(fake_services.text_encoder.encode_calls) == 1 - assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is False - - def test_a2v_without_image_uses_t2v_setting(self, client, test_state, fake_services, create_fake_model_files, tmp_path): - self._setup_api_encoding(test_state, fake_services, create_fake_model_files) - test_state.state.app_settings.prompt_enhancer_enabled_t2v = True audio_file = tmp_path / "test_audio.wav" _write_test_wav(audio_file) @@ -2576,10 +3426,8 @@ def test_a2v_without_image_uses_t2v_setting(self, client, test_state, fake_servi assert len(fake_services.text_encoder.encode_calls) == 1 assert fake_services.text_encoder.encode_calls[0]["enhance_prompt"] is True - def test_a2v_with_image_uses_i2v_setting(self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path): + def test_a2v_with_image_enhances_server_side(self, client, test_state, fake_services, create_fake_model_files, make_test_image, tmp_path): self._setup_api_encoding(test_state, fake_services, create_fake_model_files) - test_state.state.app_settings.prompt_enhancer_enabled_i2v = True - test_state.state.app_settings.prompt_enhancer_enabled_t2v = False audio_file = tmp_path / "test_audio.wav" _write_test_wav(audio_file) image_path = tmp_path / "input.png" @@ -2598,7 +3446,6 @@ def test_local_encoding_skips_api(self, client, test_state, fake_services, creat create_fake_model_files() test_state.state.app_settings.ltx_api_key = "test-key" test_state.state.app_settings.use_local_text_encoder = True - test_state.state.app_settings.prompt_enhancer_enabled_t2v = True r = client.post("/api/generate", json=_T2V_JSON) assert r.status_code == 200 @@ -2609,15 +3456,13 @@ def test_local_encoding_skips_api(self, client, test_state, fake_services, creat class TestLocalEncodingEnhancement: """The rewrite that API encoding gets server-side has to happen here for local encoding. - Without it the enhancer setting silently does nothing whenever the local encoder is - selected, and the model sees the prompt exactly as typed. + Without it nothing rewrites the prompt whenever the local encoder is selected, and the model + sees the prompt exactly as typed. """ def _setup_local(self, test_state, create_fake_model_files, *, with_enhancer: bool): create_fake_model_files(include_prompt_enhancer=with_enhancer) test_state.state.app_settings.use_local_text_encoder = True - test_state.state.app_settings.prompt_enhancer_enabled_t2v = True - test_state.state.app_settings.prompt_enhancer_enabled_i2v = True def test_t2v_prompt_is_enhanced_before_it_reaches_the_pipeline( self, client, test_state, fake_services, create_fake_model_files @@ -2643,18 +3488,6 @@ def test_enhancer_runs_before_the_generation_is_marked_running( assert r.status_code == 200 assert len(fake_services.prompt_enhancer_pipeline.created_with) == 1 - def test_disabled_setting_leaves_the_prompt_alone( - self, client, test_state, fake_services, create_fake_model_files - ): - self._setup_local(test_state, create_fake_model_files, with_enhancer=True) - test_state.state.app_settings.prompt_enhancer_enabled_t2v = False - - r = client.post("/api/generate", json=_T2V_JSON) - assert r.status_code == 200 - - assert fake_services.prompt_enhancer_pipeline.enhance_t2v_calls == [] - assert fake_services.fast_video_pipeline.generate_calls[0]["prompt"] == "test" - def test_missing_enhancer_generates_with_the_prompt_as_typed( self, client, test_state, fake_services, create_fake_model_files ): @@ -2673,7 +3506,6 @@ def test_2_5_uses_gemma3_fallback_to_enhance_before_generate( create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" test_state.state.app_settings.use_local_text_encoder = True - test_state.state.app_settings.prompt_enhancer_enabled_t2v = True fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long descriptive caption" r = client.post("/api/generate", json=_T2V_JSON) @@ -2781,7 +3613,6 @@ def test_api_encoding_still_enhances_server_side( test_state.state.app_settings.active_ltx_model_id = _API_ENCODING_MODEL_ID test_state.state.app_settings.ltx_api_key = "test-key" test_state.state.app_settings.use_local_text_encoder = False - test_state.state.app_settings.prompt_enhancer_enabled_t2v = True fake_services.text_encoder.encode_responses.append(_FakeEncodingResult()) r = client.post("/api/generate", json=_T2V_JSON) diff --git a/backend/tests/test_generation_queue.py b/backend/tests/test_generation_queue.py new file mode 100644 index 000000000..6212a7555 --- /dev/null +++ b/backend/tests/test_generation_queue.py @@ -0,0 +1,2634 @@ +from __future__ import annotations + +import logging +import sqlite3 +import sys +import threading +import time +import wave +from collections.abc import Callable, Mapping +from contextlib import AbstractContextManager, nullcontext +from dataclasses import dataclass +from datetime import datetime, timezone +from pathlib import Path + +import pytest +from pydantic import JsonValue, ValidationError +from PIL import Image + +from _routes._errors import HTTPError +from api_types import ( + AudioToVideoParams, + GenerateVideoCompleteResponse, + GenerateVideoRequest, + GenerateVideoResponse, + GenerationErrorCode, +) +from frame_math import compute_num_frames +from services.analytics import AnalyticsService +from services.features.video import TextToVideoExecutor +from services.features.video.audio_to_video import AudioToVideoExecutor +from services.features.video.image_to_video import ImageToVideoExecutor +from services.features.video.text_to_video import ReservedVideoGenerator +from services.generation_queue.control import ( + SharedGenerationSlot, + cancel_queued_generation, +) +from services.generation_queue.registry import ExecutorRegistry +from services.generation_queue.runner import QueueRunner +from services.generation_queue.types import ( + GenerationExecutor, + OutputAllocation, + OutputPlan, +) +from services.media_probe import probe_file +from services.records import AttemptError, CapabilityFailedError, GenerationRecord +from services.sqlite_store import SqliteStore +from services.generation_interrupt import ( + GenerationCancelledError, + is_requested, + request, +) +from tests.fakes import FakeResponse +from tests.fakes.generation import FakeGenerationExecutor +from tests.fakes.services import FakeHTTPClient, FakeTaskRunner + + +class _SkipParamValidation: + def validate_params( + self, spec: Mapping[str, object], *, contract_version: int + ) -> None: + del spec, contract_version + + +def _spec(prompt: str) -> dict[str, JsonValue]: + return {"params": {"prompt": prompt, "model": "ltx-2.5-fast"}, "inputs": {}} + + +def _png(path: Path, size: tuple[int, int] = (16, 16)) -> Path: + Image.new("RGB", size, color=(1, 2, 3)).save(path) + return path + + +def _wav(path: Path, *, duration_seconds: float = 8.0) -> Path: + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * int(duration_seconds * 8000)) + return path + + +def _prompt(generation: GenerationRecord) -> object: + params = generation.spec.get("params") + if isinstance(params, dict): + return params.get("prompt") + return None + + +def _a2v_params(**overrides: JsonValue) -> dict[str, JsonValue]: + params: dict[str, JsonValue] = { + "prompt": "the character speaks", + "resolution": "540p", + "model": "ltx-2.5-fast", + "fps": 24, + "numFrames": 185, + } + params.update(overrides) + return params + + +def _generation( + *, + params: dict[str, JsonValue] | None = None, + inputs: dict[str, JsonValue] | None = None, + generation_id: str = "t2v-1", + feature: str = "text-to-video", + contract_version: int = 1, +) -> GenerationRecord: + return GenerationRecord( + id=generation_id, + feature=feature, + contract_version=contract_version, + status="running", + spec={ + "params": params + if params is not None + else {"prompt": "fox", "model": "ltx-2.5-fast"}, + "inputs": inputs if inputs is not None else {}, + }, + error_code=None, + created_at=1, + queued_at=1, + attempt_count=1, + started_at=1, + finished_at=None, + outputs=(), + ) + + +def _enable_local_t2v(test_state, create_fake_model_files) -> None: + create_fake_model_files() + test_state.state.app_settings.use_local_text_encoder = True + + +def make_runner( + test_state, + db: SqliteStore, + executor: GenerationExecutor, + *, + generation: SharedGenerationSlot | None = None, + stop_join_timeout_seconds: float = 600.0, +) -> QueueRunner: + return QueueRunner( + db=db, + generation=test_state.generation if generation is None else generation, + executors=ExecutorRegistry({"text-to-video": executor}), + stop_join_timeout_seconds=stop_join_timeout_seconds, + ) + + +_WAIT_UNTIL_TIMEOUT = 10.0 if sys.platform == "win32" else 3.0 + + +def wait_until( + predicate: Callable[[], bool], timeout: float = _WAIT_UNTIL_TIMEOUT +) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if predicate(): + return True + time.sleep(0.01) + return predicate() + + +_RUNNER_VIDEO_PLAN = OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", +) + + +class _OpenGenerationSlot: + def wait_for_generation_slot( + self, shutdown: threading.Event + ) -> AbstractContextManager[None]: + del shutdown + return nullcontext() + + def cancel_generation(self) -> object: + return None + + +class _PartialFailureExecutor(_SkipParamValidation): + def __init__(self) -> None: + self.output_path: str | None = None + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + del generation + self.output_path = outputs[0].dest_path + path = Path(self.output_path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"partial output") + raise RuntimeError("partial failure") + + +class _DelayedSuccessExecutor(_SkipParamValidation): + def __init__(self) -> None: + self.started = threading.Event() + self.release = threading.Event() + self.finished = threading.Event() + self.output_path: str | None = None + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.output_path = outputs[0].dest_path + self.started.set() + try: + if not self.release.wait(timeout=3.0): + raise RuntimeError("delayed executor was not released") + FakeGenerationExecutor().execute(generation, outputs) + finally: + self.finished.set() + + +class _BlockingFileWritingExecutor(_SkipParamValidation): + def __init__(self) -> None: + self.started = threading.Event() + self.release = threading.Event() + self.finished = threading.Event() + self.output_path: str | None = None + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + del generation + self.output_path = outputs[0].dest_path + path = Path(self.output_path) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"active output") + self.started.set() + try: + if not self.release.wait(timeout=3.0): + raise RuntimeError("blocking executor was not released") + raise GenerationCancelledError() + finally: + self.finished.set() + + +class _BlockingCancelSlot: + def __init__(self, inner: SharedGenerationSlot) -> None: + self._inner = inner + self.cancel_entered = threading.Event() + self.allow_cancel = threading.Event() + + def wait_for_generation_slot( + self, shutdown: threading.Event + ) -> AbstractContextManager[None]: + return self._inner.wait_for_generation_slot(shutdown) + + def cancel_generation(self) -> object: + self.cancel_entered.set() + if not self.allow_cancel.wait(timeout=3.0): + raise RuntimeError("cancel was not released") + return self._inner.cancel_generation() + + +class _BlockingClaimDb(SqliteStore): + def __init__(self, app_data_dir: Path) -> None: + super().__init__(app_data_dir) + self.claim_started = threading.Event() + self.allow_claim = threading.Event() + + def claim_next_queued(self) -> GenerationRecord | None: + self.claim_started.set() + if not self.allow_claim.wait(timeout=2.0): + raise RuntimeError("claim was not released") + return super().claim_next_queued() + + +class _BlockAfterClaimDb(SqliteStore): + def __init__(self, app_data_dir: Path) -> None: + super().__init__(app_data_dir) + self.claimed = threading.Event() + self.allow_continue = threading.Event() + + def claim_next_queued(self) -> GenerationRecord | None: + claimed = super().claim_next_queued() + if claimed is not None: + self.claimed.set() + if not self.allow_continue.wait(timeout=2.0): + raise RuntimeError("post-claim was not released") + return claimed + + +class _ClaimBeforeCancellationDb(SqliteStore): + def __init__(self, app_data_dir: Path) -> None: + super().__init__(app_data_dir) + self.claimed: GenerationRecord | None = None + + def request_generation_cancellation(self, generation_id: str) -> GenerationRecord: + self.claimed = super().claim_next_queued() + return super().request_generation_cancellation(generation_id) + + +class _ExecuteRecorder(_SkipParamValidation): + def __init__(self) -> None: + self.executed = threading.Event() + self.planned = threading.Event() + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + self.planned.set() + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.executed.set() + FakeGenerationExecutor().execute(generation, outputs) + + +class _FailingFinalizationDb(SqliteStore): + def __init__(self, app_data_dir: Path, failure: Exception) -> None: + super().__init__(app_data_dir) + self._failure: Exception | None = failure + + def mark_failed( + self, + generation_id: str, + error_code: GenerationErrorCode, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: + if self._failure is not None: + failure = self._failure + self._failure = None + raise failure + return super().mark_failed( + generation_id, + error_code, + partial_paths, + attempt_count=attempt_count, + ) + + +class _AlwaysFailingFinalizationDb(SqliteStore): + def __init__(self, app_data_dir: Path) -> None: + super().__init__(app_data_dir) + self.finalization_attempted = threading.Event() + + def mark_failed( + self, + generation_id: str, + error_code: GenerationErrorCode, + partial_paths: list[str] | None = None, + *, + attempt_count: int, + ) -> GenerationRecord: + self.finalization_attempted.set() + raise sqlite3.OperationalError("failure terminalization unavailable") + + +class _FailFirstExecutor(_SkipParamValidation): + def __init__(self) -> None: + self.execution_ids: list[str] = [] + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + self.execution_ids.append(generation.id) + if _prompt(generation) == "first": + raise RuntimeError("executor failed") + FakeGenerationExecutor().execute(generation, outputs) + + +class _DirectoryFailureExecutor(_SkipParamValidation): + def __init__(self) -> None: + self.partial_paths: dict[str, str] = {} + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + path = Path(outputs[0].dest_path) + if _prompt(generation) == "first": + path.mkdir() + self.partial_paths[generation.id] = str(path) + raise RuntimeError("executor failed after creating a directory") + FakeGenerationExecutor().execute(generation, outputs) + + +class _DeleteGenerationExecutor(_SkipParamValidation): + def __init__(self, db_path: Path) -> None: + self._db_path = db_path + self.output_path: str | None = None + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return (_RUNNER_VIDEO_PLAN,) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + FakeGenerationExecutor().execute(generation, outputs) + if _prompt(generation) != "vanish": + return + self.output_path = outputs[0].dest_path + conn = sqlite3.connect(str(self._db_path)) + try: + conn.execute("DELETE FROM generations WHERE id = ?", (generation.id,)) + conn.commit() + finally: + conn.close() + + +def test_runner_claims_and_succeeds_one_generation(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor()) + generation = db.insert_generation("text-to-video", _spec("fox")) + runner.start() + try: + runner.wake() + assert wait_until( + lambda: db.get_generation(generation.id).status == "succeeded" + ) + finally: + runner.stop() + + +class _OptionalOutputExecutor(_SkipParamValidation): + """Writes the required output. Writes the optional one only when asked to.""" + + def __init__(self, *, write_optional: bool) -> None: + self._write_optional = write_optional + + def plan_outputs(self, generation: GenerationRecord) -> tuple[OutputPlan, ...]: + del generation + return ( + OutputPlan(slot="main", media_kind="image", mime_type="image/png", name="main.png"), + OutputPlan( + slot="extra", + media_kind="image", + mime_type="image/png", + name="extra.png", + optional=True, + ), + ) + + def execute( + self, + generation: GenerationRecord, + outputs: tuple[OutputAllocation, ...], + ) -> None: + del generation + for output in outputs[: 2 if self._write_optional else 1]: + _png(Path(output.dest_path)) + + +@pytest.mark.parametrize(("write_optional", "expected_outputs"), [(True, 2), (False, 1)]) +def test_runner_leaves_out_an_optional_output_the_executor_did_not_write( + tmp_path: Path, write_optional: bool, expected_outputs: int +) -> None: + db = SqliteStore(tmp_path / "app_data") + runner = QueueRunner( + db=db, + generation=_OpenGenerationSlot(), + executors=ExecutorRegistry( + {"text-to-video": _OptionalOutputExecutor(write_optional=write_optional)} + ), + ) + generation = db.insert_generation("text-to-video", _spec("fox")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "succeeded") + loaded = db.get_generation(generation.id) + assert loaded is not None + assert len(loaded.outputs) == expected_outputs + assert all(Path(output.path).is_file() for output in loaded.outputs) + finally: + runner.stop() + + +def test_runner_fails_when_a_required_output_is_missing(tmp_path: Path) -> None: + class _WritesNothing(_OptionalOutputExecutor): + def execute(self, generation, outputs) -> None: + del generation, outputs + + db = SqliteStore(tmp_path / "app_data") + runner = QueueRunner( + db=db, + generation=_OpenGenerationSlot(), + executors=ExecutorRegistry({"text-to-video": _WritesNothing(write_optional=False)}), + ) + generation = db.insert_generation("text-to-video", _spec("fox")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + finally: + runner.stop() + + +def test_runner_names_output_from_prompt_slug(tmp_path: Path) -> None: + db = SqliteStore(tmp_path / "app_data") + runner = QueueRunner( + db=db, + generation=_OpenGenerationSlot(), + executors=ExecutorRegistry({"text-to-video": FakeGenerationExecutor()}), + ) + generation = db.insert_generation("text-to-video", _spec("Fox run")) + runner.start() + try: + runner.wake() + assert wait_until( + lambda: db.get_generation(generation.id).status == "succeeded" + ) + loaded = db.get_generation(generation.id) + assert loaded is not None + assert len(loaded.outputs) == 1 + name = loaded.outputs[0].name + assert name != "output.mp4" + stamp = datetime.fromtimestamp( + loaded.created_at / 1000, tz=timezone.utc + ).strftime("%Y%m%d-%H%M%S") + assert name == f"fox-run-{stamp}-{loaded.outputs[0].id[:6]}.mp4" + finally: + runner.stop() + + +def test_runner_processes_queued_generations_fifo(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + seen: list[str] = [] + runner = make_runner(test_state, db, FakeGenerationExecutor(seen_prompts=seen)) + first = db.insert_generation("text-to-video", _spec("first")) + second = db.insert_generation("text-to-video", _spec("second")) + runner.start() + try: + runner.wake() + assert wait_until( + lambda: all( + db.get_generation(generation.id).status == "succeeded" + for generation in (first, second) + ) + ) + assert seen == ["first", "second"] + finally: + runner.stop() + + +def test_runner_marks_executor_failure_without_retry(test_state, caplog) -> None: + caplog.set_level(logging.ERROR, logger="logging_policy") + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner( + test_state, db, FakeGenerationExecutor(error=RuntimeError("bad input")) + ) + generation = db.insert_generation("text-to-video", _spec("bad")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.attempt_count == 1 + assert loaded.error_code == "EXECUTOR_FAILED" + traceback_records = [ + record + for record in caplog.records + if record.name == "logging_policy" + and "generation-queue-runner" in record.getMessage() + and record.exc_info is not None + ] + assert len(traceback_records) == 1 + assert traceback_records[0].exc_info[0] is RuntimeError + finally: + runner.stop() + + +def test_runner_marks_unsupported_contract_version_as_executor_failure( + test_state, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner( + test_state, db, TextToVideoExecutor(test_state.video_generation) + ) + generation = db.insert_generation( + "text-to-video", _spec("fox"), contract_version=2 + ) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.error_code == "EXECUTOR_FAILED" + finally: + runner.stop() + + +def test_runner_cancellation_marks_generation_cancelled(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor(block=True)) + generation = db.insert_generation("text-to-video", _spec("stop")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "running") + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + assert cancelled.status == "cancelling" + assert wait_until( + lambda: db.get_generation(generation.id).status == "cancelled" + ) + finally: + request() + runner.stop() + + +def test_runner_leaves_queued_generation_when_shared_slot_is_busy(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor()) + generation = db.insert_generation("text-to-video", _spec("wait")) + assert test_state.generation.try_reserve_generation_start() is True + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "queued") + test_state.generation.release_generation_start_reservation() + assert wait_until( + lambda: db.get_generation(generation.id).status == "succeeded" + ) + finally: + runner.stop() + + +def test_runner_stops_without_claiming_new_work(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor()) + runner.start() + try: + runner.stop() + generation = db.insert_generation("text-to-video", _spec("after stop")) + runner.wake() + assert db.get_generation(generation.id).status == "queued" + finally: + runner.stop() + + +def test_runner_cleans_partial_output_when_executor_fails(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + executor = _PartialFailureExecutor() + runner = make_runner(test_state, db, executor) + generation = db.insert_generation("text-to-video", _spec("partial")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + assert executor.output_path is not None + assert wait_until(lambda: not Path(executor.output_path).exists()) + finally: + runner.stop() + + +def test_runner_cancel_queued_generation_does_not_request_global_interrupt( + test_state, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor()) + generation = db.insert_generation("text-to-video", _spec("queued stop")) + + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + + assert cancelled.status == "cancelled" + assert not is_requested() + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelled" + + +def test_cancel_running_generation_not_owned_by_runner_still_cancels( + test_state, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor()) + generation = db.insert_generation("text-to-video", _spec("other")) + claimed = db.claim_next_queued() + assert claimed is not None + assert claimed.id == generation.id + + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + + assert cancelled.status == "cancelling" + assert not is_requested() + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelling" + assert db.fail_running_on_boot() == 1 + assert db.get_generation(generation.id).status == "cancelled" + + +def test_runner_does_not_overwrite_command_cancellation(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + executor = _DelayedSuccessExecutor() + runner = make_runner(test_state, db, executor) + generation = db.insert_generation("text-to-video", _spec("cancelled")) + runner.start() + try: + runner.wake() + assert executor.started.wait(timeout=2.0) + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + assert cancelled.status == "cancelling" + executor.release.set() + assert wait_until( + lambda: ( + executor.finished.is_set() + and executor.output_path is not None + and db.get_generation(generation.id).status == "cancelled" + ), + timeout=3.0, + ) + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelled" + assert loaded.outputs == () + assert executor.output_path is not None + assert not Path(executor.output_path).exists() + finally: + executor.release.set() + runner.stop() + + +def test_runner_defers_active_output_cleanup_until_executor_unwinds(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + executor = _BlockingFileWritingExecutor() + runner = make_runner(test_state, db, executor) + generation = db.insert_generation("text-to-video", _spec("cancelled")) + runner.start() + try: + runner.wake() + assert executor.started.wait(timeout=2.0) + assert executor.output_path is not None + active_path = Path(executor.output_path) + assert active_path.is_file() + + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + + assert cancelled.status == "cancelling" + assert active_path.is_file() + assert executor.finished.is_set() is False + + executor.release.set() + assert wait_until( + lambda: executor.finished.is_set() and not active_path.exists(), + timeout=3.0, + ) + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelled" + finally: + executor.release.set() + runner.stop() + + +def test_runner_stops_while_waiting_for_shared_slot_without_failing_work( + test_state, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor()) + generation = db.insert_generation("text-to-video", _spec("shutdown")) + assert test_state.generation.try_reserve_generation_start() is True + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "queued") + runner.stop() + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "queued" + assert loaded.attempt_count == 0 + assert runner.is_running is False + finally: + runner.stop() + test_state.generation.release_generation_start_reservation() + + +def test_cancel_queued_does_not_wait_for_blocked_claim(test_state) -> None: + db = _BlockingClaimDb(test_state.config.app_data_dir) + runner = make_runner(test_state, db, FakeGenerationExecutor(block=True)) + generation = db.insert_generation("text-to-video", _spec("cancel")) + runner.start() + try: + runner.wake() + assert db.claim_started.wait(timeout=2.0) + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + assert cancelled.status == "cancelled" + assert not is_requested() + db.allow_claim.set() + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelled" + finally: + db.allow_claim.set() + request() + runner.stop() + + +def test_cancel_claimed_between_read_and_write_marks_running_attempt_cancelling( + test_state, +) -> None: + db = _ClaimBeforeCancellationDb(test_state.config.app_data_dir) + generation = db.insert_generation("text-to-video", _spec("cancel-race")) + interrupted: list[tuple[str, int]] = [] + + cancelled = cancel_queued_generation( + db, + generation.id, + lambda generation_id, attempt_count: interrupted.append( + (generation_id, attempt_count) + ), + ) + + assert db.claimed is not None + assert db.claimed.id == generation.id + assert cancelled.status == "cancelling" + assert cancelled.attempt_count == db.claimed.attempt_count + assert interrupted == [(generation.id, db.claimed.attempt_count)] + + +def test_cancel_after_claim_before_active_does_not_execute(test_state) -> None: + db = _BlockAfterClaimDb(test_state.config.app_data_dir) + executor = _ExecuteRecorder() + runner = make_runner(test_state, db, executor) + generation = db.insert_generation("text-to-video", _spec("cancel-after-claim")) + runner.start() + try: + runner.wake() + assert db.claimed.wait(timeout=2.0) + cancelled = cancel_queued_generation(db, generation.id, runner.interrupt) + assert cancelled.status == "cancelling" + assert not is_requested() + db.allow_continue.set() + assert wait_until( + lambda: db.get_generation(generation.id).status == "cancelled" + ) + assert executor.planned.is_set() is False + assert executor.executed.is_set() is False + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelled" + finally: + db.allow_continue.set() + runner.stop() + + +def test_cancel_after_claim_emits_a_paired_start_and_cancelled_end(test_state) -> None: + db = _BlockAfterClaimDb(test_state.config.app_data_dir) + http = FakeHTTPClient() + http.queue("post", FakeResponse(), FakeResponse()) + analytics = AnalyticsService( + http=http, + task_runner=FakeTaskRunner(), + sink_url="http://127.0.0.1:9/analytics", + token="sink-token", + ) + runner = QueueRunner( + db=db, + generation=test_state.generation, + executors=ExecutorRegistry({"text-to-video": _ExecuteRecorder()}), + analytics=analytics, + ) + spec = _spec("cancel-after-claim") + spec["_analytics"] = {"client": "desktop"} + generation = db.insert_generation("text-to-video", spec) + runner.start() + try: + runner.wake() + assert db.claimed.wait(timeout=2.0) + cancel_queued_generation(db, generation.id, runner.interrupt) + db.allow_continue.set() + assert wait_until( + lambda: (loaded := db.get_generation(generation.id)) is not None + and loaded.status == "cancelled" + ) + + payloads = [call.json_payload for call in http.calls] + assert [payload["eventName"] for payload in payloads if payload is not None] == [ + "generate_started", + "generate_ended", + ] + start = payloads[0] + end = payloads[1] + assert start is not None and end is not None + start_details = start["extraDetails"] + end_details = end["extraDetails"] + assert isinstance(start_details, dict) + assert isinstance(end_details, dict) + assert start_details["generation_id"] == generation.id + assert start_details["feature"] == "text-to-video" + assert set(end_details) == {"generation_id", "attempt", "outcome", "runtime_ms"} + assert end_details["generation_id"] == generation.id + assert end_details["attempt"] == start_details["attempt"] + assert end_details["outcome"] == "cancelled" + assert isinstance(end_details["runtime_ms"], int) + assert "prompt" not in start_details + finally: + db.allow_continue.set() + runner.stop() + + +def test_interrupt_holds_slot_until_cancel_generation_returns(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + executor = _DelayedSuccessExecutor() + slot = _BlockingCancelSlot(test_state.generation) + runner = make_runner(test_state, db, executor, generation=slot) + generation = db.insert_generation("text-to-video", _spec("hold-slot")) + cancel_thread: threading.Thread | None = None + runner.start() + try: + runner.wake() + assert executor.started.wait(timeout=2.0) + cancel_thread = threading.Thread( + target=cancel_queued_generation, + args=(db, generation.id, runner.interrupt), + ) + cancel_thread.start() + assert slot.cancel_entered.wait(timeout=2.0) + executor.release.set() + assert executor.finished.wait(timeout=2.0) + stolen = wait_until( + lambda: test_state.generation.try_reserve_generation_start(), + timeout=0.5, + ) + assert stolen is False + slot.allow_cancel.set() + cancel_thread.join(timeout=2.0) + assert cancel_thread.is_alive() is False + assert wait_until( + lambda: test_state.generation.try_reserve_generation_start() + ) + test_state.generation.release_generation_start_reservation() + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelled" + finally: + slot.allow_cancel.set() + executor.release.set() + if cancel_thread is not None: + cancel_thread.join(timeout=2.0) + runner.stop() + + +def test_stale_executor_write_after_retry_does_not_stop_new_attempt( + test_state, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + executor = _DelayedSuccessExecutor() + runner = make_runner(test_state, db, executor) + generation = db.insert_generation("text-to-video", _spec("retried")) + claimed = db.claim_next_queued() + assert claimed is not None + db.mark_failed( + generation.id, "EXECUTOR_FAILED", attempt_count=claimed.attempt_count + ) + retried = db.retry_generation(generation.id) + assert retried.status == "queued" + assert retried.attempt_count == claimed.attempt_count + 1 + + runner.start() + try: + runner.wake() + assert executor.started.wait(timeout=2.0) + with pytest.raises(AttemptError): + db.mark_failed( + generation.id, + "EXECUTOR_FAILED", + attempt_count=claimed.attempt_count, + ) + current = db.get_generation(generation.id) + assert current is not None + assert current.status == "running" + assert current.attempt_count == retried.attempt_count + 1 + executor.release.set() + assert wait_until( + lambda: db.get_generation(generation.id).status == "succeeded" + ) + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "succeeded" + assert loaded.attempt_count == retried.attempt_count + 1 + finally: + executor.release.set() + runner.stop() + + +def test_runner_marks_capability_failed_error(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner( + test_state, + db, + FakeGenerationExecutor( + error=CapabilityFailedError( + "no local model", + code="INVALID_VIDEO_GENERATION_SPEC", + ) + ), + ) + generation = db.insert_generation("text-to-video", _spec("caps")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.error_code == "CAPABILITY_FAILED" + finally: + runner.stop() + + +def test_runner_persists_rejected_ltx_api_key(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner( + test_state, + db, + FakeGenerationExecutor( + error=CapabilityFailedError( + "This LTX API key isn’t valid.", + code="LTX_INVALID_API_KEY", + ) + ), + ) + generation = db.insert_generation("text-to-video", _spec("rejected-key")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.error_code == "LTX_INVALID_API_KEY" + finally: + runner.stop() + + +def test_runner_persists_prompt_embedding_failure(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + runner = make_runner( + test_state, + db, + FakeGenerationExecutor( + error=CapabilityFailedError( + "LTX API text encoding failed.", + code="LTX_API_PROMPT_EMBEDDING_FAILED", + ) + ), + ) + generation = db.insert_generation("text-to-video", _spec("embedding-failed")) + runner.start() + try: + runner.wake() + assert wait_until(lambda: db.get_generation(generation.id).status == "failed") + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.error_code == "LTX_API_PROMPT_EMBEDDING_FAILED" + finally: + runner.stop() + + +@pytest.mark.parametrize( + "failure", + [ + sqlite3.OperationalError("database unavailable"), + OSError("asset cleanup unavailable"), + RuntimeError("unexpected finalization failure"), + ], +) +def test_runner_continues_after_terminalization_failure( + test_state, failure: Exception +) -> None: + db = _FailingFinalizationDb(test_state.config.app_data_dir, failure) + executor = _FailFirstExecutor() + runner = make_runner(test_state, db, executor) + first = db.insert_generation("text-to-video", _spec("first")) + second = db.insert_generation("text-to-video", _spec("second")) + runner.start() + try: + runner.wake() + + def second_succeeded() -> bool: + loaded = db.get_generation(second.id) + return loaded is not None and loaded.status == "succeeded" + + assert wait_until(second_succeeded) + first_loaded = db.get_generation(first.id) + assert first_loaded is not None + assert first_loaded.status == "running" + assert executor.execution_ids.count(first.id) == 1 + assert executor.execution_ids.count(second.id) == 1 + finally: + runner.stop() + + +def test_runner_start_does_not_fail_running_generations(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + generation = db.insert_generation("text-to-video", _spec("running")) + claimed = db.claim_next_queued() + assert claimed is not None + runner = make_runner(test_state, db, FakeGenerationExecutor()) + runner.start() + try: + loaded = db.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "running" + assert loaded.error_code is None + finally: + runner.stop() + + +def test_stale_running_row_is_failed_by_boot_recovery_not_runner_start( + test_state, +) -> None: + db = _AlwaysFailingFinalizationDb(test_state.config.app_data_dir) + executor = _FailFirstExecutor() + generation = db.insert_generation("text-to-video", _spec("first")) + runner = make_runner(test_state, db, executor) + runner.start() + try: + runner.wake() + assert db.finalization_attempted.wait(timeout=2.0) + runner.stop() + + stale = db.get_generation(generation.id) + assert stale is not None + assert stale.status == "running" + + runner.start() + still_running = db.get_generation(generation.id) + assert still_running is not None + assert still_running.status == "running" + assert executor.execution_ids == [generation.id] + + assert db.fail_running_on_boot() == 1 + recovered = db.get_generation(generation.id) + assert recovered is not None + assert recovered.status == "failed" + assert recovered.error_code == "INTERRUPTED" + assert executor.execution_ids == [generation.id] + finally: + runner.stop() + + +def test_runner_cleans_output_when_generation_row_disappears(test_state) -> None: + db = SqliteStore(test_state.config.app_data_dir) + executor = _DeleteGenerationExecutor( + test_state.config.app_data_dir / "store.sqlite3" + ) + runner = make_runner(test_state, db, executor) + vanished = db.insert_generation("text-to-video", _spec("vanish")) + next_generation = db.insert_generation("text-to-video", _spec("next")) + runner.start() + try: + runner.wake() + + def next_succeeded() -> bool: + loaded = db.get_generation(next_generation.id) + return loaded is not None and loaded.status == "succeeded" + + assert wait_until(next_succeeded) + assert db.get_generation(vanished.id) is None + assert executor.output_path is not None + assert not Path(executor.output_path).exists() + finally: + runner.stop() + + +def test_runner_continues_when_partial_directory_cleanup_fails( + test_state, caplog +) -> None: + caplog.set_level(logging.WARNING) + db = SqliteStore(test_state.config.app_data_dir) + executor = _DirectoryFailureExecutor() + runner = make_runner(test_state, db, executor) + first = db.insert_generation("text-to-video", _spec("first")) + second = db.insert_generation("text-to-video", _spec("second")) + runner.start() + try: + runner.wake() + + def second_succeeded() -> bool: + loaded = db.get_generation(second.id) + return loaded is not None and loaded.status == "succeeded" + + assert wait_until(second_succeeded) + first_loaded = db.get_generation(first.id) + assert first_loaded is not None + assert first_loaded.status == "failed" + partial_path = executor.partial_paths[first.id] + assert Path(partial_path).is_dir() + assert any( + "Could not remove partial output" in record.getMessage() + for record in caplog.records + ) + finally: + runner.stop() + + +@dataclass(frozen=True) +class _ReservedVideoCall: + request: GenerateVideoRequest + generation_id: str + output_path: Path | None + prompt_wrap: Callable[[str], str] | None = None + local_model_id: str | None = None + + +class _RecordingReservedVideoGenerator: + def __init__(self, inner: ReservedVideoGenerator) -> None: + self._inner = inner + self.calls: list[_ReservedVideoCall] = [] + + def validate_local_a2v_request( + self, params: AudioToVideoParams, audio_duration_ms: int + ) -> None: + self._inner.validate_local_a2v_request(params, audio_duration_ms) + + @property + def models_dir(self) -> Path: + models_dir = getattr(self._inner, "models_dir", None) + if not isinstance(models_dir, Path): + raise AttributeError("inner generator has no models_dir") + return models_dir + + def generate_local_reserved( + self, + req: GenerateVideoRequest, + *, + generation_id: str, + output_path: Path | None = None, + prompt_wrap: Callable[[str], str] | None = None, + a2v_num_frames: int | None = None, + a2v_audio_duration_seconds: float | None = None, + local_model_id: str | None = None, + ) -> GenerateVideoResponse: + self.calls.append( + _ReservedVideoCall( + request=req, + generation_id=generation_id, + output_path=output_path, + prompt_wrap=prompt_wrap, + local_model_id=local_model_id, + ) + ) + return self._inner.generate_local_reserved( + req, + generation_id=generation_id, + output_path=output_path, + prompt_wrap=prompt_wrap, + a2v_num_frames=a2v_num_frames, + a2v_audio_duration_seconds=a2v_audio_duration_seconds, + local_model_id=local_model_id, + ) + + +class _RecordingReservedVideoGeneratorStub: + def __init__( + self, + error: Exception | None = None, + *, + models_dir: Path | None = None, + ) -> None: + self.calls: list[_ReservedVideoCall] = [] + self._error = error + self.models_dir = models_dir if models_dir is not None else Path("/nonexistent-models-dir") + + def validate_local_a2v_request( + self, params: AudioToVideoParams, audio_duration_ms: int + ) -> None: + del params, audio_duration_ms + + def generate_local_reserved( + self, + req: GenerateVideoRequest, + *, + generation_id: str, + output_path: Path | None = None, + prompt_wrap: Callable[[str], str] | None = None, + a2v_num_frames: int | None = None, + a2v_audio_duration_seconds: float | None = None, + local_model_id: str | None = None, + ) -> GenerateVideoCompleteResponse: + del a2v_num_frames, a2v_audio_duration_seconds + self.calls.append( + _ReservedVideoCall( + request=req, + generation_id=generation_id, + output_path=output_path, + prompt_wrap=prompt_wrap, + local_model_id=local_model_id, + ) + ) + if self._error is not None: + raise self._error + return GenerateVideoCompleteResponse( + status="complete", + video_path=str(output_path) if output_path is not None else "", + ) + + +def _stub_reserved( + test_state, + create_fake_model_files, + error: Exception | None = None, +) -> _RecordingReservedVideoGeneratorStub: + create_fake_model_files() + return _RecordingReservedVideoGeneratorStub( + error=error, + models_dir=test_state.config.default_models_dir, + ) + + +def test_registry_resolves_text_to_video() -> None: + executor = FakeGenerationExecutor() + registry = ExecutorRegistry({"text-to-video": executor}) + assert registry.get("text-to-video") is executor + + +def test_registry_rejects_unknown_feature() -> None: + registry = ExecutorRegistry({"text-to-video": FakeGenerationExecutor()}) + with pytest.raises(ValueError, match="unknown generation feature: cozy-felt"): + registry.get("cozy-felt") + + +def test_text_to_video_plans_one_video_mp4_output(test_state) -> None: + executor = TextToVideoExecutor(test_state.video_generation) + assert executor.plan_outputs(_generation()) == ( + OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", + ), + ) + + +def test_text_to_video_rejects_invalid_params(test_state) -> None: + executor = TextToVideoExecutor(test_state.video_generation) + with pytest.raises(ValidationError): + executor.plan_outputs(_generation(params={"prompt": ""})) + with pytest.raises(ValidationError): + executor.plan_outputs( + _generation(params={"prompt": "fox", "imagePath": "/tmp/start.png"}) + ) + + +def test_text_to_video_rejects_unsupported_contract_version(test_state) -> None: + executor = TextToVideoExecutor(test_state.video_generation) + spec = {"params": {"prompt": "fox"}, "inputs": {}} + with pytest.raises(ValueError, match="contract_version"): + executor.validate_params(spec, contract_version=2) + with pytest.raises(ValueError, match="contract_version"): + executor.plan_outputs(_generation(contract_version=2)) + with pytest.raises(ValueError, match="contract_version"): + executor.execute(_generation(contract_version=2), ()) + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_text_to_video_rejects_pipeline_model_ids( + test_state, pipeline_id: str +) -> None: + executor = TextToVideoExecutor(test_state.video_generation) + with pytest.raises(ValidationError): + executor.plan_outputs( + _generation(params={"prompt": "fox", "model": pipeline_id}) + ) + + +def test_text_to_video_rejects_capability_invalid_params_before_pipeline( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + _enable_local_t2v(test_state, create_fake_model_files) + executor = TextToVideoExecutor(test_state.video_generation) + generation = _generation( + params={ + "prompt": "a red fox", + "model": "ltx-2.5-fast", + "resolution": "1080p", + "duration": 8, + "fps": 24, + } + ) + dest = tmp_path / "assets" / "invalid.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, outputs) + + assert exc_info.value.code == "INVALID_VIDEO_GENERATION_SPEC" + assert exc_info.value.detail == ( + "Unsupported local text-to-video duration '8' for pipeline 'fast' " + "at resolution '1080p' and fps '24'" + ) + assert fake_services.fast_video_pipeline.create_loras == [] + assert fake_services.fast_video_pipeline.generate_calls == [] + assert not dest.exists() + + +def test_text_to_video_maps_valid_params_to_generation_request( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + _enable_local_t2v(test_state, create_fake_model_files) + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = TextToVideoExecutor(recorder) + generation = _generation( + generation_id="t2v-mapped", + params={ + "prompt": "a red fox", + "resolution": "540p", + "model": "ltx-2.5-fast", + "duration": 8, + "fps": 24, + "seed": 12345, + }, + ) + dest = tmp_path / "assets" / "queued.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + assert dest.exists() + assert not dest.is_relative_to(test_state.config.outputs_dir) + assert len(recorder.calls) == 1 + captured = recorder.calls[0] + assert captured.request.prompt == "a red fox" + assert captured.request.resolution == "540p" + assert captured.request.duration == 8 + assert captured.request.fps == 24 + assert captured.request.model == "fast" + assert captured.local_model_id == "ltx-2.5-22b-distilled" + assert captured.request.seed == 12345 + assert captured.generation_id == "t2v-mapped" + assert captured.output_path == dest + call = fake_services.fast_video_pipeline.generate_calls[0] + assert (call["width"], call["height"]) == (1024, 576) + assert call["num_frames"] == compute_num_frames(8, 24) + assert call["frame_rate"] == 24 + assert call["output_path"] == str(dest) + + +def test_text_to_video_maps_structural_params_without_local_validation( + tmp_path: Path, +) -> None: + recorder = _RecordingReservedVideoGeneratorStub() + executor = TextToVideoExecutor(recorder) + generation = _generation( + generation_id="t2v-structural-mapping", + params={ + "prompt": "a blue fox", + "resolution": "720p", + "model": "ltx-2.3-fast", + "duration": 8, + "fps": 25, + "seed": 67890, + }, + ) + dest = tmp_path / "assets" / "stub.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, outputs) + + assert exc_info.value.code == "LTX_MODEL_NOT_INSTALLED" + assert recorder.calls == [] + assert not dest.exists() + + +def test_recipe_executor_forwards_studio_scaffold_wrap( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + from services.features.lora_recipes import get_lora_recipe, make_recipe_prompt_wrap + + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = TextToVideoExecutor(recorder, prompt_wrap=make_recipe_prompt_wrap(recipe)) + generation = _generation( + generation_id="cozy-felt-wrap", + params={ + "prompt": "a blue fox", + "model": "ltx-2.5-fast", + "resolution": "720p", + "duration": 8, + "fps": 24, + }, + ) + dest = tmp_path / "assets" / "felt.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + executor.execute(generation, outputs) + + assert len(recorder.calls) == 1 + wrap = recorder.calls[0].prompt_wrap + assert wrap is not None + # Post-enhance the executor wraps the user scene in the felt trigger + scaffold. + wrapped = wrap("a blue fox") + assert wrapped.startswith("F3ltCut0u7 handcrafted felt") + assert "a blue fox" in wrapped + + +def test_i2v_recipe_executor_forwards_scaffold_and_start_image( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + from runtime_config.model_download_specs import resolve_lora_path + from services.features.lora_recipes import ( + get_lora_recipe, + make_recipe_lora_resolver, + make_recipe_prompt_wrap, + ) + + recipe = get_lora_recipe("dolly-in") + assert recipe is not None + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "dolly-start.png"))) + recorder = _stub_reserved(test_state, create_fake_model_files) + resolved = resolve_lora_path( + test_state.config.default_models_dir, + "dolly-in", + "ltx-2-19b-lora-camera-control-dolly-in.safetensors", + ) + resolved.parent.mkdir(parents=True, exist_ok=True) + resolved.write_bytes(b"\x00" * 64) + executor = ImageToVideoExecutor( + recorder, + db, + prompt_wrap=make_recipe_prompt_wrap(recipe), + lora_resolver=make_recipe_lora_resolver( + recipe, + catalog=test_state._lora_catalog_provider, + models_dir=lambda: test_state.config.default_models_dir, + ), + ) + generation = _generation( + generation_id="dolly-in-wrap", + feature="dolly-in", + params={ + "prompt": "push in on her face", + "model": "ltx-2.5-fast", + "aspectRatio": "auto", + "resolution": "720p", + "duration": 8, + "fps": 24, + "loras": [{"ref": "", "scale": 1.0, "catalogId": "dolly-in"}], + }, + inputs={"startFrame": {"assetId": start.id}}, + ) + dest = tmp_path / "assets" / "dolly-in.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + executor.execute(generation, outputs) + + assert len(recorder.calls) == 1 + captured = recorder.calls[0] + assert captured.request.imagePath == start.path + wrap = captured.prompt_wrap + assert wrap is not None + wrapped = wrap("push in on her face") + assert wrapped.startswith("A smooth dolly-in camera move") + assert "push in on her face" in wrapped + assert captured.request.loras is not None + assert len(captured.request.loras) == 1 + assert captured.request.loras[0].catalogId == "dolly-in" + assert captured.request.loras[0].scale == 1.0 + assert captured.request.loras[0].ref == str(resolved) + assert captured.request.loras[0].ref != "" + + +def test_text_to_video_maps_2_3_offering_without_changing_active_settings( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = TextToVideoExecutor(recorder) + generation = _generation( + generation_id="t2v-offering-2.3", + params={ + "prompt": "a red fox", + "resolution": "540p", + "model": "ltx-2.3-fast", + "duration": 5, + "fps": 24, + }, + ) + dest = tmp_path / "assets" / "queued-2.3.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + captured = recorder.calls[0] + assert captured.request.model == "fast" + assert captured.local_model_id == "ltx-2.3-22b-distilled-1.1" + slot = test_state.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_image_to_video_rejects_pipeline_model_ids( + test_state, tmp_path: Path, pipeline_id: str +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + executor = ImageToVideoExecutor(test_state.video_generation, db) + with pytest.raises(ValidationError): + executor.plan_outputs( + _generation( + feature="image-to-video", + params={"prompt": "fox", "model": pipeline_id}, + inputs={"startFrame": {"assetId": start.id}}, + ) + ) + + +def test_image_to_video_maps_2_3_offering_without_changing_active_settings( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + generation_id="i2v-offering-2.3", + feature="image-to-video", + params={ + "prompt": "a red fox", + "resolution": "540p", + "model": "ltx-2.3-fast", + "duration": 5, + "fps": 24, + }, + inputs={"startFrame": {"assetId": start.id}}, + ) + dest = tmp_path / "assets" / "queued-i2v-2.3.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + captured = recorder.calls[0] + assert captured.request.model == "fast" + assert captured.request.imagePath == start.path + assert captured.local_model_id == "ltx-2.3-22b-distilled-1.1" + slot = test_state.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + + +def test_text_to_video_rejects_undownloaded_offering( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + test_state.state.app_settings.use_local_text_encoder = True + executor = TextToVideoExecutor(test_state.video_generation) + generation = _generation( + params={ + "prompt": "a red fox", + "model": "ltx-2.3-fast", + "resolution": "540p", + "duration": 5, + "fps": 24, + } + ) + dest = tmp_path / "assets" / "missing.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, outputs) + + assert exc_info.value.code == "LTX_MODEL_NOT_INSTALLED" + + +def test_image_to_video_maps_asset_ids_to_executor_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + end = db.ingest_upload(str(_png(tmp_path / "end.png"))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + generation_id="i2v-mapped", + feature="image-to-video", + params={"prompt": "", "model": "ltx-2.5-fast"}, + inputs={ + "startFrame": {"assetId": start.id}, + "endFrame": {"assetId": end.id}, + }, + ) + dest = tmp_path / "assets" / "i2v.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + executor.execute(generation, outputs) + + assert len(recorder.calls) == 1 + captured = recorder.calls[0] + assert captured.request.prompt == "" + assert captured.request.imagePath == start.path + assert captured.request.lastImagePath == end.path + assert captured.request.audio is False + assert captured.request.keyframes == [] + assert captured.generation_id == "i2v-mapped" + assert captured.output_path == dest + assert start.path not in str(generation.spec) + assert end.path not in str(generation.spec) + + +@pytest.mark.parametrize( + ("requested_ratio", "start_size", "expected_ratio"), + [ + ("auto", (32, 16), "16:9"), + ("auto", (16, 32), "9:16"), + ("auto", (32, 32), "1:1"), + ("16:9", (16, 32), "16:9"), + ("9:16", (32, 16), "9:16"), + ], +) +def test_image_to_video_resolves_auto_aspect_ratio_from_start_frame( + test_state, + create_fake_model_files, + tmp_path: Path, + requested_ratio: str, + start_size: tuple[int, int], + expected_ratio: str, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + # Windows rejects ':' in filenames (`16:9` would be an ADS path). + case_id = f"{requested_ratio.replace(':', '-')}-{start_size[0]}x{start_size[1]}" + start = db.ingest_upload(str(_png(tmp_path / f"start-{case_id}.png", start_size))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + feature="image-to-video", + params={"prompt": "fox", "model": "ltx-2.5-fast", "aspectRatio": requested_ratio}, + inputs={"startFrame": {"assetId": start.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / f"{case_id}.mp4"), + ) + + executor.execute(generation, (output,)) + + assert recorder.calls[0].request.aspectRatio == expected_ratio + assert generation.spec["params"] == { + "prompt": "fox", + "model": "ltx-2.5-fast", + "aspectRatio": requested_ratio, + } + + +def test_image_to_video_auto_on_api_only_resolution_is_a_capability_failure( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "start.png", (32, 32)))) + recorder = _RecordingReservedVideoGeneratorStub() + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + feature="image-to-video", + params={ + "prompt": "fox", + "model": "ltx-2.5-fast", + "aspectRatio": "auto", + "resolution": "1440p", + }, + inputs={"startFrame": {"assetId": start.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "i2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INVALID_LOCAL_RESOLUTION" + assert recorder.calls == [] + + +def test_image_to_video_rejects_non_image_asset( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "input.wav"))) + recorder = _RecordingReservedVideoGeneratorStub() + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + feature="image-to-video", + inputs={"startFrame": {"assetId": audio.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "i2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "startFrame image is no longer available" + assert audio.id not in exc_info.value.detail + assert audio.path not in exc_info.value.detail + assert recorder.calls == [] + + +def test_image_to_video_execute_rejects_unavailable_start_frame( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + Path(start.path).unlink() + recorder = _RecordingReservedVideoGeneratorStub() + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + feature="image-to-video", + inputs={"startFrame": {"assetId": start.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "i2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "startFrame image is no longer available" + assert start.id not in exc_info.value.detail + assert start.path not in exc_info.value.detail + assert "/" not in exc_info.value.detail + assert "\\" not in exc_info.value.detail + assert recorder.calls == [] + + +def test_image_to_video_execute_rejects_missing_start_frame_record( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + missing_id = "missing-start-frame" + recorder = _RecordingReservedVideoGeneratorStub() + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + feature="image-to-video", + inputs={"startFrame": {"assetId": missing_id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "i2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "startFrame image is no longer available" + assert missing_id not in exc_info.value.detail + assert recorder.calls == [] + + +def test_image_to_video_execute_hides_http_error_filesystem_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + leaked_path = "/secret/models/start.png" + recorder = _stub_reserved( + test_state, + create_fake_model_files, + error=HTTPError(400, f"Image file not found: {leaked_path}"), + ) + executor = ImageToVideoExecutor(recorder, db) + generation = _generation( + feature="image-to-video", + inputs={"startFrame": {"assetId": start.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "i2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "image input is no longer available" + assert leaked_path not in exc_info.value.detail + assert start.id not in exc_info.value.detail + assert start.path not in exc_info.value.detail + assert "/" not in exc_info.value.detail + assert "\\" not in exc_info.value.detail + assert len(recorder.calls) == 1 + + +def test_audio_to_video_maps_audio_asset_to_executor_path( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + generation_id="a2v-mapped", + feature="audio-to-video", + params=_a2v_params(), + inputs={"audio": {"assetId": audio.id}}, + ) + dest = tmp_path / "assets" / "a2v.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + executor.execute(generation, outputs) + + assert len(recorder.calls) == 1 + captured = recorder.calls[0] + assert captured.request.prompt == "the character speaks" + assert captured.request.audioPath == audio.path + assert captured.request.audio is True + assert captured.request.imagePath is None + assert captured.request.lastImagePath is None + assert captured.request.resolution == "540p" + assert captured.request.model == "fast" + assert captured.local_model_id == "ltx-2.5-22b-distilled" + assert captured.request.aspectRatio == "16:9" + assert captured.generation_id == "a2v-mapped" + assert captured.output_path == dest + assert audio.path not in str(generation.spec) + + +def test_audio_to_video_executes_advertised_1080p( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + test_state.state.app_settings.use_local_text_encoder = True + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav", duration_seconds=8.0))) + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + generation_id="a2v-1080p", + feature="audio-to-video", + params=_a2v_params(resolution="1080p", numFrames=185), + inputs={"audio": {"assetId": audio.id}}, + ) + dest = tmp_path / "assets" / "a2v-1080p.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + captured = recorder.calls[0] + assert captured.request.resolution == "1080p" + call = fake_services.a2v_pipeline.generate_calls[0] + assert call["audio_start_time"] == 0.0 + assert call["num_frames"] == 185 + + +def test_audio_to_video_hears_only_the_1080p_prefix_of_a_longer_clip( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + test_state.state.app_settings.use_local_text_encoder = True + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav", duration_seconds=20.0))) + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + generation_id="a2v-1080p-prefix", + feature="audio-to-video", + params=_a2v_params(resolution="1080p", numFrames=233), + inputs={"audio": {"assetId": audio.id}}, + ) + dest = tmp_path / "assets" / "a2v-1080p-prefix.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + call = fake_services.a2v_pipeline.generate_calls[0] + assert call["audio_start_time"] == 0.0 + assert call["num_frames"] == 233 + assert call["audio_max_duration"] == 10.0 + + +def test_audio_to_video_maps_2_3_offering_without_changing_active_settings( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.use_local_text_encoder = True + test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + generation_id="a2v-offering-2.3", + feature="audio-to-video", + params=_a2v_params(model="ltx-2.3-fast"), + inputs={"audio": {"assetId": audio.id}}, + ) + dest = tmp_path / "assets" / "a2v-2.3.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + captured = recorder.calls[0] + assert captured.request.model == "fast" + assert captured.local_model_id == "ltx-2.3-22b-distilled-1.1" + slot = test_state.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + + +def test_audio_to_video_maps_start_frame_to_image_path( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + generation_id="a2v-start", + feature="audio-to-video", + params=_a2v_params(prompt=""), + inputs={ + "audio": {"assetId": audio.id}, + "startFrame": {"assetId": start.id}, + }, + ) + dest = tmp_path / "assets" / "a2v-start.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + executor.execute(generation, outputs) + + assert len(recorder.calls) == 1 + captured = recorder.calls[0] + assert captured.request.prompt == "" + assert captured.request.audioPath == audio.path + assert captured.request.audio is True + assert captured.request.imagePath == start.path + assert captured.request.lastImagePath is None + assert captured.request.resolution == "540p" + assert captured.request.model == "fast" + assert captured.local_model_id == "ltx-2.5-22b-distilled" + assert captured.generation_id == "a2v-start" + assert captured.output_path == dest + assert audio.path not in str(generation.spec) + assert start.path not in str(generation.spec) + + +@pytest.mark.parametrize( + ("requested_ratio", "start_size", "expected_ratio"), + [ + ("auto", (32, 16), "16:9"), + ("auto", (16, 32), "9:16"), + ("auto", (32, 32), "1:1"), + ("16:9", (16, 32), "16:9"), + ("9:16", (32, 16), "9:16"), + ], +) +def test_audio_to_video_resolves_auto_aspect_ratio_from_start_frame( + test_state, + create_fake_model_files, + tmp_path: Path, + requested_ratio: str, + start_size: tuple[int, int], + expected_ratio: str, +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + case_id = f"{requested_ratio.replace(':', '-')}-{start_size[0]}x{start_size[1]}" + audio = db.ingest_upload(str(_wav(tmp_path / f"line-{case_id}.wav"))) + start = db.ingest_upload(str(_png(tmp_path / f"start-{case_id}.png", start_size))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(aspectRatio=requested_ratio), + inputs={ + "audio": {"assetId": audio.id}, + "startFrame": {"assetId": start.id}, + }, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / f"{case_id}.mp4"), + ) + + executor.execute(generation, (output,)) + + assert recorder.calls[0].request.aspectRatio == expected_ratio + assert generation.spec["params"]["aspectRatio"] == requested_ratio + + +def test_audio_to_video_auto_aspect_ratio_without_start_frame_uses_16_9( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + recorder = _stub_reserved(test_state, create_fake_model_files) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(aspectRatio="auto"), + inputs={"audio": {"assetId": audio.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v-auto.mp4"), + ) + + executor.execute(generation, (output,)) + + assert recorder.calls[0].request.aspectRatio == "16:9" + assert generation.spec["params"]["aspectRatio"] == "auto" + + +def test_audio_to_video_rejects_non_audio_asset( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + image = db.ingest_upload(str(_png(tmp_path / "start.png"))) + recorder = _RecordingReservedVideoGeneratorStub() + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={"audio": {"assetId": image.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "audio is no longer available" + assert image.id not in exc_info.value.detail + assert image.path not in exc_info.value.detail + assert recorder.calls == [] + + +def test_audio_to_video_rejects_non_image_start_frame( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + other_audio = db.ingest_upload(str(_wav(tmp_path / "other.wav"))) + recorder = _RecordingReservedVideoGeneratorStub() + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={ + "audio": {"assetId": audio.id}, + "startFrame": {"assetId": other_audio.id}, + }, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "startFrame image is no longer available" + assert other_audio.id not in exc_info.value.detail + assert other_audio.path not in exc_info.value.detail + assert recorder.calls == [] + + +def test_audio_to_video_execute_rejects_unavailable_audio( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + Path(audio.path).unlink() + recorder = _RecordingReservedVideoGeneratorStub() + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={"audio": {"assetId": audio.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "audio is no longer available" + assert audio.id not in exc_info.value.detail + assert audio.path not in exc_info.value.detail + assert "/" not in exc_info.value.detail + assert "\\" not in exc_info.value.detail + assert recorder.calls == [] + + +def test_audio_to_video_execute_rejects_unavailable_start_frame( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + start = db.ingest_upload(str(_png(tmp_path / "start.png"))) + Path(start.path).unlink() + recorder = _RecordingReservedVideoGeneratorStub() + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={ + "audio": {"assetId": audio.id}, + "startFrame": {"assetId": start.id}, + }, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "startFrame image is no longer available" + assert start.id not in exc_info.value.detail + assert start.path not in exc_info.value.detail + assert "/" not in exc_info.value.detail + assert "\\" not in exc_info.value.detail + assert recorder.calls == [] + + +def test_audio_to_video_execute_rejects_missing_audio_record( + test_state, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + missing_id = "missing-audio" + recorder = _RecordingReservedVideoGeneratorStub() + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={"audio": {"assetId": missing_id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "audio is no longer available" + assert missing_id not in exc_info.value.detail + assert recorder.calls == [] + + +def test_audio_to_video_execute_hides_http_error_filesystem_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + leaked_path = "/secret/models/line.wav" + recorder = _stub_reserved( + test_state, + create_fake_model_files, + error=HTTPError(400, f"Audio file not found: {leaked_path}"), + ) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={"audio": {"assetId": audio.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(generation, (output,)) + + assert exc_info.value.code == "INPUT_ASSET_NOT_FOUND" + assert exc_info.value.detail == "input media is no longer available" + assert "image" not in exc_info.value.detail + assert leaked_path not in exc_info.value.detail + assert audio.id not in exc_info.value.detail + assert audio.path not in exc_info.value.detail + assert "/" not in exc_info.value.detail + assert "\\" not in exc_info.value.detail + assert len(recorder.calls) == 1 + + +def test_audio_to_video_converts_cancelled_to_cancelled_error( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload(str(_wav(tmp_path / "line.wav"))) + recorder = _stub_reserved( + test_state, create_fake_model_files, error=GenerationCancelledError() + ) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + feature="audio-to-video", + params=_a2v_params(), + inputs={"audio": {"assetId": audio.id}}, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + + with pytest.raises(GenerationCancelledError): + executor.execute(generation, (output,)) + + +def test_audio_to_video_uses_local_a2v_pipeline_not_ltx_api( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + test_state.state.app_settings.use_local_text_encoder = True + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload( + str(_wav(tmp_path / "line.wav", duration_seconds=10.563)) + ) + recorder = _RecordingReservedVideoGenerator(test_state.video_generation) + executor = AudioToVideoExecutor(recorder, db) + generation = _generation( + generation_id="a2v-local", + feature="audio-to-video", + params=_a2v_params(numFrames=249), + inputs={"audio": {"assetId": audio.id}}, + ) + dest = tmp_path / "assets" / "a2v-local.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + executor.execute(generation, outputs) + + assert len(recorder.calls) == 1 + captured = recorder.calls[0] + assert captured.request.audioPath == audio.path + assert captured.request.audio is True + assert captured.request.imagePath is None + assert captured.request.lastImagePath is None + assert captured.request.resolution == "540p" + assert captured.request.model == "fast" + assert captured.local_model_id == "ltx-2.5-22b-distilled" + assert dest.exists() + assert fake_services.ltx_api_client.audio_to_video_calls == [] + assert len(fake_services.a2v_pipeline.generate_calls) == 1 + call = fake_services.a2v_pipeline.generate_calls[0] + assert call["audio_path"] == audio.path + assert call["num_frames"] == 249 + assert call["audio_max_duration"] == 10.563 + assert call["output_path"] == str(dest) + + +def test_audio_to_video_rejects_retried_job_with_stale_persisted_frames( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + db = SqliteStore(test_state.config.app_data_dir) + audio = db.ingest_upload( + str(_wav(tmp_path / "line.wav", duration_seconds=10.563)) + ) + executor = AudioToVideoExecutor(test_state.video_generation, db) + generation = db.insert_generation( + "audio-to-video", + { + "params": _a2v_params(numFrames=481), + "inputs": {"audio": {"assetId": audio.id}}, + }, + ) + plans = executor.plan_outputs(generation) + output = OutputAllocation( + plan=plans[0], + asset_id="asset-1", + dest_path=str(tmp_path / "assets" / "a2v.mp4"), + ) + claimed = db.claim_next_queued() + assert claimed is not None + db.mark_failed( + generation.id, + "EXECUTOR_FAILED", + attempt_count=claimed.attempt_count, + ) + retried = db.retry_generation(generation.id) + + with pytest.raises(CapabilityFailedError) as exc_info: + executor.execute(retried, (output,)) + + assert exc_info.value.code == "INVALID_VIDEO_GENERATION_SPEC" + assert exc_info.value.detail == ( + "Audio-to-video frame count no longer matches the selected audio." + ) + + +def test_text_to_video_requires_single_output_allocation( + test_state, tmp_path: Path +) -> None: + executor = TextToVideoExecutor(test_state.video_generation) + generation = _generation() + dest = tmp_path / "assets" / "wrong.mp4" + output_plan = OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", + ) + preview_plan = OutputPlan( + slot="preview", + media_kind="video", + mime_type="video/mp4", + name="preview.mp4", + ) + output = OutputAllocation(plan=output_plan, asset_id="asset-1", dest_path=str(dest)) + preview = OutputAllocation( + plan=preview_plan, asset_id="asset-2", dest_path=str(dest) + ) + match = "text-to-video requires a single 'output' allocation" + with pytest.raises(ValueError, match=match): + executor.execute(generation, ()) + with pytest.raises(ValueError, match=match): + executor.execute(generation, (output, output)) + with pytest.raises(ValueError, match=match): + executor.execute(generation, (preview,)) + + +def test_text_to_video_converts_cancelled_response_to_cancelled_error( + test_state, fake_services, create_fake_model_files, tmp_path: Path +) -> None: + _enable_local_t2v(test_state, create_fake_model_files) + fake_services.fast_video_pipeline.raise_on_generate = GenerationCancelledError() + executor = TextToVideoExecutor(test_state.video_generation) + generation = _generation() + dest = tmp_path / "assets" / "cancelled.mp4" + plans = executor.plan_outputs(generation) + outputs = ( + OutputAllocation(plan=plans[0], asset_id="asset-1", dest_path=str(dest)), + ) + + shutdown = threading.Event() + with test_state.generation.wait_for_generation_slot(shutdown): + with pytest.raises(GenerationCancelledError): + executor.execute(generation, outputs) + + +def test_fake_generation_executor_writes_valid_video(tmp_path: Path) -> None: + dest = tmp_path / "assets" / "out.mp4" + plan = OutputPlan( + slot="output", + media_kind="video", + mime_type="video/mp4", + name="output.mp4", + ) + FakeGenerationExecutor().execute( + _generation(), + (OutputAllocation(plan=plan, asset_id="asset-1", dest_path=str(dest)),), + ) + kind, mime_type, metadata = probe_file(dest) + assert kind == "video" + assert mime_type == "video/mp4" + assert metadata.mediaType == "video" + + +def test_fake_generation_executor_records_prompts_and_configured_error() -> None: + seen: list[str] = [] + executor = FakeGenerationExecutor( + seen_prompts=seen, error=RuntimeError("bad input") + ) + with pytest.raises(RuntimeError, match="bad input"): + executor.execute(_generation(params={"prompt": "first"}), ()) + assert seen == ["first"] + + +def test_fake_generation_executor_block_raises_after_interrupt() -> None: + executor = FakeGenerationExecutor(block=True) + started = threading.Event() + result: dict[str, BaseException] = {} + + def target() -> None: + started.set() + try: + executor.execute(_generation(), ()) + except BaseException as exc: + result["error"] = exc + + thread = threading.Thread(target=target) + thread.start() + assert started.wait(timeout=2.0) + request() + thread.join(timeout=2.0) + assert not thread.is_alive() + assert isinstance(result.get("error"), GenerationCancelledError) diff --git a/backend/tests/test_generation_seed.py b/backend/tests/test_generation_seed.py new file mode 100644 index 000000000..022837ca9 --- /dev/null +++ b/backend/tests/test_generation_seed.py @@ -0,0 +1,61 @@ +"""GET/POST /api/generation-seed: the one seed shared by Settings, forms, and the remote app.""" + +from __future__ import annotations + +from starlette.testclient import TestClient + +from remote.app import create_remote_app + +AUTH = {"Authorization": "Bearer pair-token"} + + +def test_post_seed_persists_to_the_settings_the_generators_read(client, test_state) -> None: + saved = client.post("/api/generation-seed", json={"seed": 777, "locked": True}) + + assert saved.status_code == 200 + assert saved.json() == {"seed": 777, "locked": True} + assert client.get("/api/generation-seed").json() == {"seed": 777, "locked": True} + assert test_state.state.app_settings.locked_seed == 777 + assert test_state.state.app_settings.seed_locked is True + + +def test_locking_alone_keeps_the_seed(client, test_state) -> None: + client.post("/api/generation-seed", json={"seed": 555}) + + locked = client.post("/api/generation-seed", json={"locked": True}) + + assert locked.json() == {"seed": 555, "locked": True} + + +def test_seed_alone_keeps_the_lock(client, test_state) -> None: + client.post("/api/generation-seed", json={"locked": True}) + + client.post("/api/generation-seed", json={"seed": 12}) + + assert test_state.state.app_settings.seed_locked is True + + +def test_out_of_range_seed_is_rejected_not_clamped(client, test_state) -> None: + before = client.get("/api/generation-seed").json() + + too_big = client.post("/api/generation-seed", json={"seed": 2_147_483_648}) + negative = client.post("/api/generation-seed", json={"seed": -1}) + + assert too_big.status_code == 422 + assert negative.status_code == 422 + assert client.get("/api/generation-seed").json() == before + + +def test_remote_can_read_and_change_the_seed_but_only_with_the_token(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as remote: + unauth = remote.post("/api/generation-seed", json={"seed": 9}) + saved = remote.post("/api/generation-seed", headers=AUTH, json={"seed": 9, "locked": True}) + loaded = remote.get("/api/generation-seed", headers=AUTH) + settings = remote.get("/api/settings", headers=AUTH) + + assert unauth.status_code == 401 + assert saved.json() == {"seed": 9, "locked": True} + assert loaded.json() == {"seed": 9, "locked": True} + assert test_state.state.app_settings.locked_seed == 9 + assert settings.status_code == 404 diff --git a/backend/tests/test_generation_stats_schema.py b/backend/tests/test_generation_stats_schema.py new file mode 100644 index 000000000..13411668c --- /dev/null +++ b/backend/tests/test_generation_stats_schema.py @@ -0,0 +1,221 @@ +"""v1 schema stays as shipped. The stats shape is a query CTE.""" + +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path + +import pytest + +from services.generation_stats_sql import generation_stats_sql +from services.migrations import MIGRATIONS_DIR, apply_migrations + + +def _connect(db_path: Path) -> sqlite3.Connection: + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + return conn + + +def _insert_v1( + conn: sqlite3.Connection, + *, + generation_id: str, + feature: str, + spec: dict[str, object], + status: str = "succeeded", + started_at: int | None = 1_000, + finished_at: int | None = 4_000, + deleted_at: int | None = None, + queue_rank: int | None = None, +) -> None: + conn.execute( + """ + INSERT INTO generations ( + id, feature, contract_version, status, spec, error_code, + created_at, queued_at, queue_rank, attempt_count, + started_at, finished_at, deleted_at + ) VALUES (?, ?, 1, ?, ?, NULL, 1, 1, ?, 1, ?, ?, ?) + """, + ( + generation_id, + feature, + status, + json.dumps(spec), + queue_rank, + started_at, + finished_at, + deleted_at, + ), + ) + + +def test_v1_database_upgrades_without_dropping_rows(tmp_path: Path) -> None: + db_path = tmp_path / "store.sqlite3" + conn = _connect(db_path) + conn.executescript((MIGRATIONS_DIR / "0001_initial_schema.sql").read_text(encoding="utf-8")) + _insert_v1( + conn, + generation_id="t2v", + feature="text-to-video", + spec={ + "params": { + "model": "ltx-2.3-fast", + "resolution": "1080p", + "aspectRatio": "16:9", + "fps": 24, + "duration": 5, + "loras": [{"ref": "", "scale": 1, "catalogId": "cozy-felt-style"}], + } + }, + ) + _insert_v1( + conn, + generation_id="retake", + feature="retake", + spec={ + "params": { + "model": "ltx-2.3-fast", + "resolution": {"width": 1280, "height": 720}, + "duration": 3.5, + } + }, + started_at=2_000, + finished_at=8_000, + ) + _insert_v1( + conn, + generation_id="a2v", + feature="audio-to-video", + spec={ + "params": { + "model": "ltx-2.5-fast", + "resolution": "540p", + "aspectRatio": "auto", + "fps": 24, + "numFrames": 185, + } + }, + ) + _insert_v1( + conn, + generation_id="recipe", + feature="cozy-felt", + spec={ + "params": { + "model": "ltx-2.3-fast", + "resolution": "720p", + "aspectRatio": "16:9", + "fps": 24, + "duration": 6, + "loras": [{"ref": "", "scale": 1, "catalogId": "cozy-felt-style"}], + } + }, + deleted_at=9_000, + ) + _insert_v1( + conn, + generation_id="queued", + feature="text-to-video", + spec={"params": {"prompt": "still waiting"}}, + status="queued", + queue_rank=1, + started_at=None, + finished_at=None, + ) + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, output_ordinal, + mime_type, name, metadata, created_at + ) VALUES ( + 'asset-1', 'video', 'generated', 't2v', 0, + 'video/mp4', 'out.mp4', '{}', 4 + ) + """ + ) + conn.commit() + + apply_migrations(conn, MIGRATIONS_DIR) + + version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] + assert version == 1 + assert conn.execute("PRAGMA foreign_key_check").fetchone() is None + columns = { + row["name"] for row in conn.execute("PRAGMA table_info(generations)").fetchall() + } + assert "device" not in columns + assert "app_version" not in columns + assert "model" not in columns + assert ( + conn.execute( + "SELECT name FROM sqlite_master WHERE type = 'view' AND name = 'generation_stats'" + ).fetchone() + is None + ) + assert ( + conn.execute( + "SELECT producer_generation_id FROM assets WHERE id = 'asset-1'" + ).fetchone()[0] + == "t2v" + ) + + rows = { + row["id"]: row + for row in conn.execute( + generation_stats_sql("SELECT * FROM generation_stats") + ).fetchall() + } + assert set(rows) == {"t2v", "retake", "a2v", "recipe"} + + t2v = rows["t2v"] + assert t2v["model"] == "ltx-2.3-fast" + assert t2v["resolution_label"] == "1080p" + assert t2v["aspect_ratio"] == "16:9" + assert t2v["fps"] == 24 + assert t2v["feature_group"] == "text-to-video" + assert t2v["lora_catalog_id"] == "cozy-felt-style" + assert t2v["lora_name"] is None + assert t2v["render_duration_s"] == 5 + assert t2v["edited_span_s"] is None + assert t2v["run_ms"] == 3_000 + assert t2v["is_deleted"] == 0 + + retake = rows["retake"] + assert retake["resolution_label"] is None + assert retake["aspect_ratio"] is None + assert retake["fps"] is None + assert retake["render_duration_s"] is None + assert retake["edited_span_s"] == 3.5 + assert retake["feature_group"] == "retake" + assert retake["run_ms"] == 6_000 + + a2v = rows["a2v"] + assert a2v["resolution_label"] == "540p" + assert a2v["aspect_ratio"] == "auto" + assert a2v["render_duration_s"] == 8 + assert a2v["feature_group"] == "audio-to-video" + + recipe = rows["recipe"] + assert recipe["feature_group"] == "lora" + assert recipe["lora_catalog_id"] == "cozy-felt-style" + assert recipe["is_deleted"] == 1 + assert recipe["render_duration_s"] == 6 + + conn.close() + + +def test_recorded_version_without_a_file_does_not_error(tmp_path: Path) -> None: + db_path = tmp_path / "store.sqlite3" + conn = _connect(db_path) + apply_migrations(conn, MIGRATIONS_DIR) + conn.execute( + "INSERT INTO schema_migrations (version, applied_at) VALUES (99, 1)" + ) + conn.commit() + apply_migrations(conn, MIGRATIONS_DIR) + version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] + assert version == 99 + conn.close() diff --git a/backend/tests/test_gpu_job.py b/backend/tests/test_gpu_job.py new file mode 100644 index 000000000..afcb93bbe --- /dev/null +++ b/backend/tests/test_gpu_job.py @@ -0,0 +1,60 @@ +"""Queued Home Retake/Extend must claim the GPU slot like T2V / GenSpace.""" + +from __future__ import annotations + +import pytest + +from services.features.video.edit_executor import run_gpu_job +from services.generation_interrupt import GenerationCancelledError + + +class _Slot: + def __init__(self) -> None: + self.started: list[str] = [] + self.completed: list[str | None] = [] + self.failed: list[str] = [] + + def start_generation(self, generation_id: str) -> None: + self.started.append(generation_id) + + def complete_generation(self, result: str | list[str] | None = None) -> None: + self.completed.append(result if isinstance(result, str) or result is None else result[0]) + + def fail_generation(self, error: str) -> None: + self.failed.append(error) + + +def test_run_gpu_job_starts_and_completes_on_success() -> None: + slot = _Slot() + ran = [] + run_gpu_job(slot, "gen-1", "/out.mp4", lambda: ran.append(True)) + assert slot.started == ["gen-1"] + assert ran == [True] + assert slot.completed == ["/out.mp4"] + assert slot.failed == [] + + +def test_run_gpu_job_fails_the_slot_when_the_body_raises() -> None: + slot = _Slot() + + def _boom() -> None: + raise RuntimeError("encode hung") + + with pytest.raises(RuntimeError, match="encode hung"): + run_gpu_job(slot, "gen-1", "/out.mp4", _boom) + assert slot.started == ["gen-1"] + assert slot.failed == ["encode hung"] + assert slot.completed == [] + + +def test_run_gpu_job_does_not_overwrite_cancel_with_fail() -> None: + slot = _Slot() + + def _cancel() -> None: + raise GenerationCancelledError() + + with pytest.raises(GenerationCancelledError): + run_gpu_job(slot, "gen-1", "/out.mp4", _cancel) + assert slot.started == ["gen-1"] + assert slot.failed == [] + assert slot.completed == [] diff --git a/backend/tests/test_health.py b/backend/tests/test_health.py index 8270305db..5f636bbb7 100644 --- a/backend/tests/test_health.py +++ b/backend/tests/test_health.py @@ -10,6 +10,7 @@ def _set_video_pipeline(state): pipeline=FakeFastVideoPipeline(), is_compiled=False, ltx_model_id="ltx-2.5-22b-distilled", + loading_mode="full_models_loading", ), ) diff --git a/backend/tests/test_heartbeat.py b/backend/tests/test_heartbeat.py index d16c0cc2e..13cb887a8 100644 --- a/backend/tests/test_heartbeat.py +++ b/backend/tests/test_heartbeat.py @@ -4,6 +4,7 @@ import logging +import pytest import torch from server_utils import heartbeat @@ -15,11 +16,11 @@ def _heartbeat_records(caplog, *, contains: str) -> list[logging.LogRecord]: def test_cuda_memory_sample_none_when_cuda_unavailable(monkeypatch) -> None: monkeypatch.setattr(torch.cuda, "is_available", lambda: False) - assert heartbeat._cuda_memory_sample() is None + assert heartbeat.cuda_memory_sample() is None def test_device_sample_none_when_no_accelerator(monkeypatch) -> None: - monkeypatch.setattr(heartbeat, "_cuda_memory_sample", lambda: None) + monkeypatch.setattr(heartbeat, "cuda_memory_sample", lambda: None) monkeypatch.setattr(heartbeat, "mps_memory_sample", lambda: None) assert heartbeat._device_sample() is None @@ -36,6 +37,18 @@ def test_log_heartbeat_emits_done_line_on_cpu_only(caplog, monkeypatch) -> None: assert len(done_records) == 1 +def test_log_heartbeat_emits_failed_line_when_block_raises(caplog, monkeypatch) -> None: + monkeypatch.setattr(heartbeat, "_device_sample", lambda: None) + caplog.set_level(logging.INFO, logger="server_utils.heartbeat") + + with pytest.raises(RuntimeError, match="boom"): + with heartbeat.log_heartbeat("test-label", interval_s=1000.0): + raise RuntimeError("boom") + + assert _heartbeat_records(caplog, contains="test-label failed") + assert not _heartbeat_records(caplog, contains="test-label done") + + def test_log_heartbeat_includes_device_sample_when_available(caplog, monkeypatch) -> None: monkeypatch.setattr(heartbeat, "_device_sample", lambda: "fake=1.00GiB") caplog.set_level(logging.INFO, logger="server_utils.heartbeat") @@ -46,3 +59,69 @@ def test_log_heartbeat_includes_device_sample_when_available(caplog, monkeypatch done_records = _heartbeat_records(caplog, contains="test-label done") assert len(done_records) == 1 assert "fake=1.00GiB" in done_records[0].getMessage() + + +def test_nested_log_heartbeat_does_not_start_a_second_ticker(caplog, monkeypatch) -> None: + monkeypatch.setattr(heartbeat, "_device_sample", lambda: None) + caplog.set_level(logging.INFO, logger="server_utils.heartbeat") + started: list[str] = [] + + class _SpyThread(heartbeat.Thread): + def start(self) -> None: # type: ignore[override] + started.append(self.name) + super().start() + + monkeypatch.setattr(heartbeat, "Thread", _SpyThread) + with heartbeat.log_heartbeat("outer", interval_s=1000.0): + with heartbeat.log_heartbeat("inner", interval_s=1000.0): + pass + + assert started == ["generation-heartbeat"] + assert _heartbeat_records(caplog, contains="outer done") + assert not _heartbeat_records(caplog, contains="inner") + + +def test_sequential_log_heartbeat_ticks_each_generation(caplog, monkeypatch) -> None: + monkeypatch.setattr(heartbeat, "_device_sample", lambda: None) + caplog.set_level(logging.INFO, logger="server_utils.heartbeat") + with heartbeat.log_heartbeat("first", interval_s=1000.0): + pass + with heartbeat.log_heartbeat("second", interval_s=1000.0): + pass + assert len(_heartbeat_records(caplog, contains="first done")) == 1 + assert len(_heartbeat_records(caplog, contains="second done")) == 1 + + +def test_overlapping_log_heartbeat_only_ticks_the_owner(caplog, monkeypatch) -> None: + from threading import Event, Thread + + monkeypatch.setattr(heartbeat, "_device_sample", lambda: None) + caplog.set_level(logging.INFO, logger="server_utils.heartbeat") + started: list[str] = [] + + class _SpyThread(heartbeat.Thread): + def start(self) -> None: # type: ignore[override] + started.append(self.name) + super().start() + + monkeypatch.setattr(heartbeat, "Thread", _SpyThread) + owner_ready = Event() + other_tried = Event() + owner_release = Event() + + def _other() -> None: + owner_ready.wait(timeout=2.0) + with heartbeat.log_heartbeat("queued", interval_s=1000.0): + other_tried.set() + owner_release.wait(timeout=2.0) + + worker = Thread(target=_other) + worker.start() + with heartbeat.log_heartbeat("owner", interval_s=1000.0): + owner_ready.set() + assert other_tried.wait(timeout=2.0) + owner_release.set() + worker.join(timeout=2.0) + assert started == ["generation-heartbeat"] + assert _heartbeat_records(caplog, contains="owner done") + assert not _heartbeat_records(caplog, contains="queued") diff --git a/backend/tests/test_http.py b/backend/tests/test_http.py new file mode 100644 index 000000000..dee26f4ef --- /dev/null +++ b/backend/tests/test_http.py @@ -0,0 +1,2495 @@ +import logging +import sqlite3 +import time +import wave +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path + +import pytest +from PIL import Image +from pydantic import JsonValue, ValidationError +from starlette.testclient import TestClient + +from api_types import RetakeParams, RetakeRequestParams +from app_factory import create_app +from app_handler import ServiceBundle, open_store +from frame_math import compute_num_frames, num_frames_for_audio_duration +from handlers.queued_generation_handler import QueuedGenerationHandler +from services.store import Store +from services.media_probe import MAX_IMAGE_BYTES, MAX_VIDEO_BYTES +from services.sqlite_store import SqliteStore +from services.records import AssetRecord, OutputSpec, UnavailableError +from services.unavailable_store import UnavailableStore +from state import build_initial_state, set_state_service_for_tests +from state.app_state_types import HfAuthenticated +from tests.conftest import TEST_ADMIN_TOKEN +from tests.http_error_assertions import assert_http_error + + +class _RecordingQueueControl: + def __init__(self, store: SqliteStore) -> None: + self._store = store + self.queued_visible_on_wake: list[bool] = [] + + def wake(self) -> None: + self.queued_visible_on_wake.append(self._store.has_queued()) + + def interrupt(self, generation_id: str, attempt_count: int) -> None: + del generation_id, attempt_count + + +def _png(path: Path, size: tuple[int, int] = (16, 16)) -> Path: + Image.new("RGB", size, color=(1, 2, 3)).save(path) + return path + + +def _wav(path: Path, *, duration_seconds: float = 8.0) -> Path: + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * int(duration_seconds * 8000)) + return path + + +def _store(test_state) -> SqliteStore: + return SqliteStore(test_state.config.app_data_dir) + + +def _params(prompt: str = "fox") -> dict[str, JsonValue]: + return {"prompt": prompt, "model": "ltx-2.5-fast"} + + +def _spec(prompt: str | None = None) -> dict[str, JsonValue]: + spec: dict[str, JsonValue] = {"params": {}, "inputs": {}} + if prompt is not None: + spec["params"] = _params(prompt) + return spec + + +def _succeed_png(test_state, *, name: str = "out.png") -> AssetRecord: + store = _store(test_state) + gen = store.insert_generation("text-to-video", _spec("p")) + claimed = store.claim_next_queued() + assert claimed is not None + asset_id, dest = store.allocate_output_path("image", "image/png") + Image.new("RGB", (8, 8)).save(dest) + done = store.mark_succeeded( + gen.id, + [ + OutputSpec( + asset_id=asset_id, + dest_path=dest, + ordinal=0, + mime_type="image/png", + name=name, + ) + ], + attempt_count=claimed.attempt_count, + ) + return done.outputs[0] + + +def _a2v_params(**overrides: JsonValue) -> dict[str, JsonValue]: + """Public A2V create params; the server derives persisted frame count.""" + params: dict[str, JsonValue] = { + "prompt": "the character speaks", + "resolution": "540p", + "model": "ltx-2.5-fast", + "fps": 24, + } + params.update(overrides) + return params + + +def _mp4(path: Path, *, duration_seconds: float = 4.0, fps: int = 8) -> Path: + import numpy as np + import imageio.v2 as imageio + + frames = max(1, int(duration_seconds * fps)) + writer = imageio.get_writer( + str(path), fps=fps, codec="libx264", macro_block_size=None + ) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return path + + +def _retake_params(**overrides: JsonValue) -> dict[str, JsonValue]: + params: dict[str, JsonValue] = { + "prompt": "the character turns", + "model": "ltx-2.5-fast", + "startTime": 0, + "duration": 2, + "mode": "replace_audio_and_video", + } + params.update(overrides) + return params + + +def _extend_params(**overrides: JsonValue) -> dict[str, JsonValue]: + params: dict[str, JsonValue] = { + "prompt": "the scene continues", + "model": "ltx-2.5-fast", + "duration": 4, + "mode": "end", + } + params.update(overrides) + return params + + +def _create_body( + *, + prompt: str = "fox", + contract_version: int | None = None, +) -> dict[str, JsonValue]: + body: dict[str, JsonValue] = { + "params": _params(prompt), + } + if contract_version is not None: + body["contract_version"] = contract_version + return body + + +def _bundle(fake_services, store: Store) -> ServiceBundle: + return ServiceBundle( + http=fake_services.http, + gpu_cleaner=fake_services.gpu_cleaner, + model_downloader=fake_services.model_downloader, + lora_catalog_provider=fake_services.lora_catalog_provider, + gpu_info=fake_services.gpu_info, + video_processor=fake_services.video_processor, + text_encoder=fake_services.text_encoder, + task_runner=fake_services.task_runner, + ltx_api_client=fake_services.ltx_api_client, + zit_api_client=fake_services.zit_api_client, + fast_video_pipeline_class=type(fake_services.fast_video_pipeline), + image_generation_pipeline_class=type(fake_services.image_generation_pipeline), + ic_lora_pipeline_class=type(fake_services.ic_lora_pipeline), + depth_processor_pipeline_class=type(fake_services.depth_processor_pipeline), + pose_processor_pipeline_class=type(fake_services.pose_processor_pipeline), + a2v_pipeline_class=type(fake_services.a2v_pipeline), + retake_pipeline_class=type(fake_services.retake_pipeline), + prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), + store=store, + ) + + +@contextmanager +def _reserved_generation_start(test_state) -> Iterator[None]: + assert test_state.generation.try_reserve_generation_start() is True + try: + yield + finally: + test_state.generation.release_generation_start_reservation() + + +def wait_for_http_status( + client: TestClient, generation_id: str, status: str, timeout: float = 3.0 +) -> bool: + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + response = client.get(f"/api/generations/{generation_id}") + if response.status_code == 200 and response.json()["status"] == status: + return True + time.sleep(0.01) + response = client.get(f"/api/generations/{generation_id}") + return response.status_code == 200 and response.json()["status"] == status + + +def test_test_client_starts_and_stops_generation_queue_runner(test_state) -> None: + app = create_app(handler=test_state) + assert test_state.generation_queue.is_running is False + with TestClient(app): + assert test_state.generation_queue.is_running is True + assert test_state.generation_queue.is_running is False + + +def test_http_create_is_processed_by_queue_runner(client) -> None: + response = client.post( + "/api/generations/text-to-video", + json=_create_body(), + ) + assert response.status_code == 200 + generation_id = response.json()["id"] + assert response.json()["status"] == "queued" + assert wait_for_http_status(client, generation_id, "succeeded") is True + completed = client.get(f"/api/generations/{generation_id}") + assert completed.status_code == 200 + assert completed.json()["outputs"][0]["media_kind"] == "video" + assert Path(completed.json()["outputs"][0]["path"]).is_file() + + +def test_create_image_to_video_persists_asset_ids_without_paths( + client, test_state, tmp_path: Path +) -> None: + with _reserved_generation_start(test_state): + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + + response = client.post( + "/api/generations/image-to-video", + json={ + "params": {**_params("the fox turns toward camera")}, + "inputs": {"startFrame": {"assetId": start["id"]}}, + }, + ) + + assert response.status_code == 200 + payload = response.json() + assert payload["feature"] == "image-to-video" + assert payload["status"] == "queued" + assert payload["spec"]["params"]["prompt"] == "the fox turns toward camera" + assert payload["spec"]["inputs"] == { + "startFrame": {"assetId": start["id"]} + } + assert "imagePath" not in payload["spec"]["params"] + assert start["path"] not in str(payload["spec"]) + + +def test_create_image_to_video_allows_blank_prompt_with_start_frame( + client, test_state, tmp_path: Path +) -> None: + with _reserved_generation_start(test_state): + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + + response = client.post( + "/api/generations/image-to-video", + json={ + "params": {**_params("")}, + "inputs": {"startFrame": {"assetId": start["id"]}}, + }, + ) + + assert response.status_code == 200 + assert response.json()["spec"]["params"]["prompt"] == "" + + +def test_create_image_to_video_omitted_aspect_ratio_persists_auto( + client, test_state, tmp_path: Path +) -> None: + with _reserved_generation_start(test_state): + start = client.post( + "/api/assets", + json={"path": str(_png(tmp_path / "portrait.png", (16, 32)))}, + ).json() + + response = client.post( + "/api/generations/image-to-video", + json={ + "params": {**_params("fox")}, + "inputs": {"startFrame": {"assetId": start["id"]}}, + }, + ) + + assert response.status_code == 200 + assert response.json()["spec"]["params"]["aspectRatio"] == "auto" + + +def test_create_image_to_video_maps_optional_end_frame( + client, test_state, tmp_path: Path +) -> None: + with _reserved_generation_start(test_state): + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + end = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "end.png"))} + ).json() + + response = client.post( + "/api/generations/image-to-video", + json={ + "params": {**_params("camera pushes in")}, + "inputs": { + "startFrame": {"assetId": start["id"]}, + "endFrame": {"assetId": end["id"]}, + }, + }, + ) + + assert response.status_code == 200 + assert response.json()["spec"]["inputs"] == { + "startFrame": {"assetId": start["id"]}, + "endFrame": {"assetId": end["id"]}, + } + + +def test_create_image_to_video_rejects_unknown_asset(client, test_state) -> None: + response = client.post( + "/api/generations/image-to-video", + json={ + "params": {**_params("fox")}, + "inputs": {"startFrame": {"assetId": "missing-asset"}}, + }, + ) + + data = assert_http_error( + response, + status_code=422, + code="INPUT_ASSET_NOT_FOUND", + message="startFrame image is no longer available", + ) + assert "missing-asset" not in data["message"] + assert _store(test_state).list_generations("image-to-video") == [] + + +def test_create_image_to_video_rejects_non_image_assets_before_queueing( + client, test_state, tmp_path: Path +) -> None: + image = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "input.wav"))} + ).json() + invalid_inputs = ( + {"startFrame": {"assetId": audio["id"]}}, + { + "startFrame": {"assetId": image["id"]}, + "endFrame": {"assetId": audio["id"]}, + }, + ) + + for inputs in invalid_inputs: + response = client.post( + "/api/generations/image-to-video", + json={"params": {**_params("fox")}, "inputs": inputs}, + ) + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + + assert _store(test_state).list_generations("image-to-video") == [] + + +def test_create_image_to_video_rejects_missing_or_invalid_start_frame( + client, test_state +) -> None: + invalid_inputs = ( + {}, + {"startFrame": {"assetId": ""}}, + {"endFrame": {"assetId": "end-without-start"}}, + ) + + for inputs in invalid_inputs: + response = client.post( + "/api/generations/image-to-video", + json={"params": {**_params("")}, "inputs": inputs}, + ) + assert response.status_code == 422 + + assert _store(test_state).list_generations("image-to-video") == [] + + +def test_create_image_to_video_rejects_loras(client, test_state, tmp_path: Path) -> None: + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + + response = client.post( + "/api/generations/image-to-video", + json={ + "params": { + **_params("fox"), + "loras": [{"ref": "style.safetensors", "scale": 1.0}], + }, + "inputs": {"startFrame": {"assetId": start["id"]}}, + }, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("image-to-video") == [] + + +def test_create_audio_to_video_persists_asset_ids_without_paths( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + assert response.status_code == 200 + payload = response.json() + assert payload["feature"] == "audio-to-video" + assert payload["status"] == "queued" + assert payload["spec"]["inputs"] == {"audio": {"assetId": audio["id"]}} + assert audio["path"] not in str(payload["spec"]) + assert "audioPath" not in payload["spec"]["params"] + + +def test_create_audio_to_video_allows_blank_prompt_with_start_frame( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(prompt=""), + "inputs": { + "audio": {"assetId": audio["id"]}, + "startFrame": {"assetId": start["id"]}, + }, + }, + ) + + assert response.status_code == 200 + payload = response.json() + assert payload["status"] == "queued" + assert payload["spec"]["params"]["prompt"] == "" + assert payload["spec"]["params"]["resolution"] == "540p" + assert payload["spec"]["params"]["numFrames"] == 185 + assert payload["spec"]["params"]["fps"] == 24 + assert payload["spec"]["params"]["model"] == "ltx-2.5-fast" + assert payload["spec"]["inputs"] == { + "audio": {"assetId": audio["id"]}, + "startFrame": {"assetId": start["id"]}, + } + assert audio["path"] not in str(payload["spec"]) + assert start["path"] not in str(payload["spec"]) + + +def test_create_audio_to_video_rejects_blank_prompt_without_image( + client, test_state, tmp_path: Path +) -> None: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(prompt=""), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert_http_error( + response, + status_code=422, + code="INVALID_GENERATION_SPEC", + message="Connect a prompt or a start image before running this node.", + ) + assert _store(test_state).list_generations("audio-to-video") == [] + + +@pytest.mark.parametrize( + "params", + [ + _a2v_params(model="pro"), + _a2v_params(model="fast"), + _a2v_params(numFrames=185), + ], +) +def test_create_audio_to_video_rejects_cells_outside_the_derived_one( + client, test_state, tmp_path: Path, params: dict[str, JsonValue] +) -> None: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={"params": params, "inputs": {"audio": {"assetId": audio["id"]}}}, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_rejects_legacy_duration( + client, test_state, tmp_path: Path +) -> None: + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=8.0))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(duration=20), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_derives_audio_grid_frames_without_ceil_snapping( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=10.563))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 200 + assert response.json()["spec"]["params"]["numFrames"] == 249 + + +def test_create_audio_to_video_derives_frames_at_48_fps( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + duration_seconds = 10.563 + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=duration_seconds))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(fps=48), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 200 + expected = num_frames_for_audio_duration( + duration_seconds, + 48, + max_frames=compute_num_frames(20, 48), + ) + assert response.json()["spec"]["params"]["numFrames"] == expected + assert response.json()["spec"]["params"]["fps"] == 48 + + +def test_create_audio_to_video_accepts_advertised_1080p( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=8.0))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(resolution="1080p"), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 200 + assert response.json()["spec"]["params"]["resolution"] == "1080p" + assert response.json()["spec"]["params"]["numFrames"] == 185 + + +def test_create_audio_to_video_uses_1080p_prefix_when_audio_exceeds_cell( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=20.0))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(resolution="1080p"), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 200 + assert response.json()["spec"]["params"]["resolution"] == "1080p" + assert response.json()["spec"]["params"]["numFrames"] == 233 + + +def test_create_audio_to_video_rejects_unadvertised_resolution( + client, test_state, tmp_path: Path +) -> None: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(resolution="1440p"), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 422 + assert response.json()["code"] == "HTTP_422" + assert _store(test_state).list_generations("audio-to-video") == [] + + +@pytest.mark.parametrize( + ("duration_seconds", "message"), + [ + (1.0, "Audio is too short for audio-to-video."), + (20.1, "Audio is too long for audio-to-video."), + ], +) +def test_create_audio_to_video_rejects_audio_outside_duration_envelope( + client, test_state, create_fake_model_files, tmp_path: Path, duration_seconds: float, message: str +) -> None: + create_fake_model_files() + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=duration_seconds))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert_http_error( + response, + status_code=422, + code="INVALID_VIDEO_GENERATION_SPEC", + message=message, + ) + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_rejects_unadvertised_local_cell( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + test_state.config.local_generations_mode = "unsupported" + audio = client.post( + "/api/assets", + json={"path": str(_wav(tmp_path / "line.wav", duration_seconds=5.0))}, + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert_http_error( + response, + status_code=422, + code="INVALID_VIDEO_GENERATION_SPEC", + message="Audio-to-video is not available at the selected resolution.", + ) + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_rejects_missing_offering_checkpoint( + client, test_state, tmp_path: Path +) -> None: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert_http_error( + response, + status_code=409, + code="LTX_MODEL_NOT_INSTALLED", + message="LTX_MODEL_NOT_INSTALLED", + ) + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_uses_installed_2_3_checkpoint_not_catalog_preferred( + client, test_state, create_fake_model_files, tmp_path: Path, monkeypatch +) -> None: + create_fake_model_files(model_id="ltx-2.3-22b-distilled") + seen: list[object] = [] + import handlers.video_generation_handler as handler_mod + + real = handler_mod.get_local_video_generation_model_specs + + def wrapped(model_id, **kwargs): + seen.append(model_id) + return real(model_id, **kwargs) + + monkeypatch.setattr(handler_mod, "get_local_video_generation_model_specs", wrapped) + with _reserved_generation_start(test_state): + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(model="ltx-2.3-fast"), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + + assert response.status_code == 200, response.text + assert "ltx-2.3-22b-distilled" in seen + assert "ltx-2.3-22b-distilled-1.1" not in seen + + +def test_create_audio_to_video_rejects_missing_audio(client, test_state) -> None: + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {}, + }, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_rejects_image_as_audio( + client, test_state, tmp_path: Path +) -> None: + image = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": image["id"]}}, + }, + ) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_rejects_unknown_audio_asset( + client, test_state +) -> None: + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": "missing-asset"}}, + }, + ) + + data = assert_http_error( + response, + status_code=422, + code="INPUT_ASSET_NOT_FOUND", + message="audio is no longer available", + ) + assert "missing-asset" not in data["message"] + assert _store(test_state).list_generations("audio-to-video") == [] + + +def test_create_audio_to_video_runs_local_a2v_pipeline_not_ltx_api( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, +) -> None: + create_fake_model_files() + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + assert response.status_code == 200 + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.a2v_pipeline.generate_calls: + break + time.sleep(0.01) + + assert fake_services.ltx_api_client.audio_to_video_calls == [] + assert len(fake_services.a2v_pipeline.generate_calls) == 1 + assert fake_services.a2v_pipeline.generate_calls[0]["audio_path"] == audio["path"] + + +def test_create_audio_to_video_loads_2_5_weights_when_settings_is_2_3( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.a2v_pipeline.generate_calls: + break + time.sleep(0.01) + + slot = handler.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.5-22b-distilled" + assert handler.state.app_settings.active_ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert len(fake_services.a2v_pipeline.generate_calls) == 1 + + +def test_create_audio_to_video_loads_2_3_weights_when_settings_is_2_5( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + audio = client.post( + "/api/assets", json={"path": str(_wav(tmp_path / "line.wav"))} + ).json() + response = client.post( + "/api/generations/audio-to-video", + json={ + "params": _a2v_params(model="ltx-2.3-fast"), + "inputs": {"audio": {"assetId": audio["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.a2v_pipeline.generate_calls: + break + time.sleep(0.01) + + slot = handler.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert handler.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + assert len(fake_services.a2v_pipeline.generate_calls) == 1 + + +def test_create_retake_persists_asset_ids_without_paths( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + payload = response.json() + assert payload["feature"] == "retake" + assert payload["status"] == "queued" + assert payload["spec"]["inputs"] == {"video": {"assetId": video["id"]}} + assert payload["spec"]["params"]["model"] == "ltx-2.5-fast" + assert payload["spec"]["params"]["startTime"] == 0 + assert payload["spec"]["params"]["duration"] == 2 + assert payload["spec"]["params"]["mode"] == "replace_audio_and_video" + assert video["path"] not in str(payload["spec"]) + assert "video_path" not in payload["spec"]["params"] + + +def test_create_retake_rejects_selection_over_cap( + client, test_state, tmp_path: Path +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": {**_retake_params(), "duration": 10.1}, + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 422 + assert _store(test_state).list_generations("retake") == [] + + +def test_retake_cap_accepts_exactly_ten_seconds() -> None: + params = {**_retake_params(), "duration": 10.0} + assert RetakeRequestParams.model_validate(params).duration == 10.0 + + +def test_retake_queued_before_cap_still_parses() -> None: + params = {**_retake_params(), "duration": 12.0} + assert RetakeParams.model_validate(params).duration == 12.0 + with pytest.raises(ValidationError): + RetakeRequestParams.model_validate(params) + + +def test_create_retake_rejects_missing_video(client, test_state) -> None: + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": "missing-asset"}}, + }, + ) + data = assert_http_error( + response, + status_code=422, + code="INPUT_ASSET_NOT_FOUND", + message="video is no longer available", + ) + assert "missing-asset" not in data["message"] + assert _store(test_state).list_generations("retake") == [] + + +def test_create_retake_rejects_oversized_video( + client, test_state, tmp_path: Path +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + with Path(video["path"]).open("r+b") as handle: + handle.truncate(MAX_VIDEO_BYTES + 1) + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error(response, status_code=400, code="FILE_TOO_LARGE") + assert _store(test_state).list_generations("retake") == [] + + +def test_create_retake_rejects_image_as_video( + client, test_state, tmp_path: Path +) -> None: + image = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "still.png"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": image["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="INVALID_GENERATION_SPEC", + message="video must reference a video asset", + ) + assert _store(test_state).list_generations("retake") == [] + + +def test_create_retake_rejects_missing_offering_checkpoint( + client, test_state, tmp_path: Path +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=409, + code="LTX_MODEL_NOT_INSTALLED", + message="LTX_MODEL_NOT_INSTALLED", + ) + assert _store(test_state).list_generations("retake") == [] + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_create_retake_rejects_pipeline_model_ids( + client, test_state, tmp_path: Path, pipeline_id: str +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(model=pipeline_id), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 422 + assert _store(test_state).list_generations("retake") == [] + + +def test_create_retake_runs_local_pipeline_not_ltx_api( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, + caplog, +) -> None: + caplog.set_level(logging.INFO, logger="services.features.video.retake") + caplog.set_level(logging.INFO, logger="handlers.generation_handler") + create_fake_model_files() + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.retake_pipeline.generate_calls: + break + time.sleep(0.01) + + assert fake_services.ltx_api_client.retake_calls == [] + assert len(fake_services.retake_pipeline.generate_calls) == 1 + call = fake_services.retake_pipeline.generate_calls[0] + assert call["video_path"] == video["path"] + assert call["start_time"] == 0 + assert call["encode_max_duration"] is not None + assert call["target_frames"] is not None + assert call["regenerate_video"] is True + assert call["regenerate_audio"] is True + assert any( + "Retake " in record.getMessage() and " started (" in record.getMessage() + for record in caplog.records + if record.name == "services.features.video.retake" + ) + assert any( + "started (gpu)" in record.getMessage() + for record in caplog.records + if record.name == "handlers.generation_handler" + ) + + +def test_create_retake_loads_2_5_weights_when_settings_is_2_3( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/retake", + json={ + "params": _retake_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.retake_pipeline.generate_calls: + break + time.sleep(0.01) + + slot = handler.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.5-22b-distilled" + assert handler.state.app_settings.active_ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert len(fake_services.retake_pipeline.generate_calls) == 1 + + +def test_create_extend_persists_asset_ids_without_paths( + client, test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + with _reserved_generation_start(test_state): + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + payload = response.json() + assert payload["feature"] == "extend" + assert payload["status"] == "queued" + assert payload["spec"]["inputs"] == {"video": {"assetId": video["id"]}} + assert payload["spec"]["params"]["model"] == "ltx-2.5-fast" + assert payload["spec"]["params"]["duration"] == 4 + assert payload["spec"]["params"]["mode"] == "end" + assert video["path"] not in str(payload["spec"]) + assert "video_path" not in payload["spec"]["params"] + + +def test_create_extend_rejects_missing_video(client, test_state) -> None: + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(), + "inputs": {"video": {"assetId": "missing-asset"}}, + }, + ) + data = assert_http_error( + response, + status_code=422, + code="INPUT_ASSET_NOT_FOUND", + message="video is no longer available", + ) + assert "missing-asset" not in data["message"] + assert _store(test_state).list_generations("extend") == [] + + +def test_create_extend_rejects_image_as_video( + client, test_state, tmp_path: Path +) -> None: + image = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "still.png"))} + ).json() + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(), + "inputs": {"video": {"assetId": image["id"]}}, + }, + ) + assert_http_error( + response, + status_code=422, + code="INVALID_GENERATION_SPEC", + message="video must reference a video asset", + ) + assert _store(test_state).list_generations("extend") == [] + + +def test_create_extend_rejects_missing_offering_checkpoint( + client, test_state, tmp_path: Path +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert_http_error( + response, + status_code=409, + code="LTX_MODEL_NOT_INSTALLED", + message="LTX_MODEL_NOT_INSTALLED", + ) + assert _store(test_state).list_generations("extend") == [] + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_create_extend_rejects_pipeline_model_ids( + client, test_state, tmp_path: Path, pipeline_id: str +) -> None: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(model=pipeline_id), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 422 + assert _store(test_state).list_generations("extend") == [] + + +@pytest.mark.parametrize("mode", ["start", "end"]) +def test_create_extend_runs_local_pipeline_not_ltx_api( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, + mode: str, + caplog, +) -> None: + caplog.set_level(logging.INFO, logger="services.features.video.extend") + caplog.set_level(logging.INFO, logger="handlers.generation_handler") + create_fake_model_files() + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(mode=mode), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.retake_pipeline.extend_calls: + break + time.sleep(0.01) + + assert fake_services.ltx_api_client.extend_calls == [] + assert len(fake_services.retake_pipeline.extend_calls) == 1 + call = fake_services.retake_pipeline.extend_calls[0] + assert call["video_path"] == video["path"] + assert call["mode"] == mode + assert call["encode_max_duration"] is not None + assert call["extend_frames"] % 8 == 0 + assert any( + "Extend " in record.getMessage() and " started (" in record.getMessage() + for record in caplog.records + if record.name == "services.features.video.extend" + ) + assert any( + "started (gpu)" in record.getMessage() + for record in caplog.records + if record.name == "handlers.generation_handler" + ) + + +def test_create_extend_loads_2_5_weights_when_settings_is_2_3( + test_state, + fake_services, + create_fake_model_files, + tmp_path: Path, + default_app_settings, +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle( + fake_services, SqliteStore(test_state.config.app_data_dir) + ), + ) + handler.state.hf_auth_state = HfAuthenticated( + access_token="fake-hf-token", + expires_at=1e18, + ) + handler.state.app_settings.use_local_text_encoder = True + handler.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + video = client.post( + "/api/assets", json={"path": str(_mp4(tmp_path / "clip.mp4"))} + ).json() + response = client.post( + "/api/generations/extend", + json={ + "params": _extend_params(), + "inputs": {"video": {"assetId": video["id"]}}, + }, + ) + assert response.status_code == 200, response.text + deadline = time.monotonic() + 5.0 + while time.monotonic() < deadline: + if fake_services.retake_pipeline.extend_calls: + break + time.sleep(0.01) + + slot = handler.state.gpu_slot + assert slot is not None + assert slot.active_pipeline.ltx_model_id == "ltx-2.5-22b-distilled" + assert handler.state.app_settings.active_ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert len(fake_services.retake_pipeline.extend_calls) == 1 + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_create_text_to_video_rejects_pipeline_model_ids( + client, test_state, pipeline_id: str +) -> None: + response = client.post( + "/api/generations/text-to-video", + json={"params": {"prompt": "fox", "model": pipeline_id}}, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("text-to-video") == [] + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_create_image_to_video_rejects_pipeline_model_ids( + client, test_state, tmp_path: Path, pipeline_id: str +) -> None: + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "start.png"))} + ).json() + response = client.post( + "/api/generations/image-to-video", + json={ + "params": {"prompt": "fox", "model": pipeline_id}, + "inputs": {"startFrame": {"assetId": start["id"]}}, + }, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("image-to-video") == [] + + +def test_create_text_to_video_requires_model(client, test_state) -> None: + response = client.post( + "/api/generations/text-to-video", + json={"params": {"prompt": "fox"}}, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_create_text_to_video_still_rejects_blank_prompt(client, test_state) -> None: + response = client.post( + "/api/generations/text-to-video", + json={"params": {**_params("")}}, + ) + + assert response.status_code == 422 + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_http_create_rejects_unknown_recipe_id(client, test_state) -> None: + # The recipe create route matches any id under /generations/recipes/; an + # unmapped id is a typed LORA_UNKNOWN miss, and nothing is enqueued. + response = client.post( + "/api/generations/recipes/not-a-real-recipe", + json={ + "params": { + "prompt": "fox", + "model": "ltx-2.5-fast", + "catalogId": "cozy-felt-style", + "scale": 1.0, + } + }, + ) + + assert response.status_code == 422 + assert response.json()["code"] == "LORA_UNKNOWN" + assert _store(test_state).list_generations("not-a-real-recipe") == [] + + +def test_http_create_rejects_unsupported_contract_version_before_insert( + client, test_state +) -> None: + response = client.post( + "/api/generations/text-to-video", + json=_create_body(contract_version=2), + ) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_http_create_rejects_structurally_invalid_text_to_video_params_before_insert( + client, test_state +) -> None: + response = client.post( + "/api/generations/text-to-video", + json={ + "params": {**_params("fox"), "imagePath": "/tmp/start.png"}, + }, + ) + + assert response.status_code == 422 + assert response.json()["code"] == "HTTP_422" + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_http_cancel_queued_generation(client, test_state) -> None: + assert test_state.generation.try_reserve_generation_start() is True + try: + response = client.post( + "/api/generations/text-to-video", + json=_create_body(prompt="stop"), + ) + generation_id = response.json()["id"] + cancelled = client.post(f"/api/generations/{generation_id}/cancel") + assert cancelled.status_code == 200 + assert cancelled.json()["status"] == "cancelled" + finally: + test_state.generation.release_generation_start_reservation() + + +def test_queue_snapshot_lists_running_then_ranked_queued_work( + client, test_state, tmp_path: Path +) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + input_asset = store.ingest_upload(str(_png(tmp_path / "start.png"))) + running = store.insert_generation( + "image-to-video", + { + "params": {"prompt": "running"}, + "inputs": {"startFrame": {"assetId": input_asset.id}}, + }, + ) + second = store.insert_generation("text-to-video", _spec("second")) + third = store.insert_generation("text-to-video", _spec("third")) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == running.id + store.reorder_queued_generation(third.id, second.id) + + response = client.get("/api/generation-queue") + + assert response.status_code == 200, response.text + body = response.json() + assert body["active"]["generation"]["id"] == running.id + assert body["active"]["generation"]["status"] == "running" + assert body["active"]["input_assets"][0]["id"] == input_asset.id + assert body["active"]["progress"] is None + assert [entry["generation"]["id"] for entry in body["queued"]] == [ + third.id, + second.id, + ] + assert body["done"] == [] + assert body["failed"] == [] + assert body["unseen_ids"] == [] + + +def test_queue_snapshot_includes_progress_only_for_matching_active_id( + client, test_state +) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + active = store.insert_generation("text-to-video", _spec("active")) + queued = store.insert_generation("text-to-video", _spec("queued")) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == active.id + + test_state.generation.start_api_generation("unrelated-generation") + unmatched = client.get("/api/generation-queue") + test_state.generation.complete_generation(result="done") + test_state.generation.start_api_generation(active.id) + matched = client.get("/api/generation-queue") + + assert unmatched.status_code == 200, unmatched.text + assert unmatched.json()["active"]["progress"] is None + assert matched.status_code == 200, matched.text + progress = matched.json()["active"]["progress"] + assert progress == { + "phase": "", + "progress": 0, + "currentStep": None, + "totalSteps": None, + } + assert matched.json()["queued"][0]["generation"]["id"] == queued.id + + +def test_queue_snapshot_keeps_cancelling_active_and_queued_without_progress( + client, test_state +) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + active = store.insert_generation("text-to-video", _spec("active")) + queued = store.insert_generation("text-to-video", _spec("queued")) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == active.id + test_state.generation.start_api_generation(active.id) + + cancelled = client.post(f"/api/generations/{active.id}/cancel") + snapshot = client.get("/api/generation-queue") + + assert cancelled.status_code == 200, cancelled.text + assert cancelled.json()["status"] == "cancelling" + assert snapshot.status_code == 200, snapshot.text + body = snapshot.json() + assert body["active"]["generation"]["id"] == active.id + assert body["active"]["generation"]["status"] == "cancelling" + assert body["queued"][0]["generation"]["id"] == queued.id + assert body["queued"][0]["progress"] is None + + +def test_http_reorder_moves_queued_generation_before_target(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + first = store.insert_generation("text-to-video", _spec("first")) + second = store.insert_generation("text-to-video", _spec("second")) + third = store.insert_generation("text-to-video", _spec("third")) + + reordered = client.post( + "/api/generation-queue/reorder", + json={"generation_id": third.id, "before_generation_id": second.id}, + ) + persisted = client.get("/api/generation-queue") + + assert reordered.status_code == 200, reordered.text + assert reordered.json()["active"] is None + assert [entry["generation"]["id"] for entry in reordered.json()["queued"]] == [ + first.id, + third.id, + second.id, + ] + assert persisted.json() == reordered.json() + + +def test_http_reorder_returns_post_mutation_queue_snapshot( + client, test_state, tmp_path: Path +) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + input_asset = store.ingest_upload(str(_png(tmp_path / "start.png"))) + running = store.insert_generation( + "image-to-video", + { + "params": {"prompt": "running"}, + "inputs": {"startFrame": {"assetId": input_asset.id}}, + }, + ) + first = store.insert_generation("text-to-video", _spec("first")) + second = store.insert_generation( + "image-to-video", + { + "params": {"prompt": "second"}, + "inputs": {"startFrame": {"assetId": input_asset.id}}, + }, + ) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == running.id + test_state.generation.start_api_generation(running.id) + + reordered = client.post( + "/api/generation-queue/reorder", + json={"generation_id": second.id, "before_generation_id": first.id}, + ) + + assert reordered.status_code == 200, reordered.text + body = reordered.json() + assert "id" not in body + assert body["active"]["generation"]["id"] == running.id + assert body["active"]["generation"]["status"] == "running" + assert body["active"]["input_assets"][0]["id"] == input_asset.id + assert body["active"]["progress"] == { + "phase": "", + "progress": 0, + "currentStep": None, + "totalSteps": None, + } + assert [entry["generation"]["id"] for entry in body["queued"]] == [ + second.id, + first.id, + ] + assert body["queued"][0]["generation"]["status"] == "queued" + assert body["queued"][0]["input_assets"][0]["id"] == input_asset.id + assert body["queued"][0]["progress"] is None + assert body["queued"][1]["generation"]["id"] == first.id + assert body["queued"][1]["input_assets"] == [] + assert body["queued"][1]["progress"] is None + + +def test_http_reorder_rejects_unknown_fields_preserves_relative_contract( + client, test_state +) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + first = store.insert_generation("text-to-video", _spec("first")) + second = store.insert_generation("text-to-video", _spec("second")) + third = store.insert_generation("text-to-video", _spec("third")) + + revision_rejected = client.post( + "/api/generation-queue/reorder", + json={ + "generation_id": third.id, + "before_generation_id": second.id, + "revision": 1, + }, + ) + array_rejected = client.post( + "/api/generation-queue/reorder", + json={ + "generation_id": third.id, + "queue": [third.id, first.id, second.id], + }, + ) + reordered = client.post( + "/api/generation-queue/reorder", + json={"generation_id": third.id, "before_generation_id": second.id}, + ) + persisted = client.get("/api/generation-queue") + + assert revision_rejected.status_code == 422 + assert array_rejected.status_code == 422 + assert reordered.status_code == 200, reordered.text + assert [entry["generation"]["id"] for entry in reordered.json()["queued"]] == [ + first.id, + third.id, + second.id, + ] + assert persisted.json() == reordered.json() + + +def test_http_reorder_rejects_task_claimed_before_command(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + claimed = store.insert_generation("text-to-video", _spec("claimed")) + target = store.insert_generation("text-to-video", _spec("target")) + assert store.claim_next_queued() is not None + + response = client.post( + "/api/generation-queue/reorder", + json={ + "generation_id": claimed.id, + "before_generation_id": target.id, + }, + ) + + assert_http_error(response, status_code=409, code="INVALID_GENERATION_STATUS") + + +def test_http_retry_failed_generation_returns_same_id(client, test_state) -> None: + assert test_state.generation.try_reserve_generation_start() is True + try: + store = _store(test_state) + generation = store.insert_generation("text-to-video", _spec("retry")) + claimed = store.claim_next_queued() + assert claimed is not None + store.mark_failed( + generation.id, + "OUTPUT_UNREADABLE", + attempt_count=claimed.attempt_count, + ) + retried = client.post(f"/api/generations/{generation.id}/retry") + assert retried.status_code == 200 + assert retried.json()["id"] == generation.id + assert retried.json()["status"] == "queued" + finally: + test_state.generation.release_generation_start_reservation() + + +def test_ingest_asset_via_http(client, tmp_path: Path) -> None: + source = _png(tmp_path / "up.png") + r = client.post("/api/assets", json={"path": str(source)}) + assert r.status_code == 200 + data = r.json() + assert data["origin"] == "uploaded" + assert data["media_kind"] == "image" + assert Path(data["path"]).is_file() + + +def test_get_asset_via_http(client, tmp_path: Path) -> None: + ingested = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "lookup.png"))} + ) + assert ingested.status_code == 200 + asset_id = ingested.json()["id"] + + r = client.get(f"/api/assets/{asset_id}") + assert r.status_code == 200 + data = r.json() + assert data["id"] == asset_id + assert data["media_kind"] == "image" + assert data["origin"] == "uploaded" + assert Path(data["path"]).is_file() + + +def test_list_assets_via_http(client, test_state, tmp_path: Path) -> None: + ingested = client.post("/api/assets", json={"path": str(_png(tmp_path / "a.png"))}) + assert ingested.status_code == 200 + with _reserved_generation_start(test_state): + output = _succeed_png(test_state) + r = client.get("/api/assets") + assert r.status_code == 200 + body = r.json() + ids = [item["id"] for item in body["items"]] + assert ingested.json()["id"] not in ids + assert ids == [output.id] + assert body["items"][0]["origin"] == "generated" + assert "path" in body["items"][0] + assert "in_use" in body["items"][0] + + +def test_missing_asset_file_is_tombstoned_via_http(client, test_state) -> None: + with _reserved_generation_start(test_state): + asset = _succeed_png(test_state, name="gone.png") + Path(asset.path).unlink() + listed = client.get("/api/assets") + assert listed.status_code == 200 + assert asset.id not in [item["id"] for item in listed.json()["items"]] + assert_http_error( + client.get(f"/api/assets/{asset.id}"), + status_code=404, + code="ASSET_NOT_FOUND", + ) + + +def test_missing_asset_bytes_do_not_tombstone(client, tmp_path: Path) -> None: + ingested = client.post("/api/assets", json={"path": str(_png(tmp_path / "gone.png"))}) + asset = ingested.json() + payload = Path(asset["path"]).read_bytes() + Path(asset["path"]).unlink() + assert_http_error( + client.get(f"/api/assets/{asset['id']}/bytes"), + status_code=404, + code="ASSET_NOT_FOUND", + ) + Path(asset["path"]).write_bytes(payload) + restored = client.get(f"/api/assets/{asset['id']}") + assert restored.status_code == 200 + assert restored.json()["id"] == asset["id"] + + +def test_delete_asset_via_http(client, tmp_path: Path) -> None: + ingested = client.post("/api/assets", json={"path": str(_png(tmp_path / "a.png"))}) + asset_id = ingested.json()["id"] + path = Path(ingested.json()["path"]) + deleted = client.delete(f"/api/assets/{asset_id}") + assert deleted.status_code == 200 + assert not path.exists() + assert client.get(f"/api/assets/{asset_id}").status_code == 404 + + +def test_delete_in_use_asset_409(client, tmp_path: Path) -> None: + start = client.post("/api/assets", json={"path": str(_png(tmp_path / "s.png"))}).json() + created = client.post( + "/api/generations/image-to-video", + json={ + "params": {**_params("x")}, + "inputs": {"startFrame": {"assetId": start["id"]}}, + }, + ) + assert created.status_code == 200 + r = client.delete(f"/api/assets/{start['id']}") + assert_http_error(r, status_code=409, code="ASSET_IN_USE") + + +def test_desktop_serves_asset_bytes_for_the_trim_preview( + client, tmp_path: Path +) -> None: + source = _png(tmp_path / "preview.png") + ingested = client.post("/api/assets", json={"path": str(source)}) + assert ingested.status_code == 200 + asset_id = ingested.json()["id"] + + # The renderer streams these bytes for waveform decoding instead of + # marshalling a base64 copy of the whole file through IPC. + served = client.get(f"/api/assets/{asset_id}/bytes") + assert served.status_code == 200 + assert served.content == source.read_bytes() + assert served.headers["content-disposition"].startswith("inline") + assert client.head(f"/api/assets/{asset_id}/bytes").status_code == 200 + + +def test_desktop_asset_bytes_404_for_unknown_asset(client) -> None: + assert_http_error( + client.get("/api/assets/missing-asset/bytes"), + status_code=404, + code="ASSET_NOT_FOUND", + ) + + +def test_phone_asset_routes_stay_off_desktop(client, test_state, tmp_path: Path) -> None: + png_bytes = _png(tmp_path / "phone.png").read_bytes() + uploaded = client.post( + "/api/assets/upload", + files={"file": ("phone.png", png_bytes, "image/png")}, + ) + ingested = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "lookup.png"))} + ) + assert ingested.status_code == 200 + asset_id = ingested.json()["id"] + + # POST /api/assets/upload collides with GET /api/assets/{asset_id}, so FastAPI + # returns 405 rather than a missing-route 404. Bytes are registered on Desktop. + assert uploaded.status_code == 405 + assert client.get(f"/api/assets/{asset_id}/bytes").status_code == 200 + assert client.head(f"/api/assets/{asset_id}/bytes").status_code == 200 + assert client.get(f"/api/assets/{asset_id}/thumbnail/bytes").status_code == 200 + assert client.get(f"/api/assets/{asset_id}").status_code == 200 + + schema = create_app(handler=test_state).openapi() + asset_paths = { + path: sorted( + method + for method in methods + if method in {"get", "post", "put", "delete", "head", "patch"} + ) + for path, methods in schema["paths"].items() + if path.startswith("/api/assets") + } + assert asset_paths == { + "/api/assets": ["get", "post"], + "/api/assets/{asset_id}": ["delete", "get"], + "/api/assets/{asset_id}/bytes": ["get", "head"], + "/api/assets/{asset_id}/extract-audio": ["post"], + "/api/assets/{asset_id}/thumbnail/bytes": ["get", "head"], + "/api/assets/{asset_id}/trim-audio": ["post"], + "/api/assets/{asset_id}/trim-video": ["post"], + } + operation_ids = [ + operation["operationId"] + for path_item in schema["paths"].values() + for method, operation in path_item.items() + if method in {"get", "post", "put", "delete", "head", "patch"} + and "operationId" in operation + ] + assert len(operation_ids) == len(set(operation_ids)) + + +def test_get_missing_asset_404(client) -> None: + r = client.get("/api/assets/missing-asset") + assert_http_error(r, status_code=404, code="ASSET_NOT_FOUND") + + +def test_get_deleted_asset_404(client, test_state, tmp_path: Path) -> None: + ingested = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "gone.png"))} + ) + assert ingested.status_code == 200 + asset_id = ingested.json()["id"] + db_path = test_state.config.app_data_dir / "store.sqlite3" + conn = sqlite3.connect(str(db_path)) + try: + conn.execute( + "UPDATE assets SET deleted_at = 1 WHERE id = ?", + (asset_id,), + ) + conn.commit() + finally: + conn.close() + + r = client.get(f"/api/assets/{asset_id}") + assert_http_error(r, status_code=404, code="ASSET_NOT_FOUND") + + +def test_get_asset_store_unavailable_503( + test_state, fake_services, default_app_settings +) -> None: + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, UnavailableStore()), + ) + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + r = client.get("/api/assets/any-asset") + assert_http_error(r, status_code=503, code="STORE_UNAVAILABLE") + listed = client.get("/api/assets") + assert_http_error(listed, status_code=503, code="STORE_UNAVAILABLE") + deleted = client.delete("/api/assets/any-asset") + assert_http_error(deleted, status_code=503, code="STORE_UNAVAILABLE") + + +def test_ingest_missing_file_400(client, tmp_path: Path) -> None: + missing = tmp_path / "missing.png" + r = client.post("/api/assets", json={"path": str(missing)}) + assert_http_error( + r, + status_code=400, + code="FILE_NOT_FOUND", + message=f"file not found: {missing}", + ) + + +def test_ingest_unsupported_type_400(client, tmp_path: Path) -> None: + notes = tmp_path / "notes.txt" + notes.write_text("not media") + r = client.post("/api/assets", json={"path": str(notes)}) + assert r.status_code == 400 + assert r.json()["code"] == "UNSUPPORTED_MEDIA" + + +def test_ingest_oversized_image_400(client, tmp_path: Path) -> None: + source = tmp_path / "huge.png" + with source.open("wb") as handle: + handle.truncate(MAX_IMAGE_BYTES + 1) + r = client.post("/api/assets", json={"path": str(source)}) + assert r.status_code == 400 + assert r.json()["code"] == "FILE_TOO_LARGE" + + +def test_ingest_decompression_bomb_400(client, tmp_path: Path) -> None: + original = Image.MAX_IMAGE_PIXELS + Image.MAX_IMAGE_PIXELS = 1 + try: + source = _png(tmp_path / "bomb.png", (16, 16)) + r = client.post("/api/assets", json={"path": str(source)}) + assert r.status_code == 400 + assert r.json()["code"] == "UNREADABLE_MEDIA" + finally: + Image.MAX_IMAGE_PIXELS = original + + +def test_list_generations_filters_feature(client, test_state, tmp_path: Path) -> None: + assert test_state.generation.try_reserve_generation_start() is True + try: + store = _store(test_state) + png = _png(tmp_path / "a.png") + asset = client.post("/api/assets", json={"path": str(png)}).json() + store.insert_generation( + "text-to-video", + { + "params": {"prompt": "a"}, + "inputs": {"startFrame": {"assetId": asset["id"]}}, + }, + ) + store.insert_generation("cozy-felt", {"params": {"prompt": "b"}}) + listed = client.get("/api/generations", params={"feature": "text-to-video"}) + assert listed.status_code == 200 + body = listed.json() + assert len(body) == 1 + assert body[0]["feature"] == "text-to-video" + assert body[0]["status"] == "queued" + assert body[0]["queued_at"] > 0 + assert body[0]["attempt_count"] == 0 + assert body[0]["error_code"] is None + assert "error" not in body[0] + finally: + test_state.generation.release_generation_start_reservation() + + +def test_get_missing_generation_404(client) -> None: + r = client.get("/api/generations/not-a-real-id") + assert r.status_code == 404 + + +def test_http_cancel_missing_generation_404(client) -> None: + response = client.post("/api/generations/not-a-real-id/cancel") + + assert_http_error( + response, + status_code=404, + code="GENERATION_NOT_FOUND", + ) + + +def test_http_cancel_terminal_generation_returns_conflict(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + generation = store.insert_generation("text-to-video", _spec("terminal")) + claimed = store.claim_next_queued() + assert claimed is not None + store.mark_failed( + generation.id, + "OUTPUT_UNREADABLE", + attempt_count=claimed.attempt_count, + ) + + response = client.post(f"/api/generations/{generation.id}/cancel") + + assert_http_error( + response, + status_code=409, + code="INVALID_GENERATION_STATUS", + ) + + +def test_http_cancel_unowned_running_generation_marks_cancelling( + client, test_state +) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + generation = store.insert_generation("text-to-video", _spec("owned")) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == generation.id + + response = client.post(f"/api/generations/{generation.id}/cancel") + + assert response.status_code == 200 + assert response.json()["status"] == "cancelling" + + +def test_delete_generation_keeps_file(client, test_state, tmp_path: Path) -> None: + assert test_state.generation.try_reserve_generation_start() is True + try: + store = _store(test_state) + png = _png(tmp_path / "z.png") + asset = client.post("/api/assets", json={"path": str(png)}).json() + gen = store.insert_generation( + "text-to-video", + {"inputs": {"startFrame": {"assetId": asset["id"]}}}, + ) + deleted = client.delete(f"/api/generations/{gen.id}") + assert deleted.status_code == 200 + assert deleted.json() == {"status": "ok"} + assert Path(asset["path"]).is_file() + assert client.get(f"/api/generations/{gen.id}").status_code == 404 + finally: + test_state.generation.release_generation_start_reservation() + + +def test_delete_running_generation_returns_conflict(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + generation = store.insert_generation("text-to-video", {}) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == generation.id + + response = client.delete(f"/api/generations/{generation.id}") + + assert response.status_code == 409 + + +def test_missing_output_file_omitted_from_get(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + created = store.insert_generation("text-to-video", {"params": {"prompt": "p"}}) + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == created.id + asset_id, dest = store.allocate_output_path("image", "image/png") + Image.new("RGB", (8, 8)).save(dest) + done = store.mark_succeeded( + created.id, + [ + OutputSpec( + asset_id=asset_id, + dest_path=dest, + ordinal=0, + mime_type="image/png", + name="out.png", + ) + ], + attempt_count=claimed.attempt_count, + ) + Path(done.outputs[0].path).unlink() + r = client.get(f"/api/generations/{created.id}") + assert r.status_code == 200 + assert r.json()["outputs"] == [] + + +def test_missing_input_file_stays_on_get(client, test_state, tmp_path: Path) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + png = _png(tmp_path / "start.png") + asset = client.post("/api/assets", json={"path": str(png)}).json() + gen = store.insert_generation( + "image-to-video", + {"inputs": {"startFrame": {"assetId": asset["id"]}}}, + ) + Path(asset["path"]).unlink() + r = client.get(f"/api/generations/{gen.id}") + assert r.status_code == 200 + body = r.json() + assert body["status"] == "queued" + assert body["spec"]["inputs"] == {"startFrame": {"assetId": asset["id"]}} + assert body["outputs"] == [] + + +def test_create_generation_returns_queued(client, test_state) -> None: + with _reserved_generation_start(test_state): + response = client.post( + "/api/generations/text-to-video", + json=_create_body(), + ) + assert response.status_code == 200 + payload = response.json() + assert payload["status"] == "queued" + assert payload["feature"] == "text-to-video" + assert payload["spec"]["inputs"] == {} + assert payload["attempt_count"] == 0 + assert payload["started_at"] is None + + +def test_create_text_to_video_rejects_unexpected_inputs(client, test_state) -> None: + response = client.post( + "/api/generations/text-to-video", + json={ + "params": {**_params("fox")}, + "inputs": {"startFrame": {"assetId": "missing-asset"}}, + }, + ) + assert response.status_code == 422 + assert response.json()["code"] == "HTTP_422" + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_create_text_to_video_rejects_audio_flag(client, test_state) -> None: + response = client.post( + "/api/generations/text-to-video", + json={"params": {**_params("fox"), "audio": True}}, + ) + assert response.status_code == 422 + assert response.json()["code"] == "HTTP_422" + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_create_and_retry_wake_after_queued_row_is_visible(client, test_state) -> None: + assert test_state.generation.try_reserve_generation_start() is True + try: + store = _store(test_state) + recorder = _RecordingQueueControl(store) + test_state.queued_generations._queue_control = recorder + + failed = client.post( + "/api/generations/text-to-video", + json=_create_body(contract_version=2), + ) + assert failed.status_code == 422 + assert failed.json()["code"] == "INVALID_GENERATION_SPEC" + assert recorder.queued_visible_on_wake == [] + assert store.has_queued() is False + + created = client.post( + "/api/generations/text-to-video", + json=_create_body(), + ) + assert created.status_code == 200 + generation_id = created.json()["id"] + assert recorder.queued_visible_on_wake == [True] + loaded = store.get_generation(generation_id) + assert loaded is not None + assert loaded.status == "queued" + + claimed = store.claim_next_queued() + assert claimed is not None + store.mark_failed( + generation_id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count + ) + assert store.has_queued() is False + recorder.queued_visible_on_wake.clear() + + retried = client.post(f"/api/generations/{generation_id}/retry") + assert retried.status_code == 200 + assert recorder.queued_visible_on_wake == [True] + reloaded = store.get_generation(generation_id) + assert reloaded is not None + assert reloaded.status == "queued" + finally: + test_state.generation.release_generation_start_reservation() + + +def test_retry_keeps_same_generation_id(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + generation = store.insert_generation("text-to-video", _spec("retry")) + claimed = store.claim_next_queued() + assert claimed is not None + store.mark_failed( + generation.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count + ) + + response = client.post(f"/api/generations/{generation.id}/retry") + + assert response.status_code == 200 + assert response.json()["id"] == generation.id + assert response.json()["status"] == "queued" + + +def test_retry_missing_generation_404(client) -> None: + response = client.post("/api/generations/not-a-real-id/retry") + assert response.status_code == 404 + + +def test_retry_invalid_status_409(client, test_state) -> None: + with _reserved_generation_start(test_state): + store = _store(test_state) + generation = store.insert_generation("text-to-video", _spec("retry")) + response = client.post(f"/api/generations/{generation.id}/retry") + assert response.status_code == 409 + + +def test_lifecycle_routes_are_not_public(client) -> None: + for path in ( + "/api/assets/allocate", + "/api/generations/x/succeeded", + "/api/generations/x/failed", + "/api/generations/x/cancelled", + ): + assert client.post(path, json={}).status_code in {404, 405} + + +def test_handler_construction_does_not_fail_running_generations(test_state) -> None: + store = _store(test_state) + generation = store.insert_generation("text-to-video", {}) + claimed = store.claim_next_queued() + assert claimed is not None + QueuedGenerationHandler( + store=store, + executor_registry=test_state.executor_registry, + derive_local_a2v=test_state.video_generation.derive_local_a2v_params, + ) + loaded = store.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "running" + + +def test_load_persistent_state_fails_running_generations( + test_state, fake_services, default_app_settings +) -> None: + store = _store(test_state) + generation = store.insert_generation("text-to-video", {}) + claimed = store.claim_next_queued() + assert claimed is not None + build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, store), + ) + loaded = store.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "failed" + assert loaded.error_code == "INTERRUPTED" + + +def test_store_unavailable_returns_503_and_other_routes_work( + test_state, fake_services, default_app_settings +) -> None: + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, UnavailableStore()), + ) + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + assert handler.generation_queue.is_running is False + r = client.get("/api/generations", params={"feature": "text-to-video"}) + assert_http_error(r, status_code=503, code="STORE_UNAVAILABLE") + settings = client.get("/api/settings") + assert settings.status_code == 200 + + +class _RecoverFailsStore(SqliteStore): + def fail_running_on_boot(self) -> int: + raise UnavailableError() + + +def test_i2v_executor_uses_store_rebound_by_app_handler( + test_state, fake_services, default_app_settings, tmp_path: Path +) -> None: + old_store = SqliteStore(tmp_path / "old") + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, old_store), + ) + new_store = SqliteStore(tmp_path / "new") + start = new_store.ingest_upload(str(_png(tmp_path / "start.png"))) + generation = new_store.insert_generation( + "image-to-video", + { + "params": {**_params("fox"), "aspectRatio": "16:9"}, + "inputs": {"startFrame": {"assetId": start.id}}, + }, + ) + + handler._bind_store(new_store) + executor = handler.executor_registry.get("image-to-video") + + with pytest.raises( + ValueError, match="text-to-video requires a single 'output' allocation" + ): + executor.execute(generation, ()) + + +def test_boot_recovery_fallback_rebinds_i2v_asset_resolver( + test_state, fake_services, default_app_settings, tmp_path: Path +) -> None: + store = _RecoverFailsStore(tmp_path / "failing") + start = store.ingest_upload(str(_png(tmp_path / "start.png"))) + generation = store.insert_generation( + "image-to-video", + { + "params": {**_params("fox"), "aspectRatio": "16:9"}, + "inputs": {"startFrame": {"assetId": start.id}}, + }, + ) + + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, store), + ) + executor = handler.executor_registry.get("image-to-video") + + with pytest.raises(UnavailableError): + executor.execute(generation, ()) + + +def test_boot_recovery_failure_replaces_handler_and_queue_store( + test_state, fake_services, default_app_settings +) -> None: + store = _RecoverFailsStore(test_state.config.app_data_dir) + generation = store.insert_generation("text-to-video", _spec()) + claimed = store.claim_next_queued() + assert claimed is not None + handler = build_initial_state( + test_state.config, + default_app_settings, + service_bundle=_bundle(fake_services, store), + ) + set_state_service_for_tests(handler) + app = create_app(handler=handler, admin_token=TEST_ADMIN_TOKEN) + with TestClient(app) as client: + assert handler.generation_queue.is_running is False + r = client.get("/api/generations", params={"feature": "text-to-video"}) + assert_http_error(r, status_code=503, code="STORE_UNAVAILABLE") + loaded = store.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "running" + + +def test_open_store_degrades_when_assets_path_is_a_file(tmp_path: Path) -> None: + app_data = tmp_path / "blocked_app_data" + app_data.mkdir() + (app_data / "assets").write_text("not a directory") + db = open_store(app_data) + assert isinstance(db, UnavailableStore) diff --git a/backend/tests/test_ic_lora.py b/backend/tests/test_ic_lora.py index cd483c969..e549640f1 100644 --- a/backend/tests/test_ic_lora.py +++ b/backend/tests/test_ic_lora.py @@ -9,7 +9,6 @@ from tests.http_error_assertions import assert_http_error from tests.fakes import FakeCapture -from tests.conftest import _IC_LORA_MODEL_ID def _write_ic_lora_file(path: Path) -> None: @@ -22,8 +21,8 @@ def _write_ic_lora_file(path: Path) -> None: def _install_ic_lora_capable_model(create_fake_model_files, create_fake_ic_lora_files, *, include_depth: bool = True) -> None: - # Built-in control IC-LoRA is 2.3-only; 2.5 (latest) returns 409 for canny/depth. - create_fake_model_files(model_id=_IC_LORA_MODEL_ID) + # Union Control lives next to the active LTX bundle (2.3 and 2.5 share the 2.3 adapter). + create_fake_model_files() create_fake_ic_lora_files(include_depth=include_depth) @@ -55,6 +54,7 @@ def test_depth_extraction(self, client, test_state, fake_services, create_fake_m assert response.status_code == 200 assert response.json()["conditioning_type"] == "depth" assert fake_services.depth_processor_pipeline.apply_calls == ["frame-a"] + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 def test_depth_extraction_requires_downloaded_ltx_model(self, client, test_state): video_path = test_state.config.outputs_dir / "test_video.mp4" @@ -90,6 +90,63 @@ def test_happy_path(self, client, test_state, create_fake_model_files, create_fa assert response.json()["status"] == "complete" assert Path(response.json()["video_path"]).exists() + def test_stage_2_on_sizes_to_source_not_768_bucket( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + # Built-in canny defaults to two-stage. 540p must not land in the skip-stage-2 768 bucket. + _install_ic_lora_capable_model(create_fake_model_files, create_fake_ic_lora_files) + test_state.state.app_settings.use_local_text_encoder = True + + video_path = test_state.config.outputs_dir / "test_video.mp4" + video_path.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(video_path), FakeCapture(frames=["frame-a", "frame-b"], width=960, height=540) + ) + + response = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + }, + ) + assert response.status_code == 200 + call = fake_services.ic_lora_pipeline.generate_calls[-1] + assert (call["width"], call["height"]) == (896, 512) + assert call["skip_stage_2"] is False + + def test_skip_stage_2_source_mode_matches_catalog( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + # resolution_factor 0 is the same sentinel on canny/depth as on catalog IC-LoRAs. + _install_ic_lora_capable_model(create_fake_model_files, create_fake_ic_lora_files) + test_state.state.app_settings.use_local_text_encoder = True + + video_path = test_state.config.outputs_dir / "test_video.mp4" + video_path.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(video_path), FakeCapture(frames=["frame-a", "frame-b"], width=960, height=540) + ) + + response = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert response.status_code == 200 + call = fake_services.ic_lora_pipeline.generate_calls[-1] + assert (call["width"], call["height"]) == (1920, 1080) + assert call["resolution_factor"] == 1.0 + assert call["skip_stage_2"] is True + def test_stop_after_generate_unlinks_and_returns_cancelled( self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files, caplog ): @@ -127,8 +184,11 @@ def generate_then_cancel(**kwargs): assert not written.exists() assert any(record.getMessage() == "Generation cancelled by user" for record in caplog.records) - def test_builtin_control_rejected_on_2_5(self, client, test_state, create_fake_model_files): - create_fake_model_files() + def test_builtin_control_runs_on_2_5( + self, client, test_state, create_fake_model_files, create_fake_ic_lora_files + ): + # 2.5 reuses the 2.3 Union Control adapter; canny must not 409. + _install_ic_lora_capable_model(create_fake_model_files, create_fake_ic_lora_files) test_state.state.app_settings.use_local_text_encoder = True video_path = test_state.config.outputs_dir / "test_video.mp4" @@ -144,15 +204,8 @@ def test_builtin_control_rejected_on_2_5(self, client, test_state, create_fake_m "images": [], }, ) - assert_http_error( - response, - status_code=409, - code="UNSUPPORTED_IC_LORA", - message=( - "Built-in control IC-LoRA is not available for the active LTX model. " - "Switch to an LTX 2.3 local model to use depth/canny control." - ), - ) + assert response.status_code == 200 + assert response.json()["status"] == "complete" def test_canny_does_not_require_depth_cp(self, client, test_state, create_fake_model_files, create_fake_ic_lora_files): # canny preprocessing uses apply_canny, not the depth processor, so generation @@ -236,13 +289,66 @@ def test_custom_uses_supplied_control_video( # The pipeline got the supplied control video verbatim — not a derived _control_*.mp4. call = fake_services.ic_lora_pipeline.generate_calls[-1] assert call["video_conditioning"] == [(str(control_video), 1.0)] - assert call["num_frames"] == 3 + # A 3-frame clip snaps up to the 9-frame minimum on the 8k+1 grid. + assert call["num_frames"] == 9 # Recoverable via the progress endpoint, like every other local generation. progress = client.get("/api/generation/progress").json() assert progress["status"] == "complete" assert progress["result"] == result_path + def test_custom_control_video_off_the_frame_grid_is_snapped_down_to_121( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + # 123 frames are off the (n - 1) % 8 grid. The pipeline gets 121, not 123 or 129. + create_fake_model_files() + create_fake_ic_lora_files() + test_state.state.app_settings.use_local_text_encoder = True + lora_ref = test_state.config.default_models_dir / "loras" / "my-custom-ic-lora.safetensors" + _write_ic_lora_file(lora_ref) + control_video = test_state.config.outputs_dir / "control.mp4" + control_video.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(control_video), FakeCapture(frames=["c"] * 123, fps=24) + ) + + response = client.post( + "/api/ic-lora/generate", + json={ + "video_path": "", + "conditioning_type": "custom", + "custom_lora_ref": str(lora_ref), + "control_video_path": str(control_video), + "prompt": "make it night", + "images": [], + }, + ) + + assert response.status_code == 200, response.text + assert fake_services.ic_lora_pipeline.generate_calls[-1]["num_frames"] == 121 + + def test_canny_source_video_off_the_frame_grid_is_snapped_down_to_121( + self, client, test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files + ): + _install_ic_lora_capable_model(create_fake_model_files, create_fake_ic_lora_files) + test_state.state.app_settings.use_local_text_encoder = True + video_path = test_state.config.outputs_dir / "test_video.mp4" + video_path.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video(str(video_path), FakeCapture(frames=["f"] * 123)) + + response = client.post( + "/api/ic-lora/generate", + json={ + "video_path": str(video_path), + "conditioning_type": "canny", + "prompt": "test prompt", + "images": [], + }, + ) + + assert response.status_code == 200, response.text + assert fake_services.ic_lora_pipeline.generate_calls[-1]["num_frames"] == 121 + def test_custom_requires_lora_and_control_video(self, client, test_state, create_fake_model_files, create_fake_ic_lora_files): create_fake_model_files() create_fake_ic_lora_files() @@ -258,3 +364,25 @@ def test_custom_requires_lora_and_control_video(self, client, test_state, create }, ) assert response.status_code == 400 + + +def test_resolve_settings_keeps_a_tiled_entry_single_stage() -> None: + from api_types import IcLoraGenerateRequest, IcLoraSettings + from handlers.ic_lora_handler import _resolve_settings + from runtime_config.ic_lora_tiling import IcLoraTiling + + tiled = IcLoraSettings(skip_stage_2=True, tiling=IcLoraTiling(long_side=960, short_side=544)) + for override in (None, True, False): + req = IcLoraGenerateRequest(conditioning_type="custom", prompt="p", skip_stage_2=override) + resolved = _resolve_settings(req, tiled) + assert resolved.skip_stage_2 is True + assert resolved.tiling == tiled.tiling + + +def test_resolve_settings_still_lets_an_untiled_entry_override_stage_2() -> None: + from api_types import IcLoraGenerateRequest, IcLoraSettings + from handlers.ic_lora_handler import _resolve_settings + + untiled = IcLoraSettings(skip_stage_2=True) + assert _resolve_settings(IcLoraGenerateRequest(conditioning_type="custom", prompt="p", skip_stage_2=False), untiled).skip_stage_2 is False + assert _resolve_settings(IcLoraGenerateRequest(conditioning_type="custom", prompt="p"), untiled).skip_stage_2 is True diff --git a/backend/tests/test_ic_lora_chunking.py b/backend/tests/test_ic_lora_chunking.py new file mode 100644 index 000000000..e4e792077 --- /dev/null +++ b/backend/tests/test_ic_lora_chunking.py @@ -0,0 +1,97 @@ +"""IC-LoRA chunking rule: single-stage, above the former cap, past one window.""" + +from __future__ import annotations + +from runtime_config.ic_lora_chunking import ( + IC_LORA_CHUNK_PIXEL_FRAMES, + ic_lora_chunk_pixel_frames, +) +from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.ic_lora_tiling import IcLoraTiling + + +def test_large_single_stage_long_clip_chunks() -> None: + window = ic_lora_chunk_pixel_frames(1920, 1088, 193, stage_mode=IcLoraStageMode.SINGLE_STAGE) + assert window == IC_LORA_CHUNK_PIXEL_FRAMES + + +def test_clip_within_one_window_does_not_chunk() -> None: + assert ic_lora_chunk_pixel_frames(1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE) is None + + +def test_stage_1_lora_never_chunks() -> None: + assert ic_lora_chunk_pixel_frames(1920, 1088, 193, stage_mode=IcLoraStageMode.STAGE_1_LORA) is None + + +def test_job_at_or_below_the_former_cap_does_not_chunk() -> None: + assert ic_lora_chunk_pixel_frames(1024, 576, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE) is None + + +def test_stage_2_ic_lora_sizes_the_stage_2_canvas() -> None: + # Stage 1 of a 1920x1088 canvas is 960x544. + window = ic_lora_chunk_pixel_frames(960, 544, 217, stage_mode=IcLoraStageMode.STAGE_2_LORA) + assert window == IC_LORA_CHUNK_PIXEL_FRAMES + + +def test_stage_2_ic_lora_below_the_token_limit_does_not_chunk() -> None: + # Stage 1 of a 1280x704 canvas is 640x352. + assert ic_lora_chunk_pixel_frames(640, 352, 217, stage_mode=IcLoraStageMode.STAGE_2_LORA) is None + + +def test_off_grid_123_frames_decide_like_121_frames() -> None: + # Both counts are 16 latent frames. At 1920x1088 that is 16 x 2040 = 32640 tokens, + # under the 32940 limit. A raw 123 would count 16.25 latent frames: 33150 tokens. + for frames in (121, 123): + assert ic_lora_chunk_pixel_frames(1920, 1088, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE) is None + # 193 and 195 are both 25 latent frames, so both chunk. + for frames in (193, 195): + window = ic_lora_chunk_pixel_frames(1920, 1088, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE) + assert window == IC_LORA_CHUNK_PIXEL_FRAMES + + +def _restore_tiling(window_frames: int | None = 97) -> IcLoraTiling: + return IcLoraTiling(long_side=960, short_side=544, window_frames=window_frames) + + +def test_fixed_window_keeps_exactly_one_window_whole() -> None: + window = ic_lora_chunk_pixel_frames( + 1920, 1088, 97, stage_mode=IcLoraStageMode.SINGLE_STAGE, tiling=_restore_tiling() + ) + assert window is None + + +def test_fixed_window_chunks_the_next_frame_grid_count() -> None: + # 105 is the first grid count above 97. 98 to 104 snap down to 97. + for frames in (98, 104): + assert ( + ic_lora_chunk_pixel_frames( + 1920, 1088, frames, stage_mode=IcLoraStageMode.SINGLE_STAGE, tiling=_restore_tiling() + ) + is None + ) + window = ic_lora_chunk_pixel_frames( + 1920, 1088, 105, stage_mode=IcLoraStageMode.SINGLE_STAGE, tiling=_restore_tiling() + ) + assert window == 97 + + +def test_fixed_window_chunks_a_small_canvas_that_the_size_rule_leaves_whole() -> None: + # 1024x576 is at the former cap, so the size rule never chunks it. + assert ic_lora_chunk_pixel_frames(1024, 576, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE) is None + window = ic_lora_chunk_pixel_frames( + 1024, 576, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, tiling=_restore_tiling() + ) + assert window == 97 + + +def test_fixed_window_overrides_the_default_window_length() -> None: + window = ic_lora_chunk_pixel_frames( + 1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, tiling=_restore_tiling(window_frames=49) + ) + assert window == 49 + assert window != IC_LORA_CHUNK_PIXEL_FRAMES + + +def test_tiling_without_a_window_leaves_the_choice_to_the_size_rule() -> None: + tiling = IcLoraTiling(long_side=1024, short_side=576) + assert ic_lora_chunk_pixel_frames(1920, 1088, 241, stage_mode=IcLoraStageMode.SINGLE_STAGE, tiling=tiling) is None diff --git a/backend/tests/test_ic_lora_download.py b/backend/tests/test_ic_lora_download.py index 2f9443843..1aa61a857 100644 --- a/backend/tests/test_ic_lora_download.py +++ b/backend/tests/test_ic_lora_download.py @@ -20,7 +20,8 @@ def test_ic_lora_id_cannot_traverse(tmp_path: Path): resolve_ic_lora_path(tmp_path, "../escape", "i.safetensors") -def test_ic_lora_list_reports_downloaded_state(client: TestClient): +def test_ic_lora_list_reports_downloaded_state(client: TestClient, create_fake_model_files): + create_fake_model_files() # FakeLoraCatalogProvider (wired in conftest) returns one IC-LoRA "ingredients-v1". resp = client.get("/api/ic-loras") assert resp.status_code == 200 @@ -30,6 +31,47 @@ def test_ic_lora_list_reports_downloaded_state(client: TestClient): assert items[0]["downloaded_variant_ids"] == [] +def test_ic_lora_list_empty_when_no_ltx_family_installed(client: TestClient): + resp = client.get("/api/ic-loras") + assert resp.status_code == 200 + assert resp.json()["ic_loras"] == [] + assert client.get("/api/ic-loras", params={"fresh": False}).json()["ic_loras"] == [] + + fresh = client.get("/api/ic-loras", params={"fresh": True}) + assert fresh.status_code == 200 + ids = [item["ic_lora"]["id"] for item in fresh.json()["ic_loras"]] + assert "ingredients-v1" in ids + assert "colorize-v1" in ids + + +def test_ic_lora_list_hides_when_required_family_missing( + client: TestClient, create_fake_model_files, fake_services +): + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + catalog = fake_services.lora_catalog_provider._catalog + fake_services.lora_catalog_provider._catalog = catalog.model_copy( + update={ + "ic_loras": [ + catalog.ic_loras[0].model_copy(update={"supported_models": ["LTX-2.3"]}), + *catalog.ic_loras[1:], + ] + } + ) + + resp = client.get("/api/ic-loras") + assert resp.status_code == 200 + ids = [item["ic_lora"]["id"] for item in resp.json()["ic_loras"]] + assert "ingredients-v1" not in ids + assert "colorize-v1" in ids + + fresh_ids = [ + item["ic_lora"]["id"] + for item in client.get("/api/ic-loras", params={"fresh": True}).json()["ic_loras"] + ] + assert "ingredients-v1" in fresh_ids + assert "colorize-v1" in fresh_ids + + def test_ic_lora_download_then_progress_complete(client: TestClient): start = client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) assert start.status_code == 200 @@ -83,3 +125,43 @@ def test_ic_lora_download_flag_requires_auth_and_leaves_no_session(client: TestC # Once signed in again, a subsequent download still starts (would 409 if the session had leaked). test_state.state.hf_auth_state = original_auth assert client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}).status_code == 200 + + +def test_download_omits_variant_id_fetches_index_zero_when_a_later_variant_exists( + client: TestClient, fake_services +): + start = client.post("/api/ic-loras/download", json={"ic_lora_id": "multi-v1"}) + assert start.status_code == 200, start.text + call = fake_services.model_downloader.calls[-1] + assert call["filename"] == "strong.safetensors" + assert call["repo_id"] == "org/multi" + + +def test_download_uses_the_variant_repo_when_the_checkpoint_names_one( + client: TestClient, fake_services +): + catalog = fake_services.lora_catalog_provider._catalog + ic_loras = [] + for item in catalog.ic_loras: + if item.id != "multi-v1": + ic_loras.append(item) + continue + newer = item.download.variants[0].model_copy(update={"repo_id": "org/newer"}) + ic_loras.append( + item.model_copy( + update={ + "download": item.download.model_copy( + update={"variants": [newer, *item.download.variants[1:]]} + ) + } + ) + ) + fake_services.lora_catalog_provider._catalog = catalog.model_copy( + update={"ic_loras": ic_loras} + ) + + start = client.post("/api/ic-loras/download", json={"ic_lora_id": "multi-v1"}) + assert start.status_code == 200, start.text + call = fake_services.model_downloader.calls[-1] + assert call["filename"] == "strong.safetensors" + assert call["repo_id"] == "org/newer" diff --git a/backend/tests/test_ic_lora_generate.py b/backend/tests/test_ic_lora_generate.py index 193d39029..c82de809f 100644 --- a/backend/tests/test_ic_lora_generate.py +++ b/backend/tests/test_ic_lora_generate.py @@ -3,8 +3,23 @@ import numpy as np from fastapi.testclient import TestClient +from PIL import Image +from frame_math import compute_num_frames +from runtime_config.ic_lora_local_envelope import IC_LORA_SOURCE_TOO_LARGE, IC_LORA_V1_ENVELOPE_MESSAGE +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + VIDEO_JOB_TOO_LARGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, +) from tests.fakes import FakeCapture +from tests.http_error_assertions import assert_http_error + + +def _write_png(path: Path, size: tuple[int, int] = (1, 1)) -> Path: + Image.new("RGB", size, color=(1, 2, 3)).save(path, format="PNG") + return path def test_ic_lora_generate_runs_inference(client: TestClient, tmp_path: Path, create_fake_model_files, fake_services): @@ -13,7 +28,7 @@ def test_ic_lora_generate_runs_inference(client: TestClient, tmp_path: Path, cre start = client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) assert start.status_code == 200 img = tmp_path / "in.png" - img.write_bytes(b"\x89PNG\r\n") + _write_png(img) resp = client.post( "/api/ic-lora/generate", json={ @@ -30,13 +45,41 @@ def test_ic_lora_generate_runs_inference(client: TestClient, tmp_path: Path, cre assert fake_services.ic_lora_pipeline.generate_calls[-1]["num_frames"] == 121 +def test_ic_lora_generate_rejects_when_required_ltx_family_missing( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services +): + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + catalog = fake_services.lora_catalog_provider._catalog + fake_services.lora_catalog_provider._catalog = catalog.model_copy( + update={ + "ic_loras": [ + catalog.ic_loras[0].model_copy(update={"supported_models": ["LTX-2.3"]}), + *catalog.ic_loras[1:], + ] + } + ) + client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) + img = tmp_path / "in.png" + _write_png(img) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "prompt": "a slow orbit", + "conditioning_type": "custom", + }, + ) + assert_http_error(resp, status_code=422, code="IC_LORA_UNSUPPORTED_MODEL") + + def test_catalog_stop_after_generate_unlinks_and_returns_cancelled( client: TestClient, tmp_path: Path, test_state, create_fake_model_files, fake_services, caplog ): create_fake_model_files() client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) img = tmp_path / "in.png" - img.write_bytes(b"\x89PNG\r\n") + _write_png(img) pipeline = fake_services.ic_lora_pipeline real_generate = pipeline.generate @@ -71,7 +114,7 @@ def test_ic_lora_generate_uses_ic_lora_default_when_no_override( create_fake_model_files() client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) img = tmp_path / "in.png" - img.write_bytes(b"\x89PNG\r\n") + _write_png(img) resp = client.post( "/api/ic-lora/generate", json={"ic_lora_id": "ingredients-v1", "input_path": str(img), "prompt": "p", "conditioning_type": "custom"}, @@ -87,7 +130,7 @@ def test_ic_lora_generate_respects_skip_stage_2_override( create_fake_model_files() client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) img = tmp_path / "in.png" - img.write_bytes(b"\x89PNG\r\n") + _write_png(img) resp = client.post( "/api/ic-lora/generate", json={ @@ -151,11 +194,69 @@ def test_ic_lora_resolution_factor_zero_matches_source( assert call["resolution_factor"] == 1.0 # multiplier ignored in source mode -def test_ic_lora_rejects_image_for_video_input(client: TestClient, tmp_path: Path): +def test_ic_lora_stage_2_on_sizes_to_source_not_768_bucket( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + # Two-stage output is the passed canvas (stage 1 runs at half). A 540p source must + # not fall through to the skip-stage-2 768-wide bucket (768x384). + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * 50, fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": False, + }, + ) + assert resp.status_code == 200 + call = fake_services.ic_lora_pipeline.generate_calls[-1] + assert (call["width"], call["height"]) == (896, 512) # source snapped down to /128 + assert call["skip_stage_2"] is False + + +def test_ic_lora_stage_2_on_caps_explicit_resolution_to_source( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * 50, fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": False, + "resolution": {"width": 512, "height": 256}, + }, + ) + assert resp.status_code == 200 + call = fake_services.ic_lora_pipeline.generate_calls[-1] + assert (call["width"], call["height"]) == (512, 256) + + +def test_ic_lora_rejects_image_for_video_input( + client: TestClient, tmp_path: Path, create_fake_model_files +): # colorize-v1 expects a video input; feeding an image must fail with a clean 400 - # (not a deep pipeline 500). Fires before the download check, so no setup needed. + # (not a deep pipeline 500). Fires before the download check; still needs an LTX + # family on disk so the catalog visibility gate doesn't 422 first. + create_fake_model_files() img = tmp_path / "in.png" - img.write_bytes(b"\x89PNG\r\n") + _write_png(img) resp = client.post( "/api/ic-lora/generate", json={"ic_lora_id": "colorize-v1", "input_path": str(img), "prompt": "p", "conditioning_type": "custom"}, @@ -163,8 +264,11 @@ def test_ic_lora_rejects_image_for_video_input(client: TestClient, tmp_path: Pat assert resp.status_code == 400 -def test_ic_lora_rejects_video_for_image_input(client: TestClient, tmp_path: Path): +def test_ic_lora_rejects_video_for_image_input( + client: TestClient, tmp_path: Path, create_fake_model_files +): # ingredients-v1 expects an image input; feeding a video must 400. + create_fake_model_files() clip = tmp_path / "in.mp4" clip.write_bytes(b"\x00" * 10) resp = client.post( @@ -265,8 +369,11 @@ def test_outpaint_runs_with_empty_prompt( assert resp.status_code == 200, resp.text -def test_ic_lora_empty_prompt_rejected_without_flag(client: TestClient, tmp_path: Path): +def test_ic_lora_empty_prompt_rejected_without_flag( + client: TestClient, tmp_path: Path, create_fake_model_files +): # colorize-v1 has no allows_empty_prompt → a blank prompt is rejected. + create_fake_model_files() src = tmp_path / "in.mp4" src.write_bytes(b"\x00") resp = client.post( @@ -311,7 +418,7 @@ def test_reference_image_forwarded_when_allowed( src = tmp_path / "in.mp4" src.write_bytes(b"\x00") ref = tmp_path / "ref.png" - ref.write_bytes(b"\x89PNG\r\n") + _write_png(ref) resp = client.post( "/api/ic-lora/generate", json={ @@ -359,7 +466,7 @@ def test_reference_image_ignored_when_not_allowed( src = tmp_path / "in.mp4" src.write_bytes(b"\x00") ref = tmp_path / "ref.png" - ref.write_bytes(b"\x89PNG\r\n") + _write_png(ref) resp = client.post( "/api/ic-lora/generate", json={ @@ -374,6 +481,30 @@ def test_reference_image_ignored_when_not_allowed( assert fake_services.ic_lora_pipeline.generate_calls[-1]["images"] == [] +def test_request_cannot_pin_a_reference_image_at_the_negative_still_frame( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services +): + # Only a catalog entry pins the look still at -1. A request frame of -1 is a 422. + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "refimg-v1"}) + src = tmp_path / "in.mp4" + src.write_bytes(b"\x00") + ref = tmp_path / "ref.png" + _write_png(ref) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "refimg-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "images": [{"path": str(ref), "frame": -1, "strength": 1.0}], + }, + ) + assert resp.status_code == 422 + assert fake_services.ic_lora_pipeline.generate_calls == [] + + def test_canny_empty_prompt_rejected(client: TestClient, tmp_path: Path): # The non-catalog canny path has no entry to opt into promptless runs. src = tmp_path / "v.mp4" @@ -459,7 +590,10 @@ def test_download_unknown_variant_id_404(client: TestClient): assert resp.status_code == 404 -def test_list_reports_downloaded_variant_ids_after_partial_download(client: TestClient): +def test_list_reports_downloaded_variant_ids_after_partial_download( + client: TestClient, create_fake_model_files +): + create_fake_model_files() before = client.get("/api/ic-loras").json()["ic_loras"] multi = next(i for i in before if i["ic_lora"]["id"] == "multi-v1") assert multi["downloaded"] is False @@ -475,3 +609,505 @@ def test_list_reports_downloaded_variant_ids_after_partial_download(client: Test assert multi["downloaded_variant_ids"] == ["light"] # Default (strong) still missing. assert "strong" not in multi["downloaded_variant_ids"] + + +def test_ic_lora_generate_uses_process_loading_mode( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + assert test_state.config.local_generations_mode == "full_models_loading" + client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) + img = tmp_path / "in.png" + _write_png(img) + resp = client.post( + "/api/ic-lora/generate", + json={"ic_lora_id": "ingredients-v1", "input_path": str(img), "prompt": "p", "conditioning_type": "custom"}, + ) + assert resp.status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count is None + assert test_state.config.local_generations_mode == "full_models_loading" + + +def test_ic_lora_10s_540p_streams( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + assert test_state.config.local_generations_mode == "full_models_loading" + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * compute_num_frames(10, 24), fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert resp.status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + +def test_ic_lora_rejects_2160p_source_dimensions( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * 50, fps=24, width=3840, height=2160) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert_http_error( + resp, + status_code=422, + code=IC_LORA_SOURCE_TOO_LARGE, + message=IC_LORA_V1_ENVELOPE_MESSAGE, + ) + + +def test_ic_lora_streams_longer_than_20s_540p( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + assert test_state.config.local_generations_mode == "full_models_loading" + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * 521, fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert resp.status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + +def test_ic_lora_accepts_snapped_20s_540p( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + frames = compute_num_frames(20, 24) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * frames, fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert resp.status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + +def test_ic_lora_rebuilds_pipeline_when_job_switches_to_stream( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + short = tmp_path / "short.mp4" + long = tmp_path / "long.mp4" + short.write_bytes(b"\x00" * 100) + long.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(short), FakeCapture(frames=["f"] * compute_num_frames(5, 24), fps=24, width=960, height=540) + ) + test_state.video_processor.register_video( + str(long), FakeCapture(frames=["f"] * compute_num_frames(20, 24), fps=24, width=960, height=540) + ) + payload = { + "ic_lora_id": "colorize-v1", + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + } + assert client.post("/api/ic-lora/generate", json={**payload, "input_path": str(short)}).status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count is None + first_creates = fake_services.ic_lora_pipeline.create_count + assert client.post("/api/ic-lora/generate", json={**payload, "input_path": str(long)}).status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 + assert fake_services.ic_lora_pipeline.create_count == first_creates + 1 + + +def test_ic_lora_list_filters_duration_options_on_small_vram( + client: TestClient, test_state, create_fake_model_files +): + create_fake_model_files() + listed = client.get("/api/ic-loras").json()["ic_loras"] + ingredients = next(i for i in listed if i["ic_lora"]["id"] == "ingredients-v1") + duration = next(c for c in ingredients["ic_lora"]["controls"] if c["id"] == "duration") + assert duration["options"] == [5, 8, 20] + + test_state.config.vram_gb = 10 + listed = client.get("/api/ic-loras").json()["ic_loras"] + ingredients = next(i for i in listed if i["ic_lora"]["id"] == "ingredients-v1") + duration = next(c for c in ingredients["ic_lora"]["controls"] if c["id"] == "duration") + assert 20 not in duration["options"] + assert 5 in duration["options"] + assert duration["default"] in duration["options"] + + +def test_ic_lora_list_survives_junk_catalog_fps( + client: TestClient, fake_services, create_fake_model_files +): + create_fake_model_files() + from api_types import PreprocessingStep + + catalog = fake_services.lora_catalog_provider._catalog + updated = [] + for item in catalog.ic_loras: + if item.id == "ingredients-v1": + updated.append( + item.model_copy( + update={ + "preprocessing": [ + PreprocessingStep(utility="image_to_frames", params={"fps": None}) + ] + } + ) + ) + else: + updated.append(item) + fake_services.lora_catalog_provider._catalog = catalog.model_copy(update={"ic_loras": updated}) + resp = client.get("/api/ic-loras") + assert resp.status_code == 200 + assert any(row["ic_lora"]["id"] == "ingredients-v1" for row in resp.json()["ic_loras"]) + + +def test_ic_lora_stream_over_540p_returns_job_too_large( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + create_fake_model_files() + test_state.config.vram_gb = 8 + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * compute_num_frames(20, 24), fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert_http_error( + resp, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + + +def test_ic_lora_unsupported_returns_local_generation_unsupported( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) + test_state.config.local_generations_mode = "unsupported" + img = tmp_path / "in.png" + _write_png(img, size=(1024, 576)) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "prompt": "p", + "conditioning_type": "custom", + }, + ) + assert_http_error( + resp, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) + body = resp.json()["message"].lower() + assert "api" not in body + assert "resolution" not in body + + +def test_ic_lora_unsupported_without_weights_is_unsupported_not_not_downloaded( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + """The real fresh-install case: downloads are disabled, so weights are never present.""" + create_fake_model_files() + test_state.config.local_generations_mode = "unsupported" + img = tmp_path / "in.png" + _write_png(img, size=(1024, 576)) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "prompt": "p", + "conditioning_type": "custom", + }, + ) + assert_http_error( + resp, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) + + +def test_ic_lora_unsupported_oversized_source_is_unsupported_not_spatial( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) + test_state.config.local_generations_mode = "unsupported" + img = tmp_path / "in.png" + _write_png(img, size=(1280, 720)) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "ingredients-v1", + "input_path": str(img), + "prompt": "p", + "conditioning_type": "custom", + }, + ) + assert_http_error( + resp, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) + body = resp.json()["message"].lower() + assert "api" not in body + assert "resolution" not in body + + +def test_ic_lora_darwin_does_not_422_20s_540p( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services, test_state +): + create_fake_model_files() + test_state.config.darwin_unified_memory = True + test_state.config.available_ram_gb = 20 + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * compute_num_frames(20, 24), fps=24, width=960, height=540) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + }, + ) + assert resp.status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 + + +def test_ic_lora_fps_override_budgets_resampled_frames( + client: TestClient, + tmp_path: Path, + create_fake_model_files, + create_fake_ic_lora_files, + fake_services, + test_state, +): + create_fake_model_files() + create_fake_ic_lora_files() + test_state.config.vram_gb = 20 + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + frames = compute_num_frames(20, 24) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * frames, fps=24, width=960, height=540) + ) + payload = { + "video_path": str(src), + "conditioning_type": "canny", + "prompt": "p", + "skip_stage_2": True, + "resolution_factor": 0, + } + over = client.post("/api/ic-lora/generate", json=payload) + assert_http_error( + over, + status_code=422, + code=VIDEO_JOB_TOO_LARGE, + message=VIDEO_JOB_TOO_LARGE_MESSAGE, + ) + ok = client.post("/api/ic-lora/generate", json={**payload, "fps_override": 12}) + assert ok.status_code == 200 + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count == 2 + + +def test_ic_lora_rejects_unreadable_image(client: TestClient, tmp_path: Path, create_fake_model_files): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) + img = tmp_path / "in.png" + img.write_bytes(b"not-a-png") + resp = client.post( + "/api/ic-lora/generate", + json={"ic_lora_id": "ingredients-v1", "input_path": str(img), "prompt": "p", "conditioning_type": "custom"}, + ) + assert resp.status_code == 400 + assert "Could not read the input image" in resp.json()["message"] + + +def test_ic_lora_rejects_unreadable_video( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video(str(src), FakeCapture(opened=False)) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + }, + ) + assert resp.status_code == 400 + assert "Could not read the input video" in resp.json()["message"] + + +def test_ic_lora_rejects_zero_size_video( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "colorize-v1"}) + src = tmp_path / "clip.mp4" + src.write_bytes(b"\x00" * 100) + test_state.video_processor.register_video( + str(src), FakeCapture(frames=["f"] * 9, width=0, height=0, fps=24) + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "colorize-v1", + "input_path": str(src), + "prompt": "p", + "conditioning_type": "custom", + }, + ) + assert resp.status_code == 400 + assert "Could not read the input video" in resp.json()["message"] + + +def test_outpaint_over_spatial_cap_unlinks_mask( + client: TestClient, tmp_path: Path, create_fake_model_files, fake_services +): + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "outpaint-v1"}) + src = tmp_path / "in.mp4" + src.write_bytes(b"\x00") + fake_services.video_processor.videos[str(src)] = FakeCapture( + frames=[np.full((720, 1280, 3), 0x40, dtype=np.uint8) for _ in range(9)], + width=1280, + height=720, + fps=24, + ) + resp = client.post( + "/api/ic-lora/generate", + json={ + "ic_lora_id": "outpaint-v1", + "input_path": str(src), + "prompt": "extend the scene", + "conditioning_type": "custom", + "skip_stage_2": True, + "resolution_factor": 0, + "outpaint_pads": {"left": 1280, "right": 0, "top": 0, "bottom": 0}, + }, + ) + assert_http_error( + resp, + status_code=422, + code=IC_LORA_SOURCE_TOO_LARGE, + message=IC_LORA_V1_ENVELOPE_MESSAGE, + ) + written = [writer.path for writer in fake_services.video_processor.writers] + assert len(written) >= 2 + for path in written: + assert not path.exists(), path + + +def test_catalog_preprocess_runs_after_generation_started( + client: TestClient, tmp_path: Path, create_fake_model_files, test_state, monkeypatch +): + from services.generation_interrupt import GenerationCancelledError + + import handlers.ic_lora_handler as handler_mod + + create_fake_model_files() + client.post("/api/ic-loras/download", json={"ic_lora_id": "ingredients-v1"}) + img = tmp_path / "in.png" + _write_png(img) + seen: dict[str, object] = {} + + def spy(steps, artifact, ctx): + running = test_state.generation._running_generation() + assert running is not None + _, gen = running + assert gen.progress.phase == "loading_model" + assert ctx.on_frame is not None + seen["ok"] = True + raise GenerationCancelledError() + + monkeypatch.setattr(handler_mod, "run_preprocessing", spy) + resp = client.post( + "/api/ic-lora/generate", + json={"ic_lora_id": "ingredients-v1", "input_path": str(img), "prompt": "p", "conditioning_type": "custom"}, + ) + assert resp.status_code == 200 + assert resp.json()["status"] == "cancelled" + assert seen["ok"] is True diff --git a/backend/tests/test_ic_lora_local_envelope.py b/backend/tests/test_ic_lora_local_envelope.py new file mode 100644 index 000000000..460d66cc4 --- /dev/null +++ b/backend/tests/test_ic_lora_local_envelope.py @@ -0,0 +1,120 @@ +"""v1 IC-LoRA local envelope: 1080p-class spatial. Duration is the token budget.""" + +from __future__ import annotations + +from api_types import TargetResolution +from frame_math import compute_num_frames +from runtime_config.ic_lora_local_envelope import ( + IC_LORA_SOURCE_TOO_LARGE, + ic_lora_output_canvas, + ic_lora_v1_canvas_envelope_error, + ic_lora_v1_envelope_error, + stage1_size, +) + + +def test_stage1_is_half_canvas() -> None: + # skip_stage_2 renders at canvas//2; source-dim jobs pass 2×source as canvas. + assert stage1_size(1920, 1080) == (960, 540) + + +def test_540p_20s_fits_spatially() -> None: + assert ic_lora_v1_envelope_error(960, 540, duration_seconds=20.0) is None + assert ic_lora_v1_envelope_error(1024, 576, duration_seconds=20.0) is None + + +def test_skip_stage_2_explicit_resolution_is_not_the_768_bucket() -> None: + explicit = ic_lora_output_canvas( + skip_stage_2=True, + resolution_factor=1.5, + input_width=960, + input_height=540, + resolution=TargetResolution(width=1024, height=576), + ) + assert explicit == (2048, 1152, 1.0) + bucket = ic_lora_output_canvas( + skip_stage_2=True, + resolution_factor=1.5, + input_width=960, + input_height=540, + resolution=None, + ) + assert bucket[0] == 768 + assert bucket[2] == 1.5 + + +def test_1080p_cell_fits_and_larger_is_over() -> None: + for width, height in ((1280, 704), (1920, 1088)): + assert ic_lora_v1_envelope_error(width, height, duration_seconds=5.0) is None + for width, height in ((2560, 1440), (3840, 2160)): + err = ic_lora_v1_envelope_error(width, height, duration_seconds=5.0) + assert err is not None + assert err.code == IC_LORA_SOURCE_TOO_LARGE + + +def test_540p_longer_than_20s_is_still_spatial_ok() -> None: + # Duration is no longer a hard 20s cap; the job budget decides stream vs 422. + assert ic_lora_v1_envelope_error(960, 540, duration_seconds=20.1) is None + + +def test_portrait_540p_fits() -> None: + assert ic_lora_v1_envelope_error(576, 1024, duration_seconds=8.0) is None + + +def test_snapped_20s_canvas_fits() -> None: + # compute_num_frames(20, 24) == 481, slightly over 20.0s of wall time. + frames = compute_num_frames(20, 24) + assert ic_lora_v1_canvas_envelope_error(1920, 1080, frame_count=frames, fps=24.0) is None + + +def test_over_snapped_20s_canvas_is_still_spatial_ok() -> None: + frames = compute_num_frames(20, 24) + 8 + assert ic_lora_v1_canvas_envelope_error(1920, 1080, frame_count=frames, fps=24.0) is None + + +def _stage_2_ic_lora_canvas( + width: int, height: int, resolution: TargetResolution | None = None +) -> tuple[int, int]: + canvas_w, canvas_h, factor = ic_lora_output_canvas( + skip_stage_2=False, + resolution_factor=1.0, + input_width=width, + input_height=height, + resolution=resolution, + stage_2_ic_lora=True, + ) + assert factor == 1.0 + return canvas_w, canvas_h + + +def test_stage_2_canvas_of_a_1250x704_source_at_720p_keeps_the_source_height() -> None: + # The 128 grid would give 1152x640. The 64 grid keeps 1216x704, 2.7% off the source aspect. + canvas = _stage_2_ic_lora_canvas(1250, 704, TargetResolution(width=1280, height=720)) + assert canvas == (1216, 704) + + +def test_stage_2_canvas_never_upscales_a_540p_source() -> None: + # 960x540 on the 64 grid is 896x512 (1.4% off aspect). 960x576 would exceed the source. + for resolution in (None, TargetResolution(width=1920, height=1080)): + width, height = _stage_2_ic_lora_canvas(960, 540, resolution) + assert (width, height) == (896, 512) + assert width <= 960 and height <= 540 + assert width % 64 == 0 and height % 64 == 0 + + +def test_stage_2_canvas_of_a_2160p_source_without_a_resolution_is_the_1080p_cell() -> None: + assert _stage_2_ic_lora_canvas(3840, 2160) == (1920, 1088) + + +def test_stage_2_canvas_of_a_1080p_source_at_1080p_stays_inside_the_source_height() -> None: + # 1920x1088 would be 0.7% off aspect but its height is above the 1080 source. + assert _stage_2_ic_lora_canvas(1920, 1080, TargetResolution(width=1920, height=1080)) == (1856, 1024) + + +def test_stage_2_canvas_of_a_source_below_one_cell_is_the_64x64_minimum() -> None: + assert _stage_2_ic_lora_canvas(40, 30) == (64, 64) + + +def test_stage_2_canvas_of_a_portrait_source_on_the_grid_is_unchanged() -> None: + assert _stage_2_ic_lora_canvas(704, 1280) == (704, 1280) + assert _stage_2_ic_lora_canvas(704, 1280, TargetResolution(width=720, height=1280)) == (704, 1280) diff --git a/backend/tests/test_ic_lora_preprocessing.py b/backend/tests/test_ic_lora_preprocessing.py index 3569acb0f..f8e21e8e1 100644 --- a/backend/tests/test_ic_lora_preprocessing.py +++ b/backend/tests/test_ic_lora_preprocessing.py @@ -28,6 +28,26 @@ def test_image_to_frames_produces_video_artifact(tmp_path: Path): assert out.frame_count == 25 +def test_image_to_frames_calls_on_frame_per_frame(tmp_path: Path): + calls = {"n": 0} + + def on_frame() -> None: + calls["n"] += 1 + + ctx = PreprocessingContext( + num_frames=9, + outputs_dir=tmp_path, + video_processor=FakeVideoProcessor(), + on_frame=on_frame, + ) + run_preprocessing( + [PreprocessingStep(utility="image_to_frames", params={"fps": 24})], + MediaArtifact(path=str(tmp_path / "in.png"), kind="image"), + ctx, + ) + assert calls["n"] == 9 + + def test_pipeline_must_end_in_video(tmp_path: Path): # An image input with no steps still ends as an image -> rejected. inp_img = MediaArtifact(path="x.png", kind="image") diff --git a/backend/tests/test_image_edit.py b/backend/tests/test_image_edit.py index 2fc5ba5a4..fddd41e16 100644 --- a/backend/tests/test_image_edit.py +++ b/backend/tests/test_image_edit.py @@ -7,6 +7,10 @@ from services.generation_interrupt import GenerationCancelledError from services.services_utils import compute_edit_dimensions +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, +) from tests.http_error_assertions import assert_http_error @@ -307,7 +311,12 @@ def test_missing_fal_key(self, client, test_state, tmp_path): "/api/generate-image", json={"prompt": "x", "imagePath": src, "strength": 0.6}, ) - assert_http_error(r, status_code=500, code="FAL_API_KEY_NOT_CONFIGURED") + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) def test_cancelled(self, client, test_state, fake_services, tmp_path): self._force_api(test_state) diff --git a/backend/tests/test_image_to_video_aspect.py b/backend/tests/test_image_to_video_aspect.py new file mode 100644 index 000000000..02d708cb7 --- /dev/null +++ b/backend/tests/test_image_to_video_aspect.py @@ -0,0 +1,24 @@ +from services.features.video.image_to_video import find_closest_aspect_ratio_option + + +_LOCAL = ("21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16") +_API_2_3 = ("16:9", "9:16") +_API_2_5 = ("16:9", "3:2", "1:1", "9:16") + + +def test_find_closest_aspect_ratio_option_uses_studio_ratio_distance() -> None: + assert find_closest_aspect_ratio_option(2560, 1080, _LOCAL) == "21:9" + assert find_closest_aspect_ratio_option(1920, 1080, _LOCAL) == "16:9" + assert find_closest_aspect_ratio_option(1080, 1920, _LOCAL) == "9:16" + assert find_closest_aspect_ratio_option(1500, 1000, _LOCAL) == "3:2" + assert find_closest_aspect_ratio_option(400, 300, _LOCAL) == "4:3" + assert find_closest_aspect_ratio_option(32, 32, _LOCAL) == "1:1" + assert find_closest_aspect_ratio_option(1080, 1350, _LOCAL) == "4:5" + + +def test_closest_aspect_stays_inside_the_cell() -> None: + assert find_closest_aspect_ratio_option(32, 32, _API_2_3) == "9:16" + assert find_closest_aspect_ratio_option(1080, 1350, _API_2_3) == "9:16" + assert find_closest_aspect_ratio_option(32, 32, _API_2_5) == "1:1" + assert find_closest_aspect_ratio_option(400, 300, _API_2_5) == "3:2" + assert find_closest_aspect_ratio_option(1080, 1350, _API_2_5) == "1:1" diff --git a/backend/tests/test_letterbox.py b/backend/tests/test_letterbox.py new file mode 100644 index 000000000..36aa5fab5 --- /dev/null +++ b/backend/tests/test_letterbox.py @@ -0,0 +1,27 @@ +"""Letterbox pad and crop shared by retake and extend.""" + +from __future__ import annotations + +import numpy as np + +from handlers.video_resolution import generation_letterbox +from services.retake_pipeline.letterbox import crop_letterbox, fit_and_pad + + +def test_pad_then_crop_restores_the_1080p_picture() -> None: + box = generation_letterbox(8, 6) + picture = np.arange(8 * 6 * 3, dtype=np.uint8).reshape(6, 8, 3) + canvas = fit_and_pad(picture, box) + assert canvas.shape == (box.canvas_height, box.canvas_width, 3) + assert canvas[: box.top].sum() == 0 + assert canvas[box.top + box.content_height :].sum() == 0 + assert np.array_equal(crop_letterbox(canvas, box), picture) + + +def test_fit_and_pad_scales_a_larger_source_into_the_picture_before_padding() -> None: + box = generation_letterbox(4, 2) + source = np.full((4, 8, 3), 90, dtype=np.uint8) + canvas = fit_and_pad(source, box) + cropped = crop_letterbox(canvas, box) + assert cropped.shape == (2, 4, 3) + assert cropped.min() == 90 diff --git a/backend/tests/test_local_compat_matrix.py b/backend/tests/test_local_compat_matrix.py new file mode 100644 index 000000000..eb7270008 --- /dev/null +++ b/backend/tests/test_local_compat_matrix.py @@ -0,0 +1,47 @@ +"""Published matrix is the 181 generate projection, not a second Yes table.""" + +from __future__ import annotations + +from pathlib import Path + +from runtime_config.local_compat_matrix import MATRIX_PATH, render_compat_matrix, write_compat_matrix + + +def test_cuda_stream_t2v_yes_but_not_a_full_yes_table() -> None: + md = render_compat_matrix() + assert "| T2V | No | Yes | Yes | No | Yes | No |" in md + assert "CUDA stream (16 GB) still runs T2V" in md + assert "hides 720p/20s" in md + assert "1080p/10s" in md + + +def test_darwin_keeps_ceiling_and_ic_lora_footnote() -> None: + md = render_compat_matrix() + assert "| IC-LoRA | No | Yes | Yes | No | Yes | No |" in md + assert "Darwin IC-LoRA duration is unbounded" in md + assert "no token 422" in md + assert "Do not invent a CUDA-curve ceiling" in md + + +def test_intel_mac_and_cuda_unsupported_are_no() -> None: + md = render_compat_matrix() + assert "| 2.5 download | No | Yes | Yes | No | Yes | No |" in md + assert "integer **15** GiB VRAM" in md + assert "Darwin **32** GiB total RAM" in md + assert "~72 GB" in md + + +def test_retake_extend_follow_the_default_local_model() -> None: + """2.5 advertises Retake/Extend, so hardware-viable columns are a plain Yes.""" + md = render_compat_matrix() + assert "| Retake | No | Yes | Yes | No | Yes | No |" in md + assert "| Extend | No | Yes | Yes | No | Yes | No |" in md + + +def test_committed_matrix_matches_renderer() -> None: + assert MATRIX_PATH.read_text(encoding="utf-8") == render_compat_matrix() + + +def test_write_compat_matrix_roundtrip(tmp_path: Path) -> None: + path = write_compat_matrix(tmp_path / "local-compat-matrix.md") + assert path.read_text(encoding="utf-8") == render_compat_matrix() diff --git a/backend/tests/test_lora_catalog.py b/backend/tests/test_lora_catalog.py index ae049fb3d..7903d754f 100644 --- a/backend/tests/test_lora_catalog.py +++ b/backend/tests/test_lora_catalog.py @@ -8,7 +8,7 @@ _VALID = """ {"schema_version": 1, "ic_loras": [{ "id": "ingredients-v1", "name": "Ingredients", "description": "d", - "download": {"repo_id": "Lightricks/x", "variants": [{"id": "default", "label": "Default", "filename": "i.safetensors", "size_bytes": 10}]}, + "download": {"repo_id": "Lightricks/x", "variants": [{"id": "default", "label": "Default", "filename": "i.safetensors", "size_bytes": 10, "base_model": "LTX-2.3"}]}, "requires_hf_login": true, "input": {"kind": "image"}, "preprocessing": [{"utility": "image_to_frames", "params": {}}], @@ -49,11 +49,14 @@ def test_supported_models_rejects_empty_and_duplicates(): parse_lora_catalog(dup) -def test_shipped_catalog_allows_2_3_and_2_5(): +def test_shipped_ingredients_is_2_3_only(): catalog = Path(__file__).parent.parent / "runtime_config" / "lora_catalog.json" cat = parse_lora_catalog(catalog.read_text(encoding="utf-8")) + ing = next(r for r in cat.ic_loras if r.id == "ingredients") + assert ing.supported_models == ["LTX-2.3"] for item in [*cat.loras, *cat.ic_loras]: - assert item.supported_models == ["LTX-2.3", "LTX-2.5"], item.id + assert item.supported_models, item.id + assert len(item.supported_models) == len(set(item.supported_models)), item.id def test_controls_default_to_empty(): no_controls = _VALID.replace( @@ -138,7 +141,7 @@ def test_file_provider_reads_local_file(tmp_path: Path): _VALID_LORA = """ {"schema_version": 1, "loras": [{ "id": "my-style", "name": "My Style", "description": "d", - "download": {"repo_id": "Lightricks/s", "variants": [{"id": "default", "label": "Default", "filename": "s.safetensors", "size_bytes": 5}]}, + "download": {"repo_id": "Lightricks/s", "variants": [{"id": "default", "label": "Default", "filename": "s.safetensors", "size_bytes": 5, "base_model": "LTX-2.3"}]}, "requires_hf_login": false, "instructions": [{"kind": "prompting", "title": "Prompt", "body": "use TRIGGER"}], "license": {"name": "OpenRAIL-M", "url": "https://example/license"}, @@ -260,7 +263,7 @@ def test_shipped_catalog_uses_relative_demo_videos_and_author_affiliation(): assert not item.media.demo_video.startswith("http://") assert not item.media.demo_video.startswith("https://") official = [r for r in cat.ic_loras if r.author and r.author.affiliation == "ltx"] - assert len(official) == 10 + assert len(official) == 14 missing = next(r for r in cat.loras if r.id == "fantasy-anime-style") assert missing.media is not None and missing.media.demo_video == "fantasy_anime_style_demo.mp4" @@ -287,16 +290,16 @@ def test_download_variants_require_unique_filenames_and_ids(): DownloadSpec( repo_id="org/repo", variants=[ - DownloadVariant(id="a", label="A", filename="a.safetensors", size_bytes=1), - DownloadVariant(id="b", label="B", filename="a.safetensors", size_bytes=2), + DownloadVariant(id="a", label="A", filename="a.safetensors", size_bytes=1, base_model="LTX-2.3"), + DownloadVariant(id="b", label="B", filename="a.safetensors", size_bytes=2, base_model="LTX-2.3"), ], ) with pytest.raises(ValidationError): DownloadSpec( repo_id="org/repo", variants=[ - DownloadVariant(id="a", label="A", filename="a.safetensors", size_bytes=1), - DownloadVariant(id="a", label="B", filename="b.safetensors", size_bytes=2), + DownloadVariant(id="a", label="A", filename="a.safetensors", size_bytes=1, base_model="LTX-2.3"), + DownloadVariant(id="a", label="B", filename="b.safetensors", size_bytes=2, base_model="LTX-2.3"), ], ) @@ -307,8 +310,8 @@ def test_download_resolve_variant_defaults_to_first(): spec = DownloadSpec( repo_id="org/repo", variants=[ - DownloadVariant(id="strong", label="Strong", filename="strong.safetensors", size_bytes=2), - DownloadVariant(id="light", label="Light", filename="light.safetensors", size_bytes=1), + DownloadVariant(id="strong", label="Strong", filename="strong.safetensors", size_bytes=2, base_model="LTX-2.3"), + DownloadVariant(id="light", label="Light", filename="light.safetensors", size_bytes=1, base_model="LTX-2.3"), ], ) assert spec.resolve_variant(None).id == "strong" @@ -318,6 +321,48 @@ def test_download_resolve_variant_defaults_to_first(): assert spec.resolve_variant("x") is None +def test_stored_default_variant_id_resolves_to_the_original_checkpoint(): + from api_types import DownloadSpec, DownloadVariant + + spec = DownloadSpec( + repo_id="org/repo", + variants=[ + DownloadVariant(id="ltx-2.5__x", label="LTX-2.5", filename="new.safetensors", size_bytes=2, base_model="LTX-2.5"), + DownloadVariant(id="ltx-2.3__x", label="LTX-2.3", filename="old.safetensors", size_bytes=1, base_model="LTX-2.3"), + ], + ) + assert spec.resolve_variant("default").filename == "old.safetensors" + assert spec.legacy_variant().filename == "old.safetensors" + assert spec.resolve_variant("ltx-2.5__x").filename == "new.safetensors" + assert spec.resolve_variant("nope") is None + + +def test_variant_for_run_omitted_id_rules(): + from api_types import DownloadSpec, DownloadVariant + + def variant(variant_id: str, filename: str) -> DownloadVariant: + return DownloadVariant(id=variant_id, label=variant_id, filename=filename, size_bytes=1, base_model="LTX-2.3") + + single = DownloadSpec(repo_id="org/repo", variants=[variant("only", "a.safetensors")]) + multi = DownloadSpec( + repo_id="org/repo", + variants=[variant("new", "new.safetensors"), variant("old", "old.safetensors")], + ) + assert single.variant_for_run(None, ["only"]).id == "only" + assert single.variant_for_run(None, []).id == "only" + assert multi.variant_for_run(None, []).id == "new" + assert multi.variant_for_run(None, ["old"]) is None + assert multi.variant_for_run("old", ["old"]).id == "old" + + +def test_shipped_variant_ids_are_unique_and_never_default(): + catalog = Path(__file__).parent.parent / "runtime_config" / "lora_catalog.json" + cat = parse_lora_catalog(catalog.read_text(encoding="utf-8")) + ids = [v.id for item in [*cat.loras, *cat.ic_loras] for v in item.download.variants] + assert "default" not in ids + assert len(ids) == len(set(ids)) + + def test_shipped_3dreal_has_strong_v2_default_and_light_variant(): catalog = Path(__file__).parent.parent / "runtime_config" / "lora_catalog.json" cat = parse_lora_catalog(catalog.read_text(encoding="utf-8")) @@ -381,6 +426,109 @@ def test_enhancement_examples_parse_when_present(): assert parse_lora_catalog(j).loras[0].enhancement_examples == ["ex one", "ex two"] +def test_shipped_dolly_in_lora_is_wired_for_prompt_enhancement(): + from services.prompt_enhancement.system_prompt import render_catalog_item_block + + catalog = Path(__file__).parent.parent / "runtime_config" / "lora_catalog.json" + cat = parse_lora_catalog(catalog.read_text(encoding="utf-8")) + item = next(r for r in cat.loras if r.id == "dolly-in") + assert item.name == "Dolly In" + assert item.download.repo_id == "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-In" + assert item.download.default_variant().filename == ( + "ltx-2-19b-lora-camera-control-dolly-in.safetensors" + ) + assert item.download.default_variant().size_bytes == 327309208 + assert item.requires_hf_login is True + assert item.author is not None and item.author.affiliation == "ltx" + assert item.trigger is None and item.trigger_placement is None + assert item.prompt_template is None + assert item.recommended_strength == 1.0 + assert "motion" in item.tags + kinds = {instr.kind for instr in item.instructions} + assert {"summary", "prompting"}.issubset(kinds) + assert item.enhancement_examples, "catalog-aware rewrite needs few-shot examples" + block = render_catalog_item_block(item) + assert "destination of the movement" in block + for example in item.enhancement_examples: + assert example in block + assert "LoRA strength ~1.0" not in block + tips = next(instr.body for instr in item.instructions if instr.kind == "tips") + assert isinstance(tips, str) + assert "no input clip" not in tips + assert "Text-to-video" not in tips + assert "start still" in tips + + +def test_shipped_camera_control_loras_are_wired_for_prompt_enhancement(): + from services.prompt_enhancement.system_prompt import render_catalog_item_block + + catalog = Path(__file__).parent.parent / "runtime_config" / "lora_catalog.json" + cat = parse_lora_catalog(catalog.read_text(encoding="utf-8")) + expected = { + "jib-up": ( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Up", + "ltx-2-19b-lora-camera-control-jib-up.safetensors", + 2214978664, + ), + "jib-down": ( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Jib-Down", + "ltx-2-19b-lora-camera-control-jib-down.safetensors", + 2214978664, + ), + "dolly-out": ( + "Lightricks/LTX-2-19b-LoRA-Camera-Control-Dolly-Out", + "ltx-2-19b-lora-camera-control-dolly-out.safetensors", + 327309208, + ), + } + for lora_id, (repo_id, filename, size_bytes) in expected.items(): + item = next(r for r in cat.loras if r.id == lora_id) + assert item.download.repo_id == repo_id + assert item.download.default_variant().filename == filename + assert item.download.default_variant().size_bytes == size_bytes + assert item.requires_hf_login is True + assert item.author is not None and item.author.affiliation == "ltx" + assert item.trigger is None and item.trigger_placement is None + assert item.prompt_template is None + assert item.enhancement_examples, lora_id + block = render_catalog_item_block(item) + assert "destination of the movement" in block + for example in item.enhancement_examples: + assert example in block + assert "LoRA strength ~1.0" not in block + + +def test_shipped_transition_and_vbvr_have_enhancement_examples(): + from services.prompt_enhancement.system_prompt import render_catalog_item_block + + catalog = Path(__file__).parent.parent / "runtime_config" / "lora_catalog.json" + cat = parse_lora_catalog(catalog.read_text(encoding="utf-8")) + transition = next(r for r in cat.loras if r.id == "transition") + assert transition.download.repo_id == "joyfox/LTX-2.3-Transition-LORA" + assert transition.download.default_variant().filename == "ltx2.3-transition.safetensors" + assert transition.download.default_variant().size_bytes == 390229424 + assert transition.trigger == "zhuanchang" + assert transition.enhancement_examples + transition_block = render_catalog_item_block(transition) + assert "zhuanchang" in transition_block + for example in transition.enhancement_examples: + assert example in transition_block + assert "Home Transition is image-to-video" not in transition_block + + vbvr = next(r for r in cat.loras if r.id == "vbvr") + assert vbvr.download.repo_id == "LiconStudio/Ltx2.3-VBVR-lora-I2V" + assert ( + vbvr.download.default_variant().filename + == "Ltx2.3-Licon-VBVR-I2V-390K-R32.safetensors" + ) + assert vbvr.download.default_variant().size_bytes == 554006432 + assert vbvr.enhancement_examples + vbvr_block = render_catalog_item_block(vbvr) + for example in vbvr.enhancement_examples: + assert example in vbvr_block + assert "Home VBVR is image-to-video" not in vbvr_block + + def test_input_optional_defaults_false(): assert parse_lora_catalog(_VALID).ic_loras[0].input.optional is False @@ -435,3 +583,17 @@ def test_downloaded_variant_ids_lists_only_installed_checkpoints(tmp_path: Path) light.parent.mkdir(parents=True) light.write_bytes(b"x") assert downloaded_ic_lora_variant_ids(tmp_path, "3d-render-to-real", variants) == ["light"] + + +def test_catalog_entry_pins_a_reference_image_only_to_frame_0_or_the_still_frame(): + def entry(frame: int) -> str: + return _VALID.replace( + '"requires_hf_login": true,', + f'"requires_hf_login": true, "allows_reference_image": true, "reference_image_frame": {frame},', + ) + + assert parse_lora_catalog(entry(0)).ic_loras[0].reference_image_frame == 0 + assert parse_lora_catalog(entry(-1)).ic_loras[0].reference_image_frame == -1 + for frame in (5, -2): + with pytest.raises(ValidationError, match="reference_image_frame must be 0 or -1"): + parse_lora_catalog(entry(frame)) diff --git a/backend/tests/test_lora_download.py b/backend/tests/test_lora_download.py index 5afda4bd5..24deb5fd2 100644 --- a/backend/tests/test_lora_download.py +++ b/backend/tests/test_lora_download.py @@ -13,7 +13,9 @@ def test_lora_path_layout(tmp_path: Path): assert is_lora_downloaded(tmp_path, "cozy-felt-v1", "felt.safetensors") is True -def test_lora_list_reports_downloaded_state(client: TestClient): +def test_lora_list_reports_downloaded_state(client: TestClient, create_fake_model_files): + # Hide-when-unsupported-family needs a runnable LTX on disk; fake catalog rows default to both families. + create_fake_model_files() # FakeLoraCatalogProvider (wired in conftest) returns one plain LoRA "cozy-felt-v1". resp = client.get("/api/loras") assert resp.status_code == 200 @@ -36,6 +38,23 @@ def test_lora_download_then_progress_complete(client: TestClient): assert prog.json()["status"] == "complete" +def test_lora_delete_installation(client: TestClient, create_fake_model_files): + create_fake_model_files() + client.post("/api/loras/download", json={"lora_id": "cozy-felt-v1"}) + listed = client.get("/api/loras") + assert listed.json()["loras"][0]["downloaded"] is True + + delete = client.request( + "DELETE", + "/api/loras/installation", + json={"lora_id": "cozy-felt-v1"}, + ) + assert delete.status_code == 200 + + listed_after = client.get("/api/loras") + assert listed_after.json()["loras"][0]["downloaded"] is False + + def test_lora_download_anonymous_when_not_gated(client: TestClient, fake_services): # Plain LoRA is public (requires_hf_login=False) and gating is off → no token attached. client.post("/api/loras/download", json={"lora_id": "cozy-felt-v1"}) @@ -52,3 +71,80 @@ def test_lora_download_unknown_variant_id_404(client: TestClient): "/api/loras/download", json={"lora_id": "cozy-felt-v1", "variant_id": "does-not-exist"} ) assert resp.status_code == 404 + + +def test_lora_active_download_null_when_idle(client: TestClient): + resp = client.get("/api/loras/download/active") + assert resp.status_code == 200 + assert resp.json()["session_id"] is None + assert resp.json()["lora_id"] is None + assert resp.json()["progress"] is None + + +def test_lora_active_download_reports_running_session(client: TestClient, test_state): + from state.app_state_types import CatalogDownloadSession, DownloadSessionId + + # Simulate an in-flight download (FakeTaskRunner runs synchronously, so a real start + # would already be complete) — the session a remounting screen needs to reattach to. + test_state.state.lora_download_session = CatalogDownloadSession( + id=DownloadSessionId("lora-dl-1"), + item_id="cozy-felt-v1", + downloaded_bytes=40, + expected_bytes=100, + ) + + resp = client.get("/api/loras/download/active") + assert resp.status_code == 200 + assert resp.json()["session_id"] == "lora-dl-1" + assert resp.json()["lora_id"] == "cozy-felt-v1" + assert resp.json()["progress"] == 40.0 + + +def test_lora_list_empty_when_no_ltx_family_installed(client: TestClient): + resp = client.get("/api/loras") + assert resp.status_code == 200 + assert resp.json()["loras"] == [] + assert client.get("/api/loras", params={"fresh": False}).json()["loras"] == [] + + fresh = client.get("/api/loras", params={"fresh": True}) + assert fresh.status_code == 200 + ids = [item["lora"]["id"] for item in fresh.json()["loras"]] + assert "cozy-felt-v1" in ids + assert "cozy-felt-style" in ids + + +def test_lora_list_hides_adapter_when_required_family_missing( + client: TestClient, create_fake_model_files, fake_services +): + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + catalog = fake_services.lora_catalog_provider._catalog + fake_services.lora_catalog_provider._catalog = catalog.model_copy( + update={ + "loras": [ + catalog.loras[0].model_copy(update={"supported_models": ["LTX-2.3"]}), + catalog.loras[1], + ] + } + ) + + resp = client.get("/api/loras") + assert resp.status_code == 200 + ids = [item["lora"]["id"] for item in resp.json()["loras"]] + assert "cozy-felt-v1" not in ids + assert "cozy-felt-style" in ids + + fresh_ids = [ + item["lora"]["id"] + for item in client.get("/api/loras", params={"fresh": True}).json()["loras"] + ] + assert "cozy-felt-v1" in fresh_ids + assert "cozy-felt-style" in fresh_ids + + +def test_lora_list_still_shows_undownloaded_adapter_when_family_installed( + client: TestClient, create_fake_model_files +): + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + resp = client.get("/api/loras") + items = {item["lora"]["id"]: item for item in resp.json()["loras"]} + assert items["cozy-felt-style"]["downloaded"] is False diff --git a/backend/tests/test_lora_recipe.py b/backend/tests/test_lora_recipe.py new file mode 100644 index 000000000..cb493b962 --- /dev/null +++ b/backend/tests/test_lora_recipe.py @@ -0,0 +1,666 @@ +"""LoRA recipe registry + create-path behavior (LTXP-499 foundation).""" + +from __future__ import annotations + +from pathlib import Path + +import pytest +from PIL import Image +from starlette.testclient import TestClient + +from _routes._errors import HTTPError +from api_types import DownloadVariant, LoraEntry +from runtime_config.model_download_specs import resolve_lora_path +from services.features import lora_recipes +from services.features.lora_recipes import ( + apply_recipe_prompt_template, + get_lora_recipe, + i2v_lora_recipes, + make_recipe_lora_resolver, + t2v_lora_recipes, +) + + +def _store(test_state): + from services.sqlite_store import SqliteStore + + return SqliteStore(test_state.config.app_data_dir) + + +def _install_cozy_felt_weights(test_state) -> Path: + """Write the recipe's catalog weights where resolve_lora_path expects them.""" + path = resolve_lora_path( + test_state.config.default_models_dir, "cozy-felt-style", "CozyFelt.safetensors" + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\x00" * 64) + return path + + +def _recipe_body(prompt: str = "a fox on a skateboard", scale: float = 1.0): + return { + "params": { + "prompt": prompt, + "model": "ltx-2.5-fast", + "catalogId": "cozy-felt-style", + "scale": scale, + "variantId": "default", + "resolution": "720p", + "duration": 8, + "fps": 24, + } + } + + +@pytest.fixture +def supported_recipe_device(monkeypatch, create_fake_model_files): + # The gate uses the real accelerator, which is "cpu" on CI (linux/windows) — pin a device + # cozy-felt supports so these tests reach their target check, not the device gate. + # Also install a runnable LTX bundle so the supported_models filter doesn't hide the recipe. + from handlers import queued_generation_handler + + create_fake_model_files() + monkeypatch.setattr(queued_generation_handler, "accelerator_backend", lambda: "mps") + + +# --- registry / wrap (pure) --- + + +def test_registry_maps_cozy_felt_to_style_t2v() -> None: + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + assert recipe.catalog_id == "cozy-felt-style" + assert recipe.mode == "t2v" + assert recipe.devices == ("cuda", "mps") + + +def test_registry_unmapped_id_is_none() -> None: + assert get_lora_recipe("not-a-real-recipe") is None + + +def test_registry_maps_dolly_in_to_i2v() -> None: + recipe = get_lora_recipe("dolly-in") + assert recipe is not None + assert recipe.catalog_id == "dolly-in" + assert recipe.mode == "i2v" + assert recipe.devices == ("cuda", "mps") + + +def test_t2v_lora_recipes_match_shared_contract() -> None: + import json + + contract_path = Path(__file__).resolve().parents[2] / "shared" / "lora-recipes.json" + contract = json.loads(contract_path.read_text(encoding="utf-8")) + expected = [entry["id"] for entry in contract if entry["mode"] == "t2v"] + assert [r.recipe_id for r in t2v_lora_recipes()] == expected + + +def test_i2v_lora_recipes_match_shared_contract() -> None: + import json + + contract_path = Path(__file__).resolve().parents[2] / "shared" / "lora-recipes.json" + contract = json.loads(contract_path.read_text(encoding="utf-8")) + expected = [entry["id"] for entry in contract if entry["mode"] == "i2v"] + assert [r.recipe_id for r in i2v_lora_recipes()] == expected + + +def test_registry_matches_shared_contract() -> None: + # shared/lora-recipes.json is the single source of truth for the id / catalogId / + # mode / devices contract; the FE registry is asserted against the same file + # (frontend/lib/lora-recipes.test.ts), so the two can't drift. `listed` is a + # frontend-only Home concern except `requiresEndFrame`, which both sides + # must agree on so Transition cannot drift. + import json + + contract_path = ( + Path(__file__).resolve().parents[2] / "shared" / "lora-recipes.json" + ) + contract = json.loads(contract_path.read_text(encoding="utf-8")) + expected = { + entry["id"]: { + "catalogId": entry["catalogId"], + "mode": entry["mode"], + "devices": tuple(entry["devices"]), + "requiresEndFrame": bool(entry.get("requiresEndFrame", False)), + } + for entry in contract + } + actual = { + recipe.recipe_id: { + "catalogId": recipe.catalog_id, + "mode": recipe.mode, + "devices": recipe.devices, + "requiresEndFrame": recipe.requires_end_frame, + } + for recipe in lora_recipes.LORA_RECIPES.values() + } + assert actual == expected + + +def test_prompt_wrap_applies_felt_scaffold_when_trigger_absent() -> None: + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + wrapped = apply_recipe_prompt_template(recipe, "a fox on a skateboard") + assert wrapped.startswith("F3ltCut0u7 handcrafted felt") + assert "a fox on a skateboard" in wrapped + + +def test_prompt_wrap_applies_scaffold_even_when_trigger_already_present() -> None: + # Regression (LTXP-499): local enhancement enforces the trigger on every + # prompt but never adds the felt scaffold. The wrap must still apply the + # scaffold — a trigger-based skip dropped it on every enhanced generation. + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + enhanced = "A long enhanced felt scene with F3ltCut0u7 stitched in by enhancement" + wrapped = apply_recipe_prompt_template(recipe, enhanced) + assert wrapped.startswith("F3ltCut0u7 handcrafted felt") + assert enhanced in wrapped + + +def test_prompt_wrap_is_idempotent_when_scaffold_already_present() -> None: + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + already_wrapped = apply_recipe_prompt_template(recipe, "a fox on a skateboard") + assert apply_recipe_prompt_template(recipe, already_wrapped) == already_wrapped + + +def test_prompt_wrap_applies_transition_suffix() -> None: + recipe = get_lora_recipe("transition") + assert recipe is not None + wrapped = apply_recipe_prompt_template(recipe, "a wave becomes a mountain") + assert wrapped.endswith("zhuanchang") + assert wrapped.startswith("a wave becomes a mountain") + assert apply_recipe_prompt_template(recipe, wrapped) == wrapped + + +def test_prompt_wrap_applies_scaffold_when_it_appears_mid_prompt() -> None: + # Catalog-aware enhancement can echo the prompting example, embedding the + # scaffold sentence mid-prompt. The wrap must still prepend the style lock — + # a substring guard would wrongly skip it. + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + assert recipe.prompt_template is not None + prefix = recipe.prompt_template.split("{prompt}", 1)[0].strip() + mid = f"A fox on a skateboard. {prefix} And more scene details." + wrapped = apply_recipe_prompt_template(recipe, mid) + assert wrapped.startswith("F3ltCut0u7 handcrafted felt") + assert wrapped != mid + assert mid in wrapped + + +def test_prompt_wrap_fails_closed_when_template_has_no_placeholder() -> None: + # A template without {prompt} must not drop the user's scene. + recipe = lora_recipes.LoraRecipe( + recipe_id="broken", + catalog_id="broken", + mode="t2v", + devices=("cuda",), + prompt_template="F3ltCut0u7 style with no placeholder", + ) + assert apply_recipe_prompt_template(recipe, "a fox") == "a fox" + + +# --- create path (HTTP) --- + + +def test_create_recipe_resolves_catalog_id_and_stores_feature( + client: TestClient, test_state, supported_recipe_device +) -> None: + _install_cozy_felt_weights(test_state) + + response = client.post( + "/api/generations/recipes/cozy-felt", json=_recipe_body(scale=1.5) + ) + + assert response.status_code == 200, response.text + body = response.json() + assert body["feature"] == "cozy-felt" + + lora = body["spec"]["params"]["loras"][0] + assert lora["catalogId"] == "cozy-felt-style" + assert lora["displayName"] == "Cozy Felt Style" + assert lora["scale"] == 1.5 + # The stored spec carries catalogId + scale only; the absolute weights path is never + # persisted (resolved fresh at execution) so no server filesystem path leaks to the API. + assert lora["ref"] == "" + # The stored prompt is the raw user scene, not the wrapped scaffold. + assert body["spec"]["params"]["prompt"] == "a fox on a skateboard" + assert body["spec"]["params"]["model"] == "ltx-2.5-fast" + assert "F3ltCut0u7" not in body["spec"]["params"]["prompt"] + + assert len(_store(test_state).list_generations("cozy-felt")) == 1 + + +def test_create_recipe_without_a_variant_id_uses_the_only_checkpoint( + client: TestClient, test_state, supported_recipe_device +) -> None: + _install_cozy_felt_weights(test_state) + body = _recipe_body() + del body["params"]["variantId"] + + response = client.post("/api/generations/recipes/cozy-felt", json=body) + + assert response.status_code == 200, response.text + stored = response.json()["spec"]["params"]["loras"][0]["variantId"] + assert stored == "default" + + +def test_create_recipe_with_an_explicit_variant_requires_that_file_not_index_zero( + client: TestClient, test_state, fake_services, supported_recipe_device +) -> None: + catalog = fake_services.lora_catalog_provider._catalog + cozy = next(lora for lora in catalog.loras if lora.id == "cozy-felt-style") + default_filename = cozy.download.variants[0].filename + alt = DownloadVariant( + id="ltx-2.3__cozy-felt-style__alt", + label="Alt", + filename="alt.safetensors", + size_bytes=10, + base_model="LTX-2.3", + ) + loras = [] + for lora in catalog.loras: + if lora.id != "cozy-felt-style": + loras.append(lora) + continue + loras.append( + lora.model_copy( + update={ + "download": lora.download.model_copy( + update={"variants": [*lora.download.variants, alt]} + ) + } + ) + ) + fake_services.lora_catalog_provider._catalog = catalog.model_copy(update={"loras": loras}) + default_path = resolve_lora_path( + test_state.config.default_models_dir, "cozy-felt-style", default_filename + ) + default_path.parent.mkdir(parents=True, exist_ok=True) + default_path.write_bytes(b"\x00" * 64) + body = _recipe_body() + body["params"]["variantId"] = alt.id + missing = client.post("/api/generations/recipes/cozy-felt", json=body) + assert missing.status_code == 422 + assert missing.json()["code"] == "LORA_NOT_DOWNLOADED" + + alt_path = resolve_lora_path( + test_state.config.default_models_dir, "cozy-felt-style", alt.filename + ) + alt_path.write_bytes(b"\x00" * 64) + # Index 0 is gone; the requested checkpoint is the one that must exist. + default_path.unlink() + created = client.post("/api/generations/recipes/cozy-felt", json=body) + assert created.status_code == 200, created.text + assert created.json()["spec"]["params"]["loras"][0]["variantId"] == alt.id + + +def test_create_recipe_rejects_when_weights_not_downloaded( + client: TestClient, test_state, supported_recipe_device +) -> None: + response = client.post("/api/generations/recipes/cozy-felt", json=_recipe_body()) + + assert response.status_code == 422 + assert response.json()["code"] == "LORA_NOT_DOWNLOADED" + assert _store(test_state).list_generations("cozy-felt") == [] + + +def test_create_recipe_rejects_when_required_ltx_family_missing( + client: TestClient, test_state, monkeypatch, create_fake_model_files, fake_services +) -> None: + from handlers import queued_generation_handler + + create_fake_model_files(model_id="ltx-2.5-22b-distilled") + monkeypatch.setattr(queued_generation_handler, "accelerator_backend", lambda: "mps") + _install_cozy_felt_weights(test_state) + catalog = fake_services.lora_catalog_provider._catalog + fake_services.lora_catalog_provider._catalog = catalog.model_copy( + update={ + "loras": [ + lora.model_copy(update={"supported_models": ["LTX-2.3"]}) + if lora.id == "cozy-felt-style" + else lora + for lora in catalog.loras + ] + } + ) + + response = client.post("/api/generations/recipes/cozy-felt", json=_recipe_body()) + + assert response.status_code == 422 + assert response.json()["code"] == "LORA_UNSUPPORTED_MODEL" + assert _store(test_state).list_generations("cozy-felt") == [] + + +def test_create_recipe_rejects_mismatched_catalog_id( + client: TestClient, test_state, supported_recipe_device +) -> None: + _install_cozy_felt_weights(test_state) + body = _recipe_body() + body["params"]["catalogId"] = "some-other-lora" + + response = client.post("/api/generations/recipes/cozy-felt", json=body) + + assert response.status_code == 422 + assert response.json()["code"] == "LORA_UNKNOWN" + assert _store(test_state).list_generations("cozy-felt") == [] + + +def test_create_recipe_body_forbids_client_supplied_ref( + client: TestClient, test_state, supported_recipe_device +) -> None: + # Install weights so the same body *without* a ref is a valid create — otherwise + # this test would green even if extra="forbid" were dropped, because the request + # would 422 LORA_NOT_DOWNLOADED regardless. + _install_cozy_felt_weights(test_state) + body = _recipe_body() + body["params"]["ref"] = "loras/cozy-felt-style/CozyFelt.safetensors" + + response = client.post("/api/generations/recipes/cozy-felt", json=body) + + # extra="forbid": a filesystem ref is not part of the recipe wire contract. + assert response.status_code == 422 + # Rejected for the forbidden field, not because weights are missing. + assert response.json().get("code") != "LORA_NOT_DOWNLOADED" + assert _store(test_state).list_generations("cozy-felt") == [] + + +def test_create_recipe_rejects_malformed_recipe_id( + client: TestClient, test_state +) -> None: + # The {recipe_id} path param is pattern-constrained (^[a-z0-9-]+$), so a + # malformed id 422s at the route before create_lora_recipe runs. + response = client.post("/api/generations/recipes/Bad_Id", json=_recipe_body()) + + assert response.status_code == 422 + assert _store(test_state).list_generations("Bad_Id") == [] + + +def test_create_recipe_rejects_unsupported_device( + client: TestClient, test_state, monkeypatch +) -> None: + from handlers import queued_generation_handler + + _install_cozy_felt_weights(test_state) + # This machine reports mps, but the recipe only supports cuda. + monkeypatch.setattr( + queued_generation_handler, "accelerator_backend", lambda: "mps" + ) + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + monkeypatch.setitem( + lora_recipes.LORA_RECIPES, + "cozy-felt", + lora_recipes.LoraRecipe( + recipe_id="cozy-felt", + catalog_id="cozy-felt-style", + mode="t2v", + devices=("cuda",), + prompt_template=recipe.prompt_template, + ), + ) + + response = client.post("/api/generations/recipes/cozy-felt", json=_recipe_body()) + + assert response.status_code == 422 + assert response.json()["code"] == "LORA_UNSUPPORTED_DEVICE" + assert _store(test_state).list_generations("cozy-felt") == [] + + +def test_create_recipe_rejects_when_local_generation_unsupported( + client: TestClient, test_state +) -> None: + _install_cozy_felt_weights(test_state) + # A machine that can't generate locally must not enqueue a local-only recipe job. + test_state.config.local_generations_mode = "unsupported" + + response = client.post("/api/generations/recipes/cozy-felt", json=_recipe_body()) + + assert response.status_code == 422 + assert _store(test_state).list_generations("cozy-felt") == [] + + +def test_create_recipe_rejects_when_hf_login_required( + client: TestClient, test_state, monkeypatch, supported_recipe_device +) -> None: + from state.app_state_types import HfNotAuthenticated + + _install_cozy_felt_weights(test_state) + # Default test state is HF-authenticated; sign out so a gated item is refused. + test_state.state.hf_auth_state = HfNotAuthenticated() + item = test_state._lora_catalog_provider.get_lora("cozy-felt-style") + assert item is not None + monkeypatch.setattr(item, "requires_hf_login", True) + + response = client.post("/api/generations/recipes/cozy-felt", json=_recipe_body()) + + assert response.status_code == 422 + assert response.json()["code"] == "LORA_HF_AUTH_REQUIRED" + assert _store(test_state).list_generations("cozy-felt") == [] + + +# --- execution-time ref hydration (make_recipe_lora_resolver) --- + + +def _cozy_felt_resolver(test_state): + recipe = get_lora_recipe("cozy-felt") + assert recipe is not None + return make_recipe_lora_resolver( + recipe, + catalog=test_state._lora_catalog_provider, + models_dir=lambda: test_state.config.default_models_dir, + ) + + +def test_recipe_resolver_hydrates_ref_from_catalog_id(test_state) -> None: + resolved = _install_cozy_felt_weights(test_state) + resolver = _cozy_felt_resolver(test_state) + + out = resolver([LoraEntry(ref="", scale=1.5, catalogId="cozy-felt-style")]) + + # Stored spec carries no path; the resolver fills the current on-disk ref, scale intact. + assert out[0].ref == str(resolved) + assert out[0].scale == 1.5 + assert out[0].catalogId == "cozy-felt-style" + + +def test_recipe_resolver_fails_when_weights_removed(test_state) -> None: + # Weights never installed: a retry after the adapter is gone fails on this job rather + # than replaying a stale path. + resolver = _cozy_felt_resolver(test_state) + + with pytest.raises(HTTPError) as exc: + resolver([LoraEntry(ref="", scale=1.0, catalogId="cozy-felt-style")]) + + assert exc.value.code == "LORA_NOT_DOWNLOADED" + + +def test_recipe_resolver_passes_through_foreign_entries(test_state) -> None: + resolver = _cozy_felt_resolver(test_state) + + entry = LoraEntry(ref="loras/user/custom.safetensors", scale=0.8, catalogId=None) + out = resolver([entry]) + + assert out == [entry] + + +def _png(path: Path) -> Path: + Image.new("RGB", (16, 16), color=(1, 2, 3)).save(path) + return path + + +def _install_dolly_in_weights(test_state) -> Path: + path = resolve_lora_path( + test_state.config.default_models_dir, + "dolly-in", + "ltx-2-19b-lora-camera-control-dolly-in.safetensors", + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\x00" * 64) + return path + + +def _dolly_in_body(start_asset_id: str, *, prompt: str = "push in on her face"): + return { + "params": { + "prompt": prompt, + "model": "ltx-2.5-fast", + "catalogId": "dolly-in", + "scale": 1.0, + "variantId": "default", + "resolution": "720p", + "duration": 8, + "fps": 24, + "aspectRatio": "auto", + }, + "inputs": {"startFrame": {"assetId": start_asset_id}}, + } + + +def test_create_dolly_in_requires_start_frame( + client: TestClient, test_state, supported_recipe_device +) -> None: + _install_dolly_in_weights(test_state) + body = _dolly_in_body("unused") + del body["inputs"] + + response = client.post("/api/generations/recipes/dolly-in", json=body) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + assert _store(test_state).list_generations("dolly-in") == [] + + +def test_create_dolly_in_stores_start_frame_and_empty_lora_ref( + client: TestClient, test_state, supported_recipe_device, tmp_path: Path +) -> None: + _install_dolly_in_weights(test_state) + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "dolly-start.png"))} + ).json() + + response = client.post( + "/api/generations/recipes/dolly-in", json=_dolly_in_body(start["id"]) + ) + + assert response.status_code == 200, response.text + body = response.json() + assert body["feature"] == "dolly-in" + assert body["spec"]["inputs"]["startFrame"]["assetId"] == start["id"] + lora = body["spec"]["params"]["loras"][0] + assert lora["catalogId"] == "dolly-in" + assert lora["ref"] == "" + assert body["spec"]["params"]["prompt"] == "push in on her face" + assert "dolly-in camera move" not in body["spec"]["params"]["prompt"] + assert len(_store(test_state).list_generations("dolly-in")) == 1 + + +def test_create_cozy_felt_rejects_start_frame( + client: TestClient, test_state, supported_recipe_device, tmp_path: Path +) -> None: + _install_cozy_felt_weights(test_state) + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "felt-start.png"))} + ).json() + body = _recipe_body() + body["inputs"] = {"startFrame": {"assetId": start["id"]}} + + response = client.post("/api/generations/recipes/cozy-felt", json=body) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + assert _store(test_state).list_generations("cozy-felt") == [] + + +def _install_transition_weights(test_state) -> Path: + path = resolve_lora_path( + test_state.config.default_models_dir, + "transition", + "ltx2.3-transition.safetensors", + ) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\x00" * 64) + return path + + +def _transition_body(start_asset_id: str, end_asset_id: str, *, prompt: str = "morph"): + return { + "params": { + "prompt": prompt, + "model": "ltx-2.5-fast", + "catalogId": "transition", + "scale": 1.0, + "variantId": "default", + "resolution": "720p", + "duration": 8, + "fps": 24, + "aspectRatio": "auto", + }, + "inputs": { + "startFrame": {"assetId": start_asset_id}, + "endFrame": {"assetId": end_asset_id}, + }, + } + + +def test_create_transition_requires_end_frame( + client: TestClient, test_state, supported_recipe_device, tmp_path: Path +) -> None: + _install_transition_weights(test_state) + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "transition-start.png"))} + ).json() + body = _transition_body(start["id"], "unused") + del body["inputs"]["endFrame"] + + response = client.post("/api/generations/recipes/transition", json=body) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + assert _store(test_state).list_generations("transition") == [] + + +def test_create_transition_stores_start_and_end_frames( + client: TestClient, test_state, supported_recipe_device, tmp_path: Path +) -> None: + _install_transition_weights(test_state) + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "transition-start.png"))} + ).json() + end = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "transition-end.png"))} + ).json() + + response = client.post( + "/api/generations/recipes/transition", + json=_transition_body(start["id"], end["id"]), + ) + + assert response.status_code == 200, response.text + body = response.json() + assert body["feature"] == "transition" + assert body["spec"]["inputs"]["startFrame"]["assetId"] == start["id"] + assert body["spec"]["inputs"]["endFrame"]["assetId"] == end["id"] + assert body["spec"]["params"]["loras"][0]["catalogId"] == "transition" + assert body["spec"]["params"]["loras"][0]["ref"] == "" + assert "zhuanchang" not in body["spec"]["params"]["prompt"] + + +def test_create_dolly_in_rejects_end_frame( + client: TestClient, test_state, supported_recipe_device, tmp_path: Path +) -> None: + _install_dolly_in_weights(test_state) + start = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "dolly-start.png"))} + ).json() + end = client.post( + "/api/assets", json={"path": str(_png(tmp_path / "dolly-end.png"))} + ).json() + body = _dolly_in_body(start["id"]) + body["inputs"]["endFrame"] = {"assetId": end["id"]} + + response = client.post("/api/generations/recipes/dolly-in", json=body) + + assert response.status_code == 422 + assert response.json()["code"] == "INVALID_GENERATION_SPEC" + assert _store(test_state).list_generations("dolly-in") == [] diff --git a/backend/tests/test_ltx_api_client.py b/backend/tests/test_ltx_api_client.py index ed09c441a..bf8bd116d 100644 --- a/backend/tests/test_ltx_api_client.py +++ b/backend/tests/test_ltx_api_client.py @@ -20,14 +20,14 @@ def _async_client(http: FakeHTTPClient) -> LTXAPIClientImpl: ) -def _queue_upload(http: FakeHTTPClient) -> None: +def _queue_upload(http: FakeHTTPClient, storage_uri: str = "storage://extend/123") -> None: http.queue( "post", FakeResponse( status_code=200, json_payload={ "upload_url": "https://upload.example.com/extend", - "storage_uri": "storage://extend/123", + "storage_uri": storage_uri, "required_headers": {}, }, ), @@ -35,18 +35,25 @@ def _queue_upload(http: FakeHTTPClient) -> None: http.queue("put", FakeResponse(status_code=200)) -def test_generate_text_to_video_returns_binary_content() -> None: - http = FakeHTTPClient() +def _queue_completed_job( + http: FakeHTTPClient, *, job_id: str = "job-1", video_url: str, video_bytes: bytes +) -> None: + http.queue("post", FakeResponse(status_code=202, json_payload={"id": job_id})) http.queue( - "post", + "get", FakeResponse( status_code=200, - headers={"Content-Type": "video/mp4"}, - content=b"video-bytes", + json_payload={"status": "completed", "result": {"video_url": video_url}}, ), ) + http.queue("get", FakeResponse(status_code=200, content=video_bytes)) - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + +def test_generate_text_to_video_returns_downloaded_bytes() -> None: + http = FakeHTTPClient() + _queue_completed_job(http, video_url="https://cdn.example.com/t2v.mp4", video_bytes=b"video-bytes") + + client = _async_client(http) out = client.generate_text_to_video( api_key="test-key", prompt="A mountain", @@ -59,105 +66,56 @@ def test_generate_text_to_video_returns_binary_content() -> None: ) assert out == b"video-bytes" - assert len(http.calls) == 1 - call = http.calls[0] - assert call.url == "https://api.ltx.video/v1/text-to-video" - assert call.headers == { + assert len(http.calls) == 3 + submit, poll, download = http.calls + assert submit.url == "https://api.ltx.video/v2/text-to-video" + assert submit.headers == { "Authorization": "Bearer test-key", "Content-Type": "application/json", } - assert call.json_payload is not None - assert call.json_payload["prompt"] == "A mountain" - assert call.json_payload["resolution"] == "1920x1080" - assert call.json_payload["camera_motion"] == "dolly_in" - - -def test_generate_image_to_video_with_image_uri_downloads_video() -> None: - http = FakeHTTPClient() - http.queue( - "post", - FakeResponse( - status_code=200, - headers={"Content-Type": "application/json"}, - json_payload={"video_url": "https://cdn.example.com/output.mp4"}, - ), - ) - http.queue( - "get", - FakeResponse(status_code=200, content=b"downloaded-video"), - ) - - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") - out = client.generate_image_to_video( - api_key="test-key", - prompt="Animate this frame", - image_uri="storage://image/123", - model="ltx-2-3-pro", - resolution="1920x1080", - duration=4.0, - fps=24.0, - generate_audio=True, - camera_motion="jib_up", - ) - - assert out == b"downloaded-video" - assert len(http.calls) == 2 - assert http.calls[0].url == "https://api.ltx.video/v1/image-to-video" - assert http.calls[0].json_payload is not None - assert http.calls[0].json_payload["image_uri"] == "storage://image/123" - assert http.calls[0].json_payload["camera_motion"] == "jib_up" - assert "last_frame_uri" not in http.calls[0].json_payload - assert http.calls[1].url == "https://cdn.example.com/output.mp4" + assert submit.json_payload is not None + assert submit.json_payload["prompt"] == "A mountain" + assert submit.json_payload["model"] == "ltx-2-3-pro" + assert submit.json_payload["resolution"] == "1920x1080" + assert submit.json_payload["duration"] == 5.0 + assert submit.json_payload["fps"] == 24.0 + assert submit.json_payload["generate_audio"] is False + assert submit.json_payload["camera_motion"] == "dolly_in" + assert submit.json_payload["enhance_prompt"] is True + assert poll.url == "https://api.ltx.video/v2/text-to-video/job-1" + assert download.url == "https://cdn.example.com/t2v.mp4" + # Signed result URL: no Authorization header on the download. + assert download.headers is None -def test_generate_image_to_video_with_last_frame_uri() -> None: +def test_generate_text_to_video_omits_camera_motion_when_none() -> None: http = FakeHTTPClient() - http.queue( - "post", - FakeResponse( - status_code=200, - headers={"Content-Type": "application/json"}, - json_payload={"video_url": "https://cdn.example.com/output.mp4"}, - ), - ) - http.queue( - "get", - FakeResponse(status_code=200, content=b"downloaded-video"), - ) + _queue_completed_job(http, video_url="https://cdn.example.com/t2v.mp4", video_bytes=b"video-bytes") - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") - out = client.generate_image_to_video( + client = _async_client(http) + out = client.generate_text_to_video( api_key="test-key", - prompt="Animate from first to last", - image_uri="storage://image/123", - last_frame_uri="storage://image/456", + prompt="A mountain", model="ltx-2-3-pro", resolution="1920x1080", - duration=4.0, + duration=5.0, fps=24.0, - generate_audio=True, - camera_motion="jib_up", + generate_audio=False, + camera_motion="none", ) - assert out == b"downloaded-video" - assert http.calls[0].json_payload is not None - assert http.calls[0].json_payload["image_uri"] == "storage://image/123" - assert http.calls[0].json_payload["last_frame_uri"] == "storage://image/456" + assert out == b"video-bytes" + call = http.calls[0] + assert call.json_payload is not None + assert "camera_motion" not in call.json_payload -def test_generate_text_to_video_omits_camera_motion_when_none() -> None: +def test_generate_text_to_video_forwards_enhance_prompt_false() -> None: http = FakeHTTPClient() - http.queue( - "post", - FakeResponse( - status_code=200, - headers={"Content-Type": "video/mp4"}, - content=b"video-bytes", - ), - ) + _queue_completed_job(http, video_url="https://cdn.example.com/t2v.mp4", video_bytes=b"video-bytes") - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") - out = client.generate_text_to_video( + client = _async_client(http) + client.generate_text_to_video( api_key="test-key", prompt="A mountain", model="ltx-2-3-pro", @@ -165,28 +123,27 @@ def test_generate_text_to_video_omits_camera_motion_when_none() -> None: duration=5.0, fps=24.0, generate_audio=False, - camera_motion="none", + enhance_prompt=False, ) - assert out == b"video-bytes" call = http.calls[0] assert call.json_payload is not None - assert "camera_motion" not in call.json_payload + assert call.json_payload["enhance_prompt"] is False -def test_generate_text_to_video_raises_on_non_200() -> None: +def test_generate_text_to_video_submit_401_passes_through() -> None: http = FakeHTTPClient() http.queue( "post", FakeResponse( status_code=401, text="unauthorized", - headers={"Content-Type": "application/json"}, + headers={"Content-Type": "application/json", "x-request-id": "req-401"}, json_payload={"error": "unauthorized"}, ), ) - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) with pytest.raises(LTXAPIClientError, match="401") as exc: client.generate_text_to_video( api_key="bad-key", @@ -198,10 +155,10 @@ def test_generate_text_to_video_raises_on_non_200() -> None: generate_audio=False, ) assert exc.value.status_code == 401 - assert exc.value.stage == "generation" + assert exc.value.request_id == "req-401" -def test_generate_text_to_video_extracts_insufficient_funds_error() -> None: +def test_generate_text_to_video_submit_402_attaches_insufficient_funds() -> None: http = FakeHTTPClient() http.queue( "post", @@ -219,7 +176,7 @@ def test_generate_text_to_video_extracts_insufficient_funds_error() -> None: ), ) - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) with pytest.raises(LTXAPIClientError, match="insufficient_funds_error") as exc: client.generate_text_to_video( api_key="bad-key", @@ -231,12 +188,82 @@ def test_generate_text_to_video_extracts_insufficient_funds_error() -> None: generate_audio=False, ) assert exc.value.status_code == 402 - assert exc.value.stage == "generation" + # Async submit errors carry no stage by design (handlers key on status + provider type). assert exc.value.provider_error_type == "insufficient_funds_error" assert exc.value.provider_message == "Insufficient funds. Required: 36 cents" assert exc.value.request_id == "req-123" +def test_generate_text_to_video_transport_failure_maps_to_504() -> None: + http = FakeHTTPClient() + http.queue("post", HttpTransportError("Connection reset by peer")) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="please retry") as exc: + client.generate_text_to_video( + api_key="k", + prompt="A mountain", + model="ltx-2-3-pro", + resolution="1920x1080", + duration=5.0, + fps=24.0, + generate_audio=False, + ) + assert exc.value.status_code == 504 + + +def test_generate_image_to_video_with_image_uri_downloads_video() -> None: + http = FakeHTTPClient() + _queue_completed_job(http, video_url="https://cdn.example.com/output.mp4", video_bytes=b"downloaded-video") + + client = _async_client(http) + out = client.generate_image_to_video( + api_key="test-key", + prompt="Animate this frame", + image_uri="storage://image/123", + model="ltx-2-3-pro", + resolution="1920x1080", + duration=4.0, + fps=24.0, + generate_audio=True, + camera_motion="jib_up", + ) + + assert out == b"downloaded-video" + assert len(http.calls) == 3 + assert http.calls[0].url == "https://api.ltx.video/v2/image-to-video" + assert http.calls[0].json_payload is not None + assert http.calls[0].json_payload["image_uri"] == "storage://image/123" + assert http.calls[0].json_payload["camera_motion"] == "jib_up" + assert "last_frame_uri" not in http.calls[0].json_payload + assert http.calls[1].url == "https://api.ltx.video/v2/image-to-video/job-1" + assert http.calls[2].url == "https://cdn.example.com/output.mp4" + + +def test_generate_image_to_video_with_last_frame_uri() -> None: + http = FakeHTTPClient() + _queue_completed_job(http, video_url="https://cdn.example.com/output.mp4", video_bytes=b"downloaded-video") + + client = _async_client(http) + out = client.generate_image_to_video( + api_key="test-key", + prompt="Animate from first to last", + image_uri="storage://image/123", + last_frame_uri="storage://image/456", + model="ltx-2-3-pro", + resolution="1920x1080", + duration=4.0, + fps=24.0, + generate_audio=True, + camera_motion="jib_up", + ) + + assert out == b"downloaded-video" + assert http.calls[0].json_payload is not None + assert http.calls[0].json_payload["image_uri"] == "storage://image/123" + assert http.calls[0].json_payload["last_frame_uri"] == "storage://image/456" + + def test_upload_file_returns_storage_uri(tmp_path) -> None: audio_path = tmp_path / "input.wav" audio_path.write_bytes(b"fake-audio") @@ -269,17 +296,9 @@ def test_upload_file_returns_storage_uri(tmp_path) -> None: def test_generate_audio_to_video_with_audio_uri_downloads_video() -> None: http = FakeHTTPClient() - http.queue( - "post", - FakeResponse( - status_code=200, - headers={"Content-Type": "application/json"}, - json_payload={"video_url": "https://cdn.example.com/a2v.mp4"}, - ), - ) - http.queue("get", FakeResponse(status_code=200, content=b"downloaded-a2v-video")) + _queue_completed_job(http, video_url="https://cdn.example.com/a2v.mp4", video_bytes=b"downloaded-a2v-video") - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) out = client.generate_audio_to_video( api_key="test-key", prompt="Sync to this song", @@ -290,26 +309,19 @@ def test_generate_audio_to_video_with_audio_uri_downloads_video() -> None: ) assert out == b"downloaded-a2v-video" - assert len(http.calls) == 2 - assert http.calls[0].url == "https://api.ltx.video/v1/audio-to-video" + assert len(http.calls) == 3 + assert http.calls[0].url == "https://api.ltx.video/v2/audio-to-video" assert http.calls[0].json_payload is not None assert http.calls[0].json_payload["audio_uri"] == "storage://audio/123" assert "image_uri" not in http.calls[0].json_payload - assert http.calls[1].url == "https://cdn.example.com/a2v.mp4" + assert http.calls[2].url == "https://cdn.example.com/a2v.mp4" def test_generate_audio_to_video_with_image_uri_posts_both_inputs() -> None: http = FakeHTTPClient() - http.queue( - "post", - FakeResponse( - status_code=200, - headers={"Content-Type": "video/mp4"}, - content=b"direct-a2v-video", - ), - ) + _queue_completed_job(http, video_url="https://cdn.example.com/a2v.mp4", video_bytes=b"downloaded-a2v-video") - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) out = client.generate_audio_to_video( api_key="test-key", prompt="Animate from image and audio", @@ -319,9 +331,8 @@ def test_generate_audio_to_video_with_image_uri_posts_both_inputs() -> None: resolution="3840x2160", ) - assert out == b"direct-a2v-video" - assert len(http.calls) == 1 - assert http.calls[0].url == "https://api.ltx.video/v1/audio-to-video" + assert out == b"downloaded-a2v-video" + assert http.calls[0].url == "https://api.ltx.video/v2/audio-to-video" assert http.calls[0].json_payload is not None assert http.calls[0].json_payload["audio_uri"] == "storage://audio/123" assert http.calls[0].json_payload["image_uri"] == "storage://image/456" @@ -332,16 +343,9 @@ def test_generate_audio_to_video_with_image_uri_posts_both_inputs() -> None: def test_generate_audio_to_video_with_last_frame_uri() -> None: http = FakeHTTPClient() - http.queue( - "post", - FakeResponse( - status_code=200, - headers={"Content-Type": "video/mp4"}, - content=b"direct-a2v-video", - ), - ) + _queue_completed_job(http, video_url="https://cdn.example.com/a2v.mp4", video_bytes=b"downloaded-a2v-video") - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) out = client.generate_audio_to_video( api_key="test-key", prompt="Animate from image and audio", @@ -352,17 +356,17 @@ def test_generate_audio_to_video_with_last_frame_uri() -> None: resolution="3840x2160", ) - assert out == b"direct-a2v-video" + assert out == b"downloaded-a2v-video" assert http.calls[0].json_payload is not None assert http.calls[0].json_payload["last_frame_uri"] == "storage://image/789" -def test_generate_audio_to_video_raises_on_non_200() -> None: +def test_generate_audio_to_video_submit_422_maps_to_safety_filter() -> None: http = FakeHTTPClient() http.queue("post", FakeResponse(status_code=422, text="unprocessable")) - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") - with pytest.raises(LTXAPIClientError, match="422") as exc: + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Content rejected by safety filters") as exc: client.generate_audio_to_video( api_key="bad-key", prompt="Bad request", @@ -372,7 +376,6 @@ def test_generate_audio_to_video_raises_on_non_200() -> None: resolution="1920x1080", ) assert exc.value.status_code == 422 - assert exc.value.stage == "generation" def _write_dummy_video(tmp_path) -> str: @@ -381,28 +384,22 @@ def _write_dummy_video(tmp_path) -> str: return str(input_path) -def test_retake_returns_direct_video_bytes(tmp_path) -> None: +def test_retake_async_submits_polls_and_downloads(tmp_path) -> None: http = FakeHTTPClient() input_path = _write_dummy_video(tmp_path) + _queue_upload(http, storage_uri="storage://retake/123") + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-rt"})) + http.queue("get", FakeResponse(status_code=200, json_payload={"status": "processing"})) http.queue( - "post", - FakeResponse( - status_code=200, - json_payload={ - "upload_url": "https://upload.example.com/retake", - "storage_uri": "storage://retake/123", - "required_headers": {}, - }, - ), + "get", FakeResponse( status_code=200, - headers={"Content-Type": "video/mp4"}, - content=b"retake-bytes", + json_payload={"status": "completed", "result": {"video_url": "https://cdn.example.com/retake.mp4"}}, ), ) - http.queue("put", FakeResponse(status_code=200)) + http.queue("get", FakeResponse(status_code=200, content=b"retake-bytes")) - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) result = client.retake( api_key="test-key", video_path=input_path, @@ -415,107 +412,26 @@ def test_retake_returns_direct_video_bytes(tmp_path) -> None: assert result.video_bytes == b"retake-bytes" assert result.result_payload is None - assert len(http.calls) == 3 - assert http.calls[0].url == "https://api.ltx.video/v1/upload" - assert http.calls[1].method == "put" - assert http.calls[2].url == "https://api.ltx.video/v1/retake" - assert http.calls[2].json_payload is not None - assert http.calls[2].json_payload["video_uri"] == "storage://retake/123" - - -def test_retake_json_video_url_downloads_bytes(tmp_path) -> None: - http = FakeHTTPClient() - input_path = _write_dummy_video(tmp_path) - http.queue( - "post", - FakeResponse( - status_code=200, - json_payload={ - "upload_url": "https://upload.example.com/retake", - "storage_uri": "storage://retake/456", - "required_headers": {}, - }, - ), - FakeResponse( - status_code=200, - headers={"Content-Type": "application/json"}, - json_payload={"video_url": "https://cdn.example.com/retake.mp4"}, - ), - ) - http.queue("put", FakeResponse(status_code=200)) - http.queue("get", FakeResponse(status_code=200, content=b"downloaded-retake")) - - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") - result = client.retake( - api_key="test-key", - video_path=input_path, - start_time=2.0, - duration=4.0, - prompt="test", - mode="replace_video", - model="ltx-2-3-pro", - ) - - assert result.video_bytes == b"downloaded-retake" - assert result.result_payload is None + submit_call = next(c for c in http.calls if c.url == "https://api.ltx.video/v2/retake") + assert submit_call.json_payload is not None + assert submit_call.json_payload["video_uri"] == "storage://retake/123" + assert submit_call.json_payload["start_time"] == 1.0 + assert submit_call.json_payload["duration"] == 3.0 + assert submit_call.json_payload["mode"] == "replace_audio_and_video" + assert submit_call.json_payload["model"] == "ltx-2-3-pro" + assert submit_call.json_payload["prompt"] == "make it dramatic" + poll_calls = [c for c in http.calls if c.url == "https://api.ltx.video/v2/retake/job-rt"] + assert len(poll_calls) == 2 assert http.calls[-1].url == "https://cdn.example.com/retake.mp4" -def test_retake_json_without_video_url_returns_payload(tmp_path) -> None: +def test_retake_async_422_maps_to_safety_filter(tmp_path) -> None: http = FakeHTTPClient() input_path = _write_dummy_video(tmp_path) - http.queue( - "post", - FakeResponse( - status_code=200, - json_payload={ - "upload_url": "https://upload.example.com/retake", - "storage_uri": "storage://retake/789", - "required_headers": {}, - }, - ), - FakeResponse( - status_code=200, - headers={"Content-Type": "application/json"}, - json_payload={"status": "processing"}, - ), - ) - http.queue("put", FakeResponse(status_code=200)) - - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") - result = client.retake( - api_key="test-key", - video_path=input_path, - start_time=0.0, - duration=2.5, - prompt="test", - mode="replace_audio_and_video", - model="ltx-2-3-pro", - ) - - assert result.video_bytes is None - assert result.result_payload is not None - assert result.result_payload["status"] == "processing" - - -def test_retake_422_maps_to_safety_filter_error(tmp_path) -> None: - http = FakeHTTPClient() - input_path = _write_dummy_video(tmp_path) - http.queue( - "post", - FakeResponse( - status_code=200, - json_payload={ - "upload_url": "https://upload.example.com/retake", - "storage_uri": "storage://retake/000", - "required_headers": {}, - }, - ), - FakeResponse(status_code=422, text="Content filtered"), - ) - http.queue("put", FakeResponse(status_code=200)) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=422, text="filtered")) - client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + client = _async_client(http) with pytest.raises(LTXAPIClientError, match="Content rejected by safety filters") as exc: client.retake( api_key="test-key", @@ -628,12 +544,56 @@ def test_extend_async_422_maps_to_safety_filter(tmp_path) -> None: http = FakeHTTPClient() input_path = _write_dummy_video(tmp_path) _queue_upload(http) - http.queue("post", FakeResponse(status_code=422, text="filtered")) + http.queue( + "post", + FakeResponse( + status_code=422, + text='{"type":"error","error":{"type":"content_filtered_error","message":"blocked"}}', + headers={"x-request-id": "req-422"}, + json_payload={ + "type": "error", + "error": {"type": "content_filtered_error", "message": "blocked"}, + }, + ), + ) client = _async_client(http) with pytest.raises(LTXAPIClientError, match="Content rejected by safety filters") as exc: client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") assert exc.value.status_code == 422 + assert exc.value.request_id == "req-422" + assert exc.value.provider_error_type == "content_filtered_error" + assert exc.value.provider_message == "blocked" + + +def test_async_submit_missing_job_id_attaches_request_id(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue( + "post", + FakeResponse(status_code=202, json_payload={}, headers={"x-request-id": "req-noid"}), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="no job id") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.request_id == "req-noid" + + +def test_async_submit_malformed_body_attaches_request_id(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue( + "post", + FakeResponse(status_code=202, json_payload=[], headers={"x-request-id": "req-malformed"}), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Unexpected") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.request_id == "req-malformed" def test_extend_async_connection_reset_maps_to_504(tmp_path) -> None: @@ -661,6 +621,75 @@ def test_extend_async_completed_without_url_raises(tmp_path) -> None: client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") +def test_async_submit_402_attaches_provider_error_fields(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue( + "post", + FakeResponse( + status_code=402, + text='{"type":"error","error":{"type":"insufficient_funds_error","message":"Insufficient funds. Required: 36 cents"}}', + headers={"Content-Type": "application/json", "x-request-id": "req-submit-1"}, + json_payload={ + "type": "error", + "error": { + "type": "insufficient_funds_error", + "message": "Insufficient funds. Required: 36 cents", + }, + }, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Insufficient funds") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 402 + assert exc.value.provider_error_type == "insufficient_funds_error" + assert exc.value.provider_message == "Insufficient funds. Required: 36 cents" + assert exc.value.request_id == "req-submit-1" + + +def test_async_submit_401_passes_through_with_request_id(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue( + "post", + FakeResponse( + status_code=401, + text="unauthorized", + headers={"x-request-id": "req-submit-2"}, + json_payload={"error": "unauthorized"}, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="unauthorized") as exc: + client.extend(api_key="bad-key", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 401 + assert exc.value.request_id == "req-submit-2" + + +def test_retake_upload_transport_failure_maps_to_504(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + http.queue("post", HttpTransportError("connection reset")) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="please retry") as exc: + client.retake( + api_key="k", + video_path=input_path, + start_time=1.0, + duration=3.0, + prompt="", + mode="replace_audio_and_video", + model="ltx-2-3-pro", + ) + assert exc.value.status_code == 504 + + def test_retake_upload_init_failure_maps_message() -> None: http = FakeHTTPClient() http.queue("post", FakeResponse(status_code=401, text="Unauthorized")) @@ -677,3 +706,188 @@ def test_retake_upload_init_failure_maps_message() -> None: model="ltx-2-3-pro", ) assert exc.value.status_code == 401 + + +def test_async_failed_job_insufficient_funds_maps_to_402(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-funds"})) + http.queue( + "get", + FakeResponse( + status_code=200, + json_payload={ + "status": "failed", + "error": { + "type": "insufficient_funds_error", + "message": "Insufficient funds. Required: 36 cents", + }, + }, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Insufficient funds") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 402 + assert exc.value.provider_error_type == "insufficient_funds_error" + assert exc.value.provider_message == "Insufficient funds. Required: 36 cents" + + +def test_async_failed_job_content_filtered_maps_to_422(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-filter"})) + http.queue( + "get", + FakeResponse( + status_code=200, + json_payload={ + "status": "failed", + "error": {"type": "content_filtered_error", "message": "blocked by filter"}, + }, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Content rejected by safety filters") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 422 + assert exc.value.provider_error_type == "content_filtered_error" + + +def test_async_failed_job_unknown_type_surfaces_with_type(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-over"})) + http.queue( + "get", + FakeResponse( + status_code=200, + json_payload={ + "status": "failed", + "error": {"type": "overloaded_error", "message": "backend overloaded"}, + }, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="backend overloaded") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 500 + assert exc.value.provider_error_type == "overloaded_error" + assert exc.value.provider_message == "backend overloaded" + + +def test_async_download_empty_body_raises(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-empty"})) + http.queue( + "get", + FakeResponse( + status_code=200, + json_payload={"status": "completed", "result": {"video_url": "https://cdn.example.com/empty.mp4"}}, + ), + ) + http.queue("get", FakeResponse(status_code=200, content=b"")) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="empty") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 500 + + +def test_async_poll_402_attaches_provider_error_fields(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-poll402"})) + http.queue( + "get", + FakeResponse( + status_code=402, + text='{"type":"error","error":{"type":"insufficient_funds_error","message":"Insufficient funds"}}', + headers={"x-request-id": "req-poll-402"}, + json_payload={"type": "error", "error": {"type": "insufficient_funds_error", "message": "Insufficient funds"}}, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="status check failed") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 402 + assert exc.value.provider_error_type == "insufficient_funds_error" + assert exc.value.provider_message == "Insufficient funds" + assert exc.value.request_id == "req-poll-402" + + +def test_async_poll_422_maps_to_safety_filter(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-poll422"})) + http.queue( + "get", + FakeResponse( + status_code=422, + text='{"type":"error","error":{"type":"content_filtered_error","message":"blocked"}}', + headers={"x-request-id": "req-poll-422"}, + json_payload={"type": "error", "error": {"type": "content_filtered_error", "message": "blocked"}}, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Content rejected by safety filters") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 422 + assert exc.value.provider_error_type == "content_filtered_error" + assert exc.value.request_id == "req-poll-422" + + +def test_async_failed_job_payment_declined_maps_to_402(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-declined"})) + http.queue( + "get", + FakeResponse( + status_code=200, + json_payload={ + "status": "failed", + "error": {"type": "payment_declined_error", "message": "Card declined"}, + }, + ), + ) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="Card declined") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 402 + assert exc.value.provider_error_type == "payment_declined_error" + assert exc.value.provider_message == "Card declined" + + +def test_async_poll_error_attaches_request_id(tmp_path) -> None: + http = FakeHTTPClient() + input_path = _write_dummy_video(tmp_path) + _queue_upload(http) + http.queue("post", FakeResponse(status_code=202, json_payload={"id": "job-pollerr"})) + http.queue("get", FakeResponse(status_code=500, text="upstream exploded", headers={"x-request-id": "req-poll-1"})) + + client = _async_client(http) + with pytest.raises(LTXAPIClientError, match="status check failed") as exc: + client.extend(api_key="k", video_path=input_path, duration=4.0, prompt="", mode="end", model="ltx-2-3-pro") + assert exc.value.status_code == 500 + assert exc.value.request_id == "req-poll-1" + + +def test_async_default_max_wait_is_1200s() -> None: + http = FakeHTTPClient() + client = LTXAPIClientImpl(http=http, ltx_api_base_url="https://api.ltx.video") + assert client._async_max_wait_s == 1200.0 diff --git a/backend/tests/test_ltx_capabilities.py b/backend/tests/test_ltx_capabilities.py index 117f8b083..8cd8b25f9 100644 --- a/backend/tests/test_ltx_capabilities.py +++ b/backend/tests/test_ltx_capabilities.py @@ -7,8 +7,12 @@ from api_types import LOCAL_MULTI_KEYFRAME_MAX_COUNT from runtime_config.ltx_capabilities import ( LocalOfferingCapabilities, + a2v_pixels_for, api_caps, + budget_pixels, + budget_size, effective_local_caps, + local_canvas, local_caps, pixels_for, supports, @@ -25,7 +29,7 @@ def test_local_models_share_one_two_stage_pixel_map(): caps = local_caps(model_id) assert caps.resolution_pixels_16_9 == reference, model_id for resolution in reference: - for aspect in ("16:9", "9:16"): + for aspect in ("21:9", "16:9", "3:2", "4:3", "1:1", "4:5", "9:16"): width, height = pixels_for(caps, resolution, aspect) assert width % 64 == 0 and height % 64 == 0, ( f"{model_id} {resolution} {aspect}: {width}x{height}" @@ -42,6 +46,61 @@ def test_local_2_3_v10_shares_2_3_pixel_map(): assert pixels_for(local_caps("ltx-2.3-22b-distilled"), "540p", "16:9") == (1024, 576) +def test_stage1_only_labels_use_the_parent_canvas(): + caps = local_caps("ltx-2.5-22b-distilled") + video_270 = local_canvas("270p", mode="video") + parent_540 = local_canvas("540p", mode="video") + assert (video_270.width, video_270.height) == (parent_540.width, parent_540.height) == (1024, 576) + assert video_270.skip_stage_2 is True + assert parent_540.skip_stage_2 is False + assert budget_size(video_270) == (512, 288) + assert budget_size(local_canvas("360p", mode="video")) == (640, 352) + audio_270 = local_canvas("270p", mode="a2v") + assert (audio_270.width, audio_270.height) == (576, 320) + assert audio_270.skip_stage_2 is False + assert budget_size(audio_270) == (576, 320) + assert pixels_for(caps, "270p", "16:9") == (1024, 576) + assert pixels_for(caps, "360p", "16:9") == (1280, 704) + assert pixels_for(caps, "270p", "9:16") == (576, 1024) + + +def test_a2v_small_labels_finish_on_their_own_canvas(): + caps = local_caps("ltx-2.5-22b-distilled") + assert a2v_pixels_for(caps, "270p", "16:9") == (576, 320) + assert a2v_pixels_for(caps, "270p", "9:16") == (320, 576) + assert a2v_pixels_for(caps, "360p", "16:9") == (704, 384) + assert a2v_pixels_for(caps, "360p", "9:16") == (384, 704) + assert a2v_pixels_for(caps, "540p", "16:9") == (1024, 576) + + +def test_budget_pixels_uses_the_selected_ratio_and_stage1_half(): + caps = local_caps("ltx-2.5-22b-distilled") + assert budget_pixels(caps, "540p", "16:9", mode="video") == (1024, 576) + assert budget_pixels(caps, "540p", "21:9", mode="video") == (1344, 576) + assert budget_pixels(caps, "270p", "16:9", mode="video") == (512, 288) + assert budget_pixels(caps, "270p", "21:9", mode="video") == (672, 288) + assert budget_pixels(caps, "270p", "21:9", mode="a2v") == (768, 320) + + +def test_short_side_formula_keeps_16_9_anchors_and_api_tiles(): + local = local_caps("ltx-2.5-22b-distilled") + api = api_caps("fast-2.5") + assert pixels_for(local, "1080p", "16:9") == (1920, 1088) + assert pixels_for(local, "540p", "21:9") == (1344, 576) + assert pixels_for(local, "1080p", "21:9") == (2560, 1088) + assert pixels_for(local, "540p", "4:3") == (768, 576) + assert pixels_for(local, "540p", "1:1") == (576, 576) + # 720 is closer to 704 than to 768. Snapping up landed on portrait 4:3. + assert pixels_for(local, "540p", "4:5") == (576, 704) + # 1934 is closer to the 16:9 anchor's transpose (1920) than to 1984. + assert pixels_for(local, "1080p", "9:16") == (1088, 1920) + assert pixels_for(api, "1080p", "16:9") == (1920, 1080) + assert pixels_for(api, "1080p", "3:2") == (1620, 1080) + assert pixels_for(api, "1080p", "1:1") == (1080, 1080) + assert pixels_for(api, "1080p", "9:16") == (1080, 1920) + assert pixels_for(api, "720p", "3:2") == (1080, 720) + + def test_local_2_5_540p_is_legal_16_9(): caps = local_caps("ltx-2.5-22b-distilled") width, height = pixels_for(caps, "540p", "16:9") @@ -53,8 +112,8 @@ def test_local_2_5_allows_ic_lora_and_user_loras(): caps = local_caps("ltx-2.5-22b-distilled") assert supports(caps, "ic_lora") is True assert supports(caps, "user_loras") is True - assert supports(caps, "retake") is False - assert supports(caps, "extend") is False + assert supports(caps, "retake") is True + assert supports(caps, "extend") is True assert supports(caps, "multi_keyframe") is True assert caps.multi_keyframe_max_count == LOCAL_MULTI_KEYFRAME_MAX_COUNT @@ -142,6 +201,11 @@ def test_pixels_for_unknown_resolution_raises(): pixels_for(api_caps("fast"), "540p", "16:9") +def test_a2v_pixels_for_rejects_a_resolution_the_offering_does_not_list(): + with pytest.raises(KeyError): + a2v_pixels_for(api_caps("fast"), "270p", "16:9") + + def test_ic_lora_flag_is_on_for_every_local_model(): from runtime_config.model_download_specs import ALL_LTX_LOCAL_MODEL_IDS diff --git a/backend/tests/test_ltx_contract.py b/backend/tests/test_ltx_contract.py new file mode 100644 index 000000000..3e64020ed --- /dev/null +++ b/backend/tests/test_ltx_contract.py @@ -0,0 +1,101 @@ +"""Upstream LTX-2 contracts that desktop's forked pipelines and patches rely on. + +Each assertion names something desktop calls, overrides or monkey-patches. When +an LTX bump breaks one, this file fails first with a message that points at the +exact contract, instead of a shape error deep inside a fork. +Re-check this file (and `.cursor/rules/ltx2-patch-reverify.mdc`) on every bump. +""" + +from __future__ import annotations + +import dataclasses +import inspect + +import ltx_pipelines.chunks.conditionings as chunk_conditionings +import ltx_pipelines.utils.helpers as helpers +from ltx_pipelines.distilled import DistilledPipeline +from ltx_pipelines.ic_lora import ICLoraPipeline, ICLoraStageConfig +from ltx_pipelines.utils.blocks import DiffusionStage +from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop +from ltx_pipelines.utils.types import ModalitySpec, PipelineOutput, VideoAudio + + +def _params(fn: object) -> list[str]: + return list(inspect.signature(fn).parameters) # type: ignore[arg-type] + + +def test_diffusion_stage_call_takes_modalities_and_an_optional_loop() -> None: + assert _params(DiffusionStage.__call__) == [ + "self", + "denoiser", + "sigmas", + "noiser", + "modalities", + "loop", + "max_batch_size", + ] + + +def test_diffusion_stage_exposes_transformer_scale_factors() -> None: + """Latents must be sized with these, not with the decoder's tiling scale.""" + assert "self.video_scale_factors" in inspect.getsource(DiffusionStage.__init__) + + +def test_modality_spec_fields() -> None: + fields = {field.name for field in dataclasses.fields(ModalitySpec)} + assert {"latent", "conditioning_fps", "context", "conditionings", "noise_scale", "frozen"} <= fields + assert "initial_latent" not in fields + + +def test_pipeline_output_is_a_four_field_tuple() -> None: + assert PipelineOutput._fields == ("video", "audio", "num_frames", "tiling_config") + + +def test_video_audio_unpacks_as_video_then_audio() -> None: + assert tuple(VideoAudio(video=1, audio=2)) == (1, 2) + + +def test_ancestral_loop_parameters_used_by_the_sampler_partials() -> None: + assert {"noise_seed", "model_dtype", "eta", "s_noise"} <= set(_params(euler_ancestral_denoising_loop)) + + +def test_distilled_pipeline_sampler_kwargs_hook() -> None: + assert _params(DistilledPipeline._sampler_kwargs)[:3] == ["self", "seed", "noise_seed_offset"] # type: ignore[attr-defined] + + +def test_initial_latent_helpers_take_explicit_scale_factors() -> None: + assert "scale_factors" in _params(helpers.create_initial_video_latent) + assert "video_scale_factors" in _params(helpers.create_initial_av_latents) + assert "video_scale_factors" in _params(helpers.create_initial_audio_latent) + + +def test_keyframe_swap_targets_exist_in_both_modules() -> None: + """`distilled_keyframe_guiding` rebinds this name in both modules.""" + for module in (helpers, chunk_conditionings): + assert callable(module.combined_image_conditionings) + assert callable(helpers.image_conditionings_by_adding_guiding_latent) + + +def test_chunk_keyframes_resolve_the_swappable_name_from_the_chunks_module() -> None: + """The per-chunk factory looks the name up in its module globals at call time. + + If upstream stops doing that (e.g. binds it as a default argument), swapping the + module attribute silently stops changing multi-keyframe behaviour. + """ + from services.fast_video_pipeline.distilled_keyframe_guiding import distilled_keyframe_guiding + + factory_globals = chunk_conditionings.image_conditionings_for_chunk.__globals__ + assert factory_globals is vars(chunk_conditionings) + + with distilled_keyframe_guiding(): + assert factory_globals["combined_image_conditionings"] is helpers.image_conditionings_by_adding_guiding_latent + + assert factory_globals["combined_image_conditionings"] is not helpers.image_conditionings_by_adding_guiding_latent + + +def test_ic_lora_override_point_and_stage_config() -> None: + assert _params(ICLoraPipeline._video_conditionings) == ["self", "ctx", "stage_config", "frame_sources"] # type: ignore[attr-defined] + assert "apply_ic_lora" in {field.name for field in dataclasses.fields(ICLoraStageConfig)} + assert {"encode_tiling", "downscale_factor", "reference_temporal_scale_factor"} <= set( + _params(chunk_conditionings.reference_video_conditionings_for_chunk) + ) diff --git a/backend/tests/test_ltx_text_encoder.py b/backend/tests/test_ltx_text_encoder.py index 98040aa53..afe27401e 100644 --- a/backend/tests/test_ltx_text_encoder.py +++ b/backend/tests/test_ltx_text_encoder.py @@ -12,6 +12,7 @@ import pytest import torch +from _routes._errors import HTTPError from runtime_config.ltx_api_text_encoder_ids import LTX_2_5_API_PROMPT_EMBEDDING_MODEL from runtime_config.model_download_specs import get_ltx_model_spec from services.text_encoder.ltx_text_encoder import ( # noqa: SLF001 @@ -200,3 +201,53 @@ def test_encode_via_api_skips_request_when_no_selector(tmp_path: Path) -> None: assert result is None assert http.calls == [] + + +def test_encode_via_api_raises_when_the_key_is_rejected(tmp_path: Path) -> None: + http = FakeHTTPClient() + http.queue("post", FakeResponse(status_code=401, text="unauthorized")) + encoder = LTXTextEncoder( + device=torch.device("cpu"), + http=http, + ltx_api_base_url="https://api.ltx.video", + ) + checkpoint = tmp_path / "ltx-2.5.safetensors" + checkpoint.write_bytes(b"not-a-checkpoint") + + with pytest.raises(HTTPError) as exc_info: + encoder.encode_via_api( + prompt="prompt", + api_key="bad-key", + checkpoint_path=str(checkpoint), + enhance_prompt=False, + api_model=LTX_2_5_API_PROMPT_EMBEDDING_MODEL, + ) + + assert exc_info.value.status_code == 401 + assert exc_info.value.code == "LTX_INVALID_API_KEY" + assert exc_info.value.detail == "This LTX API key isn’t valid." + + +def test_encode_via_api_raises_when_the_request_times_out(tmp_path: Path) -> None: + http = FakeHTTPClient() + http.queue("post", TimeoutError("timed out")) + encoder = LTXTextEncoder( + device=torch.device("cpu"), + http=http, + ltx_api_base_url="https://api.ltx.video", + ) + checkpoint = tmp_path / "ltx-2.5.safetensors" + checkpoint.write_bytes(b"not-a-checkpoint") + + with pytest.raises(HTTPError) as exc_info: + encoder.encode_via_api( + prompt="prompt", + api_key="key", + checkpoint_path=str(checkpoint), + enhance_prompt=False, + api_model=LTX_2_5_API_PROMPT_EMBEDDING_MODEL, + ) + + assert exc_info.value.status_code == 504 + assert exc_info.value.code == "LTX_API_PROMPT_EMBEDDING_FAILED" + assert exc_info.value.detail == "LTX API text encoding failed." diff --git a/backend/tests/test_matplotlib_not_mocked.py b/backend/tests/test_matplotlib_not_mocked.py new file mode 100644 index 000000000..253876c63 --- /dev/null +++ b/backend/tests/test_matplotlib_not_mocked.py @@ -0,0 +1,25 @@ +"""colour-science must not replace matplotlib with mocks. + +Without a real matplotlib, ``colour.plotting`` fills ``sys.modules`` with stand-in +objects. ``diffusers`` then crashes at import: ``find_spec("matplotlib")`` raises +``ValueError: matplotlib.__spec__ is not set``. +""" + +from __future__ import annotations + +import importlib.util + + +def test_matplotlib_stays_real_after_ltx_imports() -> None: + import ltx_pipelines.utils.media_io # noqa: F401 # pulls in colour + + import matplotlib + + assert matplotlib.__spec__ is not None + assert importlib.util.find_spec("matplotlib") is not None + assert isinstance(matplotlib.__version__, str) + + +def test_diffusers_imports_after_ltx_imports() -> None: + import ltx_pipelines.utils.media_io # noqa: F401 + from diffusers.pipelines.auto_pipeline import ZImagePipeline # noqa: F401 diff --git a/backend/tests/test_model_download_specs.py b/backend/tests/test_model_download_specs.py index 7b676d496..89b0fca61 100644 --- a/backend/tests/test_model_download_specs.py +++ b/backend/tests/test_model_download_specs.py @@ -11,6 +11,9 @@ ALL_MODEL_CP_IDS, ALL_LTX_LOCAL_MODEL_IDS, LTX_2_5_FAMILY_DIR, + catalog_item_visible_for_installed_ltx, + installed_ltx_catalog_families, + ltx_catalog_family_for_model, ModelCheckpointSpec, delete_cp_path, get_existing_cp_path, @@ -59,7 +62,8 @@ def test_latest_ltx_model_is_relevant(): assert spec.model_cp in get_ltx_cps() assert spec.video_vae_cp is not None assert spec.audio_vae_cp is not None - assert spec.ic_loras_spec is None + assert spec.ic_loras_spec is not None + assert get_ic_loras_cp_ids(spec.ic_loras_spec) == ("ltx-2.3-22b-ic-lora-union-control-ref0.5",) def test_ic_lora_cp_ids_are_deduped_for_2_3(): @@ -77,6 +81,7 @@ def test_ltx_2_5_model_cp_ids_include_split_vaes(): spec.video_vae_conv_cp, spec.audio_vae_cp, spec.duration_head_cp, + "ltx-2.3-22b-ic-lora-union-control-ref0.5", ) assert spec.video_vae_conv_cp == "ltx-2.5-video-vae-conv" assert spec.duration_head_cp == "ltx-2.5-duration-head" @@ -278,3 +283,41 @@ def test_2_5_prefers_e2b_over_gemma3(tmp_path: Path): _write_folder_cp(tmp_path, "gemma-3-12b-it-qat-q4_0-unquantized") _write_folder_cp(tmp_path, "gemma-4-e2b-it") assert resolve_downloaded_prompt_enhancer_cp(tmp_path, spec) == "gemma-4-e2b-it" + + +def _install_generation_bundle(models_dir: Path, model_id: str) -> None: + spec = get_ltx_model_spec(model_id) + for cp_id in ( + spec.model_cp, + spec.upscale_cp, + spec.video_vae_cp, + spec.video_vae_conv_cp, + spec.audio_vae_cp, + spec.text_encoder_cp, + ): + if cp_id is None: + continue + if get_model_cp_spec(cp_id).is_folder: + _write_folder_cp(models_dir, cp_id) + continue + path = resolve_model_path(models_dir, cp_id) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"x") + + +def test_ltx_catalog_family_for_model(): + assert ltx_catalog_family_for_model("ltx-2.5-22b-distilled") == "LTX-2.5" + assert ltx_catalog_family_for_model("ltx-2.3-22b-distilled-1.1") == "LTX-2.3" + + +def test_installed_ltx_catalog_families_empty_without_bundles(tmp_path: Path): + assert installed_ltx_catalog_families(tmp_path) == set() + assert not catalog_item_visible_for_installed_ltx(["LTX-2.3"], tmp_path) + + +def test_catalog_item_visible_when_matching_family_installed(tmp_path: Path): + _install_generation_bundle(tmp_path, "ltx-2.5-22b-distilled") + assert installed_ltx_catalog_families(tmp_path) == {"LTX-2.5"} + assert catalog_item_visible_for_installed_ltx(["LTX-2.5"], tmp_path) + assert not catalog_item_visible_for_installed_ltx(["LTX-2.3"], tmp_path) + assert catalog_item_visible_for_installed_ltx(["LTX-2.3", "LTX-2.5"], tmp_path) diff --git a/backend/tests/test_models.py b/backend/tests/test_models.py index d1b5d17fa..e81117b0a 100644 --- a/backend/tests/test_models.py +++ b/backend/tests/test_models.py @@ -77,6 +77,11 @@ def _optional_download_cps(*, include_text_encoder: bool, test_state=None) -> li return cps +def _recommended_quality_cps() -> list[str]: + spec = _current_ltx_spec() + return [spec.prompt_enhancer_cp] if spec.prompt_enhancer_cp is not None else [] + + def _remove_text_encoder(test_state) -> None: from runtime_config.model_download_specs import get_model_cp_spec @@ -99,9 +104,192 @@ def test_ltx_recommendation_requires_primary_local_bundle(self, client): "status": "download", "cps_to_download": _required_download_cps(include_text_encoder=True), "optional_cp_ids": _optional_download_cps(include_text_encoder=False), + "recommended_quality_cp_ids": _recommended_quality_cps(), } assert "ltx-2.3-spatial-upscaler-x2-1.0" not in payload["cps_to_download"] + def test_fresh_recommendation_is_empty_machine_bundle_even_when_installed( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files(include_zit=True, include_prompt_enhancer=True) + test_state.state.app_settings.ltx_api_key = "test-key" + installed = client.get("/api/models/ltx-recommendation").json() + assert installed["status"] == "ok" + fresh = client.get("/api/models/ltx-recommendation", params={"fresh": True}).json() + assert fresh == { + "status": "download", + "cps_to_download": _required_download_cps(include_text_encoder=True), + "optional_cp_ids": _optional_download_cps(include_text_encoder=False), + "recommended_quality_cp_ids": _recommended_quality_cps(), + } + img = client.get("/api/models/img-gen-recommendation", params={"fresh": True}).json() + assert img == {"cp_to_download": IMG_GEN_MODEL_CP_ID} + + def test_fresh_ignores_api_key_on_empty_machine(self, client, test_state): + # Key set, nothing on disk: fresh still returns the full no-key bundle while the + # default (non-fresh) recommendation excuses the text encoder. + test_state.state.app_settings.ltx_api_key = "test-key" + fresh = client.get("/api/models/ltx-recommendation", params={"fresh": True}).json() + assert fresh == { + "status": "download", + "cps_to_download": _required_download_cps(include_text_encoder=True, test_state=test_state), + "optional_cp_ids": _optional_download_cps(include_text_encoder=False, test_state=test_state), + "recommended_quality_cp_ids": _recommended_quality_cps(), + } + default = client.get("/api/models/ltx-recommendation").json() + assert _current_ltx_spec().text_encoder_cp not in default["cps_to_download"] + assert _current_ltx_spec().text_encoder_cp in default["optional_cp_ids"] + + def test_fresh_returns_full_sets_despite_partial_downloads(self, client, test_state): + # Only the transformer on disk: fresh still lists it (no disk filtering) while the + # default recommendation filters it out. + spec = _current_ltx_spec() + base_path = _cp_path(test_state, spec.model_cp) + base_path.parent.mkdir(parents=True, exist_ok=True) + base_path.write_bytes(b"\x00" * 1024) + + fresh = client.get("/api/models/ltx-recommendation", params={"fresh": True}).json() + assert fresh["status"] == "download" + assert spec.model_cp in fresh["cps_to_download"] + assert fresh["cps_to_download"] == _required_download_cps( + include_text_encoder=True, test_state=test_state + ) + + default = client.get("/api/models/ltx-recommendation").json() + assert default["status"] == "download" + assert spec.model_cp not in default["cps_to_download"] + + def test_fresh_false_matches_default(self, client, test_state): + test_state.state.app_settings.ltx_api_key = "test-key" + explicit = client.get("/api/models/ltx-recommendation", params={"fresh": False}).json() + default = client.get("/api/models/ltx-recommendation").json() + assert explicit == default + + def test_include_installed_repairs_the_current_model_not_latest(self, client, test_state): + # Older transformer on disk, companions missing: Setup's catalog must be that + # model's full sets. `fresh` would swap in the latest bundle and the install + # queue would download different files than the card listed. + older = get_ltx_model_spec("ltx-2.3-22b-distilled-1.1") + latest = _current_ltx_spec() + assert older.model_cp != latest.model_cp + base_path = _cp_path(test_state, older.model_cp) + base_path.parent.mkdir(parents=True, exist_ok=True) + base_path.write_bytes(b"\x00" * 1024) + + live = client.get("/api/models/ltx-recommendation").json() + catalog = client.get( + "/api/models/ltx-recommendation", params={"include_installed": True} + ).json() + + assert live["status"] == "download" + assert catalog["status"] == "download" + assert older.model_cp not in live["cps_to_download"] + assert older.model_cp in catalog["cps_to_download"] + for payload in (live, catalog): + assert latest.model_cp not in payload["cps_to_download"] + assert latest.model_cp not in payload["optional_cp_ids"] + assert latest.model_cp not in payload["recommended_quality_cp_ids"] + live_ids = ( + set(live["cps_to_download"]) + | set(live["optional_cp_ids"]) + | set(live["recommended_quality_cp_ids"]) + ) + catalog_ids = ( + set(catalog["cps_to_download"]) + | set(catalog["optional_cp_ids"]) + | set(catalog["recommended_quality_cp_ids"]) + ) + assert live_ids <= catalog_ids + + def test_include_installed_keeps_downloaded_files_of_the_current_model(self, client, test_state): + spec = _current_ltx_spec() + base_path = _cp_path(test_state, spec.model_cp) + base_path.parent.mkdir(parents=True, exist_ok=True) + base_path.write_bytes(b"\x00" * 1024) + + live = client.get("/api/models/ltx-recommendation").json() + catalog = client.get( + "/api/models/ltx-recommendation", params={"include_installed": True} + ).json() + assert spec.model_cp not in live["cps_to_download"] + assert spec.model_cp in catalog["cps_to_download"] + assert set(live["cps_to_download"]) <= set(catalog["cps_to_download"]) + + def test_include_installed_follows_the_api_key_and_fresh_still_wins(self, client, test_state): + test_state.state.app_settings.ltx_api_key = "test-key" + catalog = client.get( + "/api/models/ltx-recommendation", params={"include_installed": True} + ).json() + default = client.get("/api/models/ltx-recommendation").json() + assert catalog == default + text_encoder = _current_ltx_spec().text_encoder_cp + assert text_encoder in catalog["optional_cp_ids"] + + fresh = client.get( + "/api/models/ltx-recommendation", + params={"fresh": True, "include_installed": True}, + ).json() + assert text_encoder in fresh["cps_to_download"] + + def test_include_installed_stays_ok_when_the_current_bundle_is_complete( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files(include_zit=True, include_prompt_enhancer=True) + test_state.state.app_settings.ltx_api_key = "test-key" + payload = client.get( + "/api/models/ltx-recommendation", params={"include_installed": True} + ).json() + assert payload["status"] == "ok" + + def test_pure_required_optional_sets(self): + # Pin the module-level pure spec computations directly (no handler state). + spec = _current_ltx_spec() + for use_conv_vae in (True, False): + required = models_handler_module._required_ltx_cp_ids( + spec, use_conv_vae=use_conv_vae, has_api_key=False + ) + assert spec.model_cp in required + assert spec.upscale_cp in required + assert spec.text_encoder_cp in required + expected_vae = selected_video_vae_cp(spec, use_conv_vae=use_conv_vae) + assert expected_vae is not None and expected_vae in required + if spec.video_vae_conv_cp is not None: + assert spec.video_vae_conv_cp in required + + optional = models_handler_module._optional_ltx_cp_ids( + spec, use_conv_vae=use_conv_vae, has_api_key=False + ) + assert spec.text_encoder_cp not in optional + assert not (optional & required) + + required_keyed = models_handler_module._required_ltx_cp_ids( + spec, use_conv_vae=use_conv_vae, has_api_key=True + ) + optional_keyed = models_handler_module._optional_ltx_cp_ids( + spec, use_conv_vae=use_conv_vae, has_api_key=True + ) + if spec.supports_api_text_encoding: + assert spec.text_encoder_cp not in required_keyed + assert spec.text_encoder_cp in optional_keyed + assert not (optional_keyed & required_keyed) + + recommended = models_handler_module._recommended_quality_ltx_cp_ids( + spec, required=required + ) + if spec.prompt_enhancer_cp is None: + assert recommended == set() + else: + assert recommended == {spec.prompt_enhancer_cp} + assert not (recommended & required) + + def test_pure_recommended_quality_is_empty_without_enhancer(self): + spec_2_3 = get_ltx_model_spec("ltx-2.3-22b-distilled-1.1") + assert spec_2_3.prompt_enhancer_cp is None + required = models_handler_module._required_ltx_cp_ids( + spec_2_3, use_conv_vae=False, has_api_key=False + ) + assert models_handler_module._recommended_quality_ltx_cp_ids(spec_2_3, required=required) == set() + def test_ltx_recommendation_skips_text_encoder_for_2_5_when_api_key_exists(self, client, test_state): test_state.state.app_settings.ltx_api_key = "test-key" response = client.get("/api/models/ltx-recommendation") @@ -111,6 +299,7 @@ def test_ltx_recommendation_skips_text_encoder_for_2_5_when_api_key_exists(self, "cps_to_download": _required_download_cps(include_text_encoder=False), # Excused, not withheld: first-run still offers it so an offline setup stays possible. "optional_cp_ids": _optional_download_cps(include_text_encoder=True), + "recommended_quality_cp_ids": _recommended_quality_cps(), } def test_required_video_vae_follows_fast_decode_toggle(self, client, test_state): @@ -179,6 +368,79 @@ def test_prompt_enhancer_is_never_required(self, client, create_fake_model_files assert spec.prompt_enhancer_cp not in by_id["ltx-2.5-22b-distilled"]["cps_to_download"] assert client.post("/api/models/active-ltx-model", json={"model_id": "ltx-2.5-22b-distilled"}).status_code == 200 + def test_ltx_recommendation_recommends_2_5_enhancer_as_quality_dependency(self, client): + spec = _current_ltx_spec() + assert spec.prompt_enhancer_cp == "gemma-4-e2b-it" + + payload = client.get("/api/models/ltx-recommendation").json() + assert payload["status"] == "download" + assert payload["recommended_quality_cp_ids"] == [spec.prompt_enhancer_cp] + assert spec.prompt_enhancer_cp not in payload["cps_to_download"] + assert spec.prompt_enhancer_cp not in payload["optional_cp_ids"] + + def test_recommended_quality_is_empty_for_current_2_3_install( + self, client, test_state + ): + test_state.state.app_settings.ltx_api_key = "test-key" + older_spec = get_ltx_model_spec("ltx-2.3-22b-distilled") + base_path = _cp_path(test_state, older_spec.model_cp) + base_path.parent.mkdir(parents=True, exist_ok=True) + base_path.write_bytes(b"\x00" * 1024) + + payload = client.get("/api/models/ltx-recommendation").json() + assert payload["status"] == "download" + assert payload["cps_to_download"] == [older_spec.upscale_cp] + assert payload["recommended_quality_cp_ids"] == [] + + def test_recommended_quality_omits_already_downloaded_enhancer( + self, client, test_state, create_fake_model_files + ): + spec = _current_ltx_spec() + assert spec.video_vae_conv_cp is not None + create_fake_model_files(include_prompt_enhancer=True) + test_state.state.app_settings.use_conv_vae = False + _cp_path(test_state, spec.video_vae_conv_cp).unlink() + + payload = client.get("/api/models/ltx-recommendation").json() + assert payload["status"] == "download" + assert payload["cps_to_download"] == [spec.video_vae_conv_cp] + assert payload["recommended_quality_cp_ids"] == [] + + def test_missing_2_5_companion_still_recommends_undownloaded_enhancer( + self, client, test_state, create_fake_model_files + ): + spec = _current_ltx_spec() + assert spec.video_vae_conv_cp is not None + create_fake_model_files() + test_state.state.app_settings.use_conv_vae = False + _cp_path(test_state, spec.video_vae_conv_cp).unlink() + + payload = client.get("/api/models/ltx-recommendation").json() + assert payload["status"] == "download" + assert payload["cps_to_download"] == [spec.video_vae_conv_cp] + assert payload["recommended_quality_cp_ids"] == [spec.prompt_enhancer_cp] + + def test_upgrade_to_2_5_recommends_enhancer_without_requiring_it( + self, client, test_state, create_fake_model_files, create_fake_ic_lora_files + ): + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + create_fake_ic_lora_files() + test_state.state.app_settings.ltx_api_key = "test-key" + test_state.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + + payload = client.get("/api/models/ltx-recommendation").json() + target = get_ltx_model_spec("ltx-2.5-22b-distilled") + assert payload["status"] == "upgrade" + assert payload["recommended_quality_cp_ids"] == [target.prompt_enhancer_cp] + assert target.prompt_enhancer_cp not in payload["cps_to_download"] + + def test_describe_checkpoints_labels_prompt_enhancer(self, client): + response = client.post("/api/models/describe", json={"cp_ids": ["gemma-4-e2b-it"]}) + assert response.status_code == 200 + checkpoint = response.json()["checkpoints"][0] + assert checkpoint["cp_id"] == "gemma-4-e2b-it" + assert checkpoint["role"] == "prompt_enhancer" + def test_ltx_recommendation_ok_when_required_bundle_is_downloaded(self, client, create_fake_model_files): create_fake_model_files() response = client.get("/api/models/ltx-recommendation") @@ -203,6 +465,7 @@ def test_recommendation_surfaces_missing_shared_companion_for_current_base(self, "status": "download", "cps_to_download": [older_spec.upscale_cp], "optional_cp_ids": [older_spec.text_encoder_cp], + "recommended_quality_cp_ids": [], } assert payload["cps_to_download"] == ["ltx-2.3-spatial-upscaler-x2-1.1"] assert "ltx-2.3-spatial-upscaler-x2-1.0" not in payload["cps_to_download"] @@ -217,6 +480,7 @@ def test_ltx_recommendation_reports_missing_text_encoder_for_current_model(self, "status": "download", "cps_to_download": [_current_ltx_spec().text_encoder_cp], "optional_cp_ids": [], + "recommended_quality_cp_ids": _recommended_quality_cps(), } def test_upgrade_from_2_3_downloads_split_companions( @@ -244,8 +508,8 @@ def test_upgrade_from_2_3_downloads_split_companions( target.duration_head_cp, } assert target.text_encoder_cp not in payload["cps_to_download"] - assert payload["loses_built_in_control"] is True - assert "ltx-2.3-22b-ic-lora-union-control-ref0.5" in payload["cps_to_delete"] + assert payload["loses_built_in_control"] is False + assert "ltx-2.3-22b-ic-lora-union-control-ref0.5" not in payload["cps_to_delete"] def test_upgrade_from_2_3_includes_conv_vae_even_when_fast_decode_is_off( self, client, test_state, create_fake_model_files, create_fake_ic_lora_files @@ -291,9 +555,28 @@ def test_text_encoder_recommendation(self, client, create_fake_model_files, test response = client.get("/api/models/text-encoder-recommendation") assert response.status_code == 200 assert response.json()["cp_to_download"] == _current_ltx_spec().text_encoder_cp + assert response.json()["active_local_text_encoder_cp"] is None assert response.json()["expected_size_bytes"] > 0 assert response.json()["api_encoding_supported"] is True - assert response.json()["ltx_version_label"] == "2.5" + assert response.json()["ltx_version_label"] == "LTX 2.5" + + create_fake_model_files() + response = client.get("/api/models/text-encoder-recommendation") + assert response.status_code == 200 + assert response.json()["cp_to_download"] is None + assert response.json()["active_local_text_encoder_cp"] == _current_ltx_spec().text_encoder_cp + # No API key configured, so the local encoder is the only way to encode. + assert response.json()["local_text_encoder_removable"] is False + + test_state.state.app_settings.ltx_api_key = "test-key" + response = client.get("/api/models/text-encoder-recommendation") + assert response.status_code == 200 + assert response.json()["local_text_encoder_removable"] is True + + test_state.state.app_settings.use_local_text_encoder = True + response = client.get("/api/models/text-encoder-recommendation") + assert response.status_code == 200 + assert response.json()["local_text_encoder_removable"] is False def test_describe_checkpoints(self, client, create_fake_model_files): spec = _current_ltx_spec() @@ -331,10 +614,11 @@ def test_ic_lora_recommendation(self, client, create_fake_model_files, create_fa create_fake_model_files() response = client.get("/api/models/ltx-ic-lora-recommendation") assert response.status_code == 200 - # Latest (2.5) has no built-in Union Control IC-LoRA. + # 2.5 reuses the 2.3 Union Control adapter; missing weights are a download, not unsupported. payload = response.json() - assert payload["cps_to_download"] == [] - assert payload["supported"] is False + assert payload["supported"] is True + assert "ltx-2.3-22b-ic-lora-union-control-ref0.5" in payload["cps_to_download"] + assert DEPTH_PROCESSOR_CP_ID in payload["cps_to_download"] def test_ic_lora_recommendation_supported_on_active_2_3( self, client, test_state, create_fake_model_files, create_fake_ic_lora_files @@ -522,6 +806,49 @@ def test_delete_rejects_current_ltx_bundle(self, client, create_fake_model_files ) assert_http_error(response, status_code=409, code="DELETE_PROTECTED_CHECKPOINT") + def test_delete_rejects_text_encoder_when_local_encoding_is_required( + self, client, create_fake_model_files, test_state + ): + create_fake_model_files() + # No API key: the local encoder is the only way to encode prompts. + response = client.request( + "DELETE", + "/api/models/delete", + json={"cp_ids": [_current_ltx_spec().text_encoder_cp]}, + ) + assert_http_error(response, status_code=409, code="DELETE_PROTECTED_CHECKPOINT") + + # A key alone is not enough while the user has chosen local encoding. + test_state.state.app_settings.ltx_api_key = "test-key" + test_state.state.app_settings.use_local_text_encoder = True + response = client.request( + "DELETE", + "/api/models/delete", + json={"cp_ids": [_current_ltx_spec().text_encoder_cp]}, + ) + assert_http_error(response, status_code=409, code="DELETE_PROTECTED_CHECKPOINT") + + def test_delete_allows_text_encoder_when_api_encoding_covers_it( + self, client, create_fake_model_files, test_state + ): + create_fake_model_files() + test_state.state.app_settings.ltx_api_key = "test-key" + test_state.state.app_settings.use_local_text_encoder = False + response = client.request( + "DELETE", + "/api/models/delete", + json={"cp_ids": [_current_ltx_spec().text_encoder_cp]}, + ) + assert response.status_code == 200 + assert response.json()["status"] == "ok" + # The rest of the active bundle stays protected. + response = client.request( + "DELETE", + "/api/models/delete", + json={"cp_ids": [_current_ltx_spec().model_cp]}, + ) + assert_http_error(response, status_code=409, code="DELETE_PROTECTED_CHECKPOINT") + def test_delete_removes_non_protected_checkpoint(self, client, test_state): img_gen_path = _cp_path(test_state, IMG_GEN_MODEL_CP_ID) img_gen_path.mkdir(parents=True, exist_ok=True) @@ -553,9 +880,9 @@ def test_2_3_versions_share_companions(self): assert v11.model_cp != v10.model_cp def test_version_labels(self): - assert get_ltx_model_spec("ltx-2.5-22b-distilled").version_label == "2.5" - assert get_ltx_model_spec("ltx-2.3-22b-distilled-1.1").version_label == "2.3" - assert get_ltx_model_spec("ltx-2.3-22b-distilled").version_label == "2.3 (1.0)" + assert get_ltx_model_spec("ltx-2.5-22b-distilled").version_label == "LTX 2.5" + assert get_ltx_model_spec("ltx-2.3-22b-distilled-1.1").version_label == "LTX 2.3" + assert get_ltx_model_spec("ltx-2.3-22b-distilled").version_label == "LTX 2.3 (1.0)" def test_2_5_checkpoint_spec(self): spec = get_model_cp_spec("ltx-2.5-22b-distilled") @@ -627,7 +954,7 @@ def test_versions_list_newest_first_with_flags(self, client, test_state, create_ ] newest = versions[0] older = versions[2] - assert newest["label"] == "2.5" + assert newest["label"] == "LTX 2.5" assert newest["installed"] is True assert newest["active"] is True assert versions[1]["installed"] is False @@ -677,6 +1004,23 @@ def test_set_active_succeeds_and_persists(self, client, test_state): saved = json.loads(test_state.config.settings_file.read_text()) assert saved["active_ltx_model_id"] == "ltx-2.3-22b-distilled" + def test_versions_list_marks_saved_active_when_multiple_installed( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files() + test_state.state.app_settings.ltx_api_key = "test-key" + test_state.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + spec = get_ltx_model_spec("ltx-2.3-22b-distilled-1.1") + for cp in (spec.model_cp, spec.upscale_cp): + path = resolve_model_path(test_state.config.default_models_dir, cp) + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(b"\x00" * 1024) + response = client.get("/api/models/ltx-versions") + assert response.status_code == 200 + by_id = {item["model_id"]: item for item in response.json()["versions"]} + assert by_id["ltx-2.3-22b-distilled-1.1"]["active"] is True + assert by_id["ltx-2.5-22b-distilled"]["active"] is False + class TestDeleteGuard: def _write_generation_bundle(self, test_state, model_id: str) -> None: @@ -771,7 +1115,68 @@ def test_models_specs_display_follows_active( response = client.get("/api/generate/models-specs") assert response.status_code == 200 - assert response.json()["local_models"][0]["spec"]["display_name"] == "LTX 2.3 Fast" + payload = response.json() + assert payload["local_models"][0]["spec"]["display_name"] == "LTX 2.3 Fast" + assert payload["active_offering"] == "ltx-2.3-fast" + + @pytest.mark.parametrize("darwin", [True, False]) + def test_models_specs_report_low_performance_machine(self, client, test_state, darwin): + test_state.config.darwin_unified_memory = darwin + + data = client.get("/api/generate/models-specs").json() + + assert data["low_performance_machine"] is darwin + + def test_downloaded_local_models_lists_installed_offerings_newest_first( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + + data = client.get("/api/generate/models-specs").json() + assert [item["model"] for item in data["downloaded_local_models"]] == [ + "ltx-2.5-fast", + "ltx-2.3-fast", + ] + by_model = {item["model"]: item for item in data["downloaded_local_models"]} + assert by_model["ltx-2.5-fast"]["pipeline"] == "fast" + assert by_model["ltx-2.5-fast"]["spec"]["display_name"] == "LTX 2.5 Fast" + assert by_model["ltx-2.3-fast"]["pipeline"] == "fast" + assert by_model["ltx-2.3-fast"]["spec"]["display_name"] == "LTX 2.3 Fast" + assert data["local_models"][0]["spec"]["display_name"] == "LTX 2.3 Fast" + assert data["active_offering"] == "ltx-2.3-fast" + + def test_downloaded_2_5_auto_duration_follows_its_own_duration_head( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.active_ltx_model_id = "ltx-2.3-22b-distilled-1.1" + + data = client.get("/api/generate/models-specs").json() + by_model = {item["model"]: item for item in data["downloaded_local_models"]} + assert by_model["ltx-2.5-fast"]["spec"]["capabilities"]["auto_duration"] is True + assert by_model["ltx-2.3-fast"]["spec"]["capabilities"]["auto_duration"] is False + assert data["local_models"][0]["spec"]["capabilities"]["auto_duration"] is False + + def test_downloaded_local_models_only_includes_installed_offerings( + self, client, create_fake_model_files + ): + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + + data = client.get("/api/generate/models-specs").json() + assert [item["model"] for item in data["downloaded_local_models"]] == ["ltx-2.3-fast"] + + def test_downloaded_local_models_collapses_two_2_3_checkpoints_to_one_offering( + self, client, create_fake_model_files + ): + create_fake_model_files(model_id="ltx-2.3-22b-distilled") + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + + data = client.get("/api/generate/models-specs").json() + assert [item["model"] for item in data["downloaded_local_models"]] == ["ltx-2.3-fast"] + assert data["downloaded_local_models"][0]["spec"]["display_name"] == "LTX 2.3 Fast" class TestGatedCheckpointAccess: diff --git a/backend/tests/test_mps_prebuilt_ext.py b/backend/tests/test_mps_prebuilt_ext.py index 34abb67b5..d9bafea82 100644 --- a/backend/tests/test_mps_prebuilt_ext.py +++ b/backend/tests/test_mps_prebuilt_ext.py @@ -9,6 +9,7 @@ from __future__ import annotations from pathlib import Path +import os import sys import types @@ -42,12 +43,69 @@ def test_setup_prebuilt_mps_extension_noop_off_darwin(monkeypatch) -> None: mps_prebuilt_ext.setup_prebuilt_mps_extension() # must not raise -def test_setup_prebuilt_mps_extension_noop_on_darwin_without_prebuilt(monkeypatch) -> None: +def test_setup_prebuilt_mps_extension_noop_on_darwin_without_prebuilt(tmp_path: Path, monkeypatch) -> None: monkeypatch.setattr(mps_prebuilt_ext.sys, "platform", "darwin") monkeypatch.delenv("LTX_MPS_EXT_PREBUILT_DIR", raising=False) + monkeypatch.setenv("TORCH_EXTENSIONS_DIR", str(tmp_path)) mps_prebuilt_ext.setup_prebuilt_mps_extension() # must not raise; no .so to load +def test_clear_stale_mps_extension_locks_removes_jit_lock_files(tmp_path: Path) -> None: + ext_dir = tmp_path / "py313_cpu" / "mps_sdpa_zc_ext" + ext_dir.mkdir(parents=True) + lock = ext_dir / "lock" + ninja_lock = ext_dir / ".ninja_lock" + keep = ext_dir / "mps_sdpa_zc_ext.so" + lock.write_bytes(b"") + ninja_lock.write_bytes(b"") + keep.write_bytes(b"so") + + removed = mps_prebuilt_ext.clear_stale_mps_extension_locks(tmp_path) + + assert sorted(path.name for path in removed) == [".ninja_lock", "lock"] + assert not lock.exists() + assert not ninja_lock.exists() + assert keep.exists() + + +def test_clear_stale_mps_extension_locks_removes_override_layout(tmp_path: Path) -> None: + ext_dir = tmp_path / "mps_sdpa_zc_ext" + ext_dir.mkdir() + lock = ext_dir / "lock" + ninja_lock = ext_dir / ".ninja_lock" + lock.write_bytes(b"") + ninja_lock.write_bytes(b"") + + removed = mps_prebuilt_ext.clear_stale_mps_extension_locks(tmp_path) + + assert sorted(path.name for path in removed) == [".ninja_lock", "lock"] + assert not lock.exists() + assert not ninja_lock.exists() + + +def test_clear_stale_mps_extension_locks_skips_held_ninja_lock(tmp_path: Path) -> None: + if sys.platform == "win32": + return + import fcntl + + ext_dir = tmp_path / "py313_cpu" / "mps_sdpa_zc_ext" + ext_dir.mkdir(parents=True) + ninja_lock = ext_dir / ".ninja_lock" + ninja_lock.write_bytes(b"") + fd = os.open(ninja_lock, os.O_RDWR) + try: + fcntl.flock(fd, fcntl.LOCK_EX) + removed = mps_prebuilt_ext.clear_stale_mps_extension_locks(tmp_path) + assert removed == [] + assert ninja_lock.exists() + finally: + os.close(fd) + + +def test_clear_stale_mps_extension_locks_noop_when_cache_missing(tmp_path: Path) -> None: + assert mps_prebuilt_ext.clear_stale_mps_extension_locks(tmp_path / "missing") == [] + + def test_mps_memory_sample_none_off_darwin(monkeypatch) -> None: monkeypatch.setattr(mps_prebuilt_ext.sys, "platform", "linux") assert mps_prebuilt_ext.mps_memory_sample() is None diff --git a/backend/tests/test_offload_mode.py b/backend/tests/test_offload_mode.py new file mode 100644 index 000000000..e6e094aad --- /dev/null +++ b/backend/tests/test_offload_mode.py @@ -0,0 +1,45 @@ +"""OffloadMode mapping for local streaming (LTX-Desktop#163).""" + +from __future__ import annotations + +import pytest +import torch +from ltx_pipelines.utils.types import OffloadMode + +from services.ltx_pipeline_common import offload_mode_for_prefetch_count + + +def test_full_resident_is_none() -> None: + assert offload_mode_for_prefetch_count(None, torch.device("cuda")) is OffloadMode.NONE + + +def test_mps_streaming_is_disk() -> None: + assert offload_mode_for_prefetch_count(2, torch.device("mps")) is OffloadMode.DISK + + +def test_linux_cuda_streaming_on_32gb_is_disk(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("services.ltx_pipeline_common.platform.system", lambda: "Linux") + monkeypatch.setattr("services.ltx_pipeline_common.host_total_gib", lambda: 32) + + assert offload_mode_for_prefetch_count(2, torch.device("cuda")) is OffloadMode.DISK + + +def test_linux_cuda_streaming_on_64gb_is_cpu(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("services.ltx_pipeline_common.platform.system", lambda: "Linux") + monkeypatch.setattr("services.ltx_pipeline_common.host_total_gib", lambda: 64) + + assert offload_mode_for_prefetch_count(2, torch.device("cuda")) is OffloadMode.CPU + + +def test_linux_cuda_streaming_with_unknown_ram_is_disk(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("services.ltx_pipeline_common.platform.system", lambda: "Linux") + monkeypatch.setattr("services.ltx_pipeline_common.host_total_gib", lambda: None) + + assert offload_mode_for_prefetch_count(2, torch.device("cuda")) is OffloadMode.DISK + + +def test_windows_cuda_streaming_on_32gb_stays_cpu(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr("services.ltx_pipeline_common.platform.system", lambda: "Windows") + monkeypatch.setattr("services.ltx_pipeline_common.host_total_gib", lambda: 32) + + assert offload_mode_for_prefetch_count(2, torch.device("cuda")) is OffloadMode.CPU diff --git a/backend/tests/test_oriented_image.py b/backend/tests/test_oriented_image.py new file mode 100644 index 000000000..a25c99c5d --- /dev/null +++ b/backend/tests/test_oriented_image.py @@ -0,0 +1,265 @@ +"""EXIF orientation is baked in wherever a user photo is decoded.""" + +from __future__ import annotations + +import base64 +import io +from pathlib import Path + +import pytest +from PIL import Image +from services.media_probe import probe_file +from services.records import MediaError +from services.services_utils import compute_edit_dimensions +from services.thumbnails import PillowAvThumbnailWriter +from services.video_processor.video_processor_impl import VideoProcessorImpl +from server_utils.oriented_image import ( + open_oriented_image, + open_oriented_rgb, + oriented_image_file, + oriented_image_payload, +) +from tests.fakes import FakeResponse + +_RAW_SIZE = (32, 16) +# Pillow's EXIF map: 6 is 90° clockwise (ROTATE_270), 8 is 90° counter-clockwise. +_TRANSPOSE = { + 6: Image.Transpose.ROTATE_270, + 8: Image.Transpose.ROTATE_90, +} + + +def _marked_image(size: tuple[int, int] = _RAW_SIZE) -> Image.Image: + image = Image.new("RGB", size, (10, 20, 30)) + image.putpixel((0, 0), (255, 0, 0)) + image.putpixel((size[0] - 1, 0), (0, 255, 0)) + image.putpixel((0, size[1] - 1), (0, 0, 255)) + image.putpixel((size[0] - 1, size[1] - 1), (255, 255, 0)) + return image + + +def _save_oriented(path: Path, orientation: int, *, fmt: str = "JPEG") -> None: + image = _marked_image() + exif = image.getexif() + exif[0x0112] = orientation + image.save(path, format=fmt, exif=exif, quality=95) + + +def _display_rgb(path: Path, orientation: int) -> Image.Image: + with Image.open(path) as raw: + method = _TRANSPOSE.get(orientation) + image = raw if method is None else raw.transpose(method) + return image.convert("RGB") + + +def test_open_oriented_image_rotates_phone_orientations(tmp_path: Path) -> None: + for orientation in (6, 8): + path = tmp_path / f"phone-{orientation}.jpg" + _save_oriented(path, orientation) + expected = _display_rgb(path, orientation) + loaded = open_oriented_rgb(path) + assert loaded.size == expected.size + assert loaded.tobytes() == expected.tobytes() + assert loaded.getexif().get(0x0112) in (None, 1) + + +def test_open_oriented_image_leaves_upright_pixels_and_format(tmp_path: Path) -> None: + path = tmp_path / "upright.png" + _marked_image().save(path, format="PNG") + loaded = open_oriented_image(path) + assert loaded.format == "PNG" + assert loaded.size == _RAW_SIZE + assert loaded.tobytes() == _marked_image().tobytes() + + +def test_oriented_payload_keeps_original_bytes_when_upright(tmp_path: Path) -> None: + path = tmp_path / "plain.jpg" + _marked_image().save(path, format="JPEG", quality=95) + raw, mime = oriented_image_payload(path) + assert mime == "image/jpeg" + assert raw == path.read_bytes() + + +def test_oriented_payload_reencodes_sideways_jpeg_as_jpeg(tmp_path: Path) -> None: + path = tmp_path / "sideways.jpg" + _save_oriented(path, 6) + raw, mime = oriented_image_payload(path) + assert mime == "image/jpeg" + with Image.open(io.BytesIO(raw)) as sent: + assert sent.format == "JPEG" + assert sent.size == _display_rgb(path, 6).size + assert sent.getexif().get(0x0112, 1) in (0, 1) + assert path.read_bytes()[:2] == b"\xff\xd8" + + +def test_oriented_payload_reencodes_sideways_png_as_png(tmp_path: Path) -> None: + path = tmp_path / "sideways.png" + _save_oriented(path, 6, fmt="PNG") + raw, mime = oriented_image_payload(path) + assert mime == "image/png" + with Image.open(io.BytesIO(raw)) as sent: + assert sent.format == "PNG" + assert sent.size == _display_rgb(path, 6).size + assert sent.tobytes() == _display_rgb(path, 6).tobytes() + + +def test_oriented_image_file_removes_temp_jpeg(tmp_path: Path) -> None: + path = tmp_path / "sideways.jpg" + _save_oriented(path, 6) + with oriented_image_file(path) as upload_path: + assert upload_path.suffix == ".jpg" + assert upload_path != path + with Image.open(upload_path) as sent: + assert sent.format == "JPEG" + assert sent.getexif().get(0x0112, 1) in (0, 1) + held = upload_path + assert not held.exists() + + upright = tmp_path / "upright.png" + _marked_image().save(upright, format="PNG") + with oriented_image_file(upright) as upload_path: + assert upload_path == upright + + +def test_prepare_image_crops_the_upright_frame(test_state, tmp_path: Path) -> None: + path = tmp_path / "start.jpg" + _save_oriented(path, 6) + expected = _display_rgb(path, 6) + prepared = test_state.video_generation._prepare_image(str(path), expected.width, expected.height) + assert prepared.size == expected.size + assert prepared.tobytes() == expected.tobytes() + + +def test_probe_rejects_oversized_image_before_decode(tmp_path: Path) -> None: + import services.media_probe as media_probe + + path = tmp_path / "wide.png" + _marked_image().save(path, format="PNG") + original_limit = media_probe.MAX_IMAGE_PIXELS + original_open = media_probe.open_oriented_image + + def _decode_should_not_run(_path: Path) -> Image.Image: + raise AssertionError("oversized image was decoded") + + media_probe.MAX_IMAGE_PIXELS = 1 + media_probe.open_oriented_image = _decode_should_not_run + try: + with pytest.raises(MediaError) as caught: + probe_file(path) + assert caught.value.code == "IMAGE_DIMENSIONS_TOO_LARGE" + finally: + media_probe.MAX_IMAGE_PIXELS = original_limit + media_probe.open_oriented_image = original_open + + +def test_probe_reports_upright_dimensions(tmp_path: Path) -> None: + path = tmp_path / "asset.jpg" + _save_oriented(path, 6) + kind, mime, metadata = probe_file(path) + assert kind == "image" + assert mime == "image/jpeg" + assert metadata.mediaType == "image" + assert metadata.metadata.width == _RAW_SIZE[1] + assert metadata.metadata.height == _RAW_SIZE[0] + + +def test_thumbnail_is_upright(tmp_path: Path) -> None: + path = tmp_path / "asset.jpg" + _save_oriented(path, 8) + written = PillowAvThumbnailWriter().write(str(path), "image") + assert written is not None + with Image.open(written) as thumb: + assert thumb.size == _display_rgb(path, 8).size + + +def test_ic_lora_probe_uses_upright_dimensions(test_state, tmp_path: Path) -> None: + path = tmp_path / "control.jpg" + _save_oriented(path, 6) + width, height, frames = test_state.ic_lora._probe_ic_lora_source(str(path), "image", 9) + assert (width, height, frames) == (_RAW_SIZE[1], _RAW_SIZE[0], 9) + + +def test_video_processor_reads_upright_bgr(tmp_path: Path) -> None: + path = tmp_path / "control.jpg" + _save_oriented(path, 6) + frame = VideoProcessorImpl().read_image(str(path)) + expected = _display_rgb(path, 6) + assert frame.shape == (expected.height, expected.width, 3) + assert tuple(int(channel) for channel in frame[0, 0]) == expected.getpixel((0, 0))[::-1] + + +def test_image_edit_resizes_the_upright_source(client, test_state, fake_services, tmp_path: Path) -> None: + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.fal_api_key = "fal-key" + path = tmp_path / "edit.jpg" + _save_oriented(path, 6) + expected = _display_rgb(path, 6) + + response = client.post( + "/api/generate-image", + json={"prompt": "x", "imagePath": str(path), "strength": 0.6}, + ) + assert response.status_code == 200 + sent = fake_services.zit_api_client.image_to_image_calls[0]["image_bytes"] + with Image.open(io.BytesIO(sent)) as image: + assert image.size == compute_edit_dimensions(expected.width, expected.height) + + +def test_gemini_enhance_sends_upright_image(client, test_state, tmp_path: Path) -> None: + test_state.state.app_settings.gemini_api_key = "key" + test_state.http.queue( + "post", + FakeResponse( + status_code=200, + json_payload={"candidates": [{"content": {"parts": [{"text": "enhanced"}]}}]}, + ), + ) + path = tmp_path / "frame.jpg" + _save_oriented(path, 8) + + response = client.post( + "/api/enhance-prompt", + json={"prompt": "a cat", "provider": "api", "imagePath": str(path)}, + ) + assert response.status_code == 200 + parts = test_state.http.calls[-1].json_payload["contents"][0]["parts"] + inline = next(part["inlineData"] for part in parts if "inlineData" in part) + with Image.open(io.BytesIO(base64.b64decode(inline["data"]))) as sent: + assert sent.size == _display_rgb(path, 8).size + + +def test_forced_api_uploads_upright_start_and_end_frames( + client, test_state, fake_services, tmp_path: Path +) -> None: + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "api-key" + start = tmp_path / "start.jpg" + end = tmp_path / "end.jpg" + _save_oriented(start, 6) + _save_oriented(end, 8) + + response = client.post( + "/api/generate", + json={ + "prompt": "Animate this frame", + "resolution": "2160p", + "model": "pro", + "duration": 8, + "fps": 25, + "audio": False, + "cameraMotion": "jib_up", + "imagePath": str(start), + "lastImagePath": str(end), + }, + ) + assert response.status_code == 200, response.text + uploads = fake_services.ltx_api_client.upload_file_calls + assert len(uploads) == 2 + expected_sizes = (_display_rgb(start, 6).size, _display_rgb(end, 8).size) + for upload, expected_size in zip(uploads, expected_sizes, strict=True): + with Image.open(io.BytesIO(upload["contents"])) as sent: + assert sent.format == "JPEG" + assert sent.size == expected_size + assert sent.getexif().get(0x0112, 1) in (0, 1) + assert not Path(upload["file_path"]).exists() + assert start.exists() and end.exists() diff --git a/backend/tests/test_output_names.py b/backend/tests/test_output_names.py new file mode 100644 index 000000000..4deb88a5d --- /dev/null +++ b/backend/tests/test_output_names.py @@ -0,0 +1,38 @@ +from datetime import datetime, timezone + +from services.generation_queue.output_names import output_asset_name + +CREATED = int(datetime(2026, 9, 9, 12, 30, 0, tzinfo=timezone.utc).timestamp() * 1000) +ASSET_ID = "abcdef12-3456-7890-abcd-ef1234567890" + + +def test_slugs_prompt_and_stamps_utc() -> None: + assert ( + output_asset_name( + prompt="A Fox, running!!", + created_at_ms=CREATED, + asset_id=ASSET_ID, + mime_type="video/mp4", + ) + == "a-fox-running-20260909-123000-abcdef.mp4" + ) + + +def test_empty_prompt_uses_generation() -> None: + assert output_asset_name( + prompt=" ", + created_at_ms=CREATED, + asset_id=ASSET_ID, + mime_type="image/png", + ).startswith("generation-20260909-123000-") + + +def test_non_string_prompt_uses_generation() -> None: + name = output_asset_name( + prompt=None, + created_at_ms=CREATED, + asset_id=ASSET_ID, + mime_type="audio/wav", + ) + assert name.startswith("generation-") + assert name.endswith(".wav") diff --git a/backend/tests/test_paired_devices.py b/backend/tests/test_paired_devices.py new file mode 100644 index 000000000..fadaf0589 --- /dev/null +++ b/backend/tests/test_paired_devices.py @@ -0,0 +1,102 @@ +from __future__ import annotations + +import hashlib +from pathlib import Path + +from services.migrations import MIGRATIONS_DIR, apply_migrations +from services.records import PairedDeviceRecord +from services.sqlite_store import SqliteStore +from tests.test_store import _connect + + +def test_fresh_db_includes_paired_devices(tmp_path: Path) -> None: + conn = _connect(tmp_path / "store.sqlite3") + apply_migrations(conn, MIGRATIONS_DIR) + tables = { + row[0] + for row in conn.execute( + "SELECT name FROM sqlite_master WHERE type='table'" + ).fetchall() + } + assert "paired_devices" in tables + columns = { + row["name"] for row in conn.execute("PRAGMA table_info(paired_devices)").fetchall() + } + assert columns == { + "id", + "name", + "token_hash", + "created_at", + "last_seen_at", + "first_seen_ip", + "first_seen_user_agent", + "revoked_at", + } + conn.close() + + +def test_paired_device_insert_lookup_touch_and_revoke(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + token_hash = hashlib.sha256(b"session").hexdigest() + record = store.insert_paired_device( + PairedDeviceRecord( + id="dev-1", + name="Phone", + token_hash=token_hash, + created_at=10, + last_seen_at=10, + first_seen_ip="192.168.1.4", + first_seen_user_agent="TestUA", + ) + ) + assert record.id == "dev-1" + fetched = store.get_paired_device_by_token_hash(token_hash) + assert fetched is not None + assert fetched.name == "Phone" + assert store.get_paired_device("missing") is None + + store.touch_paired_device("dev-1", now_ms=99) + touched = store.get_paired_device("dev-1") + assert touched is not None + assert touched.last_seen_at == 99 + + store.touch_paired_device( + "dev-1", + now_ms=None, + ip="10.0.0.8", + user_agent="Mozilla/5.0 (Macintosh) Chrome/120.0.0.0", + ) + filled = store.get_paired_device("dev-1") + assert filled is not None + assert filled.last_seen_at == 99 + assert filled.first_seen_ip == "192.168.1.4" + assert filled.first_seen_user_agent == "TestUA" + + assert store.revoke_paired_device("dev-1", now_ms=100) is True + assert store.revoke_paired_device("dev-1", now_ms=101) is False + revoked = store.get_paired_device("dev-1") + assert revoked is not None + assert revoked.revoked_at == 100 + listed = store.list_paired_devices() + assert [item.id for item in listed] == ["dev-1"] + + +def test_touch_replaces_unknown_first_seen_ip(tmp_path: Path) -> None: + store = SqliteStore(tmp_path) + token_hash = hashlib.sha256(b"session").hexdigest() + store.insert_paired_device( + PairedDeviceRecord( + id="dev-unknown", + name="Phone", + token_hash=token_hash, + created_at=10, + last_seen_at=10, + first_seen_ip="unknown", + first_seen_user_agent=None, + ) + ) + store.touch_paired_device("dev-unknown", now_ms=20, ip="10.0.0.8", user_agent="Phone UA") + filled = store.get_paired_device("dev-unknown") + assert filled is not None + assert filled.first_seen_ip == "10.0.0.8" + assert filled.first_seen_user_agent == "Phone UA" diff --git a/backend/tests/test_patch_import_smoke.py b/backend/tests/test_patch_import_smoke.py new file mode 100644 index 000000000..627cf7ce8 --- /dev/null +++ b/backend/tests/test_patch_import_smoke.py @@ -0,0 +1,20 @@ +"""Import every Desktop ltx-2 patch plus distilled_keyframe_guiding. + +Catches import-time AssertionError (the 1.3.0 recommended_tiling_config class +of boot failure) without starting the FastAPI server. +""" + +from __future__ import annotations + +import importlib +from pathlib import Path + +PATCHES_DIR = Path(__file__).resolve().parents[1] / "services" / "patches" + + +def test_every_patch_module_and_keyframe_guiding_import() -> None: + modules = sorted(p.stem for p in PATCHES_DIR.glob("*.py") if p.stem != "__init__") + assert modules, "expected services/patches/*.py modules" + for name in modules: + importlib.import_module(f"services.patches.{name}") + importlib.import_module("services.fast_video_pipeline.distilled_keyframe_guiding") diff --git a/backend/tests/test_perf_runner_bump.py b/backend/tests/test_perf_runner_bump.py new file mode 100644 index 000000000..dad9395f3 --- /dev/null +++ b/backend/tests/test_perf_runner_bump.py @@ -0,0 +1,107 @@ +"""Unit tests for performance_runner bump-gate wiring (no live backend).""" + +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +_PERF = Path(__file__).resolve().parents[1] / "performance_runner" +if str(_PERF) not in sys.path: + sys.path.insert(0, str(_PERF)) + +import scenarios as scn # noqa: E402 + + +def test_bump_tag_covers_gate_scenarios() -> None: + keys = {s.key for s in scn.all_scenarios() if "bump" in s.tags} + assert keys >= { + "t2v_540p_8s", + "t2v_1080p_5s", + "mkf_interpolation", + "iclora_day_to_night", + "iclora_stage2_on", + "cancel_mid_denoise", + } + + +def test_cancel_scenario_does_not_expect_output() -> None: + s = scn.SCENARIOS["cancel_mid_denoise"] + assert s.cancel_after_s == 4.0 + assert s.checks == [] + + +def test_last_frames_not_black_missing_file() -> None: + ok, msg = scn.last_frames_not_black(None) + assert ok is False + assert "no file" in msg + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not on PATH") +def test_last_frames_not_black_detects_black_tail(tmp_path: Path) -> None: + # Bright body + black tail: sampling from t-1s without reversing would still + # see white and miss E2. 8 fps, 1s: first 4 frames white, last 4 black. + mixed = tmp_path / "white_then_black.mp4" + subprocess.run( + [ + "ffmpeg", "-y", + "-f", "lavfi", "-i", "color=c=white:s=64x64:d=0.5:r=8", + "-f", "lavfi", "-i", "color=c=black:s=64x64:d=0.5:r=8", + "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0", + "-pix_fmt", "yuv420p", str(mixed), + ], + check=True, + capture_output=True, + ) + ok, msg = scn.last_frames_not_black(str(mixed), n_frames=4) + assert ok is False, msg + assert "BLACK" in msg + + white = tmp_path / "white.mp4" + subprocess.run( + [ + "ffmpeg", "-y", "-f", "lavfi", "-i", "color=c=white:s=64x64:d=1:r=8", + "-pix_fmt", "yuv420p", str(white), + ], + check=True, + capture_output=True, + ) + ok, msg = scn.last_frames_not_black(str(white), n_frames=4) + assert ok is True, msg + + +@pytest.mark.skipif(shutil.which("ffmpeg") is None, reason="ffmpeg not on PATH") +def test_last_frames_not_black_fails_partial_black_tail(tmp_path: Path) -> None: + # 8 fps, 1s: first 5 white, last 3 black. Mean-of-tail would still pass; + # per-frame min must fail. + mixed = tmp_path / "mostly_white_black_tail.mp4" + subprocess.run( + [ + "ffmpeg", "-y", + "-f", "lavfi", "-i", "color=c=white:s=64x64:d=0.625:r=8", + "-f", "lavfi", "-i", "color=c=black:s=64x64:d=0.375:r=8", + "-filter_complex", "[0:v][1:v]concat=n=2:v=1:a=0", + "-pix_fmt", "yuv420p", str(mixed), + ], + check=True, + capture_output=True, + ) + ok, msg = scn.last_frames_not_black(str(mixed), n_frames=8) + assert ok is False, msg + assert "BLACK" in msg + + +def test_last_frames_not_black_fails_without_ffmpeg(monkeypatch: pytest.MonkeyPatch, tmp_path: Path) -> None: + clip = tmp_path / "clip.mp4" + clip.write_bytes(b"not-a-real-video") + + def boom(*_a, **_k): + raise FileNotFoundError("ffmpeg") + + monkeypatch.setattr(scn.subprocess, "run", boom) + ok, msg = scn.last_frames_not_black(str(clip), n_frames=4) + assert ok is False + assert "ffmpeg not on PATH" in msg diff --git a/backend/tests/test_perf_runner_checks.py b/backend/tests/test_perf_runner_checks.py new file mode 100644 index 000000000..31e20d906 --- /dev/null +++ b/backend/tests/test_perf_runner_checks.py @@ -0,0 +1,153 @@ +"""The live-suite oracles must tell good output from broken output (synthetic media, no backend).""" + +from __future__ import annotations + +import shutil +import subprocess +import sys +from pathlib import Path + +import pytest + +_PERF = Path(__file__).resolve().parents[1] / "performance_runner" +if str(_PERF) not in sys.path: + sys.path.insert(0, str(_PERF)) + +import checks # noqa: E402 + +pytestmark = pytest.mark.skipif( + shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None, reason="needs ffmpeg/ffprobe" +) + +_MOVING = "mandelbrot=size=64x64:rate=24" +_STILL = "color=c=gray:s=64x64:r=24" +_BLACK = "color=c=black:s=64x64:r=24" +_WHITE = "color=c=white:s=64x64:r=24" +_OTHER = "smptebars=size=64x64:rate=24" + + +@pytest.fixture(autouse=True) +def _fresh_references(): + checks.reset() + yield + checks.reset() + + +def _make(tmp_path: Path, name: str, source: str, *, seconds: float = 1.0, audio: str | None = None) -> str: + out = tmp_path / name + cmd = ["ffmpeg", "-v", "error", "-y", "-f", "lavfi", "-t", str(seconds), "-i", source] + if audio: + cmd += ["-f", "lavfi", "-t", str(seconds), "-i", audio, "-c:a", "aac"] + if name.endswith(".mp4"): + cmd += ["-c:v", "libx264", "-pix_fmt", "yuv420p"] + else: + cmd += ["-frames:v", "1"] + subprocess.run([*cmd, str(out)], check=True) + return str(out) + + +def test_media_ok_accepts_a_good_clip_and_enforces_audio_and_duration(tmp_path: Path) -> None: + silent = _make(tmp_path, "silent.mp4", _MOVING) + voiced = _make(tmp_path, "voiced.mp4", _MOVING, audio="sine=frequency=440") + + assert checks.media_ok()(silent)[0] + assert checks.media_ok(audio=True)(voiced)[0] + assert not checks.media_ok(audio=True)(silent)[0] + assert not checks.media_ok(duration=(3.0, 4.0))(silent)[0] + + +def test_media_ok_rejects_a_truncated_file(tmp_path: Path) -> None: + good = Path(_make(tmp_path, "good.mp4", _MOVING, seconds=2)) + bad = tmp_path / "bad.mp4" + bad.write_bytes(good.read_bytes()[: good.stat().st_size // 2]) + + assert not checks.media_ok()(str(bad))[0] + assert not checks.media_ok()(str(tmp_path / "missing.mp4"))[0] + + +def test_not_dead_passes_motion_and_flags_black_white_and_frozen(tmp_path: Path) -> None: + assert checks.not_dead()(_make(tmp_path, "moving.mp4", _MOVING))[0] + assert "black" in checks.not_dead()(_make(tmp_path, "black.mp4", _BLACK))[1] + assert "blown-out" in checks.not_dead()(_make(tmp_path, "white.mp4", _WHITE))[1] + assert "frozen" in checks.not_dead()(_make(tmp_path, "still.mp4", _STILL))[1] + + +def test_frame_matches_finds_the_conditioning_image_and_rejects_another(tmp_path: Path) -> None: + clip = _make(tmp_path, "clip.mp4", _MOVING) + first = _make(tmp_path, "first.png", _MOVING) + other = _make(tmp_path, "other.png", _OTHER) + + assert checks.frame_matches(first)(clip)[0] + assert not checks.frame_matches(other)(clip)[0] + assert not checks.frame_matches(first)(_make(tmp_path, "black.mp4", _BLACK))[0] + + +def test_frame_matches_can_compare_a_later_frame_to_a_source_clip(tmp_path: Path) -> None: + clip = _make(tmp_path, "clip.mp4", _MOVING, seconds=2) + + assert checks.frame_matches(clip, at="last", reference_at="last")(clip)[0] + assert not checks.frame_matches(clip, at="last", reference_at="first", min_corr=0.999)(clip)[0] + + +_TONE_A = "aevalsrc='sin(2*PI*440*t)*(0.5+0.5*sin(2*PI*1.3*t))':d=4" +_TONE_B = "aevalsrc='sin(2*PI*440*t)*(0.5+0.5*sin(2*PI*0.45*t+2))':d=4" + + +def test_audio_matches_follows_the_reference_envelope_and_rejects_silence(tmp_path: Path) -> None: + source = _make(tmp_path, "src.mp4", _MOVING, seconds=4, audio=_TONE_A) + same = _make(tmp_path, "same.mp4", _MOVING, seconds=4, audio=_TONE_A) + different = _make(tmp_path, "different.mp4", _MOVING, seconds=4, audio=_TONE_B) + silent = _make(tmp_path, "silent.mp4", _MOVING, seconds=4) + + assert checks.audio_matches(source)(same)[0] + assert not checks.audio_matches(source)(different)[0] + assert not checks.audio_matches(source)(silent)[0] + + +def test_reproduces_and_differs_from_compare_against_the_remembered_run(tmp_path: Path) -> None: + ref = _make(tmp_path, "ref.mp4", _MOVING) + again = _make(tmp_path, "again.mp4", _MOVING) + other = _make(tmp_path, "other.mp4", _OTHER) + assert checks.remember("t")(ref)[0] + + assert checks.reproduces("t")(again)[0] + assert not checks.reproduces("t")(other)[0] + assert checks.differs_from("t")(other)[0] + assert not checks.differs_from("t")(again)[0] + + +def test_comparison_without_a_reference_fails_rather_than_passing_unverified(tmp_path: Path) -> None: + out = _make(tmp_path, "x.mp4", _MOVING) + + for check in (checks.reproduces("never-saved"), checks.differs_from("never-saved")): + ok, detail = check(out) + assert not ok and "no reference" in detail + + +def test_reset_forgets_remembered_references(tmp_path: Path) -> None: + out = _make(tmp_path, "x.mp4", _MOVING) + checks.remember("k")(out) + assert checks.reproduces("k")(out)[0] + + checks.reset() + + assert not checks.reproduces("k")(out)[0] + + +def test_seed_batch_needs_matching_first_and_last_and_a_different_middle(tmp_path: Path) -> None: + a = _make(tmp_path, "a.mp4", _MOVING) + a_again = _make(tmp_path, "a2.mp4", _MOVING) + b = _make(tmp_path, "b.mp4", _OTHER) + + assert checks.seed_batch()([a, b, a_again])[0] + assert not checks.seed_batch()([a, a_again, a])[0] # seed had no effect + assert not checks.seed_batch()([a, b, b])[0] # third job diverged from the first + assert not checks.seed_batch()([a, b])[0] # a job went missing + + +def test_picking_a_timed_frame_without_a_known_duration_raises_instead_of_guessing() -> None: + frames = [b"a", b"b", b"c"] + + assert checks._pick(frames, "last", None) == b"c" + with pytest.raises(RuntimeError, match="duration unknown"): + checks._pick(frames, 1.5, None) diff --git a/backend/tests/test_perf_runner_keep_awake.py b/backend/tests/test_perf_runner_keep_awake.py new file mode 100644 index 000000000..919048777 --- /dev/null +++ b/backend/tests/test_perf_runner_keep_awake.py @@ -0,0 +1,94 @@ +"""Sleep prevention during a sweep: the right OS call per platform, released at exit.""" + +from __future__ import annotations + +import ctypes +import os +import sys +from pathlib import Path + +import pytest + +_PERF = Path(__file__).resolve().parents[1] / "performance_runner" +if str(_PERF) not in sys.path: + sys.path.insert(0, str(_PERF)) + +import keep_awake # noqa: E402 + + +@pytest.fixture +def exit_hooks(monkeypatch) -> list: + hooks: list = [] + monkeypatch.setattr(keep_awake.atexit, "register", hooks.append) + return hooks + + +class _Process: + def __init__(self) -> None: + self.terminated = False + + def terminate(self) -> None: + self.terminated = True + + +def test_macos_runs_caffeinate_tied_to_this_process_and_stops_it_at_exit(monkeypatch, exit_hooks) -> None: + started: list[list[str]] = [] + proc = _Process() + + def popen(cmd): + started.append(cmd) + return proc + + monkeypatch.setattr(keep_awake.sys, "platform", "darwin") + monkeypatch.setattr(keep_awake.shutil, "which", lambda name: f"/usr/bin/{name}") + monkeypatch.setattr(keep_awake.subprocess, "Popen", popen) + + keep_awake.start() + + assert started == [["caffeinate", "-d", "-i", "-w", str(os.getpid())]] # -w: it dies with us even if we are killed + assert not proc.terminated + exit_hooks[0]() + assert proc.terminated + + +def test_windows_holds_the_system_awake_and_clears_it_at_exit(monkeypatch, exit_hooks) -> None: + calls: list[int] = [] + + class _Kernel32: + @staticmethod + def SetThreadExecutionState(flags: int) -> int: + calls.append(flags) + return 1 + + class _Windll: + kernel32 = _Kernel32 + + monkeypatch.setattr(keep_awake.sys, "platform", "win32") + monkeypatch.setattr(ctypes, "windll", _Windll, raising=False) + + keep_awake.start() + + assert calls == [0x80000000 | 0x00000001 | 0x00000002] # ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED + exit_hooks[0]() + assert calls[-1] == 0x80000000 # back to normal power management + + +def test_other_platforms_do_nothing(monkeypatch, exit_hooks) -> None: + monkeypatch.setattr(keep_awake.sys, "platform", "linux") + keep_awake.start() + assert exit_hooks == [] + + +@pytest.mark.parametrize("platform", ["darwin", "win32"]) +def test_failing_to_hold_the_machine_awake_warns_and_lets_the_run_continue( + monkeypatch, exit_hooks, capsys, platform +) -> None: + monkeypatch.setattr(keep_awake.sys, "platform", platform) + monkeypatch.setattr(keep_awake.shutil, "which", lambda name: None) # no caffeinate + monkeypatch.setattr(ctypes, "windll", type("W", (), {"kernel32": type("K", (), { + "SetThreadExecutionState": staticmethod(lambda flags: 0)})}), raising=False) + + keep_awake.start() + + assert exit_hooks == [] + assert "could not keep the machine awake" in capsys.readouterr().err diff --git a/backend/tests/test_perf_runner_queued.py b/backend/tests/test_perf_runner_queued.py new file mode 100644 index 000000000..7b8a1bb04 --- /dev/null +++ b/backend/tests/test_perf_runner_queued.py @@ -0,0 +1,248 @@ +"""queued.py drives the /api/generations ledger; exercised against a fake ledger (no backend).""" + +from __future__ import annotations + +import sys +from pathlib import Path +from typing import Any + +import pytest + +_PERF = Path(__file__).resolve().parents[1] / "performance_runner" +if str(_PERF) not in sys.path: + sys.path.insert(0, str(_PERF)) + +import perf_config # noqa: E402 +import queued # noqa: E402 +from queued import QueuedJob # noqa: E402 + + +class _Ledger: + """Just enough of /api/assets, /api/generations/* and /api/generation-queue.""" + + def __init__(self, *, polls_until_done: int = 1, final_status: str = "succeeded", phase: str = "inference") -> None: + self.calls: list[tuple[str, str]] = [] + self.created: list[dict[str, Any]] = [] + self.status: dict[str, str] = {} + self.polls: dict[str, int] = {} + self.polls_until_done = polls_until_done + self.final_status = final_status + self.phase = phase + self.cancel_error: Exception | None = None + self.versions = [{"label": "2.3", "model_id": "ltx-2.3", "active": True}] + + def post(self, path: str, payload: dict[str, Any]) -> dict[str, Any]: + self.calls.append(("POST", path)) + if path == "/api/assets": + return {"id": f"asset-{Path(payload['path']).name}"} + if path.endswith("/cancel"): + if self.cancel_error: + raise self.cancel_error + self.status[path.split("/")[3]] = "cancelled" + return {} + generation_id = f"gen-{len(self.created)}" + self.created.append(payload) + self.status[generation_id] = "queued" + return {"id": generation_id} + + def get(self, path: str) -> Any: + self.calls.append(("GET", path)) + if path == queued.QUEUE_PATH: + running = [i for i, s in self.status.items() if s in {"queued", "running"}] + if not running: + return {"active": None} + self.status[running[0]] = "running" + return {"active": {"generation": {"id": running[0]}, "progress": {"phase": self.phase}}} + generation_id = path.rsplit("/", 1)[1] + self.polls[generation_id] = self.polls.get(generation_id, 0) + 1 + if self.status[generation_id] in {"queued", "running"} and self.polls[generation_id] >= self.polls_until_done: + self.status[generation_id] = self.final_status + status = self.status[generation_id] + return {"id": generation_id, "status": status, "error_code": "EXECUTOR_FAILED" if status == "failed" else None, + "outputs": [{"path": f"/out/{generation_id}.mp4"}] if status == "succeeded" else []} + + +@pytest.fixture +def ledger(monkeypatch: pytest.MonkeyPatch) -> _Ledger: + fake = _Ledger() + monkeypatch.setattr(perf_config, "_post", fake.post) + monkeypatch.setattr(perf_config, "_get", fake.get) + monkeypatch.setattr(perf_config, "ltx_versions", lambda: fake.versions) + monkeypatch.setattr(queued, "_POLL_S", 0) + monkeypatch.setattr(queued, "_ASSET_IDS", {}) + return fake + + +def test_request_body_fills_the_model_and_ingests_inputs_once(ledger: _Ledger) -> None: + job = QueuedJob("/api/generations/retake", {"startTime": 1.0}, {"video": "/tmp/a.mp4"}) + + body = queued.request_body(job) + queued.request_body(job) + + assert body == {"params": {"model": "ltx-2.3-fast", "startTime": 1.0}, "inputs": {"video": {"assetId": "asset-a.mp4"}}} + assert ledger.calls.count(("POST", "/api/assets")) == 1 + + +def test_offering_follows_the_active_ltx_version(ledger: _Ledger) -> None: + ledger.versions = [{"label": "2.3", "model_id": "a"}, {"label": "2.5", "model_id": "b", "active": True}] + + assert queued.offering_id() == "ltx-2.5-fast" + + +def test_unknown_active_version_is_an_error_not_a_silent_default(ledger: _Ledger) -> None: + ledger.versions = [{"label": "9.9", "model_id": "z", "active": True}] + + with pytest.raises(RuntimeError, match="cannot map the active LTX version"): + queued.offering_id() + + +def test_trigger_submits_every_job_before_waiting_and_returns_outputs_in_order(ledger: _Ledger) -> None: + jobs = [QueuedJob("/api/generations/text-to-video", {"seed": seed}) for seed in (1, 2, 3)] + + outs = queued.trigger(jobs) + + assert outs == ["/out/gen-0.mp4", "/out/gen-1.mp4", "/out/gen-2.mp4"] + first_poll = next(i for i, (verb, path) in enumerate(ledger.calls) if verb == "GET") + assert sum(verb == "POST" for verb, _ in ledger.calls[:first_poll]) == 3 + + +def test_a_failed_job_raises_with_its_error_code(ledger: _Ledger) -> None: + ledger.final_status = "failed" + + with pytest.raises(RuntimeError, match="EXECUTOR_FAILED"): + queued.trigger([QueuedJob("/api/generations/text-to-video", {})]) + + +def test_cancel_waits_for_inference_then_cancels_through_the_ledger(ledger: _Ledger) -> None: + ledger.polls_until_done = 99 + + final = queued.trigger_cancellable(QueuedJob("/api/generations/extend", {}), after_s=0) + + assert final["status"] == "cancelled" + assert ("POST", "/api/generations/gen-0/cancel") in ledger.calls + + +def test_cancel_that_arrives_after_the_job_finished_is_reported(ledger: _Ledger) -> None: + ledger.cancel_error = RuntimeError("409 INVALID_GENERATION_STATUS") + + with pytest.raises(RuntimeError, match="expected cancelled, got succeeded"): + queued.trigger_cancellable(QueuedJob("/api/generations/extend", {}), after_s=0) + + +def test_cancel_still_cancels_when_inference_never_starts(ledger: _Ledger) -> None: + ledger.phase = "loading" + ledger.polls_until_done = 99 + + with pytest.raises(RuntimeError, match="never reached phase=inference"): + queued.trigger_cancellable(QueuedJob("/api/generations/extend", {}), after_s=0, wait_timeout_s=0.3) + + assert ("POST", "/api/generations/gen-0/cancel") in ledger.calls + + +def _unknown_keys(model: Any, data: Any, path: str = "") -> list[str]: + """Keys the model would silently ignore (pydantic drops extras, so a typo validates).""" + from pydantic import BaseModel + + if not (isinstance(model, type) and issubclass(model, BaseModel)) or not isinstance(data, dict): + return [] + known = {} + for name, field in model.model_fields.items(): + known[name] = field.annotation + if field.alias: + known[field.alias] = field.annotation + unknown = [f"{path}{key}" for key in data if key not in known] + for key, value in data.items(): + if key in known: + unknown += _unknown_keys(known[key], value, f"{path}{key}.") + return unknown + + +_REQUEST_MODELS = { + "/api/generations/text-to-video": "CreateTextToVideoRequest", + "/api/generations/image-to-video": "CreateImageToVideoRequest", + "/api/generations/audio-to-video": "CreateAudioToVideoRequest", + "/api/generations/extend": "CreateExtendRequest", + "/api/generations/retake": "CreateRetakeRequest", +} + + +def _queued_jobs() -> list[tuple[str, QueuedJob]]: + import scenarios as scn + + return [(s.key, job) for s in scn.all_scenarios() for job in s.queued or []] + + +@pytest.mark.parametrize("offering", ["ltx-2.3-fast", "ltx-2.5-fast"]) +def test_every_queued_scenario_body_is_valid_for_the_backend_request_model(offering: str) -> None: + """Scenario bodies are checked against the real Create*Request models, so a schema + change (or a typo in a scenario) fails here instead of on the first hardware run.""" + import api_types + + jobs = _queued_jobs() + assert jobs + for key, job in jobs: + body: dict[str, Any] = {"params": {"model": offering, **job.params}} + if job.inputs: + body["inputs"] = {name: {"assetId": "asset"} for name in job.inputs} + model = getattr(api_types, _REQUEST_MODELS[job.route]) + try: + model.model_validate(body) + except Exception as exc: # noqa: BLE001 + pytest.fail(f"{key}: {exc}") + assert not _unknown_keys(model, body), f"{key}: unknown keys {_unknown_keys(model, body)}" + + +_SYNC_MODELS = { + None: "GenerateVideoRequest", + "/api/generate-image": "GenerateImageRequest", + "/api/extend": "ExtendRequest", + "/api/retake": "RetakeRequest", + "/api/ic-lora/generate": "IcLoraGenerateRequest", +} + + +def test_every_regression_sync_body_is_valid_for_the_backend_request_model() -> None: + """GenSpace scenarios post raw bodies; check them against the real request models too.""" + import api_types + import perf_config + import scenarios as scn + + checked = 0 + for s in scn.all_scenarios(): + if "regression" not in s.tags or s.queued: + continue + body = dict(s.overrides) if s.route else {**perf_config.GEN_PAYLOAD_TEMPLATE, **s.overrides} + model = getattr(api_types, _SYNC_MODELS[s.route]) + try: + model.model_validate(body) + except Exception as exc: # noqa: BLE001 + pytest.fail(f"{s.key}: {exc}") + assert not _unknown_keys(model, body), f"{s.key}: unknown keys {_unknown_keys(model, body)}" + checked += 1 + assert checked > 10 + + +def test_progress_poll_gives_up_when_the_backend_stays_idle(monkeypatch) -> None: + import perf_config + + polls: list[str] = [] + + def idle(_path): + polls.append("idle") + return {"status": "idle"} + + monkeypatch.setattr(perf_config, "_get", idle) + + with pytest.raises(RuntimeError, match="backend is idle"): + perf_config._poll_until_done(interval_s=0) + assert len(polls) == perf_config._MAX_IDLE_POLLS + + +def test_progress_poll_returns_the_output_once_complete(monkeypatch) -> None: + import perf_config + + states = iter([{"status": "running"}, {"status": "idle"}, {"status": "running"}, + {"status": "complete", "result": ["/out.mp4"]}]) + monkeypatch.setattr(perf_config, "_get", lambda _path: next(states)) + + assert perf_config._poll_until_done(interval_s=0) == "/out.mp4" diff --git a/backend/tests/test_perf_runner_regression.py b/backend/tests/test_perf_runner_regression.py new file mode 100644 index 000000000..9a1b48d65 --- /dev/null +++ b/backend/tests/test_perf_runner_regression.py @@ -0,0 +1,215 @@ +"""Wiring of the live regression suite (tiers, ordering, assets). No backend, no GPU.""" + +from __future__ import annotations + +import os +import sys +from pathlib import Path + +import pytest + +_PERF = Path(__file__).resolve().parents[1] / "performance_runner" +if str(_PERF) not in sys.path: + sys.path.insert(0, str(_PERF)) + +import scenarios as scn # noqa: E402 + + +def _tier(*tags: str) -> list[scn.Scenario]: + return sorted((s for s in scn.all_scenarios() if set(s.tags) & set(tags)), key=lambda s: s.order) + + +def test_plain_sweep_does_not_include_the_regression_suite() -> None: + assert not any("regression" in s.tags for s in scn.ready()) + + +def test_smoke_covers_every_flow_and_code_path() -> None: + keys = {s.key for s in _tier("smoke")} + assert keys >= { + "smoke_t2v_270p", # stage-1-only path + "smoke_t2v_540p_2s", # two-stage path + "smoke_lora_t2v", # plain LoRA in the request + "smoke_mkf_270p", + "smoke_mkf_540p", # keyframe swap on each path + "smoke_i2v_270p", + "smoke_a2v_270p", + "smoke_ia2v_270p", + "smoke_t2i", + "smoke_extend_end", + "smoke_extend_start", + "smoke_retake_av", + "smoke_retake_video_only", + "smoke_retake_audio_only", + "smoke_retake_silent_source", + "smoke_iclora_canny", + "smoke_iclora_depth", + "smoke_iclora_day_to_night", + "smoke_cancel_extend", + "smoke_t2v_270p_repeat", + "smoke_q_t2v_270p", # queued surface + "smoke_q_i2v_end_270p", + "smoke_q_a2v_270p", + "smoke_q_extend_end", + "smoke_q_retake_av", + "smoke_q_batch_seeds", + "smoke_q_cancel_extend", + } + + +def test_full_tier_is_a_superset_of_smoke_and_the_bump_gate() -> None: + full = {s.key for s in _tier("smoke", "full", "bump")} + assert {s.key for s in _tier("smoke")} <= full + assert {s.key for s in _tier("bump")} <= full + assert {"full_cancel_a2v", "full_cancel_iclora", "lora_cozy_felt"} <= full + + +def test_smoke_lora_is_the_reference_request_plus_an_adapter(monkeypatch) -> None: + import catalog + + lora, ref = scn.SCENARIOS["smoke_t2v_270p"], scn.SCENARIOS["smoke_lora_t2v"] + assert ref.route is None and ref.required_loras == ["cozy-felt-style"] + assert ref.overrides == lora.overrides # only the adapter differs, so "differs" means it was applied + assert ref.order > lora.order # the reference is recorded before the comparison + assert "differs_from[t2v_270p_seed42]" in [c.__name__ for c in ref.checks] + + monkeypatch.setattr(catalog, "lora_ref", lambda cid: f"loras/{cid}/x.safetensors") + body = ref.build_overrides(dict(ref.overrides)) + assert body["loras"] == [{"ref": "loras/cozy-felt-style/x.safetensors", "scale": 1.0}] + + +def test_smoke_runs_small_generations_only() -> None: + for s in _tier("smoke"): + if s.route is None and s.cancel_after_s is None and not s.queued: + assert s.overrides["duration"] <= 5, s.key + assert s.overrides["resolution"] in {"270p", "540p"}, s.key + + +def test_reference_scenarios_run_before_the_scenarios_that_compare_to_them() -> None: + order = [s.key for s in _tier("smoke")] + assert order[:2] == ["smoke_t2v_270p", "smoke_t2v_270p_seed_b"] + assert order[-1] == "smoke_t2v_270p_repeat" + assert order.index("smoke_cancel_extend") > order.index("smoke_iclora_day_to_night") + full_order = [s.key for s in _tier("smoke", "full", "bump")] + assert full_order.index("lora_cozy_felt") < full_order.index("smoke_t2v_270p_repeat") + + +def test_every_scenario_asset_exists() -> None: + missing = [ + (s.key, path) + for s in _tier("smoke", "full") + for path in [*s.input_paths(), *_paths_in(s.overrides)] + if not os.path.exists(path) + ] + assert missing == [] + + +def _paths_in(overrides: dict) -> list[str]: + found = [v for v in overrides.values() if isinstance(v, str) and v.endswith((".mp4", ".png", ".jpg", ".wav"))] + for kf in overrides.get("keyframes") or []: + found.append(kf["imagePath"]) + return found + + +def test_generating_scenarios_assert_more_than_a_file_exists() -> None: + for s in _tier("smoke"): + if s.cancel_after_s is not None or s.key == "smoke_t2i": + continue + behavioural = [c for c in s.checks if c not in scn.DEFAULT_CHECKS] + assert behavioural, f"{s.key} only checks that a file exists" + + +def test_every_queued_create_route_has_a_scenario() -> None: + routes = {job.route for s in _tier("smoke", "full") for job in s.queued or []} + assert routes == { + "/api/generations/text-to-video", + "/api/generations/image-to-video", + "/api/generations/audio-to-video", + "/api/generations/extend", + "/api/generations/retake", + } + + +def test_last_keyframe_index_is_the_final_frame_of_a_two_second_clip() -> None: + import regression_scenarios as reg + from frame_math import compute_num_frames + + assert reg.KEYFRAME_LAST == compute_num_frames(2, 24) - 1 + + +def test_cancel_scenarios_run_no_output_checks() -> None: + cancels = [s for s in scn.all_scenarios() if "regression" in s.tags and s.cancel_after_s is not None] + assert cancels + assert all(not s.checks for s in cancels) + + +def _run_sanity(monkeypatch, *argv: str, tools: bool = True) -> int: + import perf_config + import sanity + + monkeypatch.setattr(sanity.shutil, "which", lambda name: name if tools else None) + monkeypatch.setattr(sanity.keep_awake, "start", lambda: None) # never hold the dev machine awake from a test + monkeypatch.setattr(sys, "argv", ["sanity.py", *argv]) + monkeypatch.setattr(perf_config, "wait_for_backend", lambda *a, **k: None) + return sanity.main() + + +def test_an_empty_or_mistyped_selection_fails_instead_of_passing(monkeypatch) -> None: + assert _run_sanity(monkeypatch, "--tags", "no-such-tag") == 1 + assert _run_sanity(monkeypatch, "--only", "no_such_scenario") == 1 + assert _run_sanity(monkeypatch, "--only", "smoke_t2v_270p", "no_such_scenario") == 1 + + +def test_a_crashed_backend_aborts_the_sweep_instead_of_erroring_every_scenario(monkeypatch, tmp_path) -> None: + import perf_config + import sanity + + ran: list[str] = [] + + def crashing_run(scenario, **_kwargs): + ran.append(scenario.key) + return {"key": scenario.key, "title": scenario.title, "status": "ERROR", "wall_s": 1.0, + "detail": "RemoteDisconnected", "output": None, "inputs": []} + + def backend_down(_path): + raise ConnectionRefusedError + + monkeypatch.setattr(sanity, "run_one", crashing_run) + monkeypatch.setattr(sanity, "collect_results", lambda rows, ts: tmp_path) + monkeypatch.setattr(perf_config, "_get", backend_down) + + assert _run_sanity(monkeypatch, "--only", "smoke_t2v_270p", "smoke_t2v_540p_2s", "smoke_i2v_270p") == 1 + assert ran == ["smoke_t2v_270p"] + + +def test_every_scenario_announces_its_position_in_the_sweep(monkeypatch, tmp_path, capsys) -> None: + import perf_config + import sanity + + def passing_run(scenario, **_kwargs): + return {"key": scenario.key, "title": scenario.title, "status": "PASS", "wall_s": 1.0, + "detail": "", "output": None, "inputs": []} + + monkeypatch.setattr(sanity, "run_one", passing_run) + monkeypatch.setattr(sanity, "collect_results", lambda rows, ts: tmp_path) + # smoke_extend_end is blocked by capabilities: skipped scenarios still take their place in the count. + monkeypatch.setattr(perf_config, "scenario_caps", lambda: {"extend": False, "family": "test"}) + + keys = ["smoke_t2v_270p", "smoke_extend_end", "smoke_i2v_270p"] + assert _run_sanity(monkeypatch, "--only", *keys) == 0 + + lines = [ln for ln in capsys.readouterr().out.splitlines() if ln.startswith("[sanity]")] + announced = [ln for ln in lines if "Running test" in ln] + assert announced == [f"[sanity] Running test {i}/3" for i in (1, 2, 3)] + # The announcement comes right before the scenario's own run or skip line. + for i, key in enumerate(keys): + nxt = lines[lines.index(announced[i]) + 1] + assert key in nxt, (key, nxt) + + +def test_regression_run_refuses_to_start_without_ffmpeg(monkeypatch, capsys) -> None: + import sanity + + monkeypatch.setattr(sanity, "run_one", lambda *a, **k: pytest.fail("must not run any scenario")) + + assert _run_sanity(monkeypatch, "--only", "smoke_t2v_270p", tools=False) == 1 + assert "ffmpeg and ffprobe not on PATH" in capsys.readouterr().err diff --git a/backend/tests/test_perf_runner_runtime.py b/backend/tests/test_perf_runner_runtime.py new file mode 100644 index 000000000..98304aacc --- /dev/null +++ b/backend/tests/test_perf_runner_runtime.py @@ -0,0 +1,136 @@ +"""Perf-runner Settings wiring (no live backend).""" + +from __future__ import annotations + +import sys +from pathlib import Path + +import pytest + +_PERF = Path(__file__).resolve().parents[1] / "performance_runner" +if str(_PERF) not in sys.path: + sys.path.insert(0, str(_PERF)) + +import perf_config # noqa: E402 +import scenarios as scn # noqa: E402 + +_VERSIONS = [ + {"model_id": "ltx-2.3-22b-distilled-1.1", "label": "2.3", "installed": True, "active": True}, + {"model_id": "ltx-2.3-22b-distilled", "label": "2.3 (1.0)", "installed": False, "active": False}, + {"model_id": "ltx-2.5-22b-distilled", "label": "2.5", "installed": True, "active": False}, +] + + +def test_blocked_by_caps_follows_models_specs() -> None: + caps_25 = {"family": "2.5", "retake": True, "extend": True, "builtin_control": True, "ic_lora": True} + assert scn.SCENARIOS["retake"].blocked_by_caps(caps_25) is None + assert scn.SCENARIOS["video_extend"].blocked_by_caps(caps_25) is None + assert scn.SCENARIOS["iclora_canny"].blocked_by_caps(caps_25) is None + assert scn.SCENARIOS["t2v_540p_8s"].blocked_by_caps(caps_25) is None + assert scn.SCENARIOS["iclora_day_to_night"].blocked_by_caps(caps_25) is None + assert scn.SCENARIOS["mkf_interpolation"].blocked_by_caps(caps_25) is None + assert scn.SCENARIOS["retake"].blocked_by_caps(None) is None + caps_off = {"family": "2.5", "retake": False, "extend": False, "builtin_control": True, "ic_lora": True} + assert scn.SCENARIOS["retake"].blocked_by_caps(caps_off) + assert scn.SCENARIOS["video_extend"].blocked_by_caps(caps_off) + + +def test_bump_scenarios_not_blocked_on_2_5() -> None: + caps_25 = {"family": "2.5", "retake": True, "extend": True, "builtin_control": True, "ic_lora": True} + blocked = [s.key for s in scn.all_scenarios() if "bump" in s.tags and s.blocked_by_caps(caps_25)] + assert blocked == [] + + +def test_activate_ltx_model_uses_installed_label(monkeypatch: pytest.MonkeyPatch) -> None: + posted: list[tuple[str, dict]] = [] + monkeypatch.setattr(perf_config, "_get", lambda path: {"versions": _VERSIONS}) + monkeypatch.setattr(perf_config, "_post", lambda path, payload: posted.append((path, payload))) + assert perf_config.activate_ltx_model("2.5") == "ltx-2.5-22b-distilled" + assert posted == [("/api/models/active-ltx-model", {"model_id": "ltx-2.5-22b-distilled"})] + + +def test_activate_ltx_model_rejects_uninstalled(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(perf_config, "_get", lambda path: {"versions": _VERSIONS}) + with pytest.raises(RuntimeError, match="not installed"): + perf_config.activate_ltx_model("2.3 (1.0)") + + +def test_set_use_conv_vae_requires_2_5_and_weights(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr(perf_config, "ltx_versions", lambda: _VERSIONS) # active is 2.3 + with pytest.raises(RuntimeError, match="2.5"): + perf_config.set_use_conv_vae(True) + + monkeypatch.setattr( + perf_config, "ltx_versions", + lambda: [{**_VERSIONS[2], "active": True}], + ) + monkeypatch.setattr(perf_config, "described_vaes", lambda: {"diff": True, "conv": False}) + with pytest.raises(RuntimeError, match="conv VAE"): + perf_config.set_use_conv_vae(True) + posted: list[dict] = [] + monkeypatch.setattr(perf_config, "described_vaes", lambda: {"diff": True, "conv": True}) + monkeypatch.setattr(perf_config, "_post", lambda path, payload: posted.append(payload)) + perf_config.set_use_conv_vae(True) + assert posted == [{"useConvVae": True}] + + +def test_cancel_waits_for_inference_phase_not_starting(monkeypatch: pytest.MonkeyPatch) -> None: + # status=running includes phase=starting (reservation). Cancel then would miss + # the interrupt wrapper. after_s=0 so we cancel as soon as inference is seen. + import time + + phases = iter( + [ + {"status": "running", "phase": "starting"}, + {"status": "running", "phase": "starting"}, + {"status": "running", "phase": "inference"}, + ] + ) + seen: list[str] = [] + + def fake_get(path: str): + if path != perf_config.STATUS_PATH: + return {} + st = next(phases) + seen.append(str(st["phase"])) + return st + + def fake_post(path: str, payload: dict) -> dict: + if path == perf_config.GENERATE_PATH: + time.sleep(1.5) + return {"status": "cancelled"} + if path == perf_config.CANCEL_PATH: + assert seen[-1] == "inference", f"cancelled during {seen!r}" + return {} + return {} + + monkeypatch.setattr(perf_config, "_get", fake_get) + monkeypatch.setattr(perf_config, "_post", fake_post) + perf_config.trigger_generation_cancellable( + after_s=0.0, payload=perf_config.GEN_PAYLOAD_TEMPLATE, wait_timeout_s=2.0 + ) + assert "inference" in seen + + +def test_cancel_fails_if_inference_never_starts(monkeypatch: pytest.MonkeyPatch) -> None: + import time + + posted: list[str] = [] + + def fake_get(path: str): + return {"status": "running", "phase": "starting"} + + def fake_post(path: str, payload: dict) -> dict: + posted.append(path) + if path == perf_config.GENERATE_PATH: + time.sleep(2.0) + return {"status": "complete"} + return {} + + monkeypatch.setattr(perf_config, "_get", fake_get) + monkeypatch.setattr(perf_config, "_post", fake_post) + with pytest.raises(RuntimeError, match="inference"): + perf_config.trigger_generation_cancellable( + after_s=0.0, payload=perf_config.GEN_PAYLOAD_TEMPLATE, wait_timeout_s=0.3 + ) + assert perf_config.CANCEL_PATH in posted diff --git a/backend/tests/test_prompt_enhancement.py b/backend/tests/test_prompt_enhancement.py index f70abafa3..58bd4489d 100644 --- a/backend/tests/test_prompt_enhancement.py +++ b/backend/tests/test_prompt_enhancement.py @@ -8,11 +8,8 @@ from PIL import Image from api_types import ( - IcLoraCatalogItem, - InputSpec, InstructionSection, LOCAL_MULTI_KEYFRAME_MAX_COUNT, - LoraCatalogItem, PromptTemplatePlaceholder, PromptTemplateSpec, ) @@ -21,6 +18,7 @@ from services.prompt_enhancement import build_audio_visual_caption_system_prompt from tests.fakes import FakeResponse from tests.http_error_assertions import assert_http_error +from tests.lora_catalog_helpers import add_ic_lora, add_lora # 2.3's gemma3 encoder doubles as the local enhancer, so its plain bundle is enough to make the @@ -64,36 +62,6 @@ def _gemini_error(status: int = 429, body: str = "rate limited") -> FakeResponse } -def _dl(filename: str = "x.safetensors"): - from api_types import DownloadSpec, DownloadVariant - - return DownloadSpec( - repo_id="org/x", - variants=[DownloadVariant(id="default", label="Default", filename=filename, size_bytes=10)], - ) - - -def _add_lora(fake_services, **overrides: object) -> LoraCatalogItem: - defaults: dict[str, object] = dict( - id="test-lora", name="Test Lora", description="d", download=_dl(), requires_hf_login=False, - ) - defaults.update(overrides) - lora = LoraCatalogItem(**defaults) - fake_services.lora_catalog_provider._catalog.loras.append(lora) - return lora - - -def _add_ic_lora(fake_services, **overrides: object) -> IcLoraCatalogItem: - defaults: dict[str, object] = dict( - id="test-ic-lora", name="Test IC-LoRA", description="d", download=_dl(), requires_hf_login=False, - input=InputSpec(kind="video"), - ) - defaults.update(overrides) - ic_lora = IcLoraCatalogItem(**defaults) - fake_services.lora_catalog_provider._catalog.ic_loras.append(ic_lora) - return ic_lora - - class TestNoSelection: def test_generic_fallback_uses_no_system_prompt(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) @@ -339,7 +307,7 @@ def test_seed_is_independent_of_dev_mode_lock(self, client, test_state, fake_ser class TestLoraSelection: def test_single_lora_system_prompt_and_trigger_enforced(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_lora( + add_lora( fake_services, id="cozy-felt", name="Cozy Felt", trigger="F3ltCut0u7", trigger_placement="anywhere", instructions=[InstructionSection(kind="summary", title="What it does", body="Felt look.")], ) @@ -355,8 +323,8 @@ def test_single_lora_system_prompt_and_trigger_enforced(self, client, fake_servi def test_multi_lora_prompt_includes_both(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_lora(fake_services, id="a", name="Alpha") - _add_lora(fake_services, id="b", name="Beta") + add_lora(fake_services, id="a", name="Alpha") + add_lora(fake_services, id="b", name="Beta") r = client.post("/api/enhance-prompt", json={"prompt": "x", "loraCatalogIds": ["a", "b"]}) assert r.status_code == 200 @@ -374,7 +342,7 @@ def test_ic_lora_without_template_free_rewrite_and_trigger_enforced( self, client, fake_services, create_fake_model_files ): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_ic_lora( + add_ic_lora( fake_services, id="day-to-night", name="Day to Night", instructions=[InstructionSection(kind="summary", title="What it does", body="Relights to night.")], ) @@ -390,7 +358,7 @@ def test_unknown_ic_lora_id_rejected(self, client, create_fake_model_files): def test_free_text_template_fill_stitches_deterministically(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_ic_lora( + add_ic_lora( fake_services, id="colorization", name="Colorization", prompt_template=PromptTemplateSpec( template="Reference shows {reference}. COLORIZE {result}.", @@ -407,7 +375,7 @@ def test_free_text_template_fill_stitches_deterministically(self, client, fake_s def test_enum_template_fill_stitches_deterministically(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_ic_lora( + add_ic_lora( fake_services, id="crossview-prompt", name="CrossView", prompt_template=PromptTemplateSpec( template="crossview. new camera angle: {azimuth}, {elevation}, {distance}.", @@ -428,7 +396,7 @@ def test_enum_template_fill_stitches_deterministically(self, client, fake_servic def test_template_fill_rejects_invalid_enum_choice(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_ic_lora( + add_ic_lora( fake_services, id="crossview-prompt", name="CrossView", prompt_template=PromptTemplateSpec( template="crossview. new camera angle: {azimuth}.", @@ -442,7 +410,7 @@ def test_template_fill_rejects_invalid_enum_choice(self, client, fake_services, def test_template_fill_rejects_non_json_response(self, client, fake_services, create_fake_model_files): create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) - _add_ic_lora( + add_ic_lora( fake_services, id="upscale", name="Upscale", prompt_template=PromptTemplateSpec(template="upscale", placeholders={}), ) @@ -949,7 +917,7 @@ def test_gif_rejected_before_reaching_gemini(self, client, test_state, tmp_path) def test_catalog_lora_system_prompt_reused_for_api_provider(self, client, fake_services, test_state): test_state.state.app_settings.gemini_api_key = "key" - _add_lora( + add_lora( fake_services, id="cozy-felt", name="Cozy Felt", trigger="F3ltCut0u7", trigger_placement="anywhere", ) test_state.http.queue("post", _gemini_ok("a felt fox")) @@ -967,6 +935,11 @@ def test_missing_gemini_key_rejected(self, client): r = client.post("/api/enhance-prompt", json={"prompt": "x", "provider": "api"}) assert_http_error(r, status_code=400, code="GEMINI_API_KEY_MISSING") + def test_whitespace_only_gemini_key_is_rejected(self, client, test_state): + test_state.state.app_settings.gemini_api_key = " " + r = client.post("/api/enhance-prompt", json={"prompt": "x", "provider": "api"}) + assert_http_error(r, status_code=400, code="GEMINI_API_KEY_MISSING") + def test_invalid_gemini_key_returns_distinct_code(self, client, test_state): test_state.state.app_settings.gemini_api_key = "key" test_state.http.queue( diff --git a/backend/tests/test_prompt_enhancement_system_prompt.py b/backend/tests/test_prompt_enhancement_system_prompt.py index d84f32b96..69f326646 100644 --- a/backend/tests/test_prompt_enhancement_system_prompt.py +++ b/backend/tests/test_prompt_enhancement_system_prompt.py @@ -33,7 +33,7 @@ def _dl(filename: str = "x.safetensors") -> DownloadSpec: return DownloadSpec( repo_id="org/x", - variants=[DownloadVariant(id="default", label="Default", filename=filename, size_bytes=10)], + variants=[DownloadVariant(id="default", label="Default", filename=filename, size_bytes=10, base_model="LTX-2.3")], ) diff --git a/backend/tests/test_prompt_enhancer_status.py b/backend/tests/test_prompt_enhancer_status.py new file mode 100644 index 000000000..142e091a5 --- /dev/null +++ b/backend/tests/test_prompt_enhancer_status.py @@ -0,0 +1,71 @@ +"""GET /api/prompt-enhancer and Explore asset-id Enhance on the Desktop app.""" + +from __future__ import annotations + +from pathlib import Path + +from PIL import Image + + +_LOCAL_ENHANCER_MODEL_ID = "ltx-2.3-22b-distilled-1.1" + + +class TestPromptEnhancerStatus: + def test_hides_manual_enhance_when_explore_auto_is_on( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + test_state.state.app_settings.explore_auto_enhance_prompts = True + test_state.state.app_settings.gemini_api_key = "" + + r = client.get("/api/prompt-enhancer") + assert r.status_code == 200 + body = r.json() + assert body["showManualEnhance"] is False + assert body["defaultProvider"] == "local" + assert body["localEnhancementSupported"] is True + assert body["hasGeminiApiKey"] is False + + def test_whitespace_gemini_key_is_not_a_key(self, client, test_state): + test_state.state.app_settings.gemini_api_key = " " + test_state.state.app_settings.explore_auto_enhance_prompts = False + + r = client.get("/api/prompt-enhancer") + assert r.status_code == 200 + assert r.json()["hasGeminiApiKey"] is False + + def test_prefers_persisted_api_when_both_providers_exist( + self, client, test_state, create_fake_model_files + ): + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + test_state.state.app_settings.gemini_api_key = "key" + test_state.state.app_settings.prompt_enhancer_provider_preference = "api" + test_state.state.app_settings.explore_auto_enhance_prompts = False + + r = client.get("/api/prompt-enhancer") + assert r.status_code == 200 + body = r.json() + assert body["showManualEnhance"] is True + assert body["defaultProvider"] == "api" + assert body["canToggleProvider"] is True + + +class TestEnhancePromptAssetIds: + def test_image_asset_id_routes_to_enhance_i2v( + self, client, fake_services, create_fake_model_files, tmp_path + ): + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + image_path = tmp_path / "cat.png" + Image.new("RGB", (32, 24)).save(image_path) + ingested = client.post("/api/assets", json={"path": str(image_path)}) + assert ingested.status_code == 200 + asset_id = ingested.json()["id"] + + r = client.post( + "/api/enhance-prompt", + json={"prompt": "a cat", "imageAssetId": asset_id}, + ) + assert r.status_code == 200 + call = fake_services.prompt_enhancer_pipeline.enhance_i2v_calls[0] + assert call["image_path"] + assert Path(call["image_path"]).is_file() diff --git a/backend/tests/test_pyright.py b/backend/tests/test_pyright.py deleted file mode 100644 index 0d19971ce..000000000 --- a/backend/tests/test_pyright.py +++ /dev/null @@ -1,69 +0,0 @@ -"""Static type checking gate for backend sources.""" - -from __future__ import annotations - -import json -import subprocess -from pathlib import Path -from typing import Any - -import pytest - - -def _format_diagnostics(payload: dict[str, Any], limit: int = 15) -> str: - diagnostics = payload.get("generalDiagnostics", []) - if not isinstance(diagnostics, list): - return "No diagnostics available." - - lines: list[str] = [] - for item in diagnostics[:limit]: - if not isinstance(item, dict): - continue - file_name = str(item.get("file", "")) - message = str(item.get("message", "")).splitlines()[0] - range_data = item.get("range", {}) - start = range_data.get("start", {}) if isinstance(range_data, dict) else {} - line = int(start.get("line", 0)) + 1 if isinstance(start, dict) else 0 - severity = str(item.get("severity", "unknown")) - lines.append(f"{severity}: {file_name}:{line}: {message}") - - if not lines: - return "No diagnostics available." - return "\n".join(lines) - - -def test_pyright_has_no_errors_or_warnings() -> None: - backend_root = Path(__file__).resolve().parents[1] - result = subprocess.run( - ["pyright", "--outputjson"], - cwd=backend_root, - capture_output=True, - text=True, - check=False, - ) - - output = result.stdout.strip() or result.stderr.strip() - assert output, "pyright produced no output" - - try: - payload: dict[str, Any] = json.loads(output) - except json.JSONDecodeError: - normalized = output.lower() - if "command not found" in normalized or "not found" in normalized: - pytest.skip("pyright is not available on PATH; skipping type-check gate") - raise AssertionError( - "pyright did not produce valid JSON output.\n" - f"returnCode={result.returncode}\n" - f"{output}" - ) from None - summary = payload.get("summary", {}) - assert isinstance(summary, dict), "pyright JSON output missing summary" - - error_count = int(summary.get("errorCount", -1)) - warning_count = int(summary.get("warningCount", -1)) - - assert error_count == 0 and warning_count == 0, ( - "pyright reported issues:\n" - f"errorCount={error_count}, warningCount={warning_count}, returnCode={result.returncode}\n" - f"{_format_diagnostics(payload)}" - ) diff --git a/backend/tests/test_remote_analytics.py b/backend/tests/test_remote_analytics.py new file mode 100644 index 000000000..efc1dc832 --- /dev/null +++ b/backend/tests/test_remote_analytics.py @@ -0,0 +1,34 @@ +from __future__ import annotations + +from starlette.testclient import TestClient + +from remote.app import create_remote_app +from services.analytics import queued_generation_details +from services.sqlite_store import SqliteStore + + +def test_remote_generation_is_not_mislabeled_as_desktop(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post( + "/api/generations/text-to-video", + headers={"Authorization": "Bearer pair-token"}, + json={ + "params": { + "prompt": "a fox", + "model": "ltx-2.5-fast", + } + }, + ) + + assert response.status_code == 200, response.text + assert "_analytics" not in response.json()["spec"] + stored = SqliteStore(test_state.config.app_data_dir).get_generation( + response.json()["id"] + ) + assert stored is not None + assert stored.spec["_analytics"] == {"client": "remote"} + details = queued_generation_details(stored) + assert details is not None + assert details["client"] == "remote" + assert "prompt" not in details diff --git a/backend/tests/test_remote_app.py b/backend/tests/test_remote_app.py new file mode 100644 index 000000000..b5e9beee9 --- /dev/null +++ b/backend/tests/test_remote_app.py @@ -0,0 +1,950 @@ +"""Remote FastAPI: public health/static, fail-closed Bearer on /api, LAN hosts only.""" + +from __future__ import annotations + +import asyncio +import subprocess +import tempfile +import wave +from pathlib import Path + +import imageio_ffmpeg +import pytest +from PIL import Image +from starlette.exceptions import HTTPException as StarletteHTTPException +from starlette.testclient import TestClient + +from _routes.assets import ( + _MULTIPART_OVERHEAD_BYTES, + _UPLOAD_TEMP_PREFIX, + _upload_body_exceeds_limit, +) +from remote.app import SpaStaticFiles, create_remote_app +from remote.redact import redact_asset_paths +from services.media_probe import ALLOWED_IMAGE_SUFFIXES, MAX_IMAGE_BYTES, MAX_VIDEO_BYTES +from services.records import AssetRecord, OutputSpec, UnavailableError +from services.sqlite_store import SqliteStore +from tests.http_error_assertions import assert_http_error + + +def _png(path: Path, size: tuple[int, int] = (32, 24)) -> Path: + Image.new("RGB", size, color=(10, 20, 30)).save(path) + return path + + +def _wav(path: Path, *, duration_seconds: float = 0.1) -> Path: + frame_count = max(1, int(duration_seconds * 8000)) + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * frame_count) + return path + + +def _encoded_audio(path: Path) -> Path: + wav_path = path.with_name(f"{path.stem}-src.wav") + _wav(wav_path) + suffix = path.suffix.lower() + codec = {".mp3": "libmp3lame", ".m4a": "aac"}[suffix] + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-i", + str(wav_path), + "-c:a", + codec, + str(path), + ], + check=True, + capture_output=True, + ) + return path + + +def _mp4(path: Path) -> Path: + import imageio.v2 as imageio + import numpy as np + + writer = imageio.get_writer( + str(path), fps=8, codec="libx264", macro_block_size=None + ) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(8): + writer.append_data(frame) + writer.close() + return path + + +AUTH = {"Authorization": "Bearer pair-token"} +WRONG_AUTH = {"Authorization": "Bearer wrong"} +_IMAGE_SAVE_FORMAT = { + ".png": "PNG", + ".jpg": "JPEG", + ".jpeg": "JPEG", + ".webp": "WEBP", +} + + +def _bytes_url(client: TestClient, asset_id: str) -> str: + fetched = client.get(f"/api/assets/{asset_id}", headers=AUTH) + assert fetched.status_code == 200 + url = fetched.json()["bytes_url"] + assert isinstance(url, str) + assert url.startswith(f"/api/assets/{asset_id}/bytes?") + return url + + +def _store(test_state) -> SqliteStore: + return SqliteStore(test_state.config.app_data_dir) + + +def _succeed_png(test_state, *, name: str = "out.png") -> AssetRecord: + store = _store(test_state) + gen = store.insert_generation("text-to-video", {"params": {}, "inputs": {}}) + claimed = store.claim_next_queued() + assert claimed is not None + asset_id, dest = store.allocate_output_path("image", "image/png") + Image.new("RGB", (8, 8)).save(dest) + done = store.mark_succeeded( + gen.id, + [ + OutputSpec( + asset_id=asset_id, + dest_path=dest, + ordinal=0, + mime_type="image/png", + name=name, + ) + ], + attempt_count=claimed.attempt_count, + ) + return done.outputs[0] + + +def _persistent_asset_files(test_state) -> list[Path]: + assets_dir = test_state.config.app_data_dir / "assets" + if not assets_dir.exists(): + return [] + return sorted(path for path in assets_dir.rglob("*") if path.is_file()) + + +def _upload_temp_files() -> list[Path]: + return sorted(Path(tempfile.gettempdir()).glob(f"{_UPLOAD_TEMP_PREFIX}*")) + + +def _assert_no_leaked_upload_files(test_state) -> None: + assert _persistent_asset_files(test_state) == [] + assert _upload_temp_files() == [] + + +def test_health_is_public(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.get("/health") + assert response.status_code == 200 + assert response.json() == {"status": "ok"} + + +def test_serves_bundled_index_when_present(test_state, tmp_path) -> None: + (tmp_path / "index.html").write_text("remote-ok", encoding="utf-8") + app = create_remote_app( + handler=test_state, + remote_token="pair-token", + client_dir=tmp_path, + ) + with TestClient(app) as client: + response = client.get("/") + authed_api = client.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers=AUTH, + ) + authed_session = client.get( + "/api/session", + headers=AUTH, + ) + assert response.status_code == 200 + assert "remote-ok" in response.text + assert authed_api.status_code == 200 + assert authed_api.json() == [] + assert "remote-ok" not in authed_api.text + assert authed_session.status_code == 200 + assert authed_session.json() == {"status": "ok"} + app = create_remote_app(handler=test_state, remote_token="pair-token", client_dir=None) + with TestClient(app) as client: + response = client.get("/") + assert response.status_code == 200 + assert "Remote client is not built" in response.text + + +def test_spa_fallback_does_not_mask_api_404s(test_state, tmp_path: Path) -> None: + (tmp_path / "index.html").write_text("remote-ok", encoding="utf-8") + app = create_remote_app( + handler=test_state, + remote_token="pair-token", + client_dir=tmp_path, + ) + with TestClient(app) as client: + spa = client.get("/text-to-video") + unknown_api = client.get("/api/not-a-route", headers=AUTH) + assert spa.status_code == 200 + assert "remote-ok" in spa.text + assert spa.headers["content-type"].startswith("text/html") + assert "remote-ok" not in unknown_api.text + assert "text/html" not in unknown_api.headers.get("content-type", "") + assert_http_error( + unknown_api, status_code=404, code="HTTP_404", message="Not Found" + ) + files = SpaStaticFiles(directory=str(tmp_path), html=True) + scope = { + "type": "http", + "method": "GET", + "path": "/api/not-a-route", + "headers": [], + } + for mounted_path in ("api/not-a-route", "api\\not-a-route"): + with pytest.raises(StarletteHTTPException) as raised: + asyncio.run(files.get_response(mounted_path, scope)) + assert raised.value.status_code == 404 + + +def test_api_requires_bearer_and_exposes_queued_generation_routes(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + unauth = client.get("/api/generations", params={"feature": "text-to-video"}) + wrong = client.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers=WRONG_AUTH, + ) + t2v = client.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers=AUTH, + ) + i2v = client.get( + "/api/generations", + params={"feature": "image-to-video"}, + headers=AUTH, + ) + specs = client.get("/api/generate/models-specs", headers=AUTH) + create_t2v = client.post("/api/generations/text-to-video", headers=AUTH) + create_i2v = client.post("/api/generations/image-to-video", headers=AUTH) + legacy_generate = client.post("/api/generate", headers=AUTH, json={}) + assert unauth.status_code == 401 + assert wrong.status_code == 401 + assert t2v.status_code == 200 + assert t2v.json() == [] + assert i2v.status_code == 200 + assert i2v.json() == [] + assert specs.status_code == 200 + assert "local_models" in specs.json() + assert "downloaded_local_models" in specs.json() + assert create_t2v.status_code == 422 + assert create_i2v.status_code == 422 + assert legacy_generate.status_code == 404 + + +def test_settings_and_path_ingest_stay_off_remote(test_state, tmp_path: Path) -> None: + source = _png(tmp_path / "secret.png") + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + settings = client.post( + "/api/settings", + headers=AUTH, + json={"remoteExposure": "lan"}, + ) + active_model = client.post( + "/api/models/active-ltx-model", + headers=AUTH, + json={"modelId": "ltx-2.5-22b-distilled"}, + ) + ingest = client.post( + "/api/assets", + headers=AUTH, + json={"path": str(source)}, + ) + assert settings.status_code == 404 + assert active_model.status_code == 404 + assert ingest.status_code == 405 + + +def test_remote_can_save_dashboard_selection(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + selected = { + "range": "all", + "models": ["ltx-2.5-fast"], + "resolutions": ["540p"], + "aspectRatios": ["16:9"], + "fps": ["24"], + } + with TestClient(app) as client: + assert client.get("/api/settings", headers=AUTH).status_code == 404 + saved = client.post("/api/stats/activity-dashboard-selections", headers=AUTH, json=selected) + loaded = client.get("/api/stats/activity-dashboard-selections", headers=AUTH) + assert saved.status_code == 200 + assert saved.json() == selected + assert loaded.status_code == 200 + assert loaded.json() == selected + + +def test_remote_stats_surface_is_the_two_phone_routes(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + stats_paths = {path for path in app.openapi()["paths"] if path.startswith("/api/stats/")} + assert stats_paths == {"/api/stats/dashboard", "/api/stats/activity-dashboard-selections"} + + +def test_remote_cannot_grow_settings_with_an_unbounded_selection(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + too_many = client.post( + "/api/stats/activity-dashboard-selections", + headers=AUTH, + json={"range": "7d", "models": [f"m{i}" for i in range(33)]}, + ) + too_long = client.post( + "/api/stats/activity-dashboard-selections", + headers=AUTH, + json={"range": "7d", "models": ["x" * 65]}, + ) + assert too_many.status_code == 422 + assert too_long.status_code == 422 + + +def test_remote_openapi_omits_desktop_status_route(test_state) -> None: + schema = create_remote_app(handler=test_state, remote_token="pair-token").openapi() + assert "/api/remote/status" not in schema["paths"] + + +def test_remote_asset_openapi_keeps_phone_routes_with_unique_operation_ids( + test_state, +) -> None: + schema = create_remote_app(handler=test_state, remote_token="pair-token").openapi() + http_methods = {"get", "post", "put", "delete", "head", "patch"} + asset_paths = { + path: sorted(method for method in methods if method in http_methods) + for path, methods in schema["paths"].items() + if path.startswith("/api/assets") + } + assert asset_paths == { + "/api/assets": ["get"], + "/api/assets/upload": ["post"], + "/api/assets/{asset_id}": ["get"], + "/api/assets/{asset_id}/bytes": ["get", "head"], + "/api/assets/{asset_id}/extract-audio": ["post"], + "/api/assets/{asset_id}/thumbnail/bytes": ["get", "head"], + "/api/assets/{asset_id}/trim-audio": ["post"], + "/api/assets/{asset_id}/trim-video": ["post"], + } + assert "delete" not in { + method + for methods in asset_paths.values() + for method in methods + } + operation_ids = [ + operation["operationId"] + for path_item in schema["paths"].values() + for method, operation in path_item.items() + if method in http_methods and "operationId" in operation + ] + assert len(operation_ids) == len(set(operation_ids)) + assert "route_list_phone_assets" in operation_ids + assert "route_delete_asset" not in operation_ids + + +def test_list_phone_assets_omits_paths_and_rejects_delete( + test_state, tmp_path: Path +) -> None: + png_bytes = _png(tmp_path / "phone.png").read_bytes() + output = _succeed_png(test_state) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("phone.png", png_bytes, "image/png")}, + ) + assert uploaded.status_code == 200 + listed = client.get("/api/assets", headers=AUTH) + assert listed.status_code == 200 + body = listed.json() + ids = [item["id"] for item in body["items"]] + assert uploaded.json()["id"] not in ids + item = body["items"][0] + assert item["id"] == output.id + assert item["origin"] == "generated" + assert "path" not in item + assert "thumbnail_path" not in item + assert "in_use" in item + assert item["has_thumbnail"] is True + assert item["bytes_url"].startswith(f"/api/assets/{output.id}/bytes?") + assert item["thumbnail_url"].startswith( + f"/api/assets/{output.id}/thumbnail/bytes?" + ) + deleted = client.delete(f"/api/assets/{output.id}", headers=AUTH) + assert deleted.status_code == 405 + + +def test_list_and_get_phone_assets_do_not_tombstone_missing_files( + test_state, +) -> None: + store = _store(test_state) + gone = _succeed_png(test_state, name="gone.png") + payload = Path(gone.path).read_bytes() + Path(gone.path).unlink() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + listed = client.get("/api/assets", headers=AUTH) + assert listed.status_code == 200 + assert gone.id not in [item["id"] for item in listed.json()["items"]] + fetched = client.get(f"/api/assets/{gone.id}", headers=AUTH) + assert fetched.status_code == 404 + Path(gone.path).write_bytes(payload) + assert store.get_asset(gone.id) is not None + + +def test_upload_and_bytes_round_trip_redacts_local_paths(test_state, tmp_path: Path) -> None: + png_bytes = _png(tmp_path / "phone.png").read_bytes() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("phone.png", png_bytes, "image/png")}, + ) + assert uploaded.status_code == 200 + asset = uploaded.json() + asset_id = asset["id"] + assert asset["media_kind"] == "image" + assert "path" not in asset + assert "thumbnail_path" not in asset + assert asset["id"] + assert asset["origin"] == "uploaded" + assert "metadata" in asset + + fetched = client.get(f"/api/assets/{asset_id}", headers=AUTH) + assert fetched.status_code == 200 + fetched_asset = fetched.json() + assert "path" not in fetched_asset + assert "thumbnail_path" not in fetched_asset + assert fetched_asset["id"] == asset_id + assert fetched_asset["bytes_url"].startswith(f"/api/assets/{asset_id}/bytes?") + assert fetched_asset["thumbnail_url"] is not None + assert fetched_asset["thumbnail_url"].startswith( + f"/api/assets/{asset_id}/thumbnail/bytes?" + ) + + unauth_bytes = client.get(f"/api/assets/{asset_id}/bytes") + query_bytes = client.get(f"/api/assets/{asset_id}/bytes?t=pair-token") + signed_bytes = client.get(asset["bytes_url"]) + header_bytes = client.get( + f"/api/assets/{asset_id}/bytes", + headers=AUTH, + ) + signed_thumb = ( + client.get(asset["thumbnail_url"]) + if asset["thumbnail_url"] is not None + else None + ) + unauth_query = client.get(f"/api/assets/{asset_id}/bytes?t=wrong") + + assert unauth_bytes.status_code == 401 + assert unauth_query.status_code == 401 + assert query_bytes.status_code == 401 + assert signed_bytes.status_code == 200 + assert signed_bytes.content == png_bytes + assert signed_bytes.headers["content-type"].startswith("image/png") + assert "inline" in signed_bytes.headers.get("content-disposition", "") + assert "attachment" not in signed_bytes.headers.get("content-disposition", "") + assert header_bytes.status_code == 401 + assert signed_thumb is not None + assert signed_thumb.status_code == 200 + assert signed_thumb.content + assert signed_thumb.headers["content-type"].startswith("image/jpeg") + assert "inline" in signed_thumb.headers.get("content-disposition", "") + + +def test_remote_upload_accepts_allowed_image_suffixes( + test_state, tmp_path: Path +) -> None: + assert set(_IMAGE_SAVE_FORMAT) == set(ALLOWED_IMAGE_SUFFIXES) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + for suffix, fmt in _IMAGE_SAVE_FORMAT.items(): + source = tmp_path / f"ok{suffix}" + Image.new("RGB", (32, 24), color=(10, 20, 30)).save(source, format=fmt) + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": (source.name, source.read_bytes())}, + ) + assert uploaded.status_code == 200, uploaded.text + asset = uploaded.json() + assert asset["media_kind"] == "image" + assert "path" not in asset + assert "thumbnail_path" not in asset + fetched = client.get(asset["bytes_url"]) + assert fetched.status_code == 200 + assert fetched.content == source.read_bytes() + + +def test_upload_size_guards_honor_file_bytes_not_multipart_framing() -> None: + wrapping = 512 + assert wrapping < _MULTIPART_OVERHEAD_BYTES + assert not _upload_body_exceeds_limit( + file_size=MAX_IMAGE_BYTES, + content_length=str(MAX_IMAGE_BYTES + wrapping), + max_bytes=MAX_IMAGE_BYTES, + ) + assert _upload_body_exceeds_limit( + file_size=MAX_IMAGE_BYTES + 1, + content_length=str(MAX_IMAGE_BYTES + wrapping), + max_bytes=MAX_IMAGE_BYTES, + ) + assert not _upload_body_exceeds_limit( + file_size=None, + content_length=str(MAX_IMAGE_BYTES + wrapping), + max_bytes=MAX_IMAGE_BYTES, + ) + assert not _upload_body_exceeds_limit( + file_size=None, + content_length=str(MAX_IMAGE_BYTES + _MULTIPART_OVERHEAD_BYTES), + max_bytes=MAX_IMAGE_BYTES, + ) + assert _upload_body_exceeds_limit( + file_size=None, + content_length=str(MAX_IMAGE_BYTES + _MULTIPART_OVERHEAD_BYTES + 1), + max_bytes=MAX_IMAGE_BYTES, + ) + + +def test_remote_upload_accepts_image_when_content_length_includes_framing( + test_state, tmp_path: Path +) -> None: + png_bytes = _png(tmp_path / "ok.png").read_bytes() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers={**AUTH, "content-length": str(MAX_IMAGE_BYTES + 512)}, + files={"file": ("ok.png", png_bytes, "image/png")}, + ) + assert uploaded.status_code == 200, uploaded.text + assert uploaded.json()["media_kind"] == "image" + + +def test_remote_upload_accepts_wav_mp3_m4a(test_state, tmp_path: Path) -> None: + samples = ( + (_wav(tmp_path / "input.wav"), "audio/wav"), + (_encoded_audio(tmp_path / "input.mp3"), "audio/mpeg"), + (_encoded_audio(tmp_path / "input.m4a"), "audio/mp4"), + ) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + for source, mime in samples: + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": (source.name, source.read_bytes(), mime)}, + ) + assert uploaded.status_code == 200, uploaded.text + asset = uploaded.json() + assert asset["media_kind"] == "audio" + assert "path" not in asset + assert "thumbnail_path" not in asset + fetched = client.get(asset["bytes_url"]) + assert fetched.status_code == 200 + assert fetched.content == source.read_bytes() + + +def test_remote_upload_accepts_video(test_state, tmp_path: Path) -> None: + video_bytes = _mp4(tmp_path / "input.mp4").read_bytes() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + video = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("input.mp4", video_bytes, "video/mp4")}, + ) + assert video.status_code == 200, video.text + asset = video.json() + assert asset["media_kind"] == "video" + assert "path" not in asset + assert "thumbnail_path" not in asset + fetched = client.get(asset["bytes_url"]) + assert fetched.status_code == 200 + assert fetched.content == video_bytes + + +def test_remote_upload_malformed_audio_hides_filesystem_path(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("bad.wav", b"not audio at all", "audio/wav")}, + ) + assert response.status_code == 400 + body = response.json() + assert body["code"] == "UNREADABLE_MEDIA" + assert "/" not in response.text + assert "\\" not in response.text + _assert_no_leaked_upload_files(test_state) + + +def test_remote_trim_audio_returns_remote_asset(test_state, tmp_path: Path) -> None: + store = _store(test_state) + audio = store.ingest_upload( + str(_wav(tmp_path / "line.wav", duration_seconds=2.0)) + ) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + trimmed = client.post( + f"/api/assets/{audio.id}/trim-audio", + headers=AUTH, + json={"startSec": 0, "endSec": 1}, + ) + assert trimmed.status_code == 200, trimmed.text + asset = trimmed.json() + assert asset["media_kind"] == "audio" + assert "path" not in asset + assert "thumbnail_path" not in asset + assert 900 <= asset["metadata"]["metadata"]["durationMs"] <= 1100 + + +def test_remote_upload_rejects_image_over_max_bytes( + test_state, tmp_path: Path +) -> None: + png_bytes = _png(tmp_path / "ok.png").read_bytes() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers={ + **AUTH, + "content-length": str( + MAX_IMAGE_BYTES + _MULTIPART_OVERHEAD_BYTES + 1 + ), + }, + files={"file": ("huge.png", png_bytes, "image/png")}, + ) + assert_http_error(uploaded, status_code=400, code="FILE_TOO_LARGE") + _assert_no_leaked_upload_files(test_state) + + +def test_remote_upload_rejects_video_over_max_bytes( + test_state, tmp_path: Path +) -> None: + video_bytes = _mp4(tmp_path / "ok.mp4").read_bytes() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers={ + **AUTH, + "content-length": str( + MAX_VIDEO_BYTES + _MULTIPART_OVERHEAD_BYTES + 1 + ), + }, + files={"file": ("huge.mp4", video_bytes, "video/mp4")}, + ) + assert_http_error(uploaded, status_code=400, code="FILE_TOO_LARGE") + _assert_no_leaked_upload_files(test_state) + + +def test_bytes_serves_first_last_frame_audio_and_video_inline( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + start_path = _png(tmp_path / "start.png") + end_path = _png(tmp_path / "end.png") + audio_path = _wav(tmp_path / "input.wav") + video_path = _mp4(tmp_path / "input.mp4") + start = store.ingest_upload(str(start_path)) + end = store.ingest_upload(str(end_path)) + audio = store.ingest_upload(str(audio_path)) + video = store.ingest_upload(str(video_path)) + samples = ( + (start, start_path.read_bytes(), "image/"), + (end, end_path.read_bytes(), "image/"), + (audio, audio_path.read_bytes(), "audio/"), + (video, video_path.read_bytes(), "video/"), + ) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + for record, payload, mime_prefix in samples: + fetched = client.get(f"/api/assets/{record.id}", headers=AUTH) + assert fetched.status_code == 200 + asset = fetched.json() + assert asset["media_kind"] == record.media_kind + assert "path" not in asset + assert "thumbnail_path" not in asset + response = client.get(asset["bytes_url"]) + assert response.status_code == 200 + assert response.content == payload + assert response.headers["content-type"].startswith(mime_prefix) + disposition = response.headers.get("content-disposition", "") + assert "inline" in disposition + assert "attachment" not in disposition + + head = client.head(_bytes_url(client, video.id)) + ranged = client.get( + _bytes_url(client, video.id), + headers={"Range": "bytes=0-15"}, + ) + + video_bytes = video_path.read_bytes() + assert head.status_code == 200 + assert head.content == b"" + assert head.headers["content-type"].startswith("video/") + assert ranged.status_code == 206 + assert ranged.content == video_bytes[:16] + + +def test_session_requires_bearer(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + unauth = client.get("/api/session") + wrong = client.get( + "/api/session", + headers=WRONG_AUTH, + ) + authed = client.get( + "/api/session", + headers=AUTH, + ) + assert unauth.status_code == 401 + assert wrong.status_code == 401 + assert authed.status_code == 200 + assert authed.json() == {"status": "ok"} + + +def test_session_store_outage_does_not_clear_as_unauthorized(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + pairing = app.state.remote_pairing + + def boom(_token: str): + raise UnavailableError() + + pairing._lookup_active_session = boom # type: ignore[method-assign] + with TestClient(app) as client: + response = client.get("/api/session", headers=AUTH) + assert_http_error(response, status_code=503, code="STORE_UNAVAILABLE") + + +def test_exchange_store_outage_is_unavailable(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + pairing = app.state.remote_pairing + grant = pairing.current_grant() + + def boom(_token_hash: str): + raise UnavailableError() + + pairing._store.get_paired_device_by_token_hash = boom # type: ignore[method-assign] + with TestClient(app) as client: + response = client.post( + "/api/pairing/exchange", + headers=AUTH, + json={"code": grant}, + ) + assert_http_error(response, status_code=503, code="STORE_UNAVAILABLE") + assert pairing.current_grant() == grant + + +def test_media_store_outage_is_unavailable(test_state, tmp_path: Path) -> None: + png_path = _png(tmp_path / "phone.png") + asset = _store(test_state).ingest_upload(str(png_path)) + app = create_remote_app(handler=test_state, remote_token="pair-token") + pairing = app.state.remote_pairing + with TestClient(app) as client: + url = _bytes_url(client, asset.id) + + def boom(_device_id: str): + raise UnavailableError() + + pairing._store.get_paired_device = boom # type: ignore[method-assign] + response = client.get(url) + assert_http_error(response, status_code=503, code="STORE_UNAVAILABLE") + + +def test_query_token_does_not_authenticate(test_state, tmp_path: Path) -> None: + png_path = _png(tmp_path / "phone.png") + png_bytes = png_path.read_bytes() + asset = _store(test_state).ingest_upload(str(png_path)) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + session = client.get("/api/session", params={"t": "pair-token"}) + generations = client.get( + "/api/generations", + params={"feature": "text-to-video", "t": "pair-token"}, + ) + upload = client.post( + "/api/assets/upload", + params={"t": "pair-token"}, + files={"file": ("phone.png", png_bytes, "image/png")}, + ) + query_get = client.get( + f"/api/assets/{asset.id}/bytes", params={"t": "pair-token"} + ) + query_head = client.head( + f"/api/assets/{asset.id}/bytes", params={"t": "pair-token"} + ) + + assert session.status_code == 401 + assert generations.status_code == 401 + assert upload.status_code == 401 + assert query_get.status_code == 401 + assert query_head.status_code == 401 + + +def test_pairing_exchange_issues_a_session(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + grant = app.state.remote_pairing.current_grant() + with TestClient(app) as client: + exchanged = client.post("/api/pairing/exchange", json={"code": grant}) + assert exchanged.status_code == 200 + token = exchanged.json()["token"] + replay = client.post("/api/pairing/exchange", json={"code": grant}) + session = client.get( + "/api/session", headers={"Authorization": f"Bearer {token}"} + ) + assert replay.status_code == 401 + assert session.status_code == 200 + + +_CHROME_MAC_UA = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" +) + + +def test_bearer_session_backfills_first_seen_ip_and_name(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + pairing = app.state.remote_pairing + assert pairing.list_public_devices()[0].ip is None + with TestClient(app, client=("10.0.0.4", 50000)) as client: + session = client.get( + "/api/session", + headers={ + "Authorization": "Bearer pair-token", + "User-Agent": _CHROME_MAC_UA, + }, + ) + assert session.status_code == 200 + listed = pairing.list_public_devices()[0] + assert listed.ip == "10.0.0.4" + assert listed.name == "Chrome on Mac" + + +def test_pairing_exchange_records_peer_ip_and_friendly_name(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + grant = app.state.remote_pairing.current_grant() + with TestClient(app, client=("192.168.1.4", 50000)) as client: + exchanged = client.post( + "/api/pairing/exchange", + json={"code": grant}, + headers={"User-Agent": _CHROME_MAC_UA}, + ) + assert exchanged.status_code == 200 + listed = next( + item + for item in app.state.remote_pairing.list_public_devices() + if item.id == exchanged.json()["device_id"] + ) + assert listed.ip == "192.168.1.4" + assert listed.name == "Chrome on Mac" + + +def test_pairing_exchange_reuses_device_when_bearer_present(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + pairing = app.state.remote_pairing + with TestClient(app) as client: + first = client.post( + "/api/pairing/exchange", json={"code": pairing.current_grant()} + ) + assert first.status_code == 200 + token = first.json()["token"] + device_id = first.json()["device_id"] + second = client.post( + "/api/pairing/exchange", + json={"code": pairing.current_grant()}, + headers={"Authorization": f"Bearer {token}"}, + ) + reused = client.get("/api/session", headers={"Authorization": f"Bearer {token}"}) + assert second.status_code == 200 + assert second.json()["device_id"] == device_id + assert second.json()["token"] == token + assert reused.status_code == 200 + + +def test_pairing_exchange_ignores_invalid_bearer(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + pairing = app.state.remote_pairing + with TestClient(app) as client: + first = client.post( + "/api/pairing/exchange", json={"code": pairing.current_grant()} + ) + bogus = client.post( + "/api/pairing/exchange", + json={"code": pairing.current_grant()}, + headers={"Authorization": "Bearer not-a-session"}, + ) + assert first.status_code == 200 + assert bogus.status_code == 200 + assert bogus.json()["device_id"] != first.json()["device_id"] + assert bogus.json()["token"] != first.json()["token"] + + +def test_trycloudflare_host_is_rejected(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.get("/health", headers={"host": "abc.trycloudflare.com"}) + assert response.status_code == 400 + + +def test_trusted_host_allows_configured_lan_and_rejects_unrelated( + test_state, monkeypatch +) -> None: + monkeypatch.setattr("remote.app.lan_ip", lambda: "192.168.50.12") + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + allowed = [ + client.get("/health", headers={"host": host}) + for host in ("testserver", "localhost", "127.0.0.1", "192.168.50.12") + ] + rejected = client.get("/health", headers={"host": "attacker.example"}) + assert [response.status_code for response in allowed] == [200, 200, 200, 200] + assert [response.json() for response in allowed] == [{"status": "ok"}] * 4 + assert rejected.status_code == 400 + + +def test_redact_asset_paths_only_strips_asset_shaped_objects() -> None: + payload = { + "id": "asset-1", + "media_kind": "image", + "path": "/Users/me/secret.png", + "thumbnail_path": "/Users/me/secret-thumb.jpg", + "outputs": [ + { + "id": "out-1", + "media_kind": "video", + "path": "/tmp/out.mp4", + "thumbnail_path": None, + } + ], + "spec": {"params": {"prompt": "keep me"}}, + } + redacted = redact_asset_paths(payload) + assert isinstance(redacted, dict) + assert redacted["path"] == "" + assert redacted["thumbnail_path"] is None + outputs = redacted["outputs"] + assert isinstance(outputs, list) + nested = outputs[0] + assert isinstance(nested, dict) + assert nested["path"] == "" + spec = redacted["spec"] + assert isinstance(spec, dict) + assert spec == {"params": {"prompt": "keep me"}} diff --git a/backend/tests/test_remote_controller.py b/backend/tests/test_remote_controller.py new file mode 100644 index 000000000..25d80e96e --- /dev/null +++ b/backend/tests/test_remote_controller.py @@ -0,0 +1,640 @@ +"""Exposure gates: auth token + settings toggle; isolated LAN bind.""" + +from __future__ import annotations + +import threading +import time +from pathlib import Path +from urllib.parse import urlsplit + +import httpx +from starlette.testclient import TestClient + +from app_factory import create_app +from app_handler import ServiceBundle +from remote.app import create_remote_app +from remote.controller import ( + RemoteExposureController, + _Running, + _Stopping, + remote_controller_from_app, +) +from services.records import UnavailableError +from services.sqlite_store import SqliteStore +from state import build_initial_state, get_state_service +from tests.conftest import DEFAULT_APP_SETTINGS +from tests.fakes.generation import FakeGenerationExecutor +from tests.fakes.services import FakeServices +from tests.http_error_assertions import assert_http_error + + +def _port_from_url(url: str) -> int: + port = urlsplit(url).port + assert port is not None and port > 0 + return port + + +def _wait_until_serving(client, *, timeout: float = 8.0) -> dict: + deadline = time.monotonic() + timeout + payload: dict | None = None + while time.monotonic() < deadline: + payload = client.get("/api/remote/status").json() + if payload.get("serving") is True: + return payload + time.sleep(0.05) + raise AssertionError(f"remote did not start: {payload}") + + +def test_desktop_openapi_includes_remote_status(test_state) -> None: + schema = create_app(handler=test_state).openapi() + status = schema["paths"]["/api/remote/status"]["get"] + assert status["tags"] == ["remote"] + assert status["responses"]["200"]["content"]["application/json"]["schema"] == { + "$ref": "#/components/schemas/RemoteStatusResponse" + } + assert "RemoteStatusResponse" in schema["components"]["schemas"] + assert "/api/remote/devices" in schema["paths"] + assert "/api/remote/devices/{device_id}/revoke" in schema["paths"] + + +def test_list_devices_store_outage_is_unavailable(client) -> None: + controller = remote_controller_from_app(client.app) + assert controller is not None + + def boom(): + raise UnavailableError() + + controller._pairing._store.list_paired_devices = boom # type: ignore[method-assign] + response = client.get("/api/remote/devices") + assert_http_error(response, status_code=503, code="STORE_UNAVAILABLE") + + +def test_revoke_device_store_outage_is_unavailable(client) -> None: + controller = remote_controller_from_app(client.app) + assert controller is not None + + def boom(_device_id: str, *, now_ms: int): + raise UnavailableError() + + controller._pairing._store.revoke_paired_device = boom # type: ignore[method-assign] + response = client.post("/api/remote/devices/any/revoke") + assert_http_error(response, status_code=503, code="STORE_UNAVAILABLE") + + +def test_status_permitted_when_auth_token_present(client, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + payload = client.get("/api/remote/status").json() + assert payload["permitted"] is True + assert payload["serving"] is False + assert payload["mode"] == "off" + + +def test_empty_auth_token_refuses_enable(client, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "") + assert client.post("/api/settings", json={"remoteExposure": "lan"}).status_code == 200 + payload = client.get("/api/remote/status").json() + assert payload["permitted"] is False + assert payload["serving"] is False + assert "LTX_AUTH_TOKEN" in (payload["reason"] or "") + + +def test_settings_on_binds_and_advertise_url(client, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + monkeypatch.setenv("LTX_REMOTE_PORT", "0") + + assert client.post("/api/settings", json={"remoteExposure": "lan"}).status_code == 200 + payload = _wait_until_serving(client) + assert payload["permitted"] is True + assert payload["serving"] is True + assert payload["mode"] == "lan" + assert payload["localUrl"] is not None + port = _port_from_url(payload["localUrl"]) + assert f":{port}/pairing?t=" in payload["localUrl"] + assert payload["url"] is not None + assert payload["lanUrl"] is not None + assert f":{port}/pairing?t=" in payload["lanUrl"] + assert "tunnelUrl" not in payload + assert "tunnelPending" not in payload + + # httpx, not urllib: Windows urllib can abort the socket (WinError 10053) + # instead of returning the HTTP status for a 404 POST. + grant = payload["localUrl"].split("?t=", 1)[1] + with httpx.Client(base_url=f"http://127.0.0.1:{port}", timeout=2.0) as http: + health = http.get("/health") + assert health.status_code == 200 + assert health.json() == {"status": "ok"} + + exchanged = http.post("/api/pairing/exchange", json={"code": grant}) + assert exchanged.status_code == 200 + token = exchanged.json()["token"] + authed = {"Authorization": f"Bearer {token}"} + + generations = http.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers=authed, + ) + assert generations.status_code == 200 + assert isinstance(generations.json(), list) + + unauth = http.get( + "/api/generations", + params={"feature": "text-to-video"}, + ) + assert unauth.status_code == 401 + + legacy = http.post( + "/api/generate", + headers={**authed, "Content-Type": "application/json"}, + content=b"{}", + ) + assert legacy.status_code == 404 + + assert client.post("/api/settings", json={"remoteExposure": "off"}).status_code == 200 + stopped = client.get("/api/remote/status").json() + assert stopped["serving"] is False + controller = remote_controller_from_app(client.app) + assert controller is not None + assert controller.status().localUrl is None + + +def _independent_handler(test_state, tmp_path: Path, *, prompt_cache_size: int): + fake_services = FakeServices() + data_dir = tmp_path / "other-app" + data_dir.mkdir() + handler = build_initial_state( + test_state.config, + DEFAULT_APP_SETTINGS.model_copy(deep=True), + service_bundle=ServiceBundle( + http=fake_services.http, + gpu_cleaner=fake_services.gpu_cleaner, + model_downloader=fake_services.model_downloader, + lora_catalog_provider=fake_services.lora_catalog_provider, + gpu_info=fake_services.gpu_info, + video_processor=fake_services.video_processor, + text_encoder=fake_services.text_encoder, + task_runner=fake_services.task_runner, + ltx_api_client=fake_services.ltx_api_client, + zit_api_client=fake_services.zit_api_client, + fast_video_pipeline_class=type(fake_services.fast_video_pipeline), + image_generation_pipeline_class=type(fake_services.image_generation_pipeline), + ic_lora_pipeline_class=type(fake_services.ic_lora_pipeline), + depth_processor_pipeline_class=type(fake_services.depth_processor_pipeline), + pose_processor_pipeline_class=type(fake_services.pose_processor_pipeline), + a2v_pipeline_class=type(fake_services.a2v_pipeline), + retake_pipeline_class=type(fake_services.retake_pipeline), + prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), + store=SqliteStore(data_dir), + generation_executors={ + "text-to-video": FakeGenerationExecutor(), + "image-to-video": FakeGenerationExecutor(), + }, + ), + ) + handler.state.app_settings.prompt_cache_size = prompt_cache_size + return handler + + +def test_independent_apps_do_not_share_handler_or_controller( + test_state, tmp_path: Path, monkeypatch +) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + monkeypatch.setenv("LTX_REMOTE_PORT", "0") + + handler_a = test_state + handler_a.state.app_settings.prompt_cache_size = 11 + handler_b = _independent_handler(test_state, tmp_path, prompt_cache_size=22) + + app_a = create_app(handler=handler_a) + app_b = create_app(handler=handler_b) + + assert remote_controller_from_app(app_a) is not remote_controller_from_app(app_b) + assert app_a.dependency_overrides[get_state_service]() is handler_a + assert app_b.dependency_overrides[get_state_service]() is handler_b + + with TestClient(app_a) as client_a, TestClient(app_b) as client_b: + assert client_a.get("/api/settings").json()["promptCacheSize"] == 11 + assert client_b.get("/api/settings").json()["promptCacheSize"] == 22 + + assert client_a.post("/api/settings", json={"remoteExposure": "lan"}).status_code == 200 + payload_a = _wait_until_serving(client_a) + payload_b = client_b.get("/api/remote/status").json() + + assert payload_a["serving"] is True + assert payload_a["mode"] == "lan" + assert payload_b["serving"] is False + assert payload_b["mode"] == "off" + assert handler_a.state.app_settings.remote_exposure == "lan" + assert handler_b.state.app_settings.remote_exposure == "off" + + +def test_remote_app_does_not_replace_desktop_handler_or_controller( + test_state, tmp_path: Path +) -> None: + handler_desktop = test_state + handler_desktop.state.app_settings.prompt_cache_size = 11 + handler_remote = _independent_handler(test_state, tmp_path, prompt_cache_size=22) + + desktop = create_app(handler=handler_desktop) + desktop_controller = remote_controller_from_app(desktop) + assert get_state_service() is handler_desktop + assert desktop.dependency_overrides[get_state_service]() is handler_desktop + + remote = create_remote_app(handler=handler_remote, remote_token="pair-token") + + assert get_state_service() is handler_desktop + assert remote_controller_from_app(desktop) is desktop_controller + assert remote_controller_from_app(remote) is None + assert remote.dependency_overrides[get_state_service]() is handler_remote + assert desktop.dependency_overrides[get_state_service]() is handler_desktop + + with TestClient(desktop) as desktop_client, TestClient(remote) as remote_client: + assert desktop_client.get("/api/settings").json()["promptCacheSize"] == 11 + listed = remote_client.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers={"Authorization": "Bearer pair-token"}, + ) + assert listed.status_code == 200 + assert listed.json() == [] + + +class _FakeServer: + def __init__(self, *, started: bool = True) -> None: + self.started = started + self.should_exit = False + self.run_called = False + + def run(self) -> None: + self.run_called = True + + +class _BlockingJoinThread: + def __init__(self) -> None: + self.join_started = threading.Event() + self.release_join = threading.Event() + self._alive = True + + def is_alive(self) -> bool: + return self._alive + + def join(self, timeout: float | None = None) -> None: + self.join_started.set() + self.release_join.wait(timeout) + self._alive = False + + +class _LiveJoinThread: + def __init__(self) -> None: + self._alive = True + + def is_alive(self) -> bool: + return self._alive + + def join(self, timeout: float | None = None) -> None: + del timeout + self._alive = False + + +class _DeadThread: + def is_alive(self) -> bool: + return False + + def join(self, timeout: float | None = None) -> None: + del timeout + + +class _JoinTimeoutLiveThread: + def __init__(self) -> None: + self._alive = True + + def is_alive(self) -> bool: + return self._alive + + def join(self, timeout: float | None = None) -> None: + del timeout + + def terminate(self) -> None: + self._alive = False + + +class _StartRecordingController(RemoteExposureController): + def __init__(self, handler) -> None: + super().__init__(handler) + self.start_calls = 0 + self.started_servers: list[_FakeServer] = [] + + def _start_locked(self) -> None: + self.start_calls += 1 + server = _FakeServer(started=True) + self.started_servers.append(server) + self._ownership = _Running( + server=server, + thread=_LiveJoinThread(), + port=41955, + ) + self._exposure = self._handler.settings.get_settings_snapshot().remote_exposure + self._last_reason = "starting" + + +def _install_running( + controller: RemoteExposureController, + *, + server: _FakeServer | None = None, + thread: object | None = None, +) -> tuple[_FakeServer, object]: + owned_server = server or _FakeServer(started=True) + owned_thread = thread or _LiveJoinThread() + controller._ownership = _Running( + server=owned_server, + thread=owned_thread, + port=41955, + ) + controller._exposure = "lan" + controller._last_reason = "starting" + return owned_server, owned_thread + + +def test_status_stays_responsive_while_stop_joins(test_state, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + controller = RemoteExposureController(test_state) + thread = _BlockingJoinThread() + _install_running(controller, thread=thread) + + stopped = threading.Event() + + def _stop() -> None: + controller.stop() + stopped.set() + + threading.Thread(target=_stop, name="ltx-remote-stop-test", daemon=True).start() + assert thread.join_started.wait(timeout=1.0) + assert not stopped.is_set() + + started = time.monotonic() + payload = controller.status() + elapsed = time.monotonic() - started + + assert elapsed < 1.0 + assert payload.serving is False + assert payload.permitted is True + assert not stopped.is_set() + assert isinstance(controller._ownership, _Stopping) + + thread.release_join.set() + assert stopped.wait(timeout=1.0) + assert controller._ownership is None + + +def test_sync_does_not_start_replacement_until_stop_completes( + test_state, monkeypatch +) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + test_state.state.app_settings.remote_exposure = "off" + controller = _StartRecordingController(test_state) + old_server = _FakeServer(started=True) + thread = _BlockingJoinThread() + _install_running(controller, server=old_server, thread=thread) + + first_sync_done = threading.Event() + + def _disable() -> None: + controller.sync() + first_sync_done.set() + + threading.Thread(target=_disable, name="ltx-remote-sync-stop", daemon=True).start() + assert thread.join_started.wait(timeout=1.0) + assert old_server.should_exit is True + assert controller.start_calls == 0 + + test_state.state.app_settings.remote_exposure = "lan" + controller.sync() + assert controller.start_calls == 0 + assert isinstance(controller._ownership, _Stopping) + assert controller._ownership.server is old_server + + thread.release_join.set() + assert first_sync_done.wait(timeout=1.0) + assert controller.start_calls == 1 + assert controller.started_servers[0] is not old_server + assert isinstance(controller._ownership, _Running) + assert controller._ownership.server is controller.started_servers[0] + + +def test_run_server_swallows_uvicorn_bind_systemexit(test_state) -> None: + """uvicorn.Server.startup calls sys.exit(1) on EADDRINUSE; that must not kill the thread.""" + controller = RemoteExposureController(test_state) + + class _ExitOnBind: + def run(self) -> None: + raise SystemExit(1) + + controller._run_server(_ExitOnBind()) # type: ignore[arg-type] + + +def test_run_server_uses_passed_instance_not_later_owner(test_state) -> None: + controller = RemoteExposureController(test_state) + old_server = _FakeServer() + new_server = _FakeServer() + _install_running(controller, server=new_server, thread=_DeadThread()) + + controller._run_server(old_server) + + assert old_server.run_called is True + assert new_server.run_called is False + + +def test_finish_stop_does_not_clear_a_replacement_server(test_state) -> None: + controller = RemoteExposureController(test_state) + old_server = _FakeServer() + old_thread = _LiveJoinThread() + new_server = _FakeServer() + replacement = _Running( + server=new_server, + thread=_LiveJoinThread(), + port=41955, + ) + controller._ownership = replacement + + controller._finish_stop_locked(_Stopping(server=old_server, thread=old_thread)) + + assert controller._ownership is replacement + assert controller._ownership.server is new_server + + +def test_status_reaps_dead_running_thread(test_state, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + controller = RemoteExposureController(test_state) + _install_running(controller, thread=_DeadThread()) + + payload = controller.status() + + assert payload.serving is False + assert payload.reason == "remote server stopped unexpectedly" + assert controller._ownership is None + + +def test_status_does_not_reap_stopping_as_unexpected(test_state, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + controller = RemoteExposureController(test_state) + server = _FakeServer(started=True) + controller._ownership = _Stopping(server=server, thread=_DeadThread()) + controller._exposure = "lan" + controller._last_reason = "stopped" + + payload = controller.status() + + assert payload.serving is False + assert payload.reason == "stopped" + assert isinstance(controller._ownership, _Stopping) + assert controller._ownership.server is server + + +def test_stop_does_not_restart_when_setting_still_on(test_state, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + test_state.state.app_settings.remote_exposure = "lan" + controller = _StartRecordingController(test_state) + _install_running(controller, thread=_LiveJoinThread()) + + controller.stop() + + assert controller._ownership is None + assert controller.start_calls == 0 + assert controller.status().serving is False + + +def test_fail_start_does_not_start_replacement_until_thread_exits( + test_state, monkeypatch +) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + test_state.state.app_settings.remote_exposure = "lan" + controller = _StartRecordingController(test_state) + old_server = _FakeServer(started=False) + thread = _BlockingJoinThread() + _install_running(controller, server=old_server, thread=thread) + + fail_done = threading.Event() + + def _fail() -> None: + controller._fail_start( + old_server, + reason="remote server failed to bind", + log_msg="Remote server did not bind on port", + signal_exit=True, + ) + fail_done.set() + + threading.Thread(target=_fail, name="ltx-remote-fail-start-test", daemon=True).start() + assert thread.join_started.wait(timeout=1.0) + assert old_server.should_exit is True + assert isinstance(controller._ownership, _Stopping) + assert controller._ownership.server is old_server + assert controller.start_calls == 0 + + started = time.monotonic() + controller.sync() + assert time.monotonic() - started < 1.0 + assert controller.start_calls == 0 + assert isinstance(controller._ownership, _Stopping) + assert controller._ownership.server is old_server + + thread.release_join.set() + assert fail_done.wait(timeout=1.0) + assert not thread.is_alive() + assert controller._ownership is None + + controller.sync() + assert controller.start_calls == 1 + assert controller.started_servers[0] is not old_server + assert isinstance(controller._ownership, _Running) + assert controller._ownership.server is controller.started_servers[0] + + +def test_fail_start_keeps_ownership_when_join_times_out( + test_state, monkeypatch +) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + test_state.state.app_settings.remote_exposure = "lan" + controller = _StartRecordingController(test_state) + old_server = _FakeServer(started=False) + thread = _JoinTimeoutLiveThread() + _install_running(controller, server=old_server, thread=thread) + + controller._fail_start( + old_server, + reason="remote server failed to bind", + log_msg="Remote server did not bind on port", + signal_exit=True, + ) + + assert old_server.should_exit is True + assert thread.is_alive() + assert isinstance(controller._ownership, _Stopping) + assert controller._ownership.server is old_server + assert controller.start_calls == 0 + + controller.sync() + assert controller.start_calls == 0 + assert isinstance(controller._ownership, _Stopping) + assert controller._ownership.server is old_server + + thread.terminate() + finish_reasons: list[str] = [] + original_finish = controller._finish_stop_locked + + def _record_finish(target: _Stopping, *, reason: str = "stopped") -> None: + finish_reasons.append(reason) + original_finish(target, reason=reason) + + controller._finish_stop_locked = _record_finish # type: ignore[method-assign] + controller.sync() + assert finish_reasons == ["remote server failed to bind"] + assert controller.start_calls == 1 + assert controller.started_servers[0] is not old_server + assert isinstance(controller._ownership, _Running) + assert controller._ownership.server is controller.started_servers[0] + + +def test_desktop_lists_and_revokes_paired_devices(client, monkeypatch) -> None: + monkeypatch.setenv("LTX_AUTH_TOKEN", "desktop-secret") + monkeypatch.setenv("LTX_REMOTE_PORT", "0") + assert client.post("/api/settings", json={"remoteExposure": "lan"}).status_code == 200 + payload = _wait_until_serving(client) + grant = payload["localUrl"].split("?t=", 1)[1] + port = _port_from_url(payload["localUrl"]) + with httpx.Client(base_url=f"http://127.0.0.1:{port}", timeout=2.0) as http: + exchanged = http.post( + "/api/pairing/exchange", + json={"code": grant}, + headers={ + "User-Agent": ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " + "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + ) + }, + ) + assert exchanged.status_code == 200 + body = exchanged.json() + device_id = body["device_id"] + token = body["token"] + + listed = client.get("/api/remote/devices").json() + match = next(item for item in listed if item["id"] == device_id) + assert match["revoked_at"] is None + assert match["ip"] == "127.0.0.1" + assert match["name"] == "Chrome on Mac" + + revoked = client.post(f"/api/remote/devices/{device_id}/revoke") + assert revoked.status_code == 200 + listed_after = client.get("/api/remote/devices").json() + match = next(item for item in listed_after if item["id"] == device_id) + assert match["revoked_at"] is not None + assert client.post("/api/remote/devices/missing/revoke").status_code == 404 + + session = http.get( + "/api/session", + headers={"Authorization": f"Bearer {token}"}, + ) + assert session.status_code == 401 + + assert client.post("/api/settings", json={"remoteExposure": "off"}).status_code == 200 diff --git a/backend/tests/test_remote_generations.py b/backend/tests/test_remote_generations.py new file mode 100644 index 000000000..80097049c --- /dev/null +++ b/backend/tests/test_remote_generations.py @@ -0,0 +1,1197 @@ +"""Remote generation allowlist: T2V/I2V/A2V; desktop stays unfiltered.""" + +from __future__ import annotations + +import json +import sqlite3 +import wave +from pathlib import Path + +import pytest +from PIL import Image +from pydantic import JsonValue +from starlette.testclient import TestClient + +from app_factory import create_app +from remote.app import create_remote_app +from services.records import OutputSpec +from services.sqlite_store import SqliteStore +from tests.http_error_assertions import assert_http_error + +AUTH = {"Authorization": "Bearer pair-token"} +_APPROVED_PARAM_KEYS = frozenset( + { + "prompt", + "model", + "resolution", + "duration", + "fps", + "aspectRatio", + "scale", + "numFrames", + "promptProvenance", + "mode", + "startTime", + "seed", + } +) +_SECRET_PATHS = ( + "/Users/me/secret.png", + "/tmp/nested.mp4", + "/models/secret.safetensors", + "/Users/me/start.png", + "/Users/me/input.png", + "/etc/passwd", +) + + +def _store(test_state) -> SqliteStore: + return SqliteStore(test_state.config.app_data_dir) + + +def _spec(prompt: str) -> dict[str, JsonValue]: + return {"params": {"prompt": prompt, "model": "ltx-2.5-fast"}, "inputs": {}} + + +def test_remote_lists_allowed_features_and_rejects_others(test_state) -> None: + store = _store(test_state) + allowed = store.insert_generation("text-to-video", _spec("fox")) + recipe = store.insert_generation("cozy-felt", _spec("felt")) + store.insert_generation("desktop-only-feature", _spec("hidden")) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + t2v = client.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers=AUTH, + ) + i2v = client.get( + "/api/generations", + params={"feature": "image-to-video"}, + headers=AUTH, + ) + recipe_list = client.get( + "/api/generations", + params={"feature": "cozy-felt"}, + headers=AUTH, + ) + denied = client.get( + "/api/generations", + params={"feature": "desktop-only-feature"}, + headers=AUTH, + ) + + assert t2v.status_code == 200 + body = t2v.json() + assert len(body) == 1 + assert body[0]["id"] == allowed.id + assert body[0]["feature"] == "text-to-video" + assert i2v.status_code == 200 + assert i2v.json() == [] + # LoRA recipes are Home features too, so they are allowed on remote. + assert recipe_list.status_code == 200 + assert [generation["id"] for generation in recipe_list.json()] == [recipe.id] + assert_http_error(denied, status_code=404, code="GENERATION_NOT_FOUND") + + +def test_remote_cannot_fetch_or_operate_unsupported_feature_ids(test_state) -> None: + store = _store(test_state) + hidden = store.insert_generation("desktop-only-feature", _spec("hidden")) + allowed = store.insert_generation("text-to-video", _spec("fox")) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + hidden_get = client.get(f"/api/generations/{hidden.id}", headers=AUTH) + hidden_retry = client.post( + f"/api/generations/{hidden.id}/retry", headers=AUTH + ) + hidden_cancel = client.post( + f"/api/generations/{hidden.id}/cancel", headers=AUTH + ) + hidden_delete = client.delete( + f"/api/generations/{hidden.id}", headers=AUTH + ) + allowed_get = client.get(f"/api/generations/{allowed.id}", headers=AUTH) + allowed_cancel = client.post( + f"/api/generations/{allowed.id}/cancel", headers=AUTH + ) + missing = client.get("/api/generations/not-a-real-id", headers=AUTH) + + for response in ( + hidden_get, + hidden_retry, + hidden_cancel, + hidden_delete, + missing, + ): + assert_http_error(response, status_code=404, code="GENERATION_NOT_FOUND") + assert allowed_get.status_code == 200 + assert allowed_get.json()["id"] == allowed.id + assert allowed_cancel.status_code == 200 + assert allowed_cancel.json()["status"] == "cancelled" + loaded = store.get_generation(hidden.id) + assert loaded is not None + assert loaded.status == "queued" + + +def test_remote_retry_failed_allowed_generation(test_state) -> None: + store = _store(test_state) + generation = store.insert_generation("text-to-video", _spec("retry")) + claimed = store.claim_next_queued() + assert claimed is not None + store.mark_failed( + generation.id, + "OUTPUT_UNREADABLE", + attempt_count=claimed.attempt_count, + ) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + retried = client.post( + f"/api/generations/{generation.id}/retry", headers=AUTH + ) + + assert retried.status_code == 200, retried.text + body = retried.json() + assert body["id"] == generation.id + assert body["status"] == "queued" + assert body["feature"] == "text-to-video" + _assert_no_path_keys(body) + loaded = store.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "queued" + + +def test_desktop_still_lists_and_operates_unsupported_feature(test_state) -> None: + store = _store(test_state) + assert test_state.generation.try_reserve_generation_start() is True + try: + generation = store.insert_generation("desktop-only-feature", _spec("desktop")) + app = create_app(handler=test_state) + with TestClient(app) as client: + listed = client.get( + "/api/generations", params={"feature": "desktop-only-feature"} + ) + fetched = client.get(f"/api/generations/{generation.id}") + cancelled = client.post(f"/api/generations/{generation.id}/cancel") + assert listed.status_code == 200 + assert listed.json()[0]["id"] == generation.id + assert fetched.status_code == 200 + assert fetched.json()["feature"] == "desktop-only-feature" + assert cancelled.status_code == 200 + assert cancelled.json()["status"] == "cancelled" + finally: + test_state.generation.release_generation_start_reservation() + + +def test_recent_features_match_on_desktop_and_remote(test_state) -> None: + store = _store(test_state) + older = store.insert_generation("text-to-video", _spec("older")) + newer = store.insert_generation("extend", _spec("newer")) + hidden = store.insert_generation("desktop-only-feature", _spec("hidden")) + conn = sqlite3.connect(test_state.config.app_data_dir / "store.sqlite3") + conn.executemany( + "UPDATE generations SET created_at = ? WHERE id = ?", + [(1, older.id), (2, newer.id), (3, hidden.id)], + ) + conn.commit() + conn.close() + + desktop = create_app(handler=test_state) + remote = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(desktop) as desktop_client, TestClient(remote) as remote_client: + desktop_recent = desktop_client.get("/api/generations/recent-features") + remote_recent = remote_client.get( + "/api/generations/recent-features", headers=AUTH + ) + remote_open = remote_client.get("/api/generations/recent-features") + + assert desktop_recent.status_code == 200 + assert remote_recent.status_code == 200 + assert remote_open.status_code == 401 + assert desktop_recent.json() == ["extend", "text-to-video"] + assert remote_recent.json() == desktop_recent.json() + + +def test_remote_creates_lora_recipe_and_strips_ref( + test_state, monkeypatch, create_fake_model_files +) -> None: + from runtime_config.model_download_specs import resolve_lora_path + + # Pin a device cozy-felt supports; the gate uses the real accelerator, "cpu" on CI. + from handlers import queued_generation_handler + + create_fake_model_files() + monkeypatch.setattr(queued_generation_handler, "accelerator_backend", lambda: "mps") + + weights = resolve_lora_path( + test_state.config.default_models_dir, "cozy-felt-style", "CozyFelt.safetensors" + ) + weights.parent.mkdir(parents=True, exist_ok=True) + weights.write_bytes(b"\x00" * 64) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/recipes/cozy-felt", + headers=AUTH, + json={ + "params": { + "prompt": "a felt fox", + "model": "ltx-2.5-fast", + "catalogId": "cozy-felt-style", + "scale": 1.0, + "variantId": "default", + "resolution": "720p", + "duration": 8, + "fps": 24, + } + }, + ) + + assert created.status_code == 200, created.text + body = created.json() + assert body["feature"] == "cozy-felt" + assert body["status"] == "queued" + # The resolved LoRA ref never reaches the phone (path-free RemoteGeneration DTO), + # but the strength is projected up so the slider can be restored. + assert body["spec"]["params"]["prompt"] == "a felt fox" + assert body["spec"]["params"]["scale"] == 1.0 + assert "loras" not in body["spec"]["params"] + _assert_no_secret_paths(body) + _assert_no_path_keys(body) + # But it is persisted server-side for execution. + stored = _store(test_state).get_generation(body["id"]) + assert stored is not None + stored_params = stored.spec["params"] + assert isinstance(stored_params, dict) + assert stored_params["loras"][0]["catalogId"] == "cozy-felt-style" + + +def test_remote_creates_dolly_in_and_projects_start_frame( + test_state, monkeypatch, create_fake_model_files, tmp_path: Path +) -> None: + from runtime_config.model_download_specs import resolve_lora_path + + from handlers import queued_generation_handler + + create_fake_model_files() + monkeypatch.setattr(queued_generation_handler, "accelerator_backend", lambda: "mps") + + weights = resolve_lora_path( + test_state.config.default_models_dir, + "dolly-in", + "ltx-2-19b-lora-camera-control-dolly-in.safetensors", + ) + weights.parent.mkdir(parents=True, exist_ok=True) + weights.write_bytes(b"\x00" * 64) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + start = client.post( + "/api/assets/upload", + headers=AUTH, + files={ + "file": ( + "start.png", + _png(tmp_path / "dolly-start.png").read_bytes(), + "image/png", + ) + }, + ) + assert start.status_code == 200, start.text + start_id = start.json()["id"] + created = client.post( + "/api/generations/recipes/dolly-in", + headers=AUTH, + json={ + "params": { + "prompt": "push in on her face", + "model": "ltx-2.5-fast", + "catalogId": "dolly-in", + "scale": 1.0, + "variantId": "default", + "resolution": "720p", + "duration": 8, + "fps": 24, + "aspectRatio": "auto", + }, + "inputs": {"startFrame": {"assetId": start_id}}, + }, + ) + + assert created.status_code == 200, created.text + body = created.json() + assert body["feature"] == "dolly-in" + assert body["spec"]["params"]["prompt"] == "push in on her face" + assert body["spec"]["params"]["scale"] == 1.0 + assert body["spec"]["inputs"]["startFrame"]["assetId"] == start_id + assert "loras" not in body["spec"]["params"] + _assert_no_secret_paths(body) + _assert_no_path_keys(body) + + +def test_remote_creates_transition_and_projects_end_frame( + test_state, monkeypatch, create_fake_model_files, tmp_path: Path +) -> None: + from runtime_config.model_download_specs import resolve_lora_path + + from handlers import queued_generation_handler + + create_fake_model_files() + monkeypatch.setattr(queued_generation_handler, "accelerator_backend", lambda: "mps") + + weights = resolve_lora_path( + test_state.config.default_models_dir, + "transition", + "ltx2.3-transition.safetensors", + ) + weights.parent.mkdir(parents=True, exist_ok=True) + weights.write_bytes(b"\x00" * 64) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + start = client.post( + "/api/assets/upload", + headers=AUTH, + files={ + "file": ( + "start.png", + _png(tmp_path / "transition-start.png").read_bytes(), + "image/png", + ) + }, + ) + end = client.post( + "/api/assets/upload", + headers=AUTH, + files={ + "file": ( + "end.png", + _png(tmp_path / "transition-end.png").read_bytes(), + "image/png", + ) + }, + ) + assert start.status_code == 200, start.text + assert end.status_code == 200, end.text + start_id = start.json()["id"] + end_id = end.json()["id"] + created = client.post( + "/api/generations/recipes/transition", + headers=AUTH, + json={ + "params": { + "prompt": "a wave becomes a mountain", + "model": "ltx-2.5-fast", + "catalogId": "transition", + "scale": 1.0, + "variantId": "default", + "resolution": "720p", + "duration": 8, + "fps": 24, + "aspectRatio": "auto", + }, + "inputs": { + "startFrame": {"assetId": start_id}, + "endFrame": {"assetId": end_id}, + }, + }, + ) + + assert created.status_code == 200, created.text + body = created.json() + assert body["feature"] == "transition" + assert body["spec"]["inputs"]["startFrame"]["assetId"] == start_id + assert body["spec"]["inputs"]["endFrame"]["assetId"] == end_id + assert "loras" not in body["spec"]["params"] + _assert_no_secret_paths(body) + _assert_no_path_keys(body) + + +def test_remote_generation_openapi_is_queued_only(test_state) -> None: + schema = create_remote_app(handler=test_state, remote_token="pair-token").openapi() + http_methods = {"get", "post", "put", "delete", "head", "patch"} + generation_paths = { + path: sorted(method for method in methods if method in http_methods) + for path, methods in schema["paths"].items() + if path.startswith("/api/generation") + } + assert generation_paths == { + "/api/generation-queue": ["get"], + "/api/generation-queue/done/clear": ["post"], + "/api/generation-queue/done/{generation_id}/dismiss": ["post"], + "/api/generation-queue/done/{generation_id}/seen": ["post"], + "/api/generation-queue/failed/clear": ["post"], + "/api/generation-queue/reorder": ["post"], + "/api/generation-seed": ["get", "post"], + "/api/generations": ["get"], + "/api/generations/audio-to-video": ["post"], + "/api/generations/ic-lora-recipes/{recipe_id}": ["post"], + "/api/generations/extend": ["post"], + "/api/generations/image-to-video": ["post"], + "/api/generations/recipes/{recipe_id}": ["post"], + "/api/generations/recent-features": ["get"], + "/api/generations/retake": ["post"], + "/api/generations/text-to-video": ["post"], + "/api/generations/{generation_id}": ["delete", "get"], + "/api/generations/{generation_id}/cancel": ["post"], + "/api/generations/{generation_id}/retry": ["post"], + } + schemas = schema["components"]["schemas"] + assert "audio" in schemas["RemoteVideoInputs"]["properties"] + assert "video" in schemas["RemoteVideoInputs"]["properties"] + remote_asset = schemas["RemoteAsset"]["properties"] + remote_generation = schemas["RemoteGeneration"]["properties"] + assert "path" not in remote_asset + assert "thumbnail_path" not in remote_asset + assert "path" not in remote_generation + assert schemas["RemoteGeneration"]["properties"]["outputs"]["items"][ + "$ref" + ].endswith("/RemoteAsset") + assert schemas["RemoteQueueEntry"]["properties"]["generation"]["$ref"].endswith( + "/RemoteGeneration" + ) + assert schemas["RemoteQueueSnapshot"]["properties"]["queued"]["items"]["$ref"].endswith( + "/RemoteQueueEntry" + ) + assert schemas["RemoteQueueSnapshot"]["properties"]["done"]["items"]["$ref"].endswith( + "/RemoteQueueEntry" + ) + assert "unseen_ids" in schemas["RemoteQueueSnapshot"]["properties"] + assert schema["paths"]["/api/generation-queue/reorder"]["post"]["responses"]["200"][ + "content" + ]["application/json"]["schema"]["$ref"].endswith("/RemoteQueueSnapshot") + if "AssetCore" in schemas: + assert "path" not in schemas["AssetCore"]["properties"] + assert "thumbnail_path" not in schemas["AssetCore"]["properties"] + assert "Asset" not in schemas or "path" in schemas["Asset"]["properties"] + + +def test_remote_queue_snapshot_excludes_desktop_file_paths( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + input_asset = store.ingest_upload(str(_png(tmp_path / "start.png"))) + generation = store.insert_generation( + "image-to-video", + { + "params": {"prompt": "a drummer"}, + "inputs": {"startFrame": {"assetId": input_asset.id}}, + }, + ) + hidden = store.insert_generation("desktop-only-feature", _spec("hidden")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + + with TestClient(app) as client: + snapshot = client.get("/api/generation-queue", headers=AUTH) + + assert snapshot.status_code == 200, snapshot.text + body = snapshot.json() + assert body["active"] is None + assert body["done"] == [] + assert body["failed"] == [] + assert body["unseen_ids"] == [] + assert [entry["generation"]["id"] for entry in body["queued"]] == [generation.id] + assert hidden.id not in str(body) + assert body["queued"][0]["input_assets"][0]["id"] == input_asset.id + _assert_remote_asset_payload(body["queued"][0]["input_assets"][0]) + _assert_no_path_keys(body) + _assert_no_secret_paths(body) + + +def test_remote_reorder_returns_path_free_queue_snapshot( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + input_asset = store.ingest_upload(str(_png(tmp_path / "start.png"))) + first = store.insert_generation("text-to-video", _spec("first")) + second = store.insert_generation( + "image-to-video", + { + "params": {"prompt": "second"}, + "inputs": {"startFrame": {"assetId": input_asset.id}}, + }, + ) + hidden = store.insert_generation("desktop-only-feature", _spec("hidden")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + + with TestClient(app) as client: + reordered = client.post( + "/api/generation-queue/reorder", + json={"generation_id": second.id, "before_generation_id": first.id}, + headers=AUTH, + ) + + assert reordered.status_code == 200, reordered.text + body = reordered.json() + assert "id" not in body + assert body["active"] is None + assert [entry["generation"]["id"] for entry in body["queued"]] == [ + second.id, + first.id, + ] + assert hidden.id not in str(body) + assert body["queued"][0]["generation"]["status"] == "queued" + assert body["queued"][0]["input_assets"][0]["id"] == input_asset.id + assert body["queued"][0]["progress"] is None + assert body["queued"][1]["input_assets"] == [] + _assert_no_path_keys(body) + _assert_no_secret_paths(body) + _assert_remote_asset_payload(body["queued"][0]["input_assets"][0]) + + +def _png(path: Path, size: tuple[int, int] = (32, 24)) -> Path: + Image.new("RGB", size, color=(10, 20, 30)).save(path) + return path + + +def _wav(path: Path, *, duration_seconds: float = 8.0) -> Path: + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * int(duration_seconds * 8000)) + return path + + +def _mp4(path: Path, *, duration_seconds: float = 4.0, fps: int = 8) -> Path: + import numpy as np + import imageio.v2 as imageio + + frames = max(1, int(duration_seconds * fps)) + writer = imageio.get_writer( + str(path), fps=fps, codec="libx264", macro_block_size=None + ) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return path + + +def _assert_no_path_keys(payload: object) -> None: + if isinstance(payload, dict): + assert "path" not in payload + assert "thumbnail_path" not in payload + for value in payload.values(): + _assert_no_path_keys(value) + return + if isinstance(payload, list): + for item in payload: + _assert_no_path_keys(item) + + +def _assert_no_secret_paths(payload: object) -> None: + blob = json.dumps(payload) + for secret in _SECRET_PATHS: + assert secret not in blob + + +def _assert_remote_asset_payload(payload: object) -> dict[str, object]: + assert isinstance(payload, dict) + assert "path" not in payload + assert "thumbnail_path" not in payload + assert isinstance(payload.get("id"), str) and payload["id"] + assert payload.get("media_kind") in {"image", "video", "audio"} + assert "metadata" in payload + assert isinstance(payload.get("bytes_url"), str) + assert str(payload["bytes_url"]).startswith(f"/api/assets/{payload['id']}/bytes?") + return payload + + +def test_remote_create_t2v_keeps_form_fields_and_drops_lora_refs(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/text-to-video", + headers=AUTH, + json={ + "params": { + "prompt": "a fox on a beach", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "720p", + "duration": 8, + "fps": 24, + "cameraMotion": "dolly_in", + "negativePrompt": "blurry", + "loras": [ + { + "ref": "/models/secret.safetensors", + "scale": 0.5, + "catalogId": "lora-1", + } + ], + } + }, + ) + listed = client.get( + "/api/generations", + params={"feature": "text-to-video"}, + headers=AUTH, + ) + + assert created.status_code == 200, created.text + body = created.json() + assert body["feature"] == "text-to-video" + assert body["status"] == "queued" + params = body["spec"]["params"] + assert params == { + "prompt": "a fox on a beach", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "720p", + "duration": 8, + "fps": 24, + "scale": 0.5, + "promptProvenance": "typed", + } + assert set(params) <= _APPROVED_PARAM_KEYS + assert "inputs" not in body["spec"] + assert "loras" not in body["spec"]["params"] + _assert_no_secret_paths(body) + _assert_no_path_keys(body) + assert listed.status_code == 200 + assert listed.json()[0]["spec"]["params"]["prompt"] == "a fox on a beach" + + stored = _store(test_state).get_generation(body["id"]) + assert stored is not None + stored_params = stored.spec["params"] + assert isinstance(stored_params, dict) + assert stored_params["loras"][0]["ref"] == "/models/secret.safetensors" + + +@pytest.mark.parametrize("pipeline_id", ["fast", "pro", "pro-2.5", "fast-2.5"]) +def test_remote_create_t2v_rejects_pipeline_model_ids( + test_state, pipeline_id: str +) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/text-to-video", + headers=AUTH, + json={"params": {"prompt": "a fox", "model": pipeline_id}}, + ) + assert created.status_code == 422 + assert _store(test_state).list_generations("text-to-video") == [] + + +def test_remote_create_t2v_queues_2_3_offering_without_changing_active_settings( + test_state, create_fake_model_files +) -> None: + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/text-to-video", + headers=AUTH, + json={ + "params": { + "prompt": "a fox on a beach", + "model": "ltx-2.3-fast", + "aspectRatio": "16:9", + "resolution": "720p", + "duration": 8, + "fps": 24, + } + }, + ) + + assert created.status_code == 200, created.text + body = created.json() + assert body["status"] == "queued" + assert body["spec"]["params"]["model"] == "ltx-2.3-fast" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + + +def test_remote_create_i2v_keeps_asset_ids_for_form_restore( + test_state, tmp_path: Path +) -> None: + png_bytes = _png(tmp_path / "start.png").read_bytes() + end_bytes = _png(tmp_path / "end.png").read_bytes() + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + start = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("start.png", png_bytes, "image/png")}, + ).json() + end = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("end.png", end_bytes, "image/png")}, + ).json() + created = client.post( + "/api/generations/image-to-video", + headers=AUTH, + json={ + "params": { + "prompt": "a drummer", + "model": "ltx-2.5-fast", + "aspectRatio": "auto", + "resolution": "1080p", + "duration": 8, + "fps": 50, + }, + "inputs": { + "startFrame": {"assetId": start["id"]}, + "endFrame": {"assetId": end["id"]}, + }, + }, + ) + fetched_start = client.get(f"/api/assets/{start['id']}", headers=AUTH) + + assert created.status_code == 200, created.text + body = created.json() + assert body["feature"] == "image-to-video" + assert body["spec"]["params"] == { + "prompt": "a drummer", + "model": "ltx-2.5-fast", + "aspectRatio": "auto", + "resolution": "1080p", + "duration": 8, + "fps": 50, + "promptProvenance": "typed", + } + assert body["spec"]["inputs"] == { + "startFrame": {"assetId": start["id"]}, + "endFrame": {"assetId": end["id"]}, + } + _assert_remote_asset_payload(start) + _assert_remote_asset_payload(fetched_start.json()) + _assert_no_path_keys(body) + + +def test_remote_create_a2v_keeps_audio_asset_id_and_omits_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + store = _store(test_state) + audio = store.ingest_upload(str(_wav(tmp_path / "line.wav"))) + start = store.ingest_upload(str(_png(tmp_path / "start.png"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/audio-to-video", + headers=AUTH, + json={ + "params": { + "prompt": "the character speaks", + "model": "ltx-2.5-fast", + "aspectRatio": "16:9", + "resolution": "540p", + "fps": 24, + }, + "inputs": { + "audio": {"assetId": audio.id}, + "startFrame": {"assetId": start.id}, + }, + }, + ) + assert created.status_code == 200, created.text + body = created.json() + generation_id = body["id"] + listed = client.get( + "/api/generations", + params={"feature": "audio-to-video"}, + headers=AUTH, + ) + fetched = client.get(f"/api/generations/{generation_id}", headers=AUTH) + + assert body["feature"] == "audio-to-video" + assert body["status"] == "queued" + assert body["spec"]["inputs"] == { + "audio": {"assetId": audio.id}, + "startFrame": {"assetId": start.id}, + } + params = body["spec"]["params"] + assert set(params) <= _APPROVED_PARAM_KEYS + assert params["numFrames"] == 185 + assert params["fps"] == 24 + assert "duration" not in params + assert audio.path not in json.dumps(body) + assert start.path not in json.dumps(body) + _assert_no_path_keys(body) + _assert_no_secret_paths(body) + assert listed.status_code == 200 + assert listed.json()[0]["id"] == generation_id + assert listed.json()[0]["spec"]["inputs"]["audio"]["assetId"] == audio.id + _assert_no_path_keys(listed.json()) + assert fetched.status_code == 200 + assert fetched.json()["spec"]["inputs"]["audio"]["assetId"] == audio.id + _assert_no_path_keys(fetched.json()) + + claimed = store.claim_next_queued() + assert claimed is not None + store.mark_failed( + generation_id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count + ) + with TestClient(app) as client: + retried = client.post( + f"/api/generations/{generation_id}/retry", headers=AUTH + ) + deleted = client.delete( + f"/api/generations/{generation_id}", headers=AUTH + ) + missing = client.get(f"/api/generations/{generation_id}", headers=AUTH) + + assert retried.status_code == 200, retried.text + assert retried.json()["id"] == generation_id + assert retried.json()["status"] == "queued" + assert retried.json()["feature"] == "audio-to-video" + _assert_no_path_keys(retried.json()) + assert deleted.status_code == 200 + assert deleted.json() == {"status": "ok"} + assert_http_error(missing, status_code=404, code="GENERATION_NOT_FOUND") + assert store.get_generation(generation_id) is None + + audio_only = store.insert_generation( + "audio-to-video", + { + "params": {"prompt": "speak"}, + "inputs": {"audio": {"assetId": audio.id, "path": audio.path}}, + }, + ) + with TestClient(app) as client: + projected = client.get(f"/api/generations/{audio_only.id}", headers=AUTH) + assert projected.status_code == 200, projected.text + assert projected.json()["spec"]["inputs"] == {"audio": {"assetId": audio.id}} + assert audio.path not in json.dumps(projected.json()) + _assert_no_path_keys(projected.json()) + + +def test_remote_create_retake_rejects_selection_over_cap( + test_state, tmp_path: Path +) -> None: + video = _store(test_state).ingest_upload(str(_mp4(tmp_path / "clip.mp4"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/retake", + headers=AUTH, + json={ + "params": { + "model": "ltx-2.5-fast", + "startTime": 0, + "duration": 10.5, + }, + "inputs": {"video": {"assetId": video.id}}, + }, + ) + assert created.status_code == 422 + assert _store(test_state).list_generations("retake") == [] + + +def test_remote_create_retake_keeps_video_asset_id_and_omits_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + store = _store(test_state) + video = store.ingest_upload(str(_mp4(tmp_path / "clip.mp4"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/retake", + headers=AUTH, + json={ + "params": { + "prompt": "the character turns", + "model": "ltx-2.5-fast", + "startTime": 0, + "duration": 2, + "mode": "replace_video", + }, + "inputs": {"video": {"assetId": video.id}}, + }, + ) + assert created.status_code == 200, created.text + body = created.json() + generation_id = body["id"] + listed = client.get( + "/api/generations", + params={"feature": "retake"}, + headers=AUTH, + ) + fetched = client.get(f"/api/generations/{generation_id}", headers=AUTH) + + assert body["feature"] == "retake" + assert body["status"] == "queued" + assert body["spec"]["inputs"] == {"video": {"assetId": video.id}} + params = body["spec"]["params"] + assert set(params) <= _APPROVED_PARAM_KEYS + assert params["model"] == "ltx-2.5-fast" + assert params["startTime"] == 0 + assert params["duration"] == 2 + assert params["mode"] == "replace_video" + assert video.path not in json.dumps(body) + _assert_no_path_keys(body) + _assert_no_secret_paths(body) + assert listed.status_code == 200 + assert listed.json()[0]["id"] == generation_id + assert listed.json()[0]["spec"]["inputs"]["video"]["assetId"] == video.id + _assert_no_path_keys(listed.json()) + assert fetched.status_code == 200 + assert fetched.json()["spec"]["inputs"]["video"]["assetId"] == video.id + _assert_no_path_keys(fetched.json()) + + leaked = store.insert_generation( + "retake", + { + "params": {"prompt": "turn", "model": "ltx-2.5-fast"}, + "inputs": {"video": {"assetId": video.id, "path": video.path}}, + }, + ) + with TestClient(app) as client: + projected = client.get(f"/api/generations/{leaked.id}", headers=AUTH) + assert projected.status_code == 200, projected.text + assert projected.json()["spec"]["inputs"] == {"video": {"assetId": video.id}} + assert video.path not in json.dumps(projected.json()) + _assert_no_path_keys(projected.json()) + + +def test_remote_create_extend_keeps_video_asset_id_and_omits_paths( + test_state, create_fake_model_files, tmp_path: Path +) -> None: + create_fake_model_files() + store = _store(test_state) + video = store.ingest_upload(str(_mp4(tmp_path / "clip.mp4"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + created = client.post( + "/api/generations/extend", + headers=AUTH, + json={ + "params": { + "prompt": "the scene continues", + "model": "ltx-2.5-fast", + "duration": 4, + "mode": "start", + }, + "inputs": {"video": {"assetId": video.id}}, + }, + ) + assert created.status_code == 200, created.text + body = created.json() + generation_id = body["id"] + listed = client.get( + "/api/generations", + params={"feature": "extend"}, + headers=AUTH, + ) + fetched = client.get(f"/api/generations/{generation_id}", headers=AUTH) + + assert body["feature"] == "extend" + assert body["status"] == "queued" + assert body["spec"]["inputs"] == {"video": {"assetId": video.id}} + params = body["spec"]["params"] + assert set(params) <= _APPROVED_PARAM_KEYS + assert params["model"] == "ltx-2.5-fast" + assert params["duration"] == 4 + assert params["mode"] == "start" + assert video.path not in json.dumps(body) + _assert_no_path_keys(body) + _assert_no_secret_paths(body) + assert listed.status_code == 200 + assert listed.json()[0]["id"] == generation_id + assert listed.json()[0]["spec"]["inputs"]["video"]["assetId"] == video.id + _assert_no_path_keys(listed.json()) + assert fetched.status_code == 200 + assert fetched.json()["spec"]["inputs"]["video"]["assetId"] == video.id + _assert_no_path_keys(fetched.json()) + + leaked = store.insert_generation( + "extend", + { + "params": {"prompt": "continue", "model": "ltx-2.5-fast"}, + "inputs": {"video": {"assetId": video.id, "path": video.path}}, + }, + ) + with TestClient(app) as client: + projected = client.get(f"/api/generations/{leaked.id}", headers=AUTH) + assert projected.status_code == 200, projected.text + assert projected.json()["spec"]["inputs"] == {"video": {"assetId": video.id}} + assert video.path not in json.dumps(projected.json()) + _assert_no_path_keys(projected.json()) + + +def test_remote_projects_an_integer_seed_and_drops_other_values(test_state) -> None: + store = _store(test_state) + seeded = store.insert_generation( + "text-to-video", + {"params": {"prompt": "fox", "model": "ltx-2.5-fast", "seed": 1234}, "inputs": {}}, + ) + junk = store.insert_generation( + "text-to-video", + {"params": {"prompt": "fox", "seed": "/Users/me/secret"}, "inputs": {}}, + ) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + seeded_body = client.get(f"/api/generations/{seeded.id}", headers=AUTH).json() + junk_body = client.get(f"/api/generations/{junk.id}", headers=AUTH).json() + + assert seeded_body["spec"]["params"]["seed"] == 1234 + assert "seed" not in junk_body["spec"]["params"] + _assert_no_secret_paths(junk_body) + + +def test_remote_get_strips_nested_path_like_spec_values( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + start = store.ingest_upload(str(_png(tmp_path / "start.png"))) + end = store.ingest_upload(str(_png(tmp_path / "end.png"))) + generation = store.insert_generation( + "image-to-video", + { + "params": { + "prompt": "a drummer", + "model": "fast-2.5", + "aspectRatio": "auto", + "resolution": "720p", + "duration": 8, + "fps": 24, + "imagePath": "/Users/me/secret.png", + "nested": {"path": "/tmp/nested.mp4"}, + "loras": [ + { + "ref": "/models/secret.safetensors", + "scale": 0.8, + "catalogId": "cat-1", + } + ], + "cameraMotion": "dolly_in", + }, + "inputs": { + "startFrame": { + "assetId": start.id, + "path": "/Users/me/start.png", + }, + "endFrame": {"assetId": end.id}, + "imagePath": "/Users/me/input.png", + "extra": {"path": "/etc/passwd"}, + }, + }, + ) + + remote = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(remote) as client: + fetched = client.get(f"/api/generations/{generation.id}", headers=AUTH) + listed = client.get( + "/api/generations", + params={"feature": "image-to-video"}, + headers=AUTH, + ) + cancelled = client.post( + f"/api/generations/{generation.id}/cancel", headers=AUTH + ) + + assert fetched.status_code == 200 + body = fetched.json() + assert body["spec"]["params"] == { + "prompt": "a drummer", + "model": "fast-2.5", + "aspectRatio": "auto", + "resolution": "720p", + "duration": 8, + "fps": 24, + "scale": 0.8, + } + assert body["spec"]["inputs"] == { + "startFrame": {"assetId": start.id}, + "endFrame": {"assetId": end.id}, + } + _assert_no_secret_paths(body) + _assert_no_path_keys(body) + assert listed.status_code == 200 + _assert_no_secret_paths(listed.json()) + assert cancelled.status_code == 200 + _assert_no_secret_paths(cancelled.json()) + assert cancelled.json()["status"] == "cancelled" + + assert test_state.generation.try_reserve_generation_start() is True + try: + desktop = create_app(handler=test_state) + with TestClient(desktop) as client: + desktop_body = client.get(f"/api/generations/{generation.id}").json() + desktop_params = desktop_body["spec"]["params"] + assert desktop_params["imagePath"] == "/Users/me/secret.png" + assert desktop_params["loras"][0]["ref"] == "/models/secret.safetensors" + assert desktop_body["spec"]["inputs"]["extra"]["path"] == "/etc/passwd" + finally: + test_state.generation.release_generation_start_reservation() + + +def test_remote_generation_outputs_omit_paths_and_bytes_still_work( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + created = store.insert_generation("text-to-video", _spec("output")) + claimed = store.claim_next_queued() + assert claimed is not None + asset_id, dest = store.allocate_output_path("image", "image/png") + png_path = Path(dest) + Image.new("RGB", (8, 8), color=(4, 5, 6)).save(png_path) + png_bytes = png_path.read_bytes() + store.mark_succeeded( + created.id, + [ + OutputSpec( + asset_id=asset_id, + dest_path=dest, + ordinal=0, + mime_type="image/png", + name="out.png", + ) + ], + attempt_count=claimed.attempt_count, + ) + + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + fetched = client.get(f"/api/generations/{created.id}", headers=AUTH) + assert fetched.status_code == 200 + body = fetched.json() + assert body["status"] == "succeeded" + assert len(body["outputs"]) == 1 + output = _assert_remote_asset_payload(body["outputs"][0]) + output_id = output["id"] + assert isinstance(output_id, str) + bytes_response = client.get(str(output["bytes_url"])) + asset_json = client.get(f"/api/assets/{output_id}", headers=AUTH) + + _assert_no_path_keys(body) + assert bytes_response.status_code == 200 + assert bytes_response.content == png_bytes + _assert_remote_asset_payload(asset_json.json()) + + +def test_desktop_asset_and_generation_keep_filesystem_paths( + test_state, tmp_path: Path +) -> None: + source = _png(tmp_path / "desktop.png") + assert test_state.generation.try_reserve_generation_start() is True + try: + app = create_app(handler=test_state) + with TestClient(app) as client: + ingested = client.post("/api/assets", json={"path": str(source)}) + assert ingested.status_code == 200 + asset = ingested.json() + assert Path(asset["path"]).is_file() + assert "thumbnail_path" in asset + created = client.post( + "/api/generations/text-to-video", + json={"params": {"prompt": "desktop fox", "model": "ltx-2.5-fast"}}, + ) + assert created.status_code == 200 + generation = created.json() + assert generation["spec"]["params"]["prompt"] == "desktop fox" + assert "loras" in generation["spec"]["params"] + fetched_asset = client.get(f"/api/assets/{asset['id']}") + assert fetched_asset.status_code == 200 + assert Path(fetched_asset.json()["path"]).is_file() + finally: + test_state.generation.release_generation_start_reservation() diff --git a/backend/tests/test_remote_media_urls.py b/backend/tests/test_remote_media_urls.py new file mode 100644 index 000000000..ba1938df0 --- /dev/null +++ b/backend/tests/test_remote_media_urls.py @@ -0,0 +1,81 @@ +from __future__ import annotations + +from pathlib import Path +from urllib.parse import parse_qs, urlsplit + +from remote.media_urls import MediaUrlSigner, bucket_exp, load_or_create_media_secret + + +def test_sign_and_verify_round_trip() -> None: + signer = MediaUrlSigner(b"s" * 32) + url = signer.bytes_url("asset-1", "dev-1") + parts = urlsplit(url) + assert parts.path == "/api/assets/asset-1/bytes" + device_id = signer.verify(parts.path, parts.query, asset_id="asset-1") + assert device_id == "dev-1" + + +def test_head_and_get_share_the_same_signature() -> None: + signer = MediaUrlSigner(b"s" * 32) + url = signer.bytes_url("asset-1", "dev-1") + parts = urlsplit(url) + assert signer.verify(parts.path, parts.query, asset_id="asset-1") == "dev-1" + + +def test_verify_rejects_expired_tampered_and_wrong_asset() -> None: + signer = MediaUrlSigner(b"s" * 32) + exp = bucket_exp(1_700_000_000) + url = signer.sign( + "/api/assets/asset-1/bytes", + asset_id="asset-1", + device_id="dev-1", + exp=exp, + ) + parts = urlsplit(url) + assert ( + signer.verify( + parts.path, + parts.query, + asset_id="asset-1", + now_s=exp - 1, + ) + == "dev-1" + ) + assert ( + signer.verify(parts.path, parts.query, asset_id="asset-1", now_s=exp) + is None + ) + assert signer.verify(parts.path, parts.query, asset_id="asset-2") is None + tampered = parts.query.replace("did=dev-1", "did=dev-2") + assert signer.verify(parts.path, tampered, asset_id="asset-1") is None + assert signer.verify(parts.path, "", asset_id="asset-1") is None + + +def test_same_bucket_is_stable() -> None: + signer = MediaUrlSigner(b"s" * 32) + exp = bucket_exp(1_700_000_100) + first = signer.sign( + "/api/assets/a/bytes", asset_id="a", device_id="d", exp=exp + ) + second = signer.sign( + "/api/assets/a/bytes", asset_id="a", device_id="d", exp=exp + ) + assert first == second + params = parse_qs(urlsplit(first).query) + assert params["exp"] == [str(exp)] + + +def test_bucket_exp_stays_stable_and_covers_a_full_ttl() -> None: + start = (1_700_000_000 // 300) * 300 + first = bucket_exp(start) + assert bucket_exp(start + 299) == first + assert bucket_exp(start + 300) != first + assert first - start >= 300 + assert bucket_exp(start + 299) - (start + 299) >= 300 + + +def test_load_or_create_media_secret_persists(tmp_path: Path) -> None: + first = load_or_create_media_secret(tmp_path) + second = load_or_create_media_secret(tmp_path) + assert first == second + assert len(first) == 32 diff --git a/backend/tests/test_remote_net.py b/backend/tests/test_remote_net.py new file mode 100644 index 000000000..4686ad304 --- /dev/null +++ b/backend/tests/test_remote_net.py @@ -0,0 +1,87 @@ +from remote.net import ( + advertised_lan_urls, + attach_token, + bound_server_port, + client_url, + origin_url, + remote_port, +) +from runtime_config.port_constant import REMOTE_PORT + + +def test_client_url_puts_grant_in_the_pairing_query() -> None: + assert client_url("192.168.1.9", 41955, "abc") == "http://192.168.1.9:41955/pairing?t=abc" + + +def test_https_default_port_omits_the_port() -> None: + assert ( + client_url("studio.example.ts.net", 443, "abc", scheme="https") + == "https://studio.example.ts.net/pairing?t=abc" + ) + + +def test_origin_url_strips_the_pairing_token() -> None: + assert origin_url("http://192.168.1.9:41955/pairing?t=secret") == "http://192.168.1.9:41955/pairing" + assert origin_url("http://127.0.0.1:41955/#t=secret") == "http://127.0.0.1:41955/" + + +def test_attach_token_keeps_an_existing_path() -> None: + assert ( + attach_token("http://192.168.1.9:41955/assets", "secret") + == "http://192.168.1.9:41955/assets?t=secret" + ) + + +def test_attach_token_preserves_existing_query() -> None: + assert ( + attach_token("http://192.168.1.9:41955/assets?foo=1", "secret") + == "http://192.168.1.9:41955/assets?foo=1&t=secret" + ) + + +def test_attach_token_overwrites_an_existing_t() -> None: + assert ( + attach_token("http://192.168.1.9:41955/pairing?t=old", "new") + == "http://192.168.1.9:41955/pairing?t=new" + ) + + +def test_remote_port_falls_back_to_constant(monkeypatch) -> None: + monkeypatch.delenv("LTX_REMOTE_PORT", raising=False) + assert remote_port() == REMOTE_PORT + monkeypatch.setenv("LTX_REMOTE_PORT", "not-a-port") + assert remote_port() == REMOTE_PORT + monkeypatch.setenv("LTX_REMOTE_PORT", "47001") + assert remote_port() == 47001 + monkeypatch.setenv("LTX_REMOTE_PORT", "0") + assert remote_port() == 0 + + +class _Sock: + def __init__(self, port: int) -> None: + self._port = port + + def getsockname(self) -> tuple[str, int]: + return ("0.0.0.0", self._port) + + +class _AsyncioServer: + def __init__(self, port: int) -> None: + self.sockets = [_Sock(port)] + + +class _UvicornServer: + def __init__(self, port: int) -> None: + self.servers = [_AsyncioServer(port)] + + +def test_bound_server_port_reads_uvicorn_socket() -> None: + assert bound_server_port(_UvicornServer(49259), 0) == 49259 + assert bound_server_port(object(), 41955) == 41955 + + +def test_advertised_lan_urls_include_query_grant(monkeypatch) -> None: + monkeypatch.setattr("remote.net.lan_ip", lambda: "192.168.1.9") + lan, local = advertised_lan_urls(41955, "secret") + assert lan == "http://192.168.1.9:41955/pairing?t=secret" + assert local == "http://127.0.0.1:41955/pairing?t=secret" diff --git a/backend/tests/test_remote_pairing.py b/backend/tests/test_remote_pairing.py new file mode 100644 index 000000000..d253e074b --- /dev/null +++ b/backend/tests/test_remote_pairing.py @@ -0,0 +1,305 @@ +from __future__ import annotations + +import pytest + +from remote.pairing import ( + PairingError, + RemotePairing, + _MAX_USER_AGENT_LEN, + _public_ip, + _public_user_agent, + device_name_from_user_agent, + hash_session_token, +) +from services.records import PairedDeviceRecord, UnavailableError + + +def test_device_name_from_user_agent_summarizes_browser_and_device() -> None: + assert device_name_from_user_agent(None) == "Paired device" + assert device_name_from_user_agent("Phone UA") == "Phone UA" + chrome_mac = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + ) + safari_iphone = ( + "Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 " + "(KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1" + ) + assert device_name_from_user_agent(chrome_mac) == "Chrome on Mac" + assert device_name_from_user_agent(safari_iphone) == "Safari on iPhone" + + +def test_list_public_devices_includes_ip() -> None: + pairing = RemotePairing.for_known_session("seed") + pairing.exchange(pairing.current_grant(), ip="192.168.1.4", user_agent="Phone") + listed = [item for item in pairing.list_public_devices() if item.ip == "192.168.1.4"] + assert len(listed) == 1 + + +def test_list_public_devices_uses_full_user_agent_for_display_name() -> None: + pairing = RemotePairing.for_known_session("seed") + chrome_mac = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + ) + pairing.exchange(pairing.current_grant(), ip="10.0.0.9", user_agent=chrome_mac) + match = next(item for item in pairing.list_public_devices() if item.ip == "10.0.0.9") + assert match.name == "Chrome on Mac" + + +def test_authenticate_backfills_ip_and_browser_label() -> None: + pairing = RemotePairing.for_known_session("seed") + chrome_mac = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + ) + pairing.authenticate_bearer("seed", ip="10.0.0.4", user_agent=chrome_mac) + listed = next(item for item in pairing.list_public_devices() if item.name == "Chrome on Mac") + assert listed.ip == "10.0.0.4" + + +def test_public_ip_accepts_addresses_and_rejects_junk() -> None: + assert _public_ip(" 10.0.0.4 ") == "10.0.0.4" + assert _public_ip("::1") == "::1" + assert _public_ip("[::1]") == "::1" + assert _public_ip(None) is None + assert _public_ip("") is None + assert _public_ip("unknown") is None + assert _public_ip("UNKNOWN") is None + assert _public_ip("testclient") is None + assert _public_ip("not an ip") is None + + +def test_public_user_agent_strips_and_caps() -> None: + assert _public_user_agent(None) is None + assert _public_user_agent(" \n ") is None + assert _public_user_agent("Phone UA") == "Phone UA" + assert _public_user_agent("x" * 800) == "x" * _MAX_USER_AGENT_LEN + + +def test_unknown_first_seen_ip_is_replaced_on_backfill() -> None: + pairing = RemotePairing.for_known_session("seed") + pairing._store.insert_paired_device( + PairedDeviceRecord( + id="legacy", + name="Old phone", + token_hash=hash_session_token("legacy"), + created_at=1, + last_seen_at=1, + first_seen_ip="unknown", + ) + ) + pairing.authenticate_bearer("legacy", ip="10.0.0.4", user_agent="Phone") + listed = next(item for item in pairing.list_public_devices() if item.id == "legacy") + assert listed.ip == "10.0.0.4" + + +def test_exchange_reuses_session_and_backfills_missing_ip() -> None: + pairing = RemotePairing.for_known_session("seed") + chrome_mac = ( + "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 " + "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36" + ) + first = pairing.exchange(pairing.current_grant(), ip="unknown", user_agent=None) + assert next(item for item in pairing.list_public_devices() if item.id == first.device_id).ip is None + second = pairing.exchange( + pairing.current_grant(), + ip="10.0.0.4", + user_agent=chrome_mac, + existing_token=first.token, + ) + assert second.device_id == first.device_id + listed = next(item for item in pairing.list_public_devices() if item.id == first.device_id) + assert listed.ip == "10.0.0.4" + assert listed.name == "Chrome on Mac" + + +def test_exchange_caps_stored_user_agent() -> None: + pairing = RemotePairing.for_known_session("seed") + pairing.exchange(pairing.current_grant(), ip="10.0.0.9", user_agent="x" * 800) + stored = next( + item for item in pairing._store.list_paired_devices() if item.first_seen_user_agent + ) + assert stored.first_seen_user_agent == "x" * _MAX_USER_AGENT_LEN + + +def test_exchange_consumes_grant_and_authenticates_bearer() -> None: + pairing = RemotePairing.for_known_session("seed") + grant = pairing.current_grant() + exchanged = pairing.exchange(grant, ip="192.168.1.4", user_agent="Phone UA") + assert exchanged.token != "seed" + assert exchanged.name == "Phone UA" + with pytest.raises(PairingError) as raised: + pairing.exchange(grant, ip="192.168.1.4", user_agent="Phone UA") + assert raised.value.status_code == 401 + assert pairing.authenticate_bearer(exchanged.token) is not None + assert pairing.authenticate_bearer(exchanged.token).id == exchanged.device_id + assert pairing.authenticate_bearer("seed") is not None + + +def test_exchange_rotates_grant_for_a_second_device() -> None: + pairing = RemotePairing.for_known_session("seed") + first = pairing.exchange(pairing.current_grant(), ip="10.0.0.2", user_agent="A") + second = pairing.exchange(pairing.current_grant(), ip="10.0.0.3", user_agent="B") + assert first.device_id != second.device_id + assert pairing.authenticate_bearer(first.token) is not None + assert pairing.authenticate_bearer(second.token) is not None + + +def test_exchange_with_existing_session_reuses_same_device() -> None: + pairing = RemotePairing.for_known_session("seed") + first = pairing.exchange(pairing.current_grant(), ip="10.0.0.2", user_agent="Phone") + second = pairing.exchange( + pairing.current_grant(), + ip="10.0.0.4", + user_agent="Phone v2", + existing_token=first.token, + ) + assert second.device_id == first.device_id + assert second.token == first.token + assert second.name == "Phone" + authed = pairing.authenticate_bearer(first.token) + assert authed is not None + assert authed.id == first.device_id + active_ids = [item.id for item in pairing.list_public_devices() if item.revoked_at is None] + assert active_ids.count(first.device_id) == 1 + assert len(active_ids) == 2 + + +def test_exchange_does_not_insert_when_session_lookup_fails() -> None: + pairing = RemotePairing.for_known_session("seed") + first = pairing.exchange(pairing.current_grant(), ip="10.0.0.2", user_agent="Phone") + before = [item.id for item in pairing.list_public_devices()] + store = pairing._store + original = store.get_paired_device_by_token_hash + + def boom(_token_hash: str): + raise UnavailableError() + + store.get_paired_device_by_token_hash = boom # type: ignore[method-assign] + grant = pairing.current_grant() + try: + with pytest.raises(PairingError) as raised: + pairing.exchange( + grant, + ip="10.0.0.2", + user_agent="Phone", + existing_token=first.token, + ) + assert raised.value.status_code == 503 + assert raised.value.code == "STORE_UNAVAILABLE" + finally: + store.get_paired_device_by_token_hash = original # type: ignore[method-assign] + assert [item.id for item in pairing.list_public_devices()] == before + + +def test_exchange_ignores_revoked_session_and_inserts() -> None: + pairing = RemotePairing.for_known_session("seed") + first = pairing.exchange(pairing.current_grant(), ip="10.0.0.2", user_agent="Phone") + assert pairing.revoke(first.device_id) is True + second = pairing.exchange( + pairing.current_grant(), + ip="10.0.0.2", + user_agent="Phone", + existing_token=first.token, + ) + assert second.device_id != first.device_id + assert pairing.authenticate_bearer(first.token) is None + assert pairing.authenticate_bearer(second.token) is not None + + +def test_revoke_rejects_bearer_and_media() -> None: + pairing = RemotePairing.for_known_session("seed") + device = pairing.authenticate_bearer("seed") + assert device is not None + url = pairing.signer.bytes_url("asset-1", device.id) + path, _, query = url.partition("?") + assert pairing.authenticate_media(path, query, asset_id="asset-1") is not None + assert pairing.revoke(device.id) is True + assert pairing.authenticate_bearer("seed") is None + assert pairing.authenticate_media(path, query, asset_id="asset-1") is None + + +def test_rate_limit_lockout_on_failed_exchange() -> None: + pairing = RemotePairing.for_known_session("seed") + for _ in range(8): + with pytest.raises(PairingError) as raised: + pairing.exchange("nope", ip="192.168.0.9", user_agent=None) + assert raised.value.status_code == 401 + with pytest.raises(PairingError) as raised: + pairing.exchange("nope", ip="192.168.0.9", user_agent=None) + assert raised.value.status_code == 429 + pairing.exchange(pairing.current_grant(), ip="10.0.0.8", user_agent=None) + + +def test_bearer_auth_store_outage_is_unavailable() -> None: + pairing = RemotePairing.for_known_session("seed") + + def boom(_token: str): + raise UnavailableError() + + pairing._lookup_active_session = boom # type: ignore[method-assign] + with pytest.raises(PairingError) as raised: + pairing.authenticate_bearer("seed") + assert raised.value.status_code == 503 + assert raised.value.code == "STORE_UNAVAILABLE" + assert pairing.list_public_devices()[0].name == "Test device" + + +def test_list_and_revoke_store_outage_raises() -> None: + pairing = RemotePairing.for_known_session("seed") + + def boom_list(): + raise UnavailableError() + + def boom_revoke(_device_id: str, *, now_ms: int): + raise UnavailableError() + + pairing._store.list_paired_devices = boom_list # type: ignore[method-assign] + with pytest.raises(UnavailableError): + pairing.list_public_devices() + pairing._store.revoke_paired_device = boom_revoke # type: ignore[method-assign] + with pytest.raises(UnavailableError): + pairing.revoke("any") + + +def test_media_auth_store_outage_is_unavailable() -> None: + pairing = RemotePairing.for_known_session("seed") + device = pairing.authenticate_bearer("seed") + assert device is not None + url = pairing.signer.bytes_url("asset-1", device.id) + path, _, query = url.partition("?") + + def boom(_device_id: str): + raise UnavailableError() + + pairing._store.get_paired_device = boom # type: ignore[method-assign] + with pytest.raises(PairingError) as raised: + pairing.authenticate_media(path, query, asset_id="asset-1") + assert raised.value.status_code == 503 + assert raised.value.code == "STORE_UNAVAILABLE" + + +def test_bearer_auth_throttles_last_seen_writes(monkeypatch: pytest.MonkeyPatch) -> None: + clock = {"ms": 1_000_000} + monkeypatch.setattr("remote.pairing._now_ms", lambda: clock["ms"]) + pairing = RemotePairing.for_known_session("seed") + assert pairing.authenticate_bearer("seed") is not None + assert pairing.list_public_devices()[0].last_seen_at == 1_000_000 + clock["ms"] = 1_000_000 + 59_999 + pairing.authenticate_bearer("seed") + assert pairing.list_public_devices()[0].last_seen_at == 1_000_000 + clock["ms"] = 1_000_000 + 60_000 + pairing.authenticate_bearer("seed") + assert pairing.list_public_devices()[0].last_seen_at == 1_060_000 + + +def test_session_hash_is_lookup_key() -> None: + pairing = RemotePairing.for_known_session("seed") + listed = pairing.list_public_devices() + assert listed[0].name == "Test device" + assert hash_session_token("seed") != "seed" + assert all( + "token" not in item.model_dump() and "mac_key" not in item.model_dump() + for item in listed + ) diff --git a/backend/tests/test_remote_prompt_enhancement.py b/backend/tests/test_remote_prompt_enhancement.py new file mode 100644 index 000000000..082a62d9e --- /dev/null +++ b/backend/tests/test_remote_prompt_enhancement.py @@ -0,0 +1,241 @@ +"""Remote Explore Enhance: status + /api/enhance-prompt without filesystem paths.""" + +from __future__ import annotations + +from pathlib import Path + +from PIL import Image +from starlette.testclient import TestClient + +from remote.app import create_remote_app +from tests.fakes import FakeResponse +from tests.http_error_assertions import assert_http_error + +AUTH = {"Authorization": "Bearer pair-token"} +_LOCAL_ENHANCER_MODEL_ID = "ltx-2.3-22b-distilled-1.1" + + +def _gemini_ok(text: str = "enhanced via gemini") -> FakeResponse: + return FakeResponse( + status_code=200, + json_payload={"candidates": [{"content": {"parts": [{"text": text}]}}]}, + ) + + +def _png_bytes(tmp_path: Path) -> bytes: + path = tmp_path / "frame.png" + Image.new("RGB", (32, 24), color=(10, 20, 30)).save(path) + return path.read_bytes() + + +def test_prompt_enhancer_requires_auth(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + assert client.get("/api/prompt-enhancer").status_code == 401 + assert client.post("/api/enhance-prompt", json={"prompt": "a cat"}).status_code == 401 + + +def test_remote_status_prefers_gemini_when_key_is_set(test_state) -> None: + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.state.app_settings.explore_auto_enhance_prompts = True + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.get("/api/prompt-enhancer", headers=AUTH) + assert r.status_code == 200 + body = r.json() + assert body["hasGeminiApiKey"] is True + assert body["defaultProvider"] == "api" + assert body["showManualEnhance"] is False + assert body["exploreAutoEnhancePrompts"] is True + assert "gemini_api_key" not in body + + +def test_remote_status_shows_manual_enhance_when_auto_is_off(test_state) -> None: + test_state.state.app_settings.explore_auto_enhance_prompts = False + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.get("/api/prompt-enhancer", headers=AUTH) + assert r.status_code == 200 + body = r.json() + assert body["showManualEnhance"] is True + assert body["exploreAutoEnhancePrompts"] is False + + +def test_remote_status_falls_back_to_local_without_gemini_key( + test_state, create_fake_model_files +) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + test_state.state.app_settings.gemini_api_key = "" + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.get("/api/prompt-enhancer", headers=AUTH) + assert r.status_code == 200 + body = r.json() + assert body["hasGeminiApiKey"] is False + assert body["localEnhancementSupported"] is True + assert body["defaultProvider"] == "local" + assert body["canToggleProvider"] is False + + +def test_remote_enhance_uses_gemini_when_key_is_set(test_state) -> None: + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.http.queue("post", _gemini_ok("a cat, enhanced")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "provider": "api"}, + ) + assert r.status_code == 200 + assert r.json()["enhancedPrompt"] == "a cat, enhanced" + + +def test_remote_enhance_uses_local_gemma( + test_state, fake_services, create_fake_model_files +) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long local caption" + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "provider": "local"}, + ) + assert r.status_code == 200 + assert r.json()["enhancedPrompt"] == "a long local caption" + + +def test_remote_enhance_rejects_filesystem_paths(test_state, tmp_path: Path) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "imagePath": str(tmp_path / "secret.png")}, + ) + assert r.status_code == 422 + + +def test_remote_enhance_rejects_blank_asset_ids(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + whitespace = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "imageAssetId": " "}, + ) + empty = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "imageAssetId": ""}, + ) + last_only = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "lastImageAssetId": "frame-2"}, + ) + assert whitespace.status_code == 422 + assert empty.status_code == 422 + assert last_only.status_code == 422 + + +def test_remote_enhance_resolves_image_asset_id( + test_state, tmp_path: Path +) -> None: + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.http.queue("post", _gemini_ok("a still, enhanced")) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("frame.png", _png_bytes(tmp_path), "image/png")}, + ) + assert uploaded.status_code == 200 + asset_id = uploaded.json()["id"] + assert "path" not in uploaded.json() or uploaded.json().get("path") in ("", None) + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={ + "prompt": "walk in", + "provider": "api", + "imageAssetId": asset_id, + }, + ) + assert r.status_code == 200 + assert r.json()["enhancedPrompt"] == "a still, enhanced" + + +def test_full_settings_stay_off_remote(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + settings_get = client.get("/api/settings", headers=AUTH) + settings_post = client.post( + "/api/settings", + headers=AUTH, + json={"remoteExposure": "lan"}, + ) + assert settings_get.status_code == 404 + assert settings_post.status_code == 404 + + +def test_missing_gemini_key_is_rejected_on_api_provider(test_state) -> None: + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat", "provider": "api"}, + ) + assert_http_error(r, status_code=400, code="GEMINI_API_KEY_MISSING") + + +def test_omitted_provider_uses_status_default( + test_state, fake_services, create_fake_model_files +) -> None: + create_fake_model_files(model_id=_LOCAL_ENHANCER_MODEL_ID) + fake_services.prompt_enhancer_pipeline.enhanced_prompt = "a long local caption" + test_state.state.app_settings.gemini_api_key = "" + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={"prompt": "a cat"}, + ) + assert r.status_code == 200 + assert r.json()["enhancedPrompt"] == "a long local caption" + + +def test_remote_enhance_does_not_leak_path_when_image_is_invalid( + test_state, tmp_path: Path +) -> None: + test_state.state.app_settings.gemini_api_key = "gemini-key" + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + uploaded = client.post( + "/api/assets/upload", + headers=AUTH, + files={"file": ("frame.png", _png_bytes(tmp_path), "image/png")}, + ) + assert uploaded.status_code == 200 + asset_id = uploaded.json()["id"] + asset_path = Path(test_state.assets.get_asset(asset_id).path) + asset_path.write_bytes(b"not-an-image") + r = client.post( + "/api/enhance-prompt", + headers=AUTH, + json={ + "prompt": "walk in", + "provider": "api", + "imageAssetId": asset_id, + }, + ) + assert_http_error(r, status_code=400, code="ASSET_UNAVAILABLE") + body = r.json() + assert str(asset_path) not in body["message"] + assert "/" not in body["message"] + assert "\\" not in body["message"] diff --git a/backend/tests/test_remote_upload_body_limit.py b/backend/tests/test_remote_upload_body_limit.py new file mode 100644 index 000000000..c58254da7 --- /dev/null +++ b/backend/tests/test_remote_upload_body_limit.py @@ -0,0 +1,287 @@ +"""Remote upload body limit: bounded ASGI bytes before multipart parsing.""" + +from __future__ import annotations + +import asyncio +import json +import tempfile +import wave +from pathlib import Path +from typing import Any + +import _routes.assets as assets_module +from _routes.assets import _MULTIPART_OVERHEAD_BYTES, _UPLOAD_TEMP_PREFIX +from remote.app import create_remote_app +from services.media_probe import MAX_AUDIO_BYTES, MAX_IMAGE_BYTES, MAX_VIDEO_BYTES +from starlette.testclient import TestClient +from tests.http_error_assertions import assert_http_error + +AUTH = {"Authorization": "Bearer pair-token"} + + +def _wav_bytes(path: Path, *, duration_seconds: float = 1.0) -> bytes: + frame_count = max(1, int(duration_seconds * 8000)) + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(8000) + wav_file.writeframes(b"\x00\x00" * frame_count) + return path.read_bytes() + + +def _png_bytes(path: Path) -> bytes: + from PIL import Image + + Image.new("RGB", (32, 24), color=(10, 20, 30)).save(path) + return path.read_bytes() + + +def _persistent_asset_files(test_state: Any) -> list[Path]: + assets_dir = test_state.config.app_data_dir / "assets" + if not assets_dir.exists(): + return [] + return sorted(p for p in assets_dir.rglob("*") if p.is_file()) + + +def _upload_temp_files() -> list[Path]: + return sorted(Path(tempfile.gettempdir()).glob(f"{_UPLOAD_TEMP_PREFIX}*")) + + +def _assert_no_leaked_upload_files(test_state: Any) -> None: + assert _persistent_asset_files(test_state) == [] + assert _upload_temp_files() == [] + + +def _multipart_body(payload: bytes, filename: str, mime: str, boundary: str) -> bytes: + head = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="file"; filename="{filename}"\r\n' + f"Content-Type: {mime}\r\n\r\n" + ).encode() + tail = f"\r\n--{boundary}--\r\n".encode() + return head + payload + tail + + +def _call_remote_upload_asgi( + app: Any, + *, + body: bytes, + boundary: str, + content_length: bytes | None, + chunk_size: int | None = None, + with_auth: bool = True, +) -> tuple[int, bytes]: + headers: list[tuple[bytes, bytes]] = [ + (b"host", b"testserver"), + ( + b"content-type", + f"multipart/form-data; boundary={boundary}".encode(), + ), + ] + if with_auth: + headers.append((b"authorization", b"Bearer pair-token")) + if content_length is not None: + headers.append((b"content-length", content_length)) + if chunk_size is None: + chunks = [body] + else: + chunks = [body[i : i + chunk_size] for i in range(0, len(body), chunk_size)] or [b""] + + async def _run() -> tuple[int, bytes]: + pending = list(chunks) + + async def receive() -> dict[str, Any]: + if pending: + chunk = pending.pop(0) + return { + "type": "http.request", + "body": chunk, + "more_body": bool(pending), + } + return {"type": "http.request", "body": b"", "more_body": False} + + messages: list[dict[str, Any]] = [] + + async def send(message: dict[str, Any]) -> None: + messages.append(message) + + scope: dict[str, Any] = { + "type": "http", + "http_version": "1.1", + "method": "POST", + "scheme": "http", + "path": "/api/assets/upload", + "raw_path": b"/api/assets/upload", + "query_string": b"", + "root_path": "", + "headers": headers, + "client": ("testclient", 50000), + "server": ("testserver", 80), + } + await app(scope, receive, send) + start = next(m for m in messages if m["type"] == "http.response.start") + payload = b"".join( + m.get("body", b"") for m in messages if m["type"] == "http.response.body" + ) + status = start["status"] + assert isinstance(status, int) + return status, payload + + return asyncio.run(_run()) + + +def test_upload_body_limit_derived_from_existing_constants() -> None: + assert ( + assets_module.MAX_REMOTE_UPLOAD_BODY_BYTES + == max(MAX_IMAGE_BYTES, MAX_AUDIO_BYTES, MAX_VIDEO_BYTES) + + _MULTIPART_OVERHEAD_BYTES + ) + + +def test_declared_oversize_rejected_before_multipart_parsing( + test_state: Any, tmp_path: Path, monkeypatch: Any +) -> None: + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", 4096, raising=False + ) + png = _png_bytes(tmp_path / "ok.png") + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post( + "/api/assets/upload", + headers={**AUTH, "content-length": "5000"}, + files={"file": ("ok.png", png, "image/png")}, + ) + assert_http_error(response, status_code=400, code="FILE_TOO_LARGE") + _assert_no_leaked_upload_files(test_state) + + +def test_actual_bytes_rejected_despite_lying_content_length( + test_state: Any, tmp_path: Path, monkeypatch: Any +) -> None: + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", 4096, raising=False + ) + audio = _wav_bytes(tmp_path / "input.wav", duration_seconds=1.0) + assert len(audio) > 4096 + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post( + "/api/assets/upload", + headers={**AUTH, "content-length": "10"}, + files={"file": ("input.wav", audio, "audio/wav")}, + ) + assert_http_error(response, status_code=400, code="FILE_TOO_LARGE") + _assert_no_leaked_upload_files(test_state) + + +def test_actual_bytes_without_content_length_rejected( + test_state: Any, tmp_path: Path, monkeypatch: Any +) -> None: + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", 2048, raising=False + ) + audio = _wav_bytes(tmp_path / "input.wav", duration_seconds=1.0) + boundary = "----testboundarywithoutlength" + body = _multipart_body(audio, "input.wav", "audio/wav", boundary) + assert len(body) > 2048 + app = create_remote_app(handler=test_state, remote_token="pair-token") + status, payload = _call_remote_upload_asgi( + app, body=body, boundary=boundary, content_length=None, chunk_size=1024 + ) + assert status == 400 + assert json.loads(payload.decode()) == { + "code": "FILE_TOO_LARGE", + "message": "FILE_TOO_LARGE", + } + _assert_no_leaked_upload_files(test_state) + + +def test_single_oversize_event_not_passed_through( + test_state: Any, tmp_path: Path, monkeypatch: Any +) -> None: + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", 2048, raising=False + ) + audio = _wav_bytes(tmp_path / "input.wav", duration_seconds=1.0) + boundary = "----testboundarysingleevent" + body = _multipart_body(audio, "input.wav", "audio/wav", boundary) + assert len(body) > 2048 + app = create_remote_app(handler=test_state, remote_token="pair-token") + status, payload = _call_remote_upload_asgi( + app, + body=body, + boundary=boundary, + content_length=b"10", + chunk_size=None, + ) + assert status == 400 + assert json.loads(payload.decode()) == { + "code": "FILE_TOO_LARGE", + "message": "FILE_TOO_LARGE", + } + _assert_no_leaked_upload_files(test_state) + + +def test_upload_at_limit_succeeds_and_one_byte_over_rejected( + test_state: Any, tmp_path: Path, monkeypatch: Any +) -> None: + png = _png_bytes(tmp_path / "ok.png") + boundary = "----testboundaryexactlimit" + body = _multipart_body(png, "ok.png", "image/png", boundary) + app = create_remote_app(handler=test_state, remote_token="pair-token") + + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", len(body), raising=False + ) + status_ok, payload_ok = _call_remote_upload_asgi( + app, body=body, boundary=boundary, content_length=str(len(body)).encode() + ) + assert status_ok == 200, payload_ok.decode()[:500] + asset = json.loads(payload_ok.decode()) + assert asset["media_kind"] == "image" + assert "path" not in asset + + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", len(body) - 1, raising=False + ) + status_over, payload_over = _call_remote_upload_asgi( + app, + body=body, + boundary=boundary, + content_length=str(len(body)).encode(), + chunk_size=512, + ) + assert status_over == 400 + assert json.loads(payload_over.decode()) == { + "code": "FILE_TOO_LARGE", + "message": "FILE_TOO_LARGE", + } + + +def test_body_limit_does_not_apply_to_unrelated_remote_routes( + test_state: Any, monkeypatch: Any +) -> None: + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", 16, raising=False + ) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post("/api/generations/text-to-video", headers=AUTH) + assert response.status_code == 422 + + +def test_oversize_upload_still_requires_auth( + test_state: Any, tmp_path: Path, monkeypatch: Any +) -> None: + monkeypatch.setattr( + assets_module, "MAX_REMOTE_UPLOAD_BODY_BYTES", 16, raising=False + ) + png = _png_bytes(tmp_path / "ok.png") + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + response = client.post( + "/api/assets/upload", + files={"file": ("ok.png", png, "image/png")}, + ) + assert response.status_code == 401 diff --git a/backend/tests/test_response_models.py b/backend/tests/test_response_models.py index f2250a8a2..0156a1c36 100644 --- a/backend/tests/test_response_models.py +++ b/backend/tests/test_response_models.py @@ -14,6 +14,7 @@ def test_camelcase_keys(self, client, test_state): pipeline=pipeline, is_compiled=False, ltx_model_id="ltx-2.5-22b-distilled", + loading_mode="full_models_loading", ), ) test_state.generation.start_generation("gen-1") diff --git a/backend/tests/test_retake_audio_spec.py b/backend/tests/test_retake_audio_spec.py new file mode 100644 index 000000000..1fe8d773b --- /dev/null +++ b/backend/tests/test_retake_audio_spec.py @@ -0,0 +1,75 @@ +"""Retake/extend audio modality for sources with and without a soundtrack. + +v1.4 needs the audio latent up front. A source with no audio gets a zero latent sized to the +video, and that latent must stay unfrozen and unmasked so the stage generates it freely. +""" + +from __future__ import annotations + +import torch +from ltx_core.conditioning.types.noise_mask_cond import TemporalRegionMask +from ltx_core.types import VIDEO_SCALE_FACTORS, AudioLatentShape, SpatioTemporalScaleFactors + +from services.retake_pipeline.ltx_retake_pipeline import _audio_modality_spec + +_FPS = 24.0 +# 4 latent frames at time-scale 8 is 25 pixel frames, about 1.04 s. +_VIDEO_LATENT = torch.zeros(1, 128, 4, 2, 2) +_SOURCE_AUDIO = torch.ones(1, 8, 26, 16) + + +def _spec(*, source, regenerate_audio: bool, scale_factors: SpatioTemporalScaleFactors = VIDEO_SCALE_FACTORS): + return _audio_modality_spec( + scale_factors, + source_latent=source, + video_latent=_VIDEO_LATENT, + context="ctx", + fps=_FPS, + region_start=0.25, + region_end=0.75, + regenerate_audio=regenerate_audio, + ) + + +def test_no_source_audio_is_fresh_unfrozen_and_unmasked() -> None: + for regenerate_audio in (True, False): + spec = _spec(source=None, regenerate_audio=regenerate_audio) + + assert spec.frozen is False + assert spec.conditionings == [] + assert spec.context == "ctx" + assert spec.conditioning_fps == _FPS + assert torch.count_nonzero(spec.latent) == 0 + + +def test_no_source_audio_covers_the_video_duration_using_transformer_scale() -> None: + transformer = _spec(source=None, regenerate_audio=True) + # A decoder-style 2x8x8 scale would read the same latent as a quarter of the duration. + decoder = _spec( + source=None, + regenerate_audio=True, + scale_factors=SpatioTemporalScaleFactors(time=2, height=8, width=8), + ) + + pixel_frames = (_VIDEO_LATENT.shape[2] - 1) * VIDEO_SCALE_FACTORS.time + 1 + expected = AudioLatentShape.from_duration(batch=1, duration=pixel_frames / _FPS).frames + assert transformer.latent.shape[2] == expected + assert decoder.latent.shape[2] < expected + + +def test_source_audio_kept_when_not_regenerating() -> None: + spec = _spec(source=_SOURCE_AUDIO, regenerate_audio=False) + + assert spec.frozen is True + assert spec.conditionings == [] + assert spec.latent is _SOURCE_AUDIO + + +def test_source_audio_regenerates_only_the_masked_region() -> None: + spec = _spec(source=_SOURCE_AUDIO, regenerate_audio=True) + + assert spec.frozen is False + assert spec.latent is _SOURCE_AUDIO + (mask,) = spec.conditionings + assert isinstance(mask, TemporalRegionMask) + assert (mask.start_time, mask.end_time, mask.fps) == (0.25, 0.75, _FPS) diff --git a/backend/tests/test_retake_edit_window.py b/backend/tests/test_retake_edit_window.py new file mode 100644 index 000000000..f83c0ac94 --- /dev/null +++ b/backend/tests/test_retake_edit_window.py @@ -0,0 +1,145 @@ +"""Home/Remote retake encode-window math (ltxv-api 505-frame worker cap).""" + +from __future__ import annotations + +import pytest + +from services.retake_pipeline.window import ( + MASK_DELTA_SECONDS, + MAX_INPUT_FRAMES, + RETAKE_BLEND_SECONDS, + feathered_mask_times, + window_for_retake, +) + + +def test_short_clip_keeps_the_full_source_and_splits_context() -> None: + window = window_for_retake( + source_frames=241, + mask_start_frame=96, + mask_end_frame=144, + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.encode_start_frame == 0 + assert window.encode_frames == 241 + assert window.context_before_frames == 96 + assert window.context_after_frames == 97 + assert window.mask_start_frame == 96 + assert window.mask_end_frame == 144 + assert (window.encode_frames - 1) % 8 == 0 + + +def test_long_clip_slices_505_around_the_mask() -> None: + window = window_for_retake( + source_frames=1001, + mask_start_frame=400, + mask_end_frame=496, + max_input_frames=MAX_INPUT_FRAMES, + fps=25.0, + ) + assert window.encode_frames <= MAX_INPUT_FRAMES + assert (window.encode_frames - 1) % 8 == 0 + assert window.encode_start_frame + window.encode_frames <= 1001 + assert window.mask_start_frame - window.encode_start_frame == window.context_before_frames + assert ( + window.encode_start_frame + window.encode_frames - window.mask_end_frame + == window.context_after_frames + ) + assert window.context_before_frames > 0 + assert window.context_after_frames > 0 + + +def test_mask_at_the_start_has_no_prefix_context() -> None: + window = window_for_retake( + source_frames=241, + mask_start_frame=0, + mask_end_frame=48, + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.encode_start_frame == 0 + assert window.context_before_frames == 0 + assert window.context_after_frames > 0 + + +def test_mask_larger_than_the_cap_is_rejected() -> None: + with pytest.raises(ValueError, match="too large"): + window_for_retake( + source_frames=1001, + mask_start_frame=0, + mask_end_frame=MAX_INPUT_FRAMES + 8, + max_input_frames=MAX_INPUT_FRAMES, + ) + + +def test_full_clip_longer_than_the_cap_is_rejected() -> None: + with pytest.raises(ValueError, match="too large"): + window_for_retake( + source_frames=1001, + mask_start_frame=0, + mask_end_frame=1001, + max_input_frames=MAX_INPUT_FRAMES, + ) + + +def test_exact_cap_mask_with_leftover_source_is_rejected() -> None: + with pytest.raises(ValueError, match="too large"): + window_for_retake( + source_frames=1001, + mask_start_frame=0, + mask_end_frame=MAX_INPUT_FRAMES, + max_input_frames=MAX_INPUT_FRAMES, + ) + + +def test_short_full_clip_at_the_cap_keeps_zero_context() -> None: + window = window_for_retake( + source_frames=MAX_INPUT_FRAMES, + mask_start_frame=0, + mask_end_frame=MAX_INPUT_FRAMES, + max_input_frames=MAX_INPUT_FRAMES, + ) + assert window.encode_start_frame == 0 + assert window.encode_frames == MAX_INPUT_FRAMES + assert window.context_before_frames == 0 + assert window.context_after_frames == 0 + + +def test_min_blend_does_not_push_the_window_over_the_cap() -> None: + window = window_for_retake( + source_frames=1001, + mask_start_frame=100, + mask_end_frame=596, + max_input_frames=MAX_INPUT_FRAMES, + fps=25.0, + ) + assert window.encode_frames <= MAX_INPUT_FRAMES + assert (window.encode_frames - 1) % 8 == 0 + assert window.mask_end_frame - window.mask_start_frame == 496 + + +def test_feather_pulls_the_denoise_mask_into_kept_context() -> None: + window = window_for_retake( + source_frames=241, + mask_start_frame=96, + mask_end_frame=144, + max_input_frames=MAX_INPUT_FRAMES, + ) + fps = 24.0 + start, end = feathered_mask_times(window, fps) + assert start == pytest.approx(96 / fps - MASK_DELTA_SECONDS) + assert end == pytest.approx(144 / fps + MASK_DELTA_SECONDS) + assert start >= 0 + assert end <= window.encode_duration(fps) + + +def test_feather_does_not_cross_a_missing_prefix() -> None: + window = window_for_retake( + source_frames=241, + mask_start_frame=0, + mask_end_frame=48, + max_input_frames=MAX_INPUT_FRAMES, + ) + start, end = feathered_mask_times(window, 24.0) + assert start == 0.0 + assert end > 48 / 24.0 + assert RETAKE_BLEND_SECONDS == 0.3 diff --git a/backend/tests/test_retake_extend_generation.py b/backend/tests/test_retake_extend_generation.py index 1bd99b63e..ff9dd9d13 100644 --- a/backend/tests/test_retake_extend_generation.py +++ b/backend/tests/test_retake_extend_generation.py @@ -1,11 +1,12 @@ -"""Local Retake/Extend routing for LTX 2.3 (and rejection on 2.5). +"""Local Retake/Extend routing for LTX 2.3 and 2.5. -The fake pipeline never runs GPU code. These tests pin that 2.3 loads the -matching checkpoint/VAE paths, and that local 2.5 rejects Retake/Extend. +The fake pipeline never runs GPU code. These tests pin that each local model +loads the matching checkpoint/VAE paths. """ from __future__ import annotations +import logging import uuid import pytest @@ -13,6 +14,10 @@ from api_types import LTXLocalModelId from runtime_config.ltx_runtime_paths import resolve_ltx_runtime_paths from runtime_config.model_download_specs import get_existing_cp_path, get_ltx_model_spec +from runtime_config.video_job_budget import ( + LOCAL_GENERATION_UNSUPPORTED, + LOCAL_GENERATION_UNSUPPORTED_MESSAGE, +) from state.app_settings import resolved_use_conv_vae from state.app_state_types import GpuSlot, RetakePipelineState from tests.http_error_assertions import assert_http_error @@ -94,6 +99,33 @@ def test_local_retake_routes_to_model_paths( _assert_retake_pipeline_model(test_state, _LOCAL_2_3) +def test_local_retake_emits_heartbeat_done( + client, test_state, create_fake_model_files, fake_services, caplog +) -> None: + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + video_path = _make_valid_video(test_state) + caplog.set_level(logging.INFO) + + r = client.post( + "/api/retake", + json={"video_path": video_path, "start_time": 1.0, "duration": 3.0, "prompt": "make it dramatic"}, + ) + assert r.status_code == 200 + start_records = [ + record + for record in caplog.records + if "Retake " in record.getMessage() and " started (" in record.getMessage() + ] + assert len(start_records) == 1 + done_records = [ + record + for record in caplog.records + if record.name == "server_utils.heartbeat" + and "retake inference done" in record.getMessage() + ] + assert len(done_records) == 1 + + @pytest.mark.parametrize("mode", ["start", "end"]) def test_local_extend_routes_to_model_paths( client, test_state, create_fake_model_files, fake_services, mode: str @@ -114,7 +146,34 @@ def test_local_extend_routes_to_model_paths( assert fake_services.retake_pipeline.extend_calls[-1]["mode"] == mode -def test_local_retake_rejected_on_2_5(client, test_state, create_fake_model_files, fake_services) -> None: +def test_local_extend_emits_heartbeat_done( + client, test_state, create_fake_model_files, fake_services, caplog +) -> None: + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + video_path = _make_valid_video(test_state, frames=9) + caplog.set_level(logging.INFO) + + r = client.post( + "/api/extend", + json={"video_path": video_path, "duration": 4.0, "prompt": "continue the motion", "mode": "end"}, + ) + assert r.status_code == 200 + start_records = [ + record + for record in caplog.records + if "Extend " in record.getMessage() and " started (" in record.getMessage() + ] + assert len(start_records) == 1 + done_records = [ + record + for record in caplog.records + if record.name == "server_utils.heartbeat" + and "extend inference done" in record.getMessage() + ] + assert len(done_records) == 1 + + +def test_local_retake_accepted_on_2_5(client, test_state, create_fake_model_files, fake_services) -> None: _install_local(test_state, create_fake_model_files, _LOCAL_2_5) video_path = _make_valid_video(test_state) @@ -122,17 +181,16 @@ def test_local_retake_rejected_on_2_5(client, test_state, create_fake_model_file "/api/retake", json={"video_path": video_path, "start_time": 1.0, "duration": 3.0, "prompt": "make it dramatic"}, ) - assert_http_error( - r, - status_code=409, - code="UNSUPPORTED_RETAKE", - message="Retake is not supported for the active LTX model.", - ) - assert fake_services.retake_pipeline.create_calls == [] + assert r.status_code == 200 + data = r.json() + assert data["status"] == "complete" + assert data["video_path"] + _assert_create_paths(fake_services, test_state, _LOCAL_2_5) + _assert_retake_pipeline_model(test_state, _LOCAL_2_5) @pytest.mark.parametrize("mode", ["start", "end"]) -def test_local_extend_rejected_on_2_5( +def test_local_extend_accepted_on_2_5( client, test_state, create_fake_model_files, fake_services, mode: str ) -> None: _install_local(test_state, create_fake_model_files, _LOCAL_2_5) @@ -142,16 +200,84 @@ def test_local_extend_rejected_on_2_5( "/api/extend", json={"video_path": video_path, "duration": 4.0, "prompt": "continue the motion", "mode": mode}, ) + assert r.status_code == 200 + data = r.json() + assert data["status"] == "complete" + assert data["video_path"] + _assert_create_paths(fake_services, test_state, _LOCAL_2_5) + _assert_retake_pipeline_model(test_state, _LOCAL_2_5) + assert fake_services.retake_pipeline.extend_calls[-1]["mode"] == mode + + +def test_retake_unsupported_hardware_without_a_key_is_not_an_api_key_prompt( + client, test_state, create_fake_model_files, fake_services +) -> None: + """Unsupported hardware must not be told to configure an API key.""" + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "" + video_path = _make_valid_video(test_state) + + r = client.post( + "/api/retake", + json={"video_path": video_path, "start_time": 1.0, "duration": 3.0, "prompt": "make it dramatic"}, + ) assert_http_error( r, - status_code=409, - code="UNSUPPORTED_EXTEND", - message="Extend is not supported for the active LTX model.", + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, ) + body = r.json()["message"].lower() + assert "api" not in body + assert "key" not in body + assert "settings" not in body assert fake_services.retake_pipeline.create_calls == [] -def test_retake_on_2_5_does_not_rebuild_pipeline_after_2_3( +def test_extend_unsupported_hardware_without_a_key_is_not_an_api_key_prompt( + client, test_state, create_fake_model_files, fake_services +) -> None: + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "" + video_path = _make_valid_video(test_state, frames=9) + + r = client.post( + "/api/extend", + json={"video_path": video_path, "duration": 4.0, "prompt": "continue the motion", "mode": "end"}, + ) + assert_http_error( + r, + status_code=422, + code=LOCAL_GENERATION_UNSUPPORTED, + message=LOCAL_GENERATION_UNSUPPORTED_MESSAGE, + ) + body = r.json()["message"].lower() + assert "api" not in body + assert "key" not in body + assert "settings" not in body + assert fake_services.retake_pipeline.create_calls == [] + + +def test_retake_unsupported_hardware_with_a_key_still_routes_to_the_api( + client, test_state, create_fake_model_files, fake_services +) -> None: + """The guard only fires when no API route is left.""" + _install_local(test_state, create_fake_model_files, _LOCAL_2_3) + test_state.config.local_generations_mode = "unsupported" + test_state.state.app_settings.ltx_api_key = "ltx-key" + video_path = _make_valid_video(test_state) + + r = client.post( + "/api/retake", + json={"video_path": video_path, "start_time": 1.0, "duration": 3.0, "prompt": "make it dramatic"}, + ) + assert r.json().get("code") != LOCAL_GENERATION_UNSUPPORTED + assert fake_services.retake_pipeline.create_calls == [] + + +def test_retake_on_2_5_rebuilds_pipeline_after_2_3( client, test_state, create_fake_model_files, fake_services ) -> None: create_fake_model_files(model_id=_LOCAL_2_3) @@ -169,10 +295,7 @@ def test_retake_on_2_5_does_not_rebuild_pipeline_after_2_3( test_state.state.app_settings.active_ltx_model_id = _LOCAL_2_5 second = client.post("/api/retake", json=payload) - assert_http_error( - second, - status_code=409, - code="UNSUPPORTED_RETAKE", - message="Retake is not supported for the active LTX model.", - ) - assert len(fake_services.retake_pipeline.create_calls) == 1 + assert second.status_code == 200 + _assert_create_paths(fake_services, test_state, _LOCAL_2_5) + _assert_retake_pipeline_model(test_state, _LOCAL_2_5) + assert len(fake_services.retake_pipeline.create_calls) == 2 diff --git a/backend/tests/test_retake_frame_rate.py b/backend/tests/test_retake_frame_rate.py new file mode 100644 index 000000000..a72a664a7 --- /dev/null +++ b/backend/tests/test_retake_frame_rate.py @@ -0,0 +1,78 @@ +"""The retake/extend window must play at the source rate, not ``int(fps)``.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import av +import imageio_ffmpeg +import pytest + +from services.retake_pipeline.frame_rate import restamp_to_source_rate + +NTSC_FILM = 24000 / 1001 +FRAMES = 46 + + +def _window_written_at_23fps(path: Path) -> Path: + """What the upstream encoder produces for a 23.976 fps source.""" + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-f", + "lavfi", + "-i", + f"testsrc=s=64x64:r=23:n=1,trim=end_frame={FRAMES}", + "-f", + "lavfi", + "-i", + f"sine=d={FRAMES / NTSC_FILM}", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-c:a", + "aac", + str(path), + ], + check=True, + capture_output=True, + ) + return path + + +def _frame_times(path: Path) -> list[float]: + with av.open(str(path)) as container: + return sorted(float(frame.time) for frame in container.decode(video=0)) + + +def _audio_seconds(path: Path) -> float: + with av.open(str(path)) as container: + stream = container.streams.audio[0] + assert stream.duration is not None + return float(stream.duration * stream.time_base) + + +def test_restamp_puts_every_frame_at_the_source_rate(tmp_path: Path) -> None: + window = _window_written_at_23fps(tmp_path / "w.window.mp4") + audio_before = _audio_seconds(window) + + restamp_to_source_rate(str(window), source_fps=NTSC_FILM) + + times = _frame_times(window) + assert len(times) == FRAMES + for index, time in enumerate(times): + assert time == pytest.approx(index / NTSC_FILM, abs=1e-3) + assert _audio_seconds(window) == pytest.approx(audio_before, abs=1e-3) + assert not (tmp_path / "w.window.restamp.mp4").exists() + + +def test_restamp_leaves_an_integer_rate_untouched(tmp_path: Path) -> None: + window = _window_written_at_23fps(tmp_path / "w.window.mp4") + before = window.stat().st_mtime_ns + + restamp_to_source_rate(str(window), source_fps=23.0) + + assert window.stat().st_mtime_ns == before diff --git a/backend/tests/test_retake_sampler_selection.py b/backend/tests/test_retake_sampler_selection.py index 90b878f0e..5bd432246 100644 --- a/backend/tests/test_retake_sampler_selection.py +++ b/backend/tests/test_retake_sampler_selection.py @@ -1,18 +1,21 @@ """GPU-free checks for Retake/Extend distilled sampler selection. -``_run()`` cannot be exercised here without loading real checkpoints. The helper -it calls, plus ``_invoke_diffusion_stage`` (the ``self.stage`` call site), are -the whole decision. +2.5 distilled T2V samples stage 1 ancestrally and cleans the noise in a short +Euler refine. The masked region starts at sigma=1, so Euler-only never lets +the prompt take (retake reconstructs the source; extend morphs into sludge) +and ancestral-only leaves texture boiling. Both features need the same pair. +``_run()`` cannot be exercised here without loading real checkpoints, so this +pins the sampler plan and the ``DiffusionStage`` call site. """ from __future__ import annotations +from dataclasses import dataclass from functools import partial from pathlib import Path from typing import Any, cast import torch -from ltx_core.components.diffusion_steps import EulerAncestralDiffusionStep from ltx_pipelines.distilled import ( ANCESTRAL_ETA, ANCESTRAL_NOISE_SEED_OFFSET, @@ -22,10 +25,9 @@ from ltx_pipelines.utils.samplers import euler_ancestral_denoising_loop from safetensors.torch import save_file -from services.retake_pipeline.ltx_retake_pipeline import ( - LTXRetakePipeline, - distilled_stage_sampler_kwargs, -) +from services.denoising_progress import distilled_total_steps +from services.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline +from services.retake_pipeline.retake_sampler import resolve_sampler_plan def _checkpoint_with_version(tmp_path: Path, version: str) -> str: @@ -35,15 +37,14 @@ def _checkpoint_with_version(tmp_path: Path, version: str) -> str: def _assert_ancestral_kwargs(kwargs: dict[str, Any], *, seed: int, dtype: torch.dtype) -> None: - stepper = kwargs["stepper"] - assert isinstance(stepper, EulerAncestralDiffusionStep) - assert stepper.eta == ANCESTRAL_ETA - assert stepper.s_noise == ANCESTRAL_S_NOISE + assert "stepper" not in kwargs loop = kwargs["loop"] assert isinstance(loop, partial) assert loop.func is euler_ancestral_denoising_loop assert loop.keywords["noise_seed"] == seed + ANCESTRAL_NOISE_SEED_OFFSET assert loop.keywords["model_dtype"] is dtype + assert loop.keywords["eta"] == ANCESTRAL_ETA + assert loop.keywords["s_noise"] == ANCESTRAL_S_NOISE def test_distilled_2_5_selects_ancestral_sampler(tmp_path: Path) -> None: @@ -51,67 +52,177 @@ def test_distilled_2_5_selects_ancestral_sampler(tmp_path: Path) -> None: dtype = torch.bfloat16 path = _checkpoint_with_version(tmp_path, "2.5") assert should_use_ancestral_sampler(path) - kwargs = distilled_stage_sampler_kwargs( + plan = resolve_sampler_plan( distilled=True, use_ancestral=should_use_ancestral_sampler(path), seed=seed, dtype=dtype, ) - _assert_ancestral_kwargs(kwargs, seed=seed, dtype=dtype) + _assert_ancestral_kwargs(plan.stage1, seed=seed, dtype=dtype) def test_distilled_2_3_keeps_deterministic_defaults(tmp_path: Path) -> None: path = _checkpoint_with_version(tmp_path, "2.3") assert not should_use_ancestral_sampler(path) - kwargs = distilled_stage_sampler_kwargs( + plan = resolve_sampler_plan( distilled=True, use_ancestral=should_use_ancestral_sampler(path), seed=1, dtype=torch.bfloat16, ) - assert kwargs == {} + assert plan.stage1 == {} def test_guided_path_never_selects_ancestral_sampler() -> None: - kwargs = distilled_stage_sampler_kwargs( + plan = resolve_sampler_plan( distilled=False, use_ancestral=True, seed=1, dtype=torch.bfloat16, ) - assert kwargs == {} + assert plan.stage1 == {} + + +def test_2_5_uses_ancestral_then_euler_refine() -> None: + plan = resolve_sampler_plan( + distilled=True, + use_ancestral=True, + seed=1, + dtype=torch.bfloat16, + ) + assert plan.two_stage is True + assert plan.total_steps == distilled_total_steps() + + +def test_2_3_stays_single_stage_euler() -> None: + plan = resolve_sampler_plan( + distilled=True, + use_ancestral=False, + seed=1, + dtype=torch.bfloat16, + ) + assert plan.two_stage is False + assert plan.total_steps == distilled_total_steps(stage_2=False) -def _pipeline_with_recording_stage(*, use_ancestral: bool) -> tuple[LTXRetakePipeline, list[dict[str, Any]]]: +def _pipeline_with_recording_stage( + *, use_ancestral: bool +) -> tuple[LTXRetakePipeline, list[dict[str, Any]]]: calls: list[dict[str, Any]] = [] + @dataclass + class _State: + latent: str + def fake_stage(**kwargs: Any) -> tuple[object, object]: calls.append(kwargs) - return object(), object() + return _State(f"v{len(calls)}"), _State(f"a{len(calls)}") pipeline = cast(LTXRetakePipeline, object.__new__(LTXRetakePipeline)) pipeline.dtype = torch.bfloat16 + pipeline.device = torch.device("cpu") pipeline.use_ancestral_sampler = use_ancestral pipeline.stage = fake_stage # type: ignore[method-assign] return pipeline, calls -def test_invoke_diffusion_stage_forwards_ancestral_kwargs() -> None: +def test_resolve_sampler_plan_forwards_ancestral_kwargs() -> None: + seed = 7 + dtype = torch.bfloat16 + plan = resolve_sampler_plan( + distilled=True, + use_ancestral=True, + seed=seed, + dtype=dtype, + ) + assert plan.two_stage is True + assert plan.total_steps == distilled_total_steps() + _assert_ancestral_kwargs(plan.stage1, seed=seed, dtype=dtype) + assert plan.refine == {} + + +def test_retake_denoise_runs_ancestral_then_euler_refine() -> None: + from ltx_pipelines.utils.types import ModalitySpec + seed = 7 pipeline, calls = _pipeline_with_recording_stage(use_ancestral=True) - denoiser = object() - pipeline._invoke_diffusion_stage(distilled=True, seed=seed, denoiser=denoiser) + video = ModalitySpec(latent="v0", conditioning_fps=24.0) + audio = ModalitySpec(latent="a0", conditioning_fps=24.0) + video_state, audio_state = pipeline._denoise_masked_latents( + distilled=True, + seed=seed, + denoiser=object(), + sigmas=torch.tensor([1.0, 0.0]), + noiser=object(), + video=video, + audio=audio, + ) - assert len(calls) == 1 - kwargs = calls[0] - assert kwargs["denoiser"] is denoiser - _assert_ancestral_kwargs(kwargs, seed=seed, dtype=pipeline.dtype) + assert len(calls) == 2 + _assert_ancestral_kwargs(calls[0], seed=seed, dtype=pipeline.dtype) + assert "stepper" not in calls[1] + assert "loop" not in calls[1] + assert calls[1]["modalities"].video.latent == "v1" + assert calls[1]["modalities"].audio.latent == "a1" + assert calls[1]["modalities"].video.noise_scale == calls[1]["modalities"].audio.noise_scale + assert calls[1]["modalities"].video.noise_scale > 0 + assert video_state.latent == "v2" + assert audio_state.latent == "a2" + + +def _frozen_audio_run(*, use_ancestral: bool) -> tuple[list[dict[str, Any]], Any, Any]: + from ltx_pipelines.utils.types import ModalitySpec + pipeline, calls = _pipeline_with_recording_stage(use_ancestral=use_ancestral) + video_state, audio_state = pipeline._denoise_masked_latents( + distilled=True, + seed=7, + denoiser=object(), + sigmas=torch.tensor([1.0, 0.0]), + noiser=object(), + video=ModalitySpec(latent="v0", conditioning_fps=24.0), + audio=ModalitySpec(latent="a0", conditioning_fps=24.0, frozen=True), + ) + return calls, video_state, audio_state + + +def test_frozen_modality_is_never_noised_in_any_stage() -> None: + calls, _, _ = _frozen_audio_run(use_ancestral=True) + + assert len(calls) == 2 + for call in calls: + modalities = call["modalities"] + assert modalities.audio.frozen is True + assert modalities.audio.noise_scale == 0.0 + # The live side keeps the schedule's noise: pinning must not leak onto it. + assert calls[0]["modalities"].video.noise_scale == 1.0 + assert calls[1]["modalities"].video.noise_scale > 0 + + +def test_frozen_modality_returns_the_input_latent_and_feeds_it_to_stage_2() -> None: + calls, video_state, audio_state = _frozen_audio_run(use_ancestral=True) + + assert calls[1]["modalities"].audio.latent == "a0" + assert audio_state.latent == "a0" + assert video_state.latent == "v2" + + +def test_frozen_video_is_pinned_and_restored_on_the_single_stage_path() -> None: + from ltx_pipelines.utils.types import ModalitySpec -def test_invoke_diffusion_stage_omits_sampler_overrides_when_not_ancestral() -> None: pipeline, calls = _pipeline_with_recording_stage(use_ancestral=False) - pipeline._invoke_diffusion_stage(distilled=True, seed=7, denoiser=object()) + video_state, audio_state = pipeline._denoise_masked_latents( + distilled=True, + seed=7, + denoiser=object(), + sigmas=torch.tensor([1.0, 0.0]), + noiser=object(), + video=ModalitySpec(latent="v0", conditioning_fps=24.0, frozen=True), + audio=ModalitySpec(latent="a0", conditioning_fps=24.0), + ) assert len(calls) == 1 - assert "stepper" not in calls[0] - assert "loop" not in calls[0] + assert calls[0]["modalities"].video.noise_scale == 0.0 + assert calls[0]["modalities"].audio.noise_scale == 1.0 + assert video_state.latent == "v0" + assert audio_state.latent == "a1" diff --git a/backend/tests/test_retake_stitch.py b/backend/tests/test_retake_stitch.py new file mode 100644 index 000000000..bb0e8039a --- /dev/null +++ b/backend/tests/test_retake_stitch.py @@ -0,0 +1,408 @@ +"""CPU-only checks for stitching original pixels back onto Home retake.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import imageio_ffmpeg +import numpy as np +import pytest + +from services.retake_pipeline.retake_stitch import ( + fade_window_for_retake, + reencode_span, + retake_audio_graph, + stitch_retake_output, +) +from services.ffmpeg import ( + FFMPEG_TIMEOUT_SECONDS, + STITCH_TIMEOUT_CAP_SECONDS, + timeout_for_source_duration, +) +from services.retake_pipeline.rgb_stitch import iter_span +from services.retake_pipeline.window import ( + MAX_FADE_FRAMES, + denoised_frame_span, + feathered_mask_times, + window_for_retake, +) + + +NTSC_FILM = 24000 / 1001 + + +def _ted_retake_window(): + """The 30.6s–35.6s retake on a 60s 23.976 fps clip that jumped at the seam.""" + return window_for_retake( + source_frames=1438, + mask_start_frame=734, + mask_end_frame=854, + max_input_frames=505, + fps=NTSC_FILM, + ) + + +def test_fade_sits_on_the_user_mask_for_at_most_16_frames() -> None: + window = _ted_retake_window() + fade = fade_window_for_retake(window) + fade_in = min(MAX_FADE_FRAMES, fade.edit_start - fade.context_start) + fade_out = min(MAX_FADE_FRAMES, fade.context_end - fade.edit_end) + denoised_start, denoised_end = denoised_frame_span(window, NTSC_FILM) + + assert fade.edit_start == window.context_before_frames + assert fade.edit_end - fade.edit_start == 120 + assert fade_in == MAX_FADE_FRAMES + assert fade_out == MAX_FADE_FRAMES + # Fully generated frames are the user mask. The denoised latents run wider; + # those extra frames are blended or replaced with the original. + assert denoised_start < fade.edit_start < fade.edit_end <= denoised_end + + +def test_denoised_span_snaps_out_to_whole_latents() -> None: + window = _ted_retake_window() + start, end = denoised_frame_span(window, NTSC_FILM) + region_start, region_end = feathered_mask_times(window, NTSC_FILM) + assert start / NTSC_FILM <= region_start and end / NTSC_FILM >= region_end + assert (start - 1) % 8 == 0 and (end - 1) % 8 == 0 + + +def test_mask_at_start_has_no_fade_in() -> None: + window = window_for_retake( + source_frames=241, + mask_start_frame=0, + mask_end_frame=48, + max_input_frames=505, + fps=25.0, + ) + fade = fade_window_for_retake(window) + assert fade.edit_start == 0 + assert min(MAX_FADE_FRAMES, fade.context_end - fade.edit_end) == MAX_FADE_FRAMES + + +def test_audio_cuts_at_the_mask_while_video_fades_wider() -> None: + window = _ted_retake_window() + graph = retake_audio_graph(window, NTSC_FILM, source_label="[1:a]") + edit_start = f"{window.mask_start_frame / NTSC_FILM:.6f}" + edit_end = f"{window.mask_end_frame / NTSC_FILM:.6f}" + assert f"atrim=end={edit_start}" in graph + assert f"atrim=start={edit_end}" in graph + assert "concat=n=3:v=0:a=1" in graph + fade = fade_window_for_retake(window) + fade_in_start = window.encode_start_frame + fade.edit_start - MAX_FADE_FRAMES + assert f"{fade_in_start / NTSC_FILM:.6f}" not in graph + + +def test_full_mask_stitch_copies_the_windowed_file(tmp_path: Path) -> None: + windowed = tmp_path / "window.mp4" + dest = tmp_path / "out.mp4" + windowed.write_bytes(b"window-bytes") + window = window_for_retake( + source_frames=97, + mask_start_frame=0, + mask_end_frame=97, + max_input_frames=505, + fps=25.0, + ) + stitch_retake_output( + source_path=str(tmp_path / "source.mp4"), + windowed_path=str(windowed), + dest_path=str(dest), + window=window, + fps=25.0, + target_width=64, + target_height=64, + ) + assert dest.read_bytes() == b"window-bytes" + + +def _solid_video( + path: Path, + *, + rgb: tuple[int, int, int], + frames: int, + fps: int, + height: int = 64, + width: int = 64, +) -> str: + import imageio.v2 as imageio + + writer = imageio.get_writer(str(path), fps=fps, codec="libx264", macro_block_size=None) + frame = np.full((height, width, 3), rgb, dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return str(path) + + +def _barred_video(path: Path, *, frames: int, fps: int) -> str: + """64x64 canvas with an 8px black bar on the top and bottom around a 48px picture.""" + import imageio.v2 as imageio + + frame = np.zeros((64, 64, 3), dtype=np.uint8) + frame[8:56] = 180 + writer = imageio.get_writer(str(path), fps=fps, codec="libx264", macro_block_size=None) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return str(path) + + +def test_stitch_keeps_source_outside_a_16_frame_lerp(tmp_path: Path) -> None: + fps = 25.0 + window = window_for_retake( + source_frames=81, + mask_start_frame=32, + mask_end_frame=56, + max_input_frames=505, + fps=fps, + ) + source = _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=81, fps=25) + generated = _solid_video( + tmp_path / "generated.mp4", + rgb=(30, 30, 30), + frames=window.encode_frames, + fps=25, + ) + dest = tmp_path / "out.mp4" + stitch_retake_output( + source_path=source, + windowed_path=generated, + dest_path=str(dest), + window=window, + fps=fps, + target_width=64, + target_height=64, + ) + fade = fade_window_for_retake(window) + fade_in = min(MAX_FADE_FRAMES, fade.edit_start) + with __import__("av").open(str(dest)) as container: + frames = [frame.to_ndarray(format="rgb24") for frame in container.decode(video=0)] + + assert len(frames) == 81 + assert frames[0].mean() == pytest.approx(0, abs=8) + assert frames[fade.edit_start - fade_in - 1].mean() == pytest.approx(0, abs=8) + mid = fade.edit_start - fade_in // 2 + assert 8 < frames[mid].mean() < 22 + assert frames[fade.edit_start].mean() == pytest.approx(30, abs=8) + assert frames[fade.edit_end - 1].mean() == pytest.approx(30, abs=8) + assert frames[-1].mean() == pytest.approx(0, abs=8) + + +def test_stitch_crops_letterbox_bars_instead_of_stretching_them(tmp_path: Path) -> None: + fps = 25.0 + window = window_for_retake( + source_frames=81, + mask_start_frame=32, + mask_end_frame=56, + max_input_frames=505, + fps=fps, + ) + source = _solid_video( + tmp_path / "source.mp4", rgb=(180, 180, 180), frames=81, fps=25, height=48 + ) + generated = _barred_video( + tmp_path / "generated.mp4", frames=window.encode_frames, fps=25 + ) + dest = tmp_path / "out.mp4" + stitch_retake_output( + source_path=source, + windowed_path=generated, + dest_path=str(dest), + window=window, + fps=fps, + target_width=64, + target_height=48, + ) + fade = fade_window_for_retake(window) + with __import__("av").open(str(dest)) as container: + frames = [frame.to_ndarray(format="rgb24") for frame in container.decode(video=0)] + edited = frames[fade.edit_start] + assert edited.shape == (48, 64, 3) + assert edited[0].mean() == pytest.approx(180, abs=15) + + +def test_reencode_span_is_the_mask_plus_the_fades() -> None: + window = _ted_retake_window() + span = reencode_span(window) + assert span.fade_out_end - span.fade_in_start == 120 + 2 * MAX_FADE_FRAMES + assert 0 < span.prefix_end < span.suffix_start < window.source_frames + + +def test_span_past_the_end_of_the_file_raises_instead_of_yielding_short(tmp_path: Path) -> None: + path = tmp_path / "indexed.mp4" + _indexed_clip(path, 20, 24) + with pytest.raises(ValueError, match="expected 10"): + list(iter_span(str(path), 15, 25, 16, 16)) + + +def test_python_writer_receives_only_the_blend_and_the_mask(monkeypatch, tmp_path: Path) -> None: + fps = 25.0 + window = window_for_retake( + source_frames=81, + mask_start_frame=32, + mask_end_frame=56, + max_input_frames=505, + fps=fps, + ) + _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=81, fps=25) + _solid_video( + tmp_path / "generated.mp4", rgb=(30, 30, 30), frames=window.encode_frames, fps=25 + ) + seen: list[int] = [] + + def _capture(dest: Path, frames: object, **_kwargs: object) -> None: + seen.append(sum(1 for _ in frames)) # type: ignore[arg-type] + Path(dest).write_bytes(b"middle") + + monkeypatch.setattr("services.retake_pipeline.retake_stitch.write_rgb_video", _capture) + monkeypatch.setattr("services.retake_pipeline.retake_stitch.run_ffmpeg", lambda *_a, **_k: None) + monkeypatch.setattr("services.retake_pipeline.retake_stitch._has_audio", lambda _path: False) + stitch_retake_output( + source_path=str(tmp_path / "source.mp4"), + windowed_path=str(tmp_path / "generated.mp4"), + dest_path=str(tmp_path / "out.mp4"), + window=window, + fps=fps, + target_width=64, + target_height=64, + ) + span = reencode_span(window) + assert seen == [span.fade_out_end - span.fade_in_start] + assert seen[0] < window.source_frames + + +def test_short_generated_span_raises(tmp_path: Path) -> None: + fps = 25.0 + window = window_for_retake( + source_frames=81, + mask_start_frame=32, + mask_end_frame=56, + max_input_frames=505, + fps=fps, + ) + source = _solid_video(tmp_path / "source.mp4", rgb=(0, 0, 0), frames=81, fps=25) + generated = _solid_video(tmp_path / "generated.mp4", rgb=(30, 30, 30), frames=1, fps=25) + with pytest.raises(ValueError, match="Span"): + stitch_retake_output( + source_path=source, + windowed_path=generated, + dest_path=str(tmp_path / "out.mp4"), + window=window, + fps=fps, + target_width=64, + target_height=64, + ) + + +def test_silent_source_keeps_generated_audio(monkeypatch, tmp_path: Path) -> None: + captured: list[list[str]] = [] + + def _capture(args: list[str], **_kwargs: object) -> None: + captured.append(args) + + monkeypatch.setattr("services.retake_pipeline.retake_stitch.run_ffmpeg", _capture) + monkeypatch.setattr( + "services.retake_pipeline.retake_stitch.write_rgb_video", + lambda *_args, **_kwargs: None, + ) + monkeypatch.setattr( + "services.retake_pipeline.retake_stitch._has_audio", + lambda path: path == "/window.mp4", + ) + window = window_for_retake( + source_frames=241, + mask_start_frame=96, + mask_end_frame=144, + max_input_frames=505, + fps=25.0, + ) + dest = tmp_path / "out.mp4" + stitch_retake_output( + source_path="/source.mp4", + windowed_path="/window.mp4", + dest_path=str(dest), + window=window, + fps=25.0, + target_width=64, + target_height=64, + ) + assert len(captured) == 1 + args = captured[0] + assert "-f" in args and args[args.index("-f") + 1] == "lavfi" + assert "anullsrc=" in args[args.index("-i", args.index("-f")) + 1] + assert args.index("-shortest") > max(i for i, arg in enumerate(args) if arg == "-i") + graph = args[args.index("-filter_complex") + 1] + span = reencode_span(window) + assert f"trim=end_frame={span.prefix_end}" in graph + assert f"trim=start_frame={span.suffix_start}" in graph + assert "[1:v]" in graph + assert "[2:a]" in graph + assert "[3:a]" in graph + assert "[0:a]" not in graph + assert "[1:a]" not in graph + + +def test_stitch_timeout_grows_with_the_source_and_stays_bounded() -> None: + assert timeout_for_source_duration(10) == FFMPEG_TIMEOUT_SECONDS + assert timeout_for_source_duration(60) == 480 + assert timeout_for_source_duration(10_000) == STITCH_TIMEOUT_CAP_SECONDS + + +def _indexed_clip(path: Path, frames: int, rate) -> None: + import av + + with av.open(str(path), mode="w") as container: + stream = container.add_stream("libx264", rate=rate) + stream.width = 16 + stream.height = 16 + stream.pix_fmt = "yuv420p" + stream.codec_context.gop_size = 8 + stream.codec_context.color_range = 1 + for index in range(frames): + pixels = np.full((16, 16, 3), (index * 40) % 256, dtype=np.uint8) + video_frame = av.VideoFrame.from_ndarray(pixels, format="rgb24") + video_frame.pts = index + for packet in stream.encode(video_frame): + container.mux(packet) + for packet in stream.encode(): + container.mux(packet) + + +def test_late_rgb_span_matches_a_decode_from_the_start(tmp_path: Path) -> None: + from fractions import Fraction + + path = tmp_path / "indexed.mp4" + _indexed_clip(path, 160, Fraction(24000, 1001)) + full = list(iter_span(str(path), 0, 160, 16, 16)) + late = list(iter_span(str(path), 100, 108, 16, 16)) + assert np.array_equal(late, full[100:108]) + assert not np.array_equal(late[0], late[1]) + + +def _shift_start_time(source: Path, dest: Path, offset: str) -> None: + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-i", + str(source), + "-c", + "copy", + "-output_ts_offset", + offset, + str(dest), + ], + check=True, + capture_output=True, + ) + + +def test_late_rgb_span_matches_when_timestamps_do_not_start_at_zero(tmp_path: Path) -> None: + path = tmp_path / "indexed.mp4" + shifted = tmp_path / "shifted.mp4" + _indexed_clip(path, 180, 24) + _shift_start_time(path, shifted, "0.125") + full = list(iter_span(str(shifted), 0, 180, 16, 16)) + late = list(iter_span(str(shifted), 100, 108, 16, 16)) + assert np.array_equal(late, full[100:108]) diff --git a/backend/tests/test_retake_stitch_e2e.py b/backend/tests/test_retake_stitch_e2e.py new file mode 100644 index 000000000..a7226cd14 --- /dev/null +++ b/backend/tests/test_retake_stitch_e2e.py @@ -0,0 +1,106 @@ +"""Real-ffmpeg check that the retake stitch neither skips nor repeats a frame.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import av +import imageio_ffmpeg +import numpy as np + +from services.retake_pipeline.frame_rate import restamp_to_source_rate +from services.retake_pipeline.retake_stitch import stitch_retake_output +from services.retake_pipeline.window import window_for_retake + +NTSC_FILM = 24000 / 1001 +SOURCE_FRAMES = 300 +SIZE = 64 + + +def _ffmpeg(*args: str) -> None: + subprocess.run( + [imageio_ffmpeg.get_ffmpeg_exe(), "-y", *args], check=True, capture_output=True + ) + + +def _source(path: Path) -> Path: + # Brightness steps 20 levels per frame, so neighbours are easy to tell apart. + _ffmpeg( + "-f", "lavfi", "-i", + f"nullsrc=s={SIZE}x{SIZE}:r=24000/1001," + f"format=gray,geq=lum='mod(N*20,240)+8',trim=end_frame={SOURCE_FRAMES}", + "-f", "lavfi", "-i", f"sine=d={SOURCE_FRAMES / NTSC_FILM}", + "-c:v", "libx264", "-pix_fmt", "yuv420p", "-c:a", "aac", + str(path), + ) + return path + + +def _window_like_the_encoder(source: Path, path: Path, start: int, frames: int) -> Path: + """The source's own frames written as ``ltx_pipelines`` does, then restamped. + + PyAV at ``rate=23`` plus the restamp leaves every timestamp a hair early, + which is what made seconds-based trims drop the boundary frame. + """ + with av.open(str(source)) as reader, av.open(str(path), "w") as writer: + stream = writer.add_stream("libx264", rate=int(NTSC_FILM), options={"crf": "12"}) + stream.width = stream.height = SIZE + stream.pix_fmt = "yuv420p" + for index, frame in enumerate(reader.decode(video=0)): + if start <= index < start + frames: + image = av.VideoFrame.from_ndarray(frame.to_ndarray(format="rgb24")) + for packet in stream.encode(image): + writer.mux(packet) + for packet in stream.encode(): + writer.mux(packet) + restamp_to_source_rate(str(path), source_fps=NTSC_FILM) + return path + + +def _gray_frames(path: Path) -> np.ndarray: + with av.open(str(path)) as container: + return np.stack( + [ + frame.reformat(width=32, height=32, format="gray") + .to_ndarray() + .astype(np.float32) + for frame in container.decode(video=0) + ] + ) + + +def test_stitched_retake_keeps_every_source_frame_in_place(tmp_path: Path) -> None: + source = _source(tmp_path / "source.mp4") + window = window_for_retake( + source_frames=SOURCE_FRAMES, + mask_start_frame=140, + mask_end_frame=170, + max_input_frames=161, + fps=NTSC_FILM, + ) + windowed = _window_like_the_encoder( + source, + tmp_path / "out.window.mp4", + window.encode_start_frame, + window.encode_frames, + ) + dest = tmp_path / "out.mp4" + + stitch_retake_output( + source_path=str(source), + windowed_path=str(windowed), + dest_path=str(dest), + window=window, + fps=NTSC_FILM, + target_width=SIZE, + target_height=SIZE, + ) + + expected = _gray_frames(source) + stitched = _gray_frames(dest) + assert len(stitched) == SOURCE_FRAMES + for index, frame in enumerate(stitched): + lo, hi = max(0, index - 2), min(SOURCE_FRAMES, index + 3) + errors = [float(np.mean((frame - expected[j]) ** 2)) for j in range(lo, hi)] + assert lo + int(np.argmin(errors)) == index, f"frame {index} is out of place" diff --git a/backend/tests/test_runtime_policy.py b/backend/tests/test_runtime_policy.py index b36828db9..578dfef8e 100644 --- a/backend/tests/test_runtime_policy.py +++ b/backend/tests/test_runtime_policy.py @@ -8,7 +8,7 @@ def test_runtime_policy_true(client, test_state): response = client.get("/api/runtime-policy") assert response.status_code == 200 - assert response.json() == {"force_api_generations": True} + assert response.json() == {"force_api_generations": True, "local_viable": False} def test_runtime_policy_false(client, test_state): @@ -16,4 +16,22 @@ def test_runtime_policy_false(client, test_state): response = client.get("/api/runtime-policy") assert response.status_code == 200 - assert response.json() == {"force_api_generations": False} + assert response.json() == {"force_api_generations": False, "local_viable": True} + + +def test_runtime_policy_stream_is_locally_viable(client, test_state): + test_state.config.local_generations_mode = "streaming_models_loading" + + response = client.get("/api/runtime-policy") + assert response.status_code == 200 + assert response.json() == {"force_api_generations": False, "local_viable": True} + + +def test_runtime_policy_dev_force_local_viable(client, test_state, monkeypatch): + test_state.config.local_generations_mode = "unsupported" + test_state.config.dev_mode = True + monkeypatch.setenv("LTX_DEV_FORCE_LOCAL_VIABLE", "1") + + response = client.get("/api/runtime-policy") + assert response.status_code == 200 + assert response.json() == {"force_api_generations": True, "local_viable": True} diff --git a/backend/tests/test_runtime_policy_decision.py b/backend/tests/test_runtime_policy_decision.py index 397450edb..b4da79464 100644 --- a/backend/tests/test_runtime_policy_decision.py +++ b/backend/tests/test_runtime_policy_decision.py @@ -5,7 +5,11 @@ import pytest from runtime_config.runtime_policy import ( + CUDA_CPU_OFFLOAD_RAM_FLOOR_GB, + DARWIN_ADVERTISED_FLOOR_GB, + DARWIN_STREAMING_FLOOR_GB, decide_local_generation_mode, + should_disk_stream_cuda_weights, streaming_prefetch_count_for_mode, ) @@ -19,7 +23,13 @@ def test_darwin_without_mps_unsupported() -> None: def test_darwin_with_low_ram_unsupported() -> None: assert ( - decide_local_generation_mode(system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=14) + decide_local_generation_mode( + system="Darwin", + cuda_available=False, + vram_gb=None, + mps_available=True, + ram_gb=DARWIN_STREAMING_FLOOR_GB - 1, + ) == "unsupported" ) @@ -31,30 +41,14 @@ def test_darwin_with_unknown_ram_unsupported() -> None: ) -def test_darwin_streams_below_full_resident_floor() -> None: - assert ( - decide_local_generation_mode(system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=15) - == "streaming_models_loading" - ) - assert ( - decide_local_generation_mode(system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=48) - == "streaming_models_loading" - ) - assert ( - decide_local_generation_mode(system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=84) - == "streaming_models_loading" - ) - - -def test_darwin_full_resident_at_and_above_floor() -> None: - assert ( - decide_local_generation_mode(system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=85) - == "full_models_loading" - ) - assert ( - decide_local_generation_mode(system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=128) - == "full_models_loading" - ) +def test_darwin_always_streams_when_ram_is_sufficient() -> None: + for ram_gb in (DARWIN_STREAMING_FLOOR_GB, DARWIN_ADVERTISED_FLOOR_GB, 48, 64, 128): + assert ( + decide_local_generation_mode( + system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=ram_gb + ) + == "streaming_models_loading" + ) def test_darwin_defaults_to_unsupported_without_mps_kwargs() -> None: @@ -161,7 +155,7 @@ def test_darwin_ignores_fp8_capable() -> None: decide_local_generation_mode( system="Darwin", cuda_available=False, vram_gb=None, mps_available=True, ram_gb=85, fp8_capable=False ) - == "full_models_loading" + == "streaming_models_loading" ) @@ -169,6 +163,31 @@ def test_other_systems_fail_closed() -> None: assert decide_local_generation_mode(system="FreeBSD", cuda_available=True, vram_gb=48) == "unsupported" +def test_linux_32gb_must_disk_stream_cuda_weights() -> None: + """LTX-Desktop#163: advertised 32 GB Linux floor cannot pin OffloadMode.CPU.""" + assert should_disk_stream_cuda_weights("Linux", 32) is True + assert should_disk_stream_cuda_weights("Linux", CUDA_CPU_OFFLOAD_RAM_FLOOR_GB - 1) is True + + +def test_linux_high_ram_keeps_cpu_weight_streaming() -> None: + assert should_disk_stream_cuda_weights("Linux", CUDA_CPU_OFFLOAD_RAM_FLOOR_GB) is False + assert should_disk_stream_cuda_weights("Linux", 64) is False + + +def test_linux_unknown_ram_fails_closed_to_disk_streaming() -> None: + assert should_disk_stream_cuda_weights("Linux", None) is True + + +def test_windows_does_not_force_disk_streaming_on_32gb() -> None: + """Windows already uses pageable host buffers (LTX-Desktop#141).""" + assert should_disk_stream_cuda_weights("Windows", 32) is False + assert should_disk_stream_cuda_weights("Windows", None) is False + + +def test_darwin_disk_vs_cpu_is_not_this_gate() -> None: + assert should_disk_stream_cuda_weights("Darwin", 16) is False + + def test_streaming_prefetch_count_for_full_loading_is_none() -> None: assert streaming_prefetch_count_for_mode("full_models_loading") is None diff --git a/backend/tests/test_safetensors_loader_fix.py b/backend/tests/test_safetensors_loader_fix.py new file mode 100644 index 000000000..a1871cb34 --- /dev/null +++ b/backend/tests/test_safetensors_loader_fix.py @@ -0,0 +1,34 @@ +"""Patched SafetensorsStateDictLoader.load must match safetensors.torch.load_file.""" + +from __future__ import annotations + +from pathlib import Path + +import torch +from ltx_core.loader.sft_loader import SafetensorsStateDictLoader +from safetensors.torch import load_file, save_file + +import services.patches.safetensors_loader_fix as patch + + +def test_patch_rebinds_loader() -> None: + assert SafetensorsStateDictLoader.load is patch._patched_load + + +def test_patched_load_matches_safetensors_load_file(tmp_path: Path) -> None: + path = tmp_path / "tiny.safetensors" + expected = { + "weight": torch.randn(8, 4, dtype=torch.float32), + "bias": torch.ones(4, dtype=torch.bfloat16), + } + save_file(expected, str(path)) + + loaded = patch._patched_load(SafetensorsStateDictLoader(), str(path), sd_ops=None) # type: ignore[arg-type] + reference = load_file(str(path)) + + assert set(loaded.sd) == set(reference) == set(expected) + for key, tensor in expected.items(): + torch.testing.assert_close(loaded.sd[key], tensor, rtol=0, atol=0) + torch.testing.assert_close(loaded.sd[key], reference[key], rtol=0, atol=0) + assert loaded.sd[key].dtype == tensor.dtype + assert loaded.sd[key].shape == tensor.shape diff --git a/backend/tests/test_settings.py b/backend/tests/test_settings.py index 8186da85b..9ba5c814b 100644 --- a/backend/tests/test_settings.py +++ b/backend/tests/test_settings.py @@ -18,6 +18,7 @@ from services.interfaces import HttpTransportError from state import build_initial_state from app_handler import ServiceBundle +from services.sqlite_store import SqliteStore from tests.conftest import TEST_ADMIN_TOKEN from tests.fakes import FakeResponse from tests.fakes.services import FakeServices @@ -35,13 +36,21 @@ def test_default_settings(self, client, default_app_settings, test_state): assert data["hasFalApiKey"] is False assert data["useLocalTextEncoder"] is False assert data["promptCacheSize"] == 100 - assert data["promptEnhancerEnabledT2V"] is True - assert data["promptEnhancerEnabledI2V"] is False + assert data["promptEnhancerEnabled"] is True + assert data["exploreAutoEnhancePrompts"] is True assert data["hasGeminiApiKey"] is False assert data["geminiModel"] == "" assert data["seedLocked"] is False assert data["lockedSeed"] == 42 assert data["useConvVae"] is resolved_use_conv_vae(AppSettings()) + assert data["remoteExposure"] == "off" + assert data["activityDashboardSelections"] == { + "range": "7d", + "models": [], + "resolutions": [], + "aspectRatios": [], + "fps": [], + } # When no custom path is set, the response surfaces the runtime default # so the first-run UI can show the install location. assert data["modelsDir"] == str(test_state.config.default_models_dir) @@ -70,6 +79,42 @@ def test_update_single_field(self, client, test_state): assert r.status_code == 200 assert test_state.state.app_settings.use_torch_compile is True + def test_dashboard_selection_round_trip(self, client, test_state): + selected = { + "range": "all", + "models": ["ltx-2.5-fast"], + "resolutions": ["540p"], + "aspectRatios": ["16:9"], + "fps": ["24"], + } + saved = client.post("/api/settings", json={"activityDashboardSelections": selected}) + assert saved.status_code == 200 + assert client.get("/api/settings").json()["activityDashboardSelections"] == selected + cleared = client.post( + "/api/settings", + json={"activityDashboardSelections": {**selected, "models": [], "range": "30d"}}, + ) + assert cleared.status_code == 200 + stored = test_state.state.app_settings.activity_dashboard_selections + assert stored.models == [] + assert stored.range == "30d" + assert stored.fps == ["24"] + + def test_dashboard_selection_rejects_an_unknown_range(self, client): + bogus = {"range": "bogus"} + assert client.post("/api/stats/activity-dashboard-selections", json=bogus).status_code == 422 + assert client.post("/api/settings", json={"activityDashboardSelections": bogus}).status_code == 422 + + def test_stored_unknown_dashboard_range_loads_as_seven_days(self): + loaded = AppSettings.model_validate({"activity_dashboard_selections": {"range": "bogus"}}) + assert loaded.activity_dashboard_selections.range == "7d" + + def test_explore_auto_enhance_prompts_round_trip(self, client, test_state): + r = client.post("/api/settings", json={"exploreAutoEnhancePrompts": False}) + assert r.status_code == 200 + assert test_state.state.app_settings.explore_auto_enhance_prompts is False + assert client.get("/api/settings").json()["exploreAutoEnhancePrompts"] is False + def test_update_multiple_fields(self, client, test_state): r = client.post("/api/settings", json={"useTorchCompile": True, "promptCacheSize": 42}) assert r.status_code == 200 @@ -95,13 +140,16 @@ def test_prompt_cache_shrinks_cache(self, client, test_state): te = test_state.state.text_encoder assert te is not None for i in range(5): - te.prompt_cache[(f"key_{i}", False)] = f"value_{i}" # type: ignore[assignment] + te.prompt_cache[(f"key_{i}", False, "ltx-2.5-22b-distilled")] = f"value_{i}" # type: ignore[assignment] r = client.post("/api/settings", json={"promptCacheSize": 2}) assert r.status_code == 200 assert len(te.prompt_cache) <= 2 def test_update_api_keys(self, client, test_state): + # LTX is stored without a provider probe. Gemini then Fal are checked. + test_state.http.queue("get", FakeResponse(status_code=200, json_payload={"models": []})) + test_state.http.queue("get", FakeResponse(status_code=200, json_payload={"models": []})) r = client.post( "/api/settings", json={ @@ -114,19 +162,92 @@ def test_update_api_keys(self, client, test_state): assert test_state.state.app_settings.ltx_api_key == "ltx-key-abc" assert test_state.state.app_settings.gemini_api_key == "gemini-key-xyz" assert test_state.state.app_settings.fal_api_key == "fal-key-123" + assert [call.url for call in test_state.http.calls] == [ + "https://generativelanguage.googleapis.com/v1beta/models?pageSize=1", + "https://api.fal.ai/v1/models?limit=1", + ] + + def test_ltx_api_key_is_stored_without_a_probe(self, client, test_state): + test_state.state.app_settings.ltx_api_key = "real-key" + r = client.post("/api/settings", json={"ltxApiKey": " random-junk "}) + assert r.status_code == 200 + assert test_state.state.app_settings.ltx_api_key == "random-junk" + assert test_state.http.calls == [] + + def test_api_key_is_stored_trimmed(self, client, test_state): + test_state.http.queue("get", FakeResponse(status_code=200, json_payload={"models": []})) + r = client.post("/api/settings", json={"falApiKey": " fal-key "}) + assert r.status_code == 200 + assert test_state.state.app_settings.fal_api_key == "fal-key" + headers = test_state.http.calls[0].headers + assert headers is not None + assert headers["Authorization"] == "Key fal-key" + + def test_rejected_fal_api_key_is_not_saved(self, client, test_state): + test_state.state.app_settings.fal_api_key = "real-fal-key" + test_state.http.queue("get", FakeResponse(status_code=401, text="Invalid API key")) + r = client.post("/api/settings", json={"falApiKey": "random-junk"}) + assert_http_error( + r, + status_code=400, + code="FAL_INVALID_API_KEY", + message="This key isn’t valid.", + ) + assert test_state.state.app_settings.fal_api_key == "real-fal-key" + + def test_fal_non_auth_failure_is_not_an_invalid_key(self, client, test_state): + test_state.state.app_settings.fal_api_key = "real-fal-key" + test_state.http.queue("get", FakeResponse(status_code=404, text="missing")) + r = client.post("/api/settings", json={"falApiKey": "real-looking-key"}) + assert_http_error( + r, + status_code=502, + code="FAL_API_KEY_UNVERIFIED", + message="Couldn’t verify this key. Try again in a moment.", + ) + assert test_state.state.app_settings.fal_api_key == "real-fal-key" + + def test_gemini_server_error_is_not_an_invalid_key(self, client, test_state): + test_state.state.app_settings.gemini_api_key = "real-gemini-key" + test_state.http.queue("get", FakeResponse(status_code=503, text="unavailable")) + r = client.post("/api/settings", json={"geminiApiKey": "real-looking-key"}) + assert_http_error( + r, + status_code=502, + code="GEMINI_API_KEY_UNVERIFIED", + message="Couldn’t verify this key. Try again in a moment.", + ) + assert test_state.state.app_settings.gemini_api_key == "real-gemini-key" def test_update_user_prefers_api_video_generations(self, client, test_state): r = client.post("/api/settings", json={"userPrefersLtxApiVideoGenerations": True}) assert r.status_code == 200 assert test_state.state.app_settings.user_prefers_ltx_api_video_generations is True - def test_empty_string_does_not_erase_key(self, client, test_state): + def test_empty_string_clears_api_key(self, client, test_state): test_state.state.app_settings.ltx_api_key = "real-key" test_state.state.app_settings.fal_api_key = "fal-key" r = client.post("/api/settings", json={"ltxApiKey": "", "falApiKey": ""}) assert r.status_code == 200 - assert test_state.state.app_settings.ltx_api_key == "real-key" - assert test_state.state.app_settings.fal_api_key == "fal-key" + assert test_state.state.app_settings.ltx_api_key == "" + assert test_state.state.app_settings.fal_api_key == "" + + def test_null_clears_api_key(self, client, test_state): + test_state.state.app_settings.ltx_api_key = "real-key" + test_state.state.app_settings.gemini_api_key = "gemini-key" + test_state.state.app_settings.fal_api_key = "fal-key" + r = client.post( + "/api/settings", + json={"ltxApiKey": None, "geminiApiKey": None, "falApiKey": None}, + ) + assert r.status_code == 200 + assert test_state.state.app_settings.ltx_api_key == "" + assert test_state.state.app_settings.gemini_api_key == "" + assert test_state.state.app_settings.fal_api_key == "" + body = client.get("/api/settings").json() + assert body["hasLtxApiKey"] is False + assert body["hasGeminiApiKey"] is False + assert body["hasFalApiKey"] is False def test_empty_gemini_model_persists_as_use_default(self, client, test_state): # Unlike API keys, an empty model string is stored so generate-time resolution can @@ -266,6 +387,7 @@ def test_models_dir_persists_and_loads(self, client, test_state, default_app_set a2v_pipeline_class=type(fake_services.a2v_pipeline), retake_pipeline_class=type(fake_services.retake_pipeline), prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), + store=SqliteStore(test_state.config.app_data_dir), ) loaded = build_initial_state(test_state.config, default_app_settings.model_copy(deep=True), service_bundle=bundle) assert loaded.state.app_settings.models_dir == "/tmp/persisted-models" @@ -294,6 +416,7 @@ def _new_state(self, test_state, default_app_settings): a2v_pipeline_class=type(fake_services.a2v_pipeline), retake_pipeline_class=type(fake_services.retake_pipeline), prompt_enhancer_pipeline_class=type(fake_services.prompt_enhancer_pipeline), + store=SqliteStore(test_state.config.app_data_dir), ) return build_initial_state(test_state.config, default_app_settings.model_copy(deep=True), service_bundle=bundle) @@ -316,15 +439,56 @@ def test_load_settings_clamps_from_disk_and_ignores_removed_fields(self, test_st assert "fast_model" not in loaded.state.app_settings.model_dump(by_alias=False) assert "pro_model" not in loaded.state.app_settings.model_dump(by_alias=False) - def test_legacy_prompt_enhancer_key_migrates(self, test_state, default_app_settings): + def test_legacy_prompt_enhancer_key_is_kept(self, test_state, default_app_settings): test_state.config.settings_file.write_text( json.dumps({"prompt_enhancer_enabled": False}), encoding="utf-8", ) loaded = self._new_state(test_state, default_app_settings) - assert loaded.state.app_settings.prompt_enhancer_enabled_t2v is False - assert loaded.state.app_settings.prompt_enhancer_enabled_i2v is False + assert loaded.state.app_settings.prompt_enhancer_enabled is False + + def test_split_prompt_enhancer_flags_fold_back_into_one( + self, test_state, default_app_settings + ): + test_state.config.settings_file.write_text( + json.dumps( + { + "prompt_enhancer_enabled_t2v": False, + "prompt_enhancer_enabled_i2v": False, + } + ), + encoding="utf-8", + ) + + loaded = self._new_state(test_state, default_app_settings) + assert loaded.state.app_settings.prompt_enhancer_enabled is False + dumped = loaded.state.app_settings.model_dump(by_alias=False) + assert "prompt_enhancer_enabled_t2v" not in dumped + assert "prompt_enhancer_enabled_i2v" not in dumped + + def test_a_disagreeing_split_pair_keeps_enhancement_on( + self, test_state, default_app_settings + ): + # OR, not AND: someone who had it on for one conditioning should not lose it silently. + test_state.config.settings_file.write_text( + json.dumps( + { + "prompt_enhancer_enabled_t2v": True, + "prompt_enhancer_enabled_i2v": False, + } + ), + encoding="utf-8", + ) + + loaded = self._new_state(test_state, default_app_settings) + assert loaded.state.app_settings.prompt_enhancer_enabled is True + + def test_missing_prompt_enhancer_flag_defaults_on(self, test_state, default_app_settings): + test_state.config.settings_file.write_text("{}", encoding="utf-8") + + loaded = self._new_state(test_state, default_app_settings) + assert loaded.state.app_settings.prompt_enhancer_enabled is True def test_user_prefers_api_video_generations_persists(self, client, test_state, default_app_settings): r = client.post("/api/settings", json={"userPrefersLtxApiVideoGenerations": True}) @@ -334,6 +498,25 @@ def test_user_prefers_api_video_generations_persists(self, client, test_state, d loaded = self._new_state(test_state, default_app_settings) assert loaded.state.app_settings.user_prefers_ltx_api_video_generations is True + def test_remote_exposure_round_trip(self, client, test_state, monkeypatch): + monkeypatch.setenv("LTX_AUTH_TOKEN", "") + r = client.post("/api/settings", json={"remoteExposure": "lan"}) + assert r.status_code == 200 + assert test_state.state.app_settings.remote_exposure == "lan" + assert client.get("/api/settings").json()["remoteExposure"] == "lan" + + r = client.post("/api/settings", json={"remoteExposure": "off"}) + assert r.status_code == 200 + assert test_state.state.app_settings.remote_exposure == "off" + + def test_poc_tunnel_mode_on_disk_coerces_to_off(self, test_state, default_app_settings): + test_state.config.settings_file.write_text( + json.dumps({"remote_exposure": "personal"}), + encoding="utf-8", + ) + loaded = self._new_state(test_state, default_app_settings) + assert loaded.state.app_settings.remote_exposure == "off" + def test_gemini_model_persists_and_loads(self, client, test_state, default_app_settings): r = client.post("/api/settings", json={"geminiModel": "gemini-2.0-flash"}) assert r.status_code == 200 diff --git a/backend/tests/test_source_encode.py b/backend/tests/test_source_encode.py new file mode 100644 index 000000000..921be1b56 --- /dev/null +++ b/backend/tests/test_source_encode.py @@ -0,0 +1,174 @@ +"""Source encode must not assemble the pixel tensor on CUDA. + +Windows WDDM retake: first tiled encode reserved ~67 GiB with free=0 and still +returned; the next encode after DiffVAE decode never did. Keeping pixels on CPU +until each tile copies in is the observable contract. +""" + +from __future__ import annotations + +import inspect + +import torch +from ltx_core.types import VIDEO_SCALE_FACTORS, VideoPixelShape + +from services.retake_pipeline.source_encode import ( + _freeze_pad_pixels, + _match_latent_length, + encode_source_video_latent, + extend_freeze_pad_frames, + source_encode_tiling, +) + + +def test_mps_encode_uses_default_tiles_cuda_stays_small() -> None: + from ltx_core.model.video_vae import TileSizeConfig + + default = TileSizeConfig.default() + assert source_encode_tiling(torch.device("mps")) == default + # 720p stays split. 540p (long edge 960) is one spatial tile. + assert source_encode_tiling(torch.device("mps"), height=704, width=1280) == default + small = source_encode_tiling(torch.device("mps"), height=512, width=960) + assert small.width.tile_size >= 960 + assert small.height.tile_size >= 512 + assert small.frames == default.frames + # Same measured cell, portrait. A square or a taller portrait is unmeasured. + portrait = source_encode_tiling(torch.device("mps"), height=960, width=512) + assert portrait.height.tile_size >= 960 + assert portrait.width.tile_size >= 512 + assert source_encode_tiling(torch.device("mps"), height=960, width=960) == default + assert source_encode_tiling(torch.device("mps"), height=960, width=800) == default + cuda = source_encode_tiling(torch.device("cuda"), height=512, width=960) + assert cuda.frames.tile_size == 24 + assert cuda.height.tile_size == 256 + assert cuda.width.tile_size == 256 + + +def test_mps_extend_skips_pixel_freeze_other_devices_keep_it() -> None: + assert extend_freeze_pad_frames(torch.device("mps"), 152) == 0 + assert extend_freeze_pad_frames(torch.device("cuda"), 152) == 152 + assert extend_freeze_pad_frames(torch.device("cpu"), 152) == 152 + + +class _FakeEncoder: + def __init__(self) -> None: + self.video_scale_factors = VIDEO_SCALE_FACTORS + self.seen: torch.Tensor | None = None + self.tiling = None + + def tiled_encode(self, video: torch.Tensor, tiling_config: object) -> torch.Tensor: + self.seen = video + self.tiling = tiling_config + frames = 1 + (video.shape[2] - 1) // VIDEO_SCALE_FACTORS.time + return torch.zeros(1, 4, frames, 2, 2) + + +def test_encode_source_video_latent_keeps_pixels_on_cpu(monkeypatch) -> None: + encoder = _FakeEncoder() + frames = [torch.zeros(1, 64, 64, 3, dtype=torch.uint8) for _ in range(9)] + monkeypatch.setattr( + "services.retake_pipeline.source_encode.decode_video_from_file", + lambda **_kwargs: iter(frames), + ) + shape = VideoPixelShape(batch=1, frames=9, height=64, width=64, fps=24.0) + encode_source_video_latent( + encoder, + "clip.mp4", + shape, + dtype=torch.float32, + tiling_config="tiles", + ) + assert encoder.seen is not None + assert encoder.seen.device.type == "cpu" + assert encoder.tiling == "tiles" + + +def test_extend_and_generate_both_encode_source_from_cpu() -> None: + """Home/GenSpace extend shares ``_run`` with retake; that is the CUDA hang path.""" + from services.retake_pipeline.ltx_retake_pipeline import LTXRetakePipeline + + run_src = inspect.getsource(LTXRetakePipeline._run) + assert "encode_source_video_latent(" in run_src + assert "lambda enc: encode_source_video_latent" in run_src + assert "freeze_pad_frames=freeze_pad_frames" in run_src + assert "pad_video_frames" not in run_src + assert "_run(" in inspect.getsource(LTXRetakePipeline.generate) + assert "_run(" in inspect.getsource(LTXRetakePipeline.extend) + + +def test_freeze_pad_pixels_repeats_last_frame_at_end() -> None: + frames = torch.arange(3, dtype=torch.float32).view(1, 1, 3, 1, 1) + padded = _freeze_pad_pixels(frames, 5, at="end") + assert padded.shape[2] == 5 + assert padded[0, 0, :3, 0, 0].tolist() == [0.0, 1.0, 2.0] + assert padded[0, 0, 3:, 0, 0].tolist() == [2.0, 2.0] + + +def test_freeze_pad_pixels_repeats_first_frame_at_start() -> None: + frames = torch.arange(3, dtype=torch.float32).view(1, 1, 3, 1, 1) + padded = _freeze_pad_pixels(frames, 5, at="start") + assert padded[0, 0, :2, 0, 0].tolist() == [0.0, 0.0] + assert padded[0, 0, 2:, 0, 0].tolist() == [0.0, 1.0, 2.0] + + +def test_match_latent_length_repeats_edge_instead_of_zeros() -> None: + latent = torch.arange(3, dtype=torch.float32).view(1, 1, 3, 1, 1) + matched = _match_latent_length(latent, 5) + assert matched[0, 0, 3:, 0, 0].tolist() == [2.0, 2.0] + + +def test_match_latent_length_repeats_first_frame_at_start() -> None: + latent = torch.arange(3, dtype=torch.float32).view(1, 1, 3, 1, 1) + matched = _match_latent_length(latent, 5, at="start") + assert matched[0, 0, :2, 0, 0].tolist() == [0.0, 0.0] + assert matched[0, 0, 2:, 0, 0].tolist() == [0.0, 1.0, 2.0] + + +def test_encode_source_video_latent_freeze_pads_pixels_before_vae(monkeypatch) -> None: + encoder = _FakeEncoder() + frames = [ + torch.full((1, 64, 64, 3), fill_value=i, dtype=torch.uint8) for i in range(9) + ] + monkeypatch.setattr( + "services.retake_pipeline.source_encode.decode_video_from_file", + lambda **_kwargs: iter(frames), + ) + shape = VideoPixelShape(batch=1, frames=17, height=64, width=64, fps=24.0) + encode_source_video_latent( + encoder, + "clip.mp4", + shape, + dtype=torch.float32, + tiling_config="tiles", + freeze_pad_frames=8, + freeze_at="end", + max_duration=9 / 24, + ) + assert encoder.seen is not None + assert encoder.seen.shape[2] == 17 + frozen = encoder.seen[:, :, 8:9] + assert torch.equal(encoder.seen[:, :, 9:], frozen.expand_as(encoder.seen[:, :, 9:])) + + +def test_encode_without_freeze_pad_repeats_the_latent_edge(monkeypatch) -> None: + encoder = _FakeEncoder() + frames = [ + torch.full((1, 64, 64, 3), fill_value=i, dtype=torch.uint8) for i in range(9) + ] + monkeypatch.setattr( + "services.retake_pipeline.source_encode.decode_video_from_file", + lambda **_kwargs: iter(frames), + ) + shape = VideoPixelShape(batch=1, frames=17, height=64, width=64, fps=24.0) + latent = encode_source_video_latent( + encoder, + "clip.mp4", + shape, + dtype=torch.float32, + tiling_config="tiles", + freeze_pad_frames=0, + max_duration=9 / 24, + ) + assert encoder.seen is not None + assert encoder.seen.shape[2] == 9 + assert latent.shape[2] == 3 diff --git a/backend/tests/test_state_actions.py b/backend/tests/test_state_actions.py index dfc0992f1..09cee1e2a 100644 --- a/backend/tests/test_state_actions.py +++ b/backend/tests/test_state_actions.py @@ -8,7 +8,14 @@ import pytest from _routes._errors import HTTPError -from handlers.generation_handler import _RESERVATION_TIMEOUT_S +from runtime_config.video_job_budget import ( + EDIT_JOB_TOO_LARGE_MESSAGE, + VIDEO_JOB_TOO_LARGE_MESSAGE, + VideoJobLoad, + decide_edit_job, +) +from frame_math import compute_num_frames +from handlers.generation_handler import GenerationSlotWaitAborted, _RESERVATION_TIMEOUT_S from services import generation_interrupt from runtime_config.model_download_specs import ( DEPTH_PROCESSOR_CP_ID, @@ -185,6 +192,68 @@ def attempt() -> None: assert results.count(False) == thread_count - 1 +def test_wait_for_generation_slot_acquires_after_existing_job_releases(test_state) -> None: + assert test_state.generation.try_reserve_generation_start() is True + shutdown = threading.Event() + acquired = threading.Event() + thread_error: BaseException | None = None + + def wait_for_slot() -> None: + nonlocal thread_error + try: + with test_state.generation.wait_for_generation_slot(shutdown): + acquired.set() + except Exception as exc: + thread_error = exc + + thread = threading.Thread(target=wait_for_slot) + thread.start() + try: + assert acquired.wait(timeout=0.05) is False + + test_state.generation.release_generation_start_reservation() + assert acquired.wait(timeout=1.0) is True + thread.join(timeout=1.0) + assert thread.is_alive() is False + assert thread_error is None + assert test_state.generation.try_reserve_generation_start() is True + test_state.generation.release_generation_start_reservation() + finally: + shutdown.set() + if thread.is_alive(): + test_state.generation.release_generation_start_reservation() + thread.join(timeout=1.0) + + +def test_wait_for_generation_slot_exits_on_shutdown(test_state) -> None: + assert test_state.generation.try_reserve_generation_start() is True + shutdown = threading.Event() + entered = threading.Event() + thread_error: BaseException | None = None + + def wait_for_slot() -> None: + nonlocal thread_error + try: + with test_state.generation.wait_for_generation_slot(shutdown): + entered.set() + except Exception as exc: + thread_error = exc + + thread = threading.Thread(target=wait_for_slot) + try: + thread.start() + shutdown.set() + thread.join(timeout=1.0) + assert thread.is_alive() is False + assert entered.is_set() is False + assert isinstance(thread_error, GenerationSlotWaitAborted) + assert test_state.generation.try_reserve_generation_start() is False + finally: + test_state.generation.release_generation_start_reservation() + assert test_state.generation.try_reserve_generation_start() is True + test_state.generation.release_generation_start_reservation() + + def test_download_terminal_state_is_sticky_until_next_session(test_state): session_id = test_state.downloads.start_download({"ltx-2.3-22b-distilled"}) test_state.downloads.start_file("ltx-2.3-22b-distilled", "ltx-2.3-22b-distilled.safetensors") @@ -201,6 +270,8 @@ def test_handler_attributes_are_wired(test_state): assert test_state.text is not None assert test_state.pipelines is not None assert test_state.generation is not None + assert test_state.queued_generations is not None + assert test_state.assets is not None assert test_state.video_generation is not None assert test_state.image_generation is not None assert test_state.health is not None @@ -237,6 +308,86 @@ def test_retake_pipeline_eviction(test_state, create_fake_model_files): assert isinstance(test_state.state.gpu_slot.active_pipeline, VideoPipelineState) +def test_retake_1080p_streams_without_flipping_process_mode( + test_state, fake_services, create_fake_model_files +): + create_fake_model_files() + assert test_state.config.local_generations_mode == "full_models_loading" + frames = compute_num_frames(10, 24) + + state = test_state.pipelines.load_retake_pipeline( + distilled=True, width=1920, height=1088, frames=frames + ) + + assert state.loading_mode == "streaming_models_loading" + assert fake_services.retake_pipeline.last_streaming_prefetch_count == 2 + assert test_state.config.local_generations_mode == "full_models_loading" + + +def test_long_1080p_edit_window_is_capped_to_what_31gb_loads( + test_state, create_fake_model_files +): + create_fake_model_files() + cap = test_state.pipelines.edit_encode_frame_cap(1920, 1088) + assert cap < 505 + assert test_state.pipelines.edit_encode_frame_cap(1280, 736) == 505 + decision = decide_edit_job( + 1920, + 1088, + cap, + memory_gb=31, + process_mode="full_models_loading", + ) + assert isinstance(decision, VideoJobLoad) + + state = test_state.pipelines.load_retake_pipeline( + distilled=True, width=1920, height=1088, frames=cap + ) + assert state.loading_mode == "streaming_models_loading" + + with pytest.raises(HTTPError) as gen_space: + test_state.pipelines.load_retake_pipeline( + distilled=True, width=1920, height=1088, frames=505 + ) + assert gen_space.value.status_code == 422 + assert gen_space.value.detail == VIDEO_JOB_TOO_LARGE_MESSAGE + + with pytest.raises(HTTPError) as home: + test_state.pipelines.load_retake_pipeline( + distilled=True, width=1920, height=1088, frames=505, queued_home=True + ) + assert home.value.detail == EDIT_JOB_TOO_LARGE_MESSAGE + + +def test_retake_540p_5s_stays_full(test_state, fake_services, create_fake_model_files): + create_fake_model_files() + frames = compute_num_frames(5, 24) + + state = test_state.pipelines.load_retake_pipeline( + distilled=True, width=1024, height=576, frames=frames + ) + + assert state.loading_mode == "full_models_loading" + assert fake_services.retake_pipeline.last_streaming_prefetch_count is None + + +def test_retake_full_pipeline_is_not_reused_for_a_stream_job( + test_state, fake_services, create_fake_model_files +): + create_fake_model_files() + small = test_state.pipelines.load_retake_pipeline( + distilled=True, width=1024, height=576, frames=compute_num_frames(5, 24) + ) + large = test_state.pipelines.load_retake_pipeline( + distilled=True, width=1920, height=1088, frames=compute_num_frames(10, 24) + ) + + assert small.loading_mode == "full_models_loading" + assert large.loading_mode == "streaming_models_loading" + assert large is not small + assert len(fake_services.retake_pipeline.create_calls) == 2 + + def test_ic_lora_load_includes_depth_resources(test_state, fake_services, create_fake_model_files, create_fake_ic_lora_files): create_fake_model_files(model_id=_IC_LORA_MODEL_ID) create_fake_ic_lora_files() @@ -252,6 +403,7 @@ def test_ic_lora_load_includes_depth_resources(test_state, fake_services, create assert ic_state.depth_pipeline is fake_services.depth_processor_pipeline assert ic_state.lora_path == lora_path assert ic_state.depth_model_path == depth_path + assert fake_services.ic_lora_pipeline.last_streaming_prefetch_count is None def test_ic_lora_unload_clears_preprocessing_resources(test_state, create_fake_model_files, create_fake_ic_lora_files): @@ -289,3 +441,23 @@ def test_pipeline_cache_rebuilds_when_active_model_changes(test_state, create_fa assert second.ltx_model_id == "ltx-2.3-22b-distilled" assert second.gemma_root is None assert second is not first + + +def test_pipeline_load_override_does_not_change_active_settings( + test_state, create_fake_model_files +): + create_fake_model_files() + create_fake_model_files(model_id="ltx-2.3-22b-distilled-1.1") + test_state.state.app_settings.ltx_api_key = "test-key" + test_state.state.app_settings.use_local_text_encoder = False + test_state.state.app_settings.active_ltx_model_id = "ltx-2.5-22b-distilled" + + loaded = test_state.pipelines.load_gpu_pipeline( + "fast", ltx_model_id="ltx-2.3-22b-distilled-1.1" + ) + assert loaded.ltx_model_id == "ltx-2.3-22b-distilled-1.1" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" + + reloaded = test_state.pipelines.load_gpu_pipeline("fast") + assert reloaded.ltx_model_id == "ltx-2.5-22b-distilled" + assert test_state.state.app_settings.active_ltx_model_id == "ltx-2.5-22b-distilled" diff --git a/backend/tests/test_stitch_silence.py b/backend/tests/test_stitch_silence.py new file mode 100644 index 000000000..c08d5b71b --- /dev/null +++ b/backend/tests/test_stitch_silence.py @@ -0,0 +1,53 @@ +"""Silence stands in for a silent source's audio in retake/extend stitches. It must end.""" + +from __future__ import annotations + +from pathlib import Path + +import av +import numpy as np +import pytest + +from services.ffmpeg import run_ffmpeg +from services.records import MediaError +from services.retake_pipeline.stitch_silence import append_silence_input + + +def _silent_video(path: Path, *, frames: int, fps: int) -> str: + import imageio.v2 as imageio + + writer = imageio.get_writer(str(path), fps=fps, codec="libx264", macro_block_size=None) + frame = np.zeros((64, 64, 3), dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return str(path) + + +def test_silence_input_is_added_after_every_input_and_ends_the_output_with_the_video() -> None: + args = ["-i", "video.mp4"] + append_silence_input(args) + assert args[-1] == "-shortest" + assert args.index("-shortest") > max(i for i, arg in enumerate(args) if arg == "-i") + + +def test_a_stitch_that_keeps_the_silence_tail_finishes_with_the_video(tmp_path: Path) -> None: + """Retake with a suffix and extend at the start keep ``atrim=start=...`` of the silence; + without ``-shortest`` ffmpeg encodes silence until the timeout.""" + video = _silent_video(tmp_path / "video.mp4", frames=50, fps=25) + dest = tmp_path / "out.mp4" + args = ["-y", "-i", video] + append_silence_input(args) + args += [ + "-filter_complex", + "[0:v]setpts=PTS-STARTPTS[v];[1:a]atrim=start=1,asetpts=PTS-STARTPTS[a]", + "-map", "[v]", "-map", "[a]", str(dest), + ] + + try: + run_ffmpeg(args, timeout=30) + except MediaError as exc: + pytest.fail(f"ffmpeg did not stop on its own: {exc}") + + with av.open(str(dest)) as container: + assert float(container.duration) / av.time_base == pytest.approx(2.0, abs=0.2) diff --git a/backend/tests/test_store.py b/backend/tests/test_store.py new file mode 100644 index 000000000..f4ebb5429 --- /dev/null +++ b/backend/tests/test_store.py @@ -0,0 +1,1991 @@ +from __future__ import annotations + +import json +import logging +import sqlite3 +from pathlib import Path + +import pytest +from PIL import Image +from pydantic import JsonValue, ValidationError + +from api_types import ( + Asset, + AudioAssetMetadata, + AudioMeta, + ImageAssetMetadata, + ImageMeta, +) +from services.migrations import MIGRATIONS_DIR, apply_migrations +from services.media_probe import MAX_IMAGE_BYTES, MAX_IMAGE_PIXELS, MAX_VIDEO_BYTES, validate_ingest_source +from services.sqlite_store import ( + SqliteStore, + _unlink_path, + collect_asset_ids, +) +from services.records import ( + AssetInUseError, + AssetRecord, + AttemptError, + GenerationRecord, + MarkSucceededError, + MediaError, + OutputSpec, + StatusError, + UnavailableError, +) +from services.unavailable_store import UnavailableStore + + +def _connect(db_path: Path) -> sqlite3.Connection: + conn = sqlite3.connect(str(db_path)) + conn.row_factory = sqlite3.Row + conn.execute("PRAGMA foreign_keys = ON") + conn.execute("PRAGMA journal_mode = WAL") + return conn + + +def test_fresh_db_applies_initial_schema(tmp_path: Path) -> None: + db_path = tmp_path / "store.sqlite3" + conn = _connect(db_path) + apply_migrations(conn, MIGRATIONS_DIR) + tables = { + row[0] + for row in conn.execute( + "SELECT name FROM sqlite_master WHERE type='table'" + ).fetchall() + } + assert tables >= { + "schema_migrations", + "generations", + "assets", + "paired_devices", + } + version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] + assert version == 1 + asset_columns = { + row["name"] for row in conn.execute("PRAGMA table_info(assets)").fetchall() + } + assert "thumbnail_path" in asset_columns + asset_indexes = { + row["name"] for row in conn.execute("PRAGMA index_list(assets)").fetchall() + } + assert "idx_assets_created_at" in asset_indexes + columns = { + row["name"] for row in conn.execute("PRAGMA table_info(generations)").fetchall() + } + assert { + "queued_at", + "attempt_count", + "error_code", + "spec", + "contract_version", + "deleted_at", + "queue_rank", + } <= columns + assert "error" not in columns + assert "params" not in columns + assert ( + conn.execute( + "SELECT sql FROM sqlite_master WHERE name = 'generation_assets'" + ).fetchone() + is None + ) + asset_sql = conn.execute( + "SELECT sql FROM sqlite_master WHERE name = 'assets'" + ).fetchone()[0] + assert "producer_generation_id" in asset_sql + assert "output_ordinal" in asset_sql + index_sql = conn.execute( + "SELECT sql FROM sqlite_master WHERE name = 'idx_assets_producer_ordinal'" + ).fetchone()[0] + assert "deleted_at IS NULL" in index_sql + indexes = { + row["name"] for row in conn.execute("PRAGMA index_list(generations)").fetchall() + } + assert "idx_generations_queue" in indexes + assert "idx_generations_pending_queue_rank" in indexes + assert "idx_generations_status" not in indexes + conn.close() + + +def test_second_open_is_noop(tmp_path: Path) -> None: + db_path = tmp_path / "store.sqlite3" + conn = _connect(db_path) + apply_migrations(conn, MIGRATIONS_DIR) + apply_migrations(conn, MIGRATIONS_DIR) + count = conn.execute("SELECT COUNT(*) FROM schema_migrations").fetchone()[0] + assert count == 1 + conn.close() + + +def test_rerun_after_ddl_without_ledger_row_does_not_brick(tmp_path: Path) -> None: + db_path = tmp_path / "store.sqlite3" + conn = _connect(db_path) + conn.executescript( + (MIGRATIONS_DIR / "0001_initial_schema.sql").read_text(encoding="utf-8") + ) + conn.execute("DELETE FROM schema_migrations") + conn.commit() + apply_migrations(conn, MIGRATIONS_DIR) + version = conn.execute("SELECT MAX(version) FROM schema_migrations").fetchone()[0] + assert version == 1 + tables = { + row[0] + for row in conn.execute( + "SELECT name FROM sqlite_master WHERE type='table'" + ).fetchall() + } + assert tables >= {"schema_migrations", "generations", "assets", "paired_devices"} + conn.close() + + +def test_failed_migration_rolls_back_ddl_and_skips_ledger_row(tmp_path: Path) -> None: + migrations = tmp_path / "migrations" + migrations.mkdir() + (migrations / "0001_ok.sql").write_text("CREATE TABLE t1 (id INTEGER PRIMARY KEY);") + (migrations / "0002_bad.sql").write_text( + "CREATE TABLE t2 (id INTEGER PRIMARY KEY);\nCREATE TABLE t2 (id INTEGER PRIMARY KEY);" + ) + conn = _connect(tmp_path / "store.sqlite3") + try: + apply_migrations(conn, migrations) + except sqlite3.OperationalError: + pass + else: + raise AssertionError("expected OperationalError from duplicate CREATE TABLE") + tables = { + row[0] + for row in conn.execute( + "SELECT name FROM sqlite_master WHERE type='table'" + ).fetchall() + } + assert "t1" in tables + assert "t2" not in tables + versions = [row[0] for row in conn.execute("SELECT version FROM schema_migrations")] + assert versions == [1] + conn.close() + + +def _png(path: Path, size: tuple[int, int] = (32, 24)) -> Path: + Image.new("RGB", size, color=(10, 20, 30)).save(path) + return path + + +def _mp4( + path: Path, *, frames: int = 8, width: int = 16, height: int = 16, fps: int = 8 +) -> Path: + import numpy as np + import imageio.v2 as imageio + + writer = imageio.get_writer( + str(path), fps=fps, codec="libx264", macro_block_size=None + ) + frame = np.zeros((height, width, 3), dtype=np.uint8) + for _ in range(frames): + writer.append_data(frame) + writer.close() + return path + + +def _wav( + path: Path, *, duration_seconds: float = 0.25, sample_rate: int = 8000 +) -> Path: + import wave + + frame_count = max(1, int(duration_seconds * sample_rate)) + with wave.open(str(path), "wb") as wav_file: + wav_file.setnchannels(1) + wav_file.setsampwidth(2) + wav_file.setframerate(sample_rate) + wav_file.writeframes(b"\x00\x00" * frame_count) + return path + + +def _claim(store: SqliteStore, generation_id: str): + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == generation_id + return claimed + + +def _spec( + prompt: str | None = None, + inputs: dict[str, JsonValue] | None = None, +) -> dict[str, JsonValue]: + spec: dict[str, JsonValue] = {"params": {}, "inputs": {}} + if prompt is not None: + spec["params"] = {"prompt": prompt} + if inputs is not None: + spec["inputs"] = inputs + return spec + + +def _output( + asset_id: str, + dest: str, + *, + ordinal: int = 0, + mime_type: str = "image/png", + name: str = "out.png", +) -> OutputSpec: + return OutputSpec( + asset_id=asset_id, + dest_path=dest, + ordinal=ordinal, + mime_type=mime_type, + name=name, + ) + + +def _succeed_png( + store: SqliteStore, + *, + name: str = "out.png", + prompt: str | None = None, + size: tuple[int, int] = (8, 8), +) -> AssetRecord: + gen = store.insert_generation("text-to-video", _spec(prompt=prompt)) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), size) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest, name=name)], + attempt_count=claimed.attempt_count, + ) + return done.outputs[0] + + +def _succeed_wav(store: SqliteStore, *, name: str = "clip.wav") -> AssetRecord: + gen = store.insert_generation("audio-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("audio", "audio/wav") + _wav(Path(dest)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest, mime_type="audio/wav", name=name)], + attempt_count=claimed.attempt_count, + ) + return done.outputs[0] + + +class _FailOnceHydrationDb(SqliteStore): + def __init__(self, app_data_dir: Path) -> None: + super().__init__(app_data_dir) + self._fail_next_hydration = True + + def _load_required( + self, conn: sqlite3.Connection, generation_id: str + ) -> GenerationRecord: + if self._fail_next_hydration: + self._fail_next_hydration = False + raise RuntimeError("forced hydration failure") + return super()._load_required(conn, generation_id) + + +def test_collect_asset_ids_walks_nested_objects_and_lists() -> None: + assert collect_asset_ids( + { + "params": {"prompt": "x"}, + "inputs": { + "startFrame": {"assetId": "start"}, + "keyframes": [ + {"assetId": "k0", "timeMs": 0}, + {"assetId": "k1", "timeMs": 1000}, + ], + }, + } + ) == ["start", "k0", "k1"] + + +def test_collect_asset_ids_dedupes_and_ignores_non_ids() -> None: + assert collect_asset_ids( + { + "inputs": { + "startFrame": {"assetId": "same"}, + "endFrame": {"assetId": "same"}, + "empty": {"assetId": ""}, + "number": {"assetId": 12}, + "nested": {"assetId": {"assetId": "inner"}}, + "snake": {"asset_id": "snake-ignored"}, + "pascal": {"AssetId": "pascal-ignored"}, + } + } + ) == ["same", "inner"] + assert collect_asset_ids({}) == [] + assert collect_asset_ids("assetId") == [] + + +def test_ingest_rejects_symlink_disguised_as_video(tmp_path: Path) -> None: + secret = tmp_path / "secret.txt" + secret.write_text("not media") + disguised = tmp_path / "clip.mp4" + try: + disguised.symlink_to(secret) + except OSError: + pytest.skip("symlinks not available") + store = SqliteStore(tmp_path / "app_data") + try: + store.ingest_upload(str(disguised)) + except MediaError: + return + raise AssertionError("expected MediaError for disguised ingest path") + + +def test_ingest_upload_copies_file_and_survives_source_delete(tmp_path: Path) -> None: + app_data = tmp_path / "app_data" + source = _png(tmp_path / "cat.png", (64, 48)) + store = SqliteStore(app_data) + asset = store.ingest_upload(str(source)) + source.unlink() + assert Path(asset.path).is_file() + assert asset.origin == "uploaded" + assert asset.media_kind == "image" + assert asset.mime_type == "image/png" + assert asset.metadata.mediaType == "image" + assert asset.metadata.metadata.width == 64 + assert asset.metadata.metadata.height == 48 + copied = Path(app_data / "assets") + assert Path(asset.path).parent == copied + + +def test_get_asset_returns_ingested_asset_and_none_for_unknown(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + asset = store.ingest_upload(str(_png(tmp_path / "cat.png", (64, 48)))) + + assert store.get_asset(asset.id) == asset + assert store.get_asset("missing-asset") is None + + +def test_ingest_video_stores_studio_metadata(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + source = _mp4(tmp_path / "clip.mp4", frames=8, width=16, height=12, fps=8) + asset = store.ingest_upload(str(source)) + assert asset.media_kind == "video" + assert asset.metadata.mediaType == "video" + meta = asset.metadata.metadata + assert meta.width == 16 + assert meta.height == 12 + assert meta.durationMs == 1000 + assert meta.sizeBytes == source.stat().st_size + assert meta.audioStreamCount == 0 + + +def test_ingest_audio_stores_studio_metadata(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + source = _wav(tmp_path / "clip.wav", duration_seconds=0.25, sample_rate=8000) + asset = store.ingest_upload(str(source)) + assert asset.media_kind == "audio" + assert asset.metadata.mediaType == "audio" + meta = asset.metadata.metadata + assert meta.durationMs == 250 + expected_bitrate = round((source.stat().st_size * 8) / 0.25) + assert meta.bitrate == expected_bitrate + + +def test_ingest_image_persists_jpeg_thumbnail(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + source = _png(tmp_path / "still.png") + record = store.ingest_upload(str(source)) + assert record.thumbnail_path is not None + assert Path(record.thumbnail_path).is_file() + loaded = store.get_asset(record.id) + assert loaded is not None + assert loaded.thumbnail_path == record.thumbnail_path + + +def test_ingest_audio_leaves_thumbnail_null(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + source = _wav(tmp_path / "clip.wav") + record = store.ingest_upload(str(source)) + assert record.media_kind == "audio" + assert record.thumbnail_path is None + + +def test_ingest_succeeds_when_thumbnail_writer_fails(tmp_path: Path) -> None: + class Boom: + def write(self, source_path: str, media_kind: object) -> str | None: + del source_path, media_kind + raise RuntimeError("thumb boom") + + store = SqliteStore(tmp_path / "app_data", thumbnail_writer=Boom()) + record = store.ingest_upload(str(_png(tmp_path / "still.png"))) + assert record.id + assert record.thumbnail_path is None + assert Path(record.path).is_file() + + +def test_audio_metadata_bitrate_is_optional() -> None: + metadata = AudioAssetMetadata( + mediaType="audio", + metadata=AudioMeta(durationMs=250), + ) + assert metadata.metadata.bitrate is None + + +def test_audio_metadata_without_bitrate_hydrates(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + source = _wav(tmp_path / "clip.wav", duration_seconds=0.25, sample_rate=8000) + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("audio", "audio/wav") + Path(dest).write_bytes(source.read_bytes()) + store.mark_succeeded( + gen.id, + [_output(asset_id, dest, mime_type="audio/wav", name="out.wav")], + attempt_count=claimed.attempt_count, + ) + db_path = tmp_path / "app_data" / "store.sqlite3" + conn = sqlite3.connect(str(db_path)) + conn.execute( + "UPDATE assets SET metadata = ? WHERE id = ?", + ( + json.dumps({"mediaType": "audio", "metadata": {"durationMs": 250}}), + asset_id, + ), + ) + conn.commit() + conn.close() + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.outputs[0].metadata.mediaType == "audio" + assert loaded.outputs[0].metadata.metadata.bitrate is None + + +def test_asset_rejects_media_kind_metadata_mismatch() -> None: + image_metadata = ImageAssetMetadata( + mediaType="image", + metadata=ImageMeta(width=8, height=8), + ) + with pytest.raises(ValidationError): + AssetRecord( + id="asset-1", + media_kind="video", + origin="uploaded", + path="/tmp/x.png", + thumbnail_path=None, + mime_type="image/png", + name="x.png", + metadata=image_metadata, + created_at=1, + ) + with pytest.raises(ValidationError): + Asset( + id="asset-1", + media_kind="video", + origin="uploaded", + path="/tmp/x.png", + thumbnail_path=None, + mime_type="image/png", + name="x.png", + metadata=image_metadata, + created_at=1, + ) + + +def test_ingest_unreadable_video_does_not_leave_dest(tmp_path: Path) -> None: + junk = tmp_path / "clip.mp4" + junk.write_bytes(b"not a video") + store = SqliteStore(tmp_path / "app_data") + try: + store.ingest_upload(str(junk)) + except MediaError as exc: + assert exc.code == "UNREADABLE_MEDIA" + assets = list((tmp_path / "app_data" / "assets").iterdir()) + assert assets == [] + return + raise AssertionError("expected MediaError for unreadable video") + + +def test_allocate_output_path_has_no_row(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + asset_id, dest = store.allocate_output_path("video", "video/mp4") + dest_path = Path(dest) + assert asset_id + assert dest_path.name == f"{asset_id}.mp4" + assert dest_path.parent.name == ".in-flight" + assert not dest_path.exists() + conn = sqlite3.connect(str(tmp_path / "app_data" / "store.sqlite3")) + count = conn.execute("SELECT COUNT(*) FROM assets").fetchone()[0] + conn.close() + assert count == 0 + + +def test_insert_and_list_filters_by_feature(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + a = store.ingest_upload(str(_png(tmp_path / "a.png"))) + gen_a = store.insert_generation( + "text-to-video", + _spec(prompt="fox", inputs={"startFrame": {"assetId": a.id}}), + ) + store.insert_generation("cozy-felt", _spec(prompt="felt")) + listed = store.list_generations("text-to-video") + assert [g.id for g in listed] == [gen_a.id] + assert listed[0].status == "queued" + assert listed[0].queued_at is not None + assert listed[0].attempt_count == 0 + assert listed[0].started_at is None + assert listed[0].contract_version == 1 + assert listed[0].spec == { + "params": {"prompt": "fox"}, + "inputs": {"startFrame": {"assetId": a.id}}, + } + assert listed[0].outputs == () + + +def test_list_recent_features_is_unique_newest_first(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + oldest = store.insert_generation("text-to-video", _spec(prompt="a")) + middle = store.insert_generation("extend", _spec(prompt="b")) + newest = store.insert_generation("text-to-video", _spec(prompt="c")) + dropped = store.insert_generation("retake", _spec(prompt="d")) + conn = sqlite3.connect(tmp_path / "app_data" / "store.sqlite3") + conn.executemany( + "UPDATE generations SET created_at = ? WHERE id = ?", + [ + (1, oldest.id), + (2, middle.id), + (3, newest.id), + (4, dropped.id), + ], + ) + conn.execute( + "UPDATE generations SET deleted_at = 5 WHERE id = ?", + (dropped.id,), + ) + conn.commit() + conn.close() + + assert store.list_recent_features(limit=4) == ["text-to-video", "extend"] + assert store.list_recent_features(limit=1) == ["text-to-video"] + assert store.list_recent_features( + limit=4, allowed=frozenset({"extend"}) + ) == ["extend"] + assert store.list_recent_features(limit=4, allowed=frozenset()) == [] + + +def test_list_queue_generations_resolves_generation_inputs(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + asset = store.ingest_upload(str(_png(tmp_path / "input.png"))) + generation = store.insert_generation( + "image-to-video", + _spec(inputs={"startFrame": {"assetId": asset.id}}), + ) + + queued = store.list_queue_generations() + + assert len(queued) == 1 + assert queued[0].generation.id == generation.id + assert queued[0].input_assets == (asset,) + + +def test_list_queue_generations_includes_active_and_pending_work( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + active = store.insert_generation("text-to-video", _spec(prompt="active")) + pending = store.insert_generation("text-to-video", _spec(prompt="pending")) + _claim(store, active.id) + + queue = store.list_queue_generations() + + assert [ + (entry.generation.id, entry.generation.status) for entry in queue + ] == [(active.id, "running"), (pending.id, "queued")] + + +def test_insert_generation_stores_contract_version(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation( + "image-to-video", + _spec(), + contract_version=2, + ) + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.contract_version == 2 + with pytest.raises(ValueError, match="contract_version"): + store.insert_generation("image-to-video", _spec(), contract_version=0) + + +def test_list_keeps_missing_input_and_groups_generations( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.ingest_upload(str(_png(tmp_path / "first.png"))) + second = store.ingest_upload(str(_png(tmp_path / "second.png"))) + gen_first = store.insert_generation( + "text-to-video", + _spec(prompt="first", inputs={"startFrame": {"assetId": first.id}}), + ) + gen_second = store.insert_generation( + "text-to-video", + _spec(prompt="second", inputs={"startFrame": {"assetId": second.id}}), + ) + Path(first.path).unlink() + listed = store.list_generations("text-to-video") + assert [g.id for g in listed] == [gen_second.id, gen_first.id] + assert listed[0].spec["inputs"] == {"startFrame": {"assetId": second.id}} + assert listed[1].spec["inputs"] == {"startFrame": {"assetId": first.id}} + + +def test_spec_preserves_input_slot_names(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + start = store.ingest_upload(str(_png(tmp_path / "start.png"))) + end = store.ingest_upload(str(_png(tmp_path / "end.png"))) + ref = store.ingest_upload(str(_png(tmp_path / "ref.png"))) + gen = store.insert_generation( + "image-to-video", + _spec( + inputs={ + "startFrame": {"assetId": start.id}, + "endFrame": {"assetId": end.id}, + "ref": {"assetId": ref.id}, + } + ), + ) + assert gen.spec["inputs"] == { + "startFrame": {"assetId": start.id}, + "endFrame": {"assetId": end.id}, + "ref": {"assetId": ref.id}, + } + + +def test_claim_next_queued_is_fifo_and_increments_attempt(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.insert_generation("text-to-video", _spec(prompt="first")) + second = store.insert_generation("text-to-video", _spec(prompt="second")) + + claimed_first = _claim(store, first.id) + assert claimed_first.status == "running" + assert claimed_first.attempt_count == 1 + assert claimed_first.started_at is not None + assert store.claim_next_queued() is not None + assert store.claim_next_queued() is None + + loaded_second = store.get_generation(second.id) + assert loaded_second is not None + assert loaded_second.status == "running" + assert loaded_second.attempt_count == 1 + + +def test_reorder_moves_queued_generation_before_target(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.insert_generation("text-to-video", _spec(prompt="first")) + second = store.insert_generation("text-to-video", _spec(prompt="second")) + third = store.insert_generation("text-to-video", _spec(prompt="third")) + + reordered = store.reorder_queued_generation(third.id, second.id) + + assert reordered.id == third.id + assert [entry.generation.id for entry in store.list_queue_generations()] == [ + first.id, + third.id, + second.id, + ] + + +def test_reordered_generation_is_next_claimed(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.insert_generation("text-to-video", _spec(prompt="first")) + second = store.insert_generation("text-to-video", _spec(prompt="second")) + third = store.insert_generation("text-to-video", _spec(prompt="third")) + + store.reorder_queued_generation(third.id, first.id) + + claimed = store.claim_next_queued() + + assert claimed is not None + assert claimed.id == third.id + assert claimed.status == "running" + assert claimed.attempt_count == 1 + still_first = store.get_generation(first.id) + still_second = store.get_generation(second.id) + assert still_first is not None + assert still_second is not None + assert still_first.status == "queued" + assert still_second.status == "queued" + + +def test_reorder_moves_queued_generation_to_tail(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.insert_generation("text-to-video", _spec(prompt="first")) + second = store.insert_generation("text-to-video", _spec(prompt="second")) + third = store.insert_generation("text-to-video", _spec(prompt="third")) + + reordered = store.reorder_queued_generation(first.id, None) + + assert reordered.id == first.id + assert [entry.generation.id for entry in store.list_queue_generations()] == [ + second.id, + third.id, + first.id, + ] + + +def test_reorder_rejects_running_or_cancelled_generation(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + running = store.insert_generation("text-to-video", _spec(prompt="running")) + target = store.insert_generation("text-to-video", _spec(prompt="target")) + cancelled = store.insert_generation("text-to-video", _spec(prompt="cancelled")) + _claim(store, running.id) + store.request_generation_cancellation(cancelled.id) + + with pytest.raises(StatusError): + store.reorder_queued_generation(running.id, target.id) + with pytest.raises(StatusError): + store.reorder_queued_generation(cancelled.id, target.id) + + +def test_reorder_rebalances_when_adjacent_ranks_have_no_gap(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.insert_generation("text-to-video", _spec(prompt="first")) + second = store.insert_generation("text-to-video", _spec(prompt="second")) + third = store.insert_generation("text-to-video", _spec(prompt="third")) + conn = _connect(tmp_path / "app_data" / "store.sqlite3") + conn.executemany( + "UPDATE generations SET queue_rank = ? WHERE id = ?", + [(10, first.id), (11, second.id), (12, third.id)], + ) + conn.commit() + conn.close() + + store.reorder_queued_generation(third.id, second.id) + + rows = _connect(tmp_path / "app_data" / "store.sqlite3").execute( + """ + SELECT id, queue_rank FROM generations + WHERE status = 'queued' + ORDER BY queue_rank ASC, id ASC + """ + ).fetchall() + assert [row["id"] for row in rows] == [first.id, third.id, second.id] + assert rows[2]["queue_rank"] - rows[1]["queue_rank"] > 1 + + +def test_request_cancel_queued_finalizes_immediately(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + + cancelled = store.request_generation_cancellation(generation.id) + + assert cancelled.status == "cancelled" + assert cancelled.finished_at is not None + row = _connect(tmp_path / "app_data" / "store.sqlite3").execute( + "SELECT queue_rank FROM generations WHERE id = ?", (generation.id,) + ).fetchone() + assert row["queue_rank"] is None + + +def test_request_cancel_running_marks_cancelling(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, generation.id) + + cancelling = store.request_generation_cancellation(generation.id) + + assert cancelling.status == "cancelling" + assert cancelling.attempt_count == claimed.attempt_count + assert cancelling.finished_at is None + + +def test_boot_recovery_finalizes_cancelling_generation(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + _claim(store, generation.id) + store.request_generation_cancellation(generation.id) + + assert store.fail_running_on_boot() == 1 + + recovered = store.get_generation(generation.id) + assert recovered is not None + assert recovered.status == "cancelled" + assert recovered.finished_at is not None + + +def test_claim_next_queued_rolls_back_when_hydration_fails(tmp_path: Path) -> None: + store = _FailOnceHydrationDb(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec(prompt="retry")) + + with pytest.raises(RuntimeError, match="forced hydration failure"): + store.claim_next_queued() + + loaded = store.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "queued" + assert loaded.attempt_count == 0 + assert store.has_queued() is True + + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == generation.id + assert claimed.status == "running" + assert claimed.attempt_count == 1 + + +def test_has_queued_only_reports_pending_work(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + assert store.has_queued() is False + generation = store.insert_generation("text-to-video", _spec()) + assert store.has_queued() is True + store.claim_next_queued() + assert store.has_queued() is False + assert generation.status == "queued" + + +def test_fail_running_on_boot_preserves_queued_generation(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + running = store.insert_generation("text-to-video", _spec()) + queued = store.insert_generation("text-to-video", _spec()) + _claim(store, running.id) + + assert store.fail_running_on_boot() == 1 + + failed = store.get_generation(running.id) + still_queued = store.get_generation(queued.id) + assert failed is not None + assert failed.status == "failed" + assert failed.error_code == "INTERRUPTED" + assert still_queued is not None + assert still_queued.status == "queued" + + +def test_retry_requeues_same_generation_id(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, generation.id) + store.mark_failed( + generation.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count + ) + + retried = store.retry_generation(generation.id) + + assert retried.id == generation.id + assert retried.status == "queued" + assert retried.error_code is None + assert retried.started_at is None + assert retried.finished_at is None + assert retried.attempt_count == 2 + claimed_again = _claim(store, generation.id) + assert claimed_again.attempt_count == 3 + + +def test_mark_cancelled_rejects_stale_attempt_after_retry(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, generation.id) + store.mark_failed( + generation.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count + ) + retried = store.retry_generation(generation.id) + current = _claim(store, generation.id) + store.request_generation_cancellation(generation.id) + + with pytest.raises(AttemptError) as exc_info: + store.mark_cancelled( + generation.id, + attempt_count=claimed.attempt_count, + ) + + assert exc_info.value.expected == claimed.attempt_count + assert exc_info.value.actual == current.attempt_count + loaded = store.get_generation(generation.id) + assert loaded is not None + assert loaded.status == "cancelling" + assert loaded.attempt_count == retried.attempt_count + 1 + + +def test_retry_appends_generation_to_queue(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + first = store.insert_generation("text-to-video", _spec(prompt="first")) + second = store.insert_generation("text-to-video", _spec(prompt="second")) + first_claim = _claim(store, first.id) + store.mark_failed( + first.id, "OUTPUT_UNREADABLE", attempt_count=first_claim.attempt_count + ) + store.retry_generation(first.id) + + assert _claim(store, second.id).id == second.id + assert _claim(store, first.id).id == first.id + + +def test_retry_requires_failed_generation(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + + with pytest.raises(StatusError): + store.retry_generation(generation.id) + + +def test_terminal_update_rejects_stale_attempt(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + first_claim = _claim(store, generation.id) + store.mark_failed( + generation.id, + "OUTPUT_UNREADABLE", + attempt_count=first_claim.attempt_count, + ) + store.retry_generation(generation.id) + _claim(store, generation.id) + + with pytest.raises(AttemptError): + store.mark_failed( + generation.id, + "OUTPUT_UNREADABLE", + attempt_count=first_claim.attempt_count, + ) + + +def test_unknown_input_asset_rejected(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + with pytest.raises(ValueError, match="unknown input asset"): + store.insert_generation( + "image-to-video", + _spec(inputs={"startFrame": {"assetId": "missing-id"}}), + ) + + +def test_uploaded_has_no_producer(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "in.png"))) + conn = sqlite3.connect(str(tmp_path / "app_data" / "store.sqlite3")) + row = conn.execute( + """ + SELECT producer_generation_id, output_ordinal, origin + FROM assets WHERE id = ? + """, + (uploaded.id,), + ).fetchone() + conn.close() + assert row[0] is None + assert row[1] is None + assert row[2] == "uploaded" + + +def test_same_file_as_start_and_end(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "in.png"))) + gen = store.insert_generation( + "image-to-video", + _spec( + inputs={ + "startFrame": {"assetId": uploaded.id}, + "endFrame": {"assetId": uploaded.id}, + } + ), + ) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + assert done.status == "succeeded" + assert done.spec["inputs"] == { + "startFrame": {"assetId": uploaded.id}, + "endFrame": {"assetId": uploaded.id}, + } + assert len(done.outputs) == 1 + assert done.outputs[0].origin == "generated" + + +def test_mark_succeeded_missing_output_raises_without_failing(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + with pytest.raises(MarkSucceededError) as caught: + store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + assert caught.value.error_code == "OUTPUT_MISSING" + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "running" + failed = store.mark_failed( + gen.id, + "OUTPUT_MISSING", + [dest], + attempt_count=claimed.attempt_count, + ) + assert failed.status == "failed" + assert failed.error_code == "OUTPUT_MISSING" + + +def test_mark_succeeded_missing_output_leaves_partials_for_caller( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + kept_id, kept_dest = store.allocate_output_path("image", "image/png") + missing_id, missing_dest = store.allocate_output_path("image", "image/png") + _png(Path(kept_dest), (8, 8)) + with pytest.raises(MarkSucceededError) as caught: + store.mark_succeeded( + gen.id, + [ + _output(kept_id, kept_dest, ordinal=0, name="a.png"), + _output(missing_id, missing_dest, ordinal=1, name="b.png"), + ], + attempt_count=claimed.attempt_count, + ) + assert caught.value.error_code == "OUTPUT_MISSING" + assert Path(kept_dest).exists() + store.mark_failed( + gen.id, + "OUTPUT_MISSING", + [kept_dest, missing_dest], + attempt_count=claimed.attempt_count, + ) + assert not Path(kept_dest).exists() + assert not Path(missing_dest).exists() + + +def test_mark_succeeded_unreadable_output_raises_without_failing( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("video", "video/mp4") + Path(dest).write_bytes(b"not a video") + with pytest.raises(MarkSucceededError) as caught: + store.mark_succeeded( + gen.id, + [_output(asset_id, dest, mime_type="video/mp4", name="out.mp4")], + attempt_count=claimed.attempt_count, + ) + assert caught.value.error_code == "OUTPUT_UNREADABLE" + assert Path(dest).exists() + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "running" + store.mark_failed( + gen.id, + "OUTPUT_UNREADABLE", + [dest], + attempt_count=claimed.attempt_count, + ) + assert not Path(dest).exists() + retried = store.retry_generation(gen.id) + assert retried.status == "queued" + + +def test_mark_failed_rejects_unknown_error_code(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + with pytest.raises(ValueError): + store.mark_failed( + gen.id, + "transient", # type: ignore[arg-type] + attempt_count=claimed.attempt_count, + ) + + +def test_mark_succeeded_requires_output(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + try: + store.mark_succeeded(gen.id, [], attempt_count=claimed.attempt_count) + except ValueError: + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "running" + return + raise AssertionError("expected ValueError for empty outputs") + + +def test_mark_succeeded_rejects_path_outside_assets(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + outsider = _png(tmp_path / "outside.png") + try: + store.mark_succeeded( + gen.id, + [_output("not-used", str(outsider))], + attempt_count=claimed.attempt_count, + ) + except ValueError: + assert outsider.is_file() + return + raise AssertionError("expected ValueError for dest outside assets") + + +def test_mark_succeeded_inserts_output_asset(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + assert done.status == "succeeded" + assert done.finished_at is not None + assert len(done.outputs) == 1 + assert done.outputs[0].media_kind == "image" + assert done.outputs[0].mime_type == "image/png" + assert done.outputs[0].origin == "generated" + assert done.outputs[0].id == asset_id + assert Path(done.outputs[0].path).is_file() + assert ".in-flight" not in Path(done.outputs[0].path).parts + assert not Path(dest).exists() + assert "path" not in done.spec + + +def test_mark_succeeded_persists_video_thumbnail(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("video", "video/mp4") + _mp4(Path(dest)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest, mime_type="video/mp4", name="out.mp4")], + attempt_count=claimed.attempt_count, + ) + assert done.outputs[0].thumbnail_path is not None + assert Path(done.outputs[0].thumbnail_path).is_file() + + +def test_mark_succeeded_persists_probed_mime_not_spec(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest, mime_type="video/mp4", name="out.mp4")], + attempt_count=claimed.attempt_count, + ) + assert len(done.outputs) == 1 + assert done.outputs[0].media_kind == "image" + assert done.outputs[0].mime_type == "image/png" + + +def test_delete_generation_keeps_asset_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "keep.png"))) + gen = store.insert_generation( + "text-to-video", + _spec(inputs={"startFrame": {"assetId": uploaded.id}}), + ) + assert store.delete_generation(gen.id) is True + assert store.get_generation(gen.id) is None + assert Path(uploaded.path).is_file() + conn = sqlite3.connect(str(tmp_path / "app_data" / "store.sqlite3")) + remaining = conn.execute("SELECT COUNT(*) FROM assets").fetchone()[0] + deleted = conn.execute( + "SELECT deleted_at FROM generations WHERE id = ?", (gen.id,) + ).fetchone()[0] + conn.close() + assert remaining == 1 + assert deleted is not None + + +def test_deleted_queued_generation_is_not_claimed(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + hidden = store.insert_generation("text-to-video", _spec(prompt="hidden")) + visible = store.insert_generation("text-to-video", _spec(prompt="visible")) + assert store.delete_generation(hidden.id) is True + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == visible.id + assert store.get_generation(hidden.id) is None + + +def test_missing_output_file_omitted_from_get(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + Path(done.outputs[0].path).unlink() + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.outputs == () + + +def test_missing_input_file_stays_on_get(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "start.png"))) + gen = store.insert_generation( + "image-to-video", + _spec(inputs={"startFrame": {"assetId": uploaded.id}}), + ) + Path(uploaded.path).unlink() + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "queued" + assert loaded.spec["inputs"] == {"startFrame": {"assetId": uploaded.id}} + assert loaded.outputs == () + + +def test_claim_fails_generation_when_input_file_missing_and_claims_next( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "start.png"))) + broken = store.insert_generation( + "image-to-video", + _spec(inputs={"startFrame": {"assetId": uploaded.id}}), + ) + healthy = store.insert_generation("text-to-video", _spec(prompt="ok")) + Path(uploaded.path).unlink() + claimed = store.claim_next_queued() + assert claimed is not None + assert claimed.id == healthy.id + failed = store.get_generation(broken.id) + assert failed is not None + assert failed.status == "failed" + assert failed.error_code == "INPUT_MISSING" + assert failed.spec["inputs"] == {"startFrame": {"assetId": uploaded.id}} + + +def test_fail_running_on_boot_marks_only_running_failed(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + _claim(store, gen.id) + n = store.fail_running_on_boot() + assert n == 1 + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "failed" + assert loaded.error_code == "INTERRUPTED" + assert loaded.finished_at is not None + + +def test_succeed_after_cancel_raises(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + store.request_generation_cancellation(gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + try: + store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + except StatusError: + return + raise AssertionError("expected StatusError") + + +def test_mark_cancelled_deletes_partial_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + _, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + store.request_generation_cancellation(gen.id) + store.mark_cancelled( + gen.id, + partial_paths=[dest], + attempt_count=claimed.attempt_count, + ) + assert not Path(dest).exists() + + +def test_mark_cancelled_does_not_unlink_outside_assets(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + outsider = tmp_path / "keep.txt" + outsider.write_text("x") + store.request_generation_cancellation(gen.id) + store.mark_cancelled( + gen.id, + partial_paths=[str(outsider)], + attempt_count=claimed.attempt_count, + ) + assert outsider.is_file() + + +def test_mark_cancelled_commits_when_partial_path_is_directory( + tmp_path: Path, caplog +) -> None: + caplog.set_level(logging.WARNING) + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, generation.id) + _, partial_path = store.allocate_output_path("video", "video/mp4") + Path(partial_path).mkdir() + store.request_generation_cancellation(generation.id) + + cancelled = store.mark_cancelled( + generation.id, + partial_paths=[partial_path], + attempt_count=claimed.attempt_count, + ) + + assert cancelled.status == "cancelled" + assert Path(partial_path).is_dir() + assert any( + "Could not remove partial output" in record.getMessage() + for record in caplog.records + ) + + +def test_delete_running_generation_is_rejected(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + generation = store.insert_generation("text-to-video", _spec()) + _claim(store, generation.id) + + with pytest.raises(StatusError): + store.delete_generation(generation.id) + + +def test_services_package_does_not_export_store_plumbing() -> None: + import services + + assert not hasattr(services, "apply_migrations") + assert not hasattr(services, "MIGRATIONS_DIR") + assert not hasattr(services, "SqliteStore") + + +def test_ingest_jpeg_named_png_uses_decoded_mime(tmp_path: Path) -> None: + source = tmp_path / "photo.png" + Image.new("RGB", (8, 8), color=(4, 5, 6)).save(source, format="JPEG") + store = SqliteStore(tmp_path / "app_data") + asset = store.ingest_upload(str(source)) + assert asset.mime_type == "image/jpeg" + assert asset.media_kind == "image" + assert Path(asset.path).suffix in {".jpg", ".jpeg"} + assert Path(asset.path).is_file() + + +def test_mark_failed_deletes_generated_assets_so_retry_can_succeed( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + leftover_id, leftover_dest = store.allocate_output_path("image", "image/png") + leftover_path = Path(leftover_dest).parent.parent / f"{leftover_id}.png" + _png(Path(leftover_dest), (8, 8)) + Path(leftover_dest).replace(leftover_path) + db_path = tmp_path / "app_data" / "store.sqlite3" + conn = sqlite3.connect(str(db_path)) + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, output_ordinal, + mime_type, name, metadata, created_at, deleted_at + ) VALUES (?, 'image', 'generated', ?, 0, 'image/png', 'old.png', ?, 1, NULL) + """, + ( + leftover_id, + gen.id, + json.dumps( + { + "mediaType": "image", + "metadata": {"width": 8, "height": 8}, + } + ), + ), + ) + conn.commit() + conn.close() + store.mark_failed(gen.id, "OUTPUT_UNREADABLE", attempt_count=claimed.attempt_count) + assert not leftover_path.exists() + retried = store.retry_generation(gen.id) + claimed_again = _claim(store, retried.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed_again.attempt_count, + ) + assert done.status == "succeeded" + assert [out.origin for out in done.outputs] == ["generated"] + + +def test_retry_deletes_generated_assets_left_on_failed_row(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + store.mark_failed(gen.id, "OUTPUT_MISSING", attempt_count=claimed.attempt_count) + leftover_id, leftover_dest = store.allocate_output_path("image", "image/png") + leftover_path = Path(leftover_dest).parent.parent / f"{leftover_id}.png" + _png(Path(leftover_dest), (8, 8)) + Path(leftover_dest).replace(leftover_path) + db_path = tmp_path / "app_data" / "store.sqlite3" + conn = sqlite3.connect(str(db_path)) + conn.execute( + """ + INSERT INTO assets ( + id, media_kind, origin, producer_generation_id, output_ordinal, + mime_type, name, metadata, created_at, deleted_at + ) VALUES (?, 'image', 'generated', ?, 0, 'image/png', 'old.png', ?, 1, NULL) + """, + ( + leftover_id, + gen.id, + json.dumps( + { + "mediaType": "image", + "metadata": {"width": 8, "height": 8}, + } + ), + ), + ) + conn.commit() + conn.close() + store.retry_generation(gen.id) + assert not leftover_path.exists() + claimed_again = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed_again.attempt_count, + ) + assert done.status == "succeeded" + + +def test_duplicate_output_ordinal_rejected(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + first_id, first_dest = store.allocate_output_path("image", "image/png") + second_id, second_dest = store.allocate_output_path("image", "image/png") + _png(Path(first_dest), (8, 8)) + _png(Path(second_dest), (8, 8)) + with pytest.raises(ValueError, match="ordinals must be unique"): + store.mark_succeeded( + gen.id, + [ + _output(first_id, first_dest, ordinal=0), + _output(second_id, second_dest, ordinal=0), + ], + attempt_count=claimed.attempt_count, + ) + + +def test_mark_failed_return_survives_immediate_delete(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + failed = store.mark_failed( + gen.id, "OUTPUT_MISSING", attempt_count=claimed.attempt_count + ) + assert store.delete_generation(gen.id) is True + assert failed.status == "failed" + assert failed.error_code == "OUTPUT_MISSING" + assert store.get_generation(gen.id) is None + + +def test_mark_succeeded_unlinks_dests_when_attempt_check_fails(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + store.request_generation_cancellation(gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + with pytest.raises(StatusError): + store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + assert not Path(dest).exists() + + +class _CommitFailsStore(SqliteStore): + def __init__(self, app_data_dir: Path) -> None: + super().__init__(app_data_dir) + self.fail_commit = False + + def _commit_loaded( + self, conn: sqlite3.Connection, generation_id: str + ) -> GenerationRecord: + if self.fail_commit: + raise sqlite3.OperationalError("commit failed") + return super()._commit_loaded(conn, generation_id) + + +def test_mark_succeeded_restores_promoted_file_when_commit_fails( + tmp_path: Path, +) -> None: + store = _CommitFailsStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + canonical = Path(dest).parent.parent / f"{asset_id}.png" + store.fail_commit = True + with pytest.raises(sqlite3.OperationalError, match="commit failed"): + store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + assert Path(dest).is_file() + assert not canonical.exists() + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "running" + + +def test_mark_failed_unlinks_partials_when_attempt_check_fails(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + _, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + store.request_generation_cancellation(gen.id) + with pytest.raises(StatusError): + store.mark_failed( + gen.id, + "OUTPUT_MISSING", + [dest], + attempt_count=claimed.attempt_count, + ) + assert not Path(dest).exists() + + +def test_unlink_path_retries_permission_error( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + path = tmp_path / "partial.mp4" + path.write_bytes(b"partial output") + attempts = {"n": 0} + real_unlink = Path.unlink + + def flaky(self: Path, *args: object, **kwargs: object) -> None: + if self == path: + attempts["n"] += 1 + if attempts["n"] == 1: + raise PermissionError("sharing violation") + real_unlink(self, *args, **kwargs) + + monkeypatch.setattr(Path, "unlink", flaky) + _unlink_path(path) + assert not path.exists() + assert attempts["n"] == 2 + + +def test_fail_running_on_boot_reclaims_in_flight_files(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "keep.png"))) + gen = store.insert_generation( + "text-to-video", + _spec(inputs={"startFrame": {"assetId": uploaded.id}}), + ) + _claim(store, gen.id) + _, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + stray = Path(uploaded.path).parent / "stray.png" + _png(stray, (8, 8)) + assert store.fail_running_on_boot() == 1 + assert not Path(dest).exists() + assert Path(uploaded.path).is_file() + assert stray.is_file() + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "failed" + assert loaded.error_code == "INTERRUPTED" + + +def test_fail_running_on_boot_does_not_wipe_assets_if_db_is_recreated( + tmp_path: Path, +) -> None: + app_data = tmp_path / "app_data" + store = SqliteStore(app_data) + uploaded = store.ingest_upload(str(_png(tmp_path / "keep.png"))) + keep = Path(uploaded.path) + assert keep.is_file() + for suffix in ("", "-wal", "-shm"): + (app_data / f"store.sqlite3{suffix}").unlink(missing_ok=True) + store = SqliteStore(app_data) + store.fail_running_on_boot() + assert keep.is_file() + + +def test_mark_succeeded_accepts_already_promoted_output(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec()) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + canonical = Path(dest).parent.parent / f"{asset_id}.png" + Path(dest).replace(canonical) + done = store.mark_succeeded( + gen.id, + [_output(asset_id, dest)], + attempt_count=claimed.attempt_count, + ) + assert done.status == "succeeded" + assert Path(done.outputs[0].path) == canonical + assert canonical.is_file() + assert not Path(dest).exists() + + +def test_ingest_rejects_oversized_image_before_copy(tmp_path: Path) -> None: + source = tmp_path / "huge.png" + with source.open("wb") as handle: + handle.truncate(MAX_IMAGE_BYTES + 1) + store = SqliteStore(tmp_path / "app_data") + with pytest.raises(MediaError) as caught: + store.ingest_upload(str(source)) + assert caught.value.code == "FILE_TOO_LARGE" + assets_dir = tmp_path / "app_data" / "assets" + assert list(assets_dir.iterdir()) == [] + + +def test_validate_ingest_source_does_not_cap_video_bytes(tmp_path: Path) -> None: + source = tmp_path / "huge.mp4" + with source.open("wb") as handle: + handle.truncate(MAX_VIDEO_BYTES + 1) + validate_ingest_source(source) + + +def test_ingest_rejects_image_dimensions_too_large(tmp_path: Path) -> None: + source = tmp_path / "wide.png" + Image.new("RGB", (MAX_IMAGE_PIXELS + 1, 1), color=(1, 2, 3)).save(source) + store = SqliteStore(tmp_path / "app_data") + with pytest.raises(MediaError) as caught: + store.ingest_upload(str(source)) + assert caught.value.code == "IMAGE_DIMENSIONS_TOO_LARGE" + assets_dir = tmp_path / "app_data" / "assets" + assert list(assets_dir.iterdir()) == [] + + +def test_ingest_decompression_bomb_is_unreadable(tmp_path: Path) -> None: + original = Image.MAX_IMAGE_PIXELS + Image.MAX_IMAGE_PIXELS = 1 + try: + source = _png(tmp_path / "bomb.png", (16, 16)) + store = SqliteStore(tmp_path / "app_data") + with pytest.raises(MediaError) as caught: + store.ingest_upload(str(source)) + assert caught.value.code == "UNREADABLE_MEDIA" + assets_dir = tmp_path / "app_data" / "assets" + assert list(assets_dir.iterdir()) == [] + finally: + Image.MAX_IMAGE_PIXELS = original + + +def test_list_assets_omits_uploaded(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + uploaded = store.ingest_upload(str(_png(tmp_path / "in.png"))) + generated = _succeed_png(store) + ids = [item.asset.id for item in store.list_assets().items] + assert uploaded.id not in ids + assert generated.id in ids + assert all(item.asset.origin == "generated" for item in store.list_assets().items) + + +def test_list_assets_filters_kind_q_and_sort(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + img = _succeed_png(store, name="Fox.png") + _succeed_wav(store, name="clip.wav") + page = store.list_assets(media_kind="image", q="fox") + assert [item.asset.id for item in page.items] == [img.id] + oldest = store.list_assets(sort="created_at-asc") + newest = store.list_assets(sort="created_at-desc") + assert oldest.items[0].asset.created_at <= oldest.items[-1].asset.created_at + assert newest.items[0].asset.id != oldest.items[0].asset.id or len(newest.items) == 1 + + +def test_list_assets_escapes_like_metacharacters(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + _succeed_png(store, name="100%.png") + _succeed_png(store, name="100x.png") + page = store.list_assets(q="100%") + assert [item.asset.name for item in page.items] == ["100%.png"] + + +def test_list_assets_tombstones_missing_files(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + kept = _succeed_png(store, name="kept.png") + gone = _succeed_png(store, name="gone.png") + Path(gone.path).unlink() + page = store.list_assets() + ids = [item.asset.id for item in page.items] + assert kept.id in ids + assert gone.id not in ids + assert store.get_asset(gone.id) is None + + +def test_get_asset_tombstones_missing_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gone = store.ingest_upload(str(_png(tmp_path / "gone.png"))) + Path(gone.path).unlink() + assert store.get_asset(gone.id) is None + assert gone.id not in [item.asset.id for item in store.list_assets().items] + + +def test_list_assets_can_omit_missing_files_without_tombstoning( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + gone = _succeed_png(store, name="gone.png") + payload = Path(gone.path).read_bytes() + Path(gone.path).unlink() + page = store.list_assets(tombstone_missing=False) + assert gone.id not in [item.asset.id for item in page.items] + Path(gone.path).write_bytes(payload) + assert store.get_asset(gone.id) is not None + + +def test_get_asset_can_miss_without_tombstoning(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gone = store.ingest_upload(str(_png(tmp_path / "gone.png"))) + payload = Path(gone.path).read_bytes() + Path(gone.path).unlink() + assert store.get_asset(gone.id, tombstone_missing=False) is None + Path(gone.path).write_bytes(payload) + assert store.get_asset(gone.id) is not None + + +def test_list_assets_does_not_tombstone_in_use_missing_files(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + start = _succeed_png(store, name="start.png") + payload = Path(start.path).read_bytes() + store.insert_generation( + "image-to-video", + _spec(inputs={"startFrame": {"assetId": start.id}}), + ) + Path(start.path).unlink() + page = store.list_assets() + assert start.id not in [item.asset.id for item in page.items] + Path(start.path).write_bytes(payload) + assert store.get_asset(start.id) is not None + + +def test_list_assets_marks_nested_in_use(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + start = _succeed_png(store, name="start.png") + free = _succeed_png(store, name="free.png") + store.insert_generation( + "image-to-video", + _spec( + inputs={ + "startFrame": {"assetId": start.id}, + "keyframes": [{"assetId": start.id}], + } + ), + ) + by_id = {item.asset.id: item.in_use for item in store.list_assets().items} + assert by_id[start.id] is True + assert by_id[free.id] is False + + +def test_list_assets_keyset_stable_order(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + for i in range(3): + _succeed_png(store, name=f"{i}.png") + first = store.list_assets(limit=2) + assert first.next_cursor is not None + rest = store.list_assets(limit=2, cursor=first.next_cursor) + listed = [item.asset.id for item in first.items] + [ + item.asset.id for item in rest.items + ] + assert len(listed) == 3 + assert len(set(listed)) == 3 + + +def test_list_assets_keyset_continues_after_tombstoned_head(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + later = _succeed_png(store, name="later.png") + gone = _succeed_png(store, name="gone.png") + Path(gone.path).unlink() + conn = sqlite3.connect(str(tmp_path / "app_data" / "store.sqlite3")) + conn.execute( + "UPDATE assets SET created_at = ? WHERE id = ?", + (later.created_at + 1, gone.id), + ) + conn.commit() + conn.close() + first = store.list_assets(limit=1) + assert [item.asset.id for item in first.items] == [] + assert first.next_cursor is not None + rest = store.list_assets(limit=1, cursor=first.next_cursor) + assert [item.asset.id for item in rest.items] == [later.id] + assert store.get_asset(gone.id) is None + + +def test_list_assets_rejects_invalid_cursor(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + _succeed_png(store, name="a.png") + with pytest.raises(ValueError): + store.list_assets(cursor="not-a-cursor") + with pytest.raises(ValueError): + store.list_assets(cursor="123:") + + +def test_unavailable_store_list_assets_raises() -> None: + with pytest.raises(UnavailableError): + UnavailableStore().list_assets() + + +def test_delete_unused_upload_unlinks_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + record = store.ingest_upload(str(_png(tmp_path / "solo.png"))) + path = Path(record.path) + assert store.delete_asset(record.id) is True + assert not path.exists() + assert store.get_asset(record.id) is None + assert store.delete_asset(record.id) is True # idempotent + + +def test_delete_unknown_asset_returns_false(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + assert store.delete_asset("missing") is False + + +def test_delete_asset_blocks_cancelling_producer(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, [_output(asset_id, dest)], attempt_count=claimed.attempt_count + ) + conn = sqlite3.connect(str(tmp_path / "app_data" / "store.sqlite3")) + conn.execute( + "UPDATE generations SET status = 'cancelling' WHERE id = ?", + (gen.id,), + ) + conn.commit() + conn.close() + with pytest.raises(StatusError) as caught: + store.delete_asset(done.outputs[0].id) + assert caught.value.status == "cancelling" + assert store.get_asset(done.outputs[0].id) is not None + loaded = store.get_generation(gen.id) + assert loaded is not None + assert loaded.status == "cancelling" + + +def test_delete_generated_output_hides_producer(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, [_output(asset_id, dest)], attempt_count=claimed.attempt_count + ) + out = done.outputs[0] + assert store.delete_asset(out.id) is True + assert store.get_generation(gen.id) is None + assert store.get_asset(out.id) is None + + +def test_delete_when_producer_already_results_deleted_is_success( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, [_output(asset_id, dest)], attempt_count=claimed.attempt_count + ) + assert store.delete_generation(gen.id) is True + assert store.delete_asset(done.outputs[0].id) is True + + +def test_delete_blocks_when_used_as_nested_input(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + start = store.ingest_upload(str(_png(tmp_path / "start.png"))) + store.insert_generation( + "image-to-video", + {"params": {}, "inputs": {"nested": [{"assetId": start.id}]}}, + ) + with pytest.raises(AssetInUseError): + store.delete_asset(start.id) + assert Path(start.path).is_file() + + +def test_delete_blocks_generated_asset_used_as_later_input(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + asset_id, dest = store.allocate_output_path("image", "image/png") + _png(Path(dest), (8, 8)) + done = store.mark_succeeded( + gen.id, [_output(asset_id, dest)], attempt_count=claimed.attempt_count + ) + out_id = done.outputs[0].id + store.insert_generation( + "image-to-video", + {"params": {}, "inputs": {"startFrame": {"assetId": out_id}}}, + ) + with pytest.raises(AssetInUseError): + store.delete_asset(out_id) + + +def test_delete_sibling_output_keeps_generation_until_last( + tmp_path: Path, +) -> None: + store = SqliteStore(tmp_path / "app_data") + gen = store.insert_generation("text-to-video", _spec(prompt="x")) + claimed = _claim(store, gen.id) + a_id, a_dest = store.allocate_output_path("image", "image/png") + b_id, b_dest = store.allocate_output_path("image", "image/png") + _png(Path(a_dest), (8, 8)) + _png(Path(b_dest), (8, 8)) + store.mark_succeeded( + gen.id, + [_output(a_id, a_dest, ordinal=0), _output(b_id, b_dest, ordinal=1)], + attempt_count=claimed.attempt_count, + ) + assert store.delete_asset(a_id) is True + assert store.get_generation(gen.id) is not None + assert store.delete_asset(b_id) is True + assert store.get_generation(gen.id) is None + + +def test_delete_already_deleted_succeeds_without_file(tmp_path: Path) -> None: + store = SqliteStore(tmp_path / "app_data") + record = store.ingest_upload(str(_png(tmp_path / "gone.png"))) + path = Path(record.path) + assert store.delete_asset(record.id) is True + path.unlink(missing_ok=True) + assert store.delete_asset(record.id) is True + assert store.get_asset(record.id) is None + + +def test_delete_returns_true_when_canonical_unlink_fails( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + store = SqliteStore(tmp_path / "app_data") + record = store.ingest_upload(str(_png(tmp_path / "busy.png"))) + canonical = Path(record.path) + real_unlink = Path.unlink + + def boom(self: Path, *args: object, **kwargs: object) -> None: + if self == canonical: + raise OSError("busy") + real_unlink(self, *args, **kwargs) + + monkeypatch.setattr(Path, "unlink", boom) + assert store.delete_asset(record.id) is True + assert store.get_asset(record.id) is None diff --git a/backend/tests/test_thumbnails.py b/backend/tests/test_thumbnails.py new file mode 100644 index 000000000..c013354ea --- /dev/null +++ b/backend/tests/test_thumbnails.py @@ -0,0 +1,112 @@ +from pathlib import Path + +import pytest +from PIL import Image +from services.thumbnails import PillowAvThumbnailWriter + + +def _png(path: Path, size: tuple[int, int] = (64, 48)) -> Path: + Image.new("RGB", size, color=(10, 20, 30)).save(path) + return path + + +def test_image_write_returns_jpeg_beside_source(tmp_path: Path) -> None: + source = _png(tmp_path / "a.png") + written = PillowAvThumbnailWriter().write(str(source), "image") + assert written is not None + thumb = Path(written) + assert thumb.suffix.lower() == ".jpg" + assert thumb.parent == source.parent + with Image.open(thumb) as im: + assert im.format == "JPEG" + + +def _half_clear_image(path: Path) -> Path: + """Red on the left. The right is clear, with green under it as ffmpeg may leave it.""" + image = Image.new("RGBA", (64, 48), (0, 255, 0, 0)) + image.paste((200, 40, 40, 255), (0, 0, 32, 48)) + image.save(path) + return path + + +@pytest.mark.parametrize("suffix", [".gif", ".png"]) +def test_an_image_thumbnail_shows_the_grid_where_the_image_is_clear( + tmp_path: Path, suffix: str +) -> None: + source = _half_clear_image(tmp_path / f"cutout{suffix}") + written = PillowAvThumbnailWriter().write(str(source), "image") + assert written is not None + with Image.open(written) as thumb: + opaque = thumb.getpixel((8, 24)) + clear = thumb.getpixel((56, 24)) + assert opaque[0] > 150 and opaque[1] < 90 # the red subject + assert all(channel > 200 for channel in clear) # the grid, not the green under it + + +def test_audio_write_returns_none(tmp_path: Path) -> None: + wav = tmp_path / "a.wav" + wav.write_bytes(b"RIFF") + assert PillowAvThumbnailWriter().write(str(wav), "audio") is None + + +def test_write_swallows_errors(tmp_path: Path) -> None: + missing = tmp_path / "gone.png" + assert PillowAvThumbnailWriter().write(str(missing), "image") is None + + +def test_webm_cutout_thumbnail_shows_the_grid_where_the_clip_is_transparent( + tmp_path: Path, +) -> None: + """A cutout keeps its source color under alpha 0. The thumbnail must not show it.""" + source = tmp_path / "cutout.webm" + _bake_half_transparent_webm(source) + written = PillowAvThumbnailWriter().write(str(source), "video") + assert written is not None + with Image.open(written) as thumb: + width, height = thumb.size + opaque = thumb.getpixel((8, height // 2)) + transparent = thumb.getpixel((width - 8, height // 2)) + assert opaque[0] > 150 and opaque[1] < 90 # the red subject + assert all(channel > 200 for channel in transparent) # the grid, not the red source + + +def test_a_plain_webm_keeps_the_generic_decoder(tmp_path: Path) -> None: + """A VP8 WebM is valid input. Only a VP9 alpha stream needs libvpx-vp9.""" + import numpy as np + import imageio.v2 as imageio + + source = tmp_path / "plain.webm" + writer = imageio.get_writer(str(source), fps=10, codec="libvpx", macro_block_size=None) + for _ in range(5): + writer.append_data(np.full((64, 96, 3), 120, dtype=np.uint8)) + writer.close() + written = PillowAvThumbnailWriter().write(str(source), "video") + assert written is not None + + +def test_a_large_alpha_webm_gets_a_capped_thumbnail(tmp_path: Path) -> None: + source = tmp_path / "cutout.webm" + _bake_half_transparent_webm(source) + written = PillowAvThumbnailWriter().write(str(source), "video") + assert written is not None + with Image.open(written) as thumb: + assert max(thumb.size) <= 512 + + +def _bake_half_transparent_webm(dest: Path) -> None: + import numpy as np + from services.features.video.alpha_cutout import bake_alpha_cutout + import imageio.v2 as imageio + + def mp4(path: Path, frame: "np.ndarray") -> Path: + writer = imageio.get_writer(str(path), fps=24, codec="libx264", macro_block_size=None) + for _ in range(9): + writer.append_data(frame) + writer.close() + return path + + source = np.zeros((64, 96, 3), dtype=np.uint8) + source[:, :] = (200, 40, 40) + matte = np.zeros((64, 96, 3), dtype=np.uint8) + matte[:, :48] = 255 + bake_alpha_cutout(mp4(dest.with_name("s.mp4"), source), mp4(dest.with_name("m.mp4"), matte), dest) diff --git a/backend/tests/test_tiled_ic_lora_pipeline.py b/backend/tests/test_tiled_ic_lora_pipeline.py new file mode 100644 index 000000000..c6a0f9b4c --- /dev/null +++ b/backend/tests/test_tiled_ic_lora_pipeline.py @@ -0,0 +1,240 @@ +"""TiledICLoraPipeline tiles the IC-LoRA reference encode when the canvas exceeds one tile.""" + +from __future__ import annotations + +import inspect +from types import SimpleNamespace + +import pytest +import torch +from ltx_core.model.video_vae import TileSizeConfig +from ltx_pipelines.ic_lora import ICLoraPipeline +from ltx_pipelines.utils.types import ImageConditioningInput + +from services.ic_lora_pipeline.ic_lora_inference import InferenceResult, encode_result +from services.ic_lora_pipeline.tiled_ic_lora_pipeline import ( + TiledICLoraPipeline, + encode_tiling_for_canvas, + reference_encode_canvas, + reference_encode_tiling, +) + + +def test_video_conditionings_signature_matches_upstream() -> None: + ours = inspect.signature(TiledICLoraPipeline._video_conditionings) + upstream = inspect.signature(ICLoraPipeline._video_conditionings) + assert list(ours.parameters) == list(upstream.parameters) + + +def test_reference_encode_tiling_skips_sub_tile_canvas() -> None: + tile = TileSizeConfig.default() + assert reference_encode_tiling(tile.height.tile_size, tile.width.tile_size, 9) is None + assert reference_encode_tiling(512, 768, 9) is None + + +def test_reference_encode_tiling_uses_default_when_canvas_exceeds_tile() -> None: + tile = TileSizeConfig.default() + assert reference_encode_tiling(1080, 1920, 241) == tile + assert reference_encode_tiling(512, 768, tile.frames.tile_size + 1) == tile + + +def test_reference_encode_canvas_aligns_stage1_to_vae_grid() -> None: + assert reference_encode_canvas(1280, 704, downscale_factor=1) == (1280, 704) + assert reference_encode_canvas(1280, 704, downscale_factor=2) == (1280, 704) + assert reference_encode_canvas(1300, 700, downscale_factor=1) == (1280, 672) + + +def test_encode_tiling_for_canvas_matches_post_downscale_size() -> None: + assert encode_tiling_for_canvas(512, 768, 9, downscale_factor=1) is None + assert encode_tiling_for_canvas(1080, 1920, 241, downscale_factor=1) == TileSizeConfig.default() + assert encode_tiling_for_canvas(1280, 704, 121, downscale_factor=1) == TileSizeConfig.default() + # append encodes at stage-1 / 2 = 640×352. That fits one 768 tile at 9 frames. + assert encode_tiling_for_canvas(1280, 704, 9, downscale_factor=2) is None + + +def test_video_conditionings_passes_desktop_encode_tiling(monkeypatch) -> None: + captured: dict[str, object] = {} + + def fake_reference(chunk, **kwargs): # noqa: ARG001 + captured["encode_tiling"] = kwargs.get("encode_tiling") + captured["downscale"] = kwargs.get("downscale_factor") + captured["temporal"] = kwargs.get("reference_temporal_scale_factor") + captured["strength"] = kwargs.get("conditioning_attention_strength") + captured["color_space"] = kwargs.get("color_space") + return ["reference"] + + def fake_images(chunk, **kwargs): # noqa: ARG001 + captured["image_color_space"] = kwargs.get("color_space") + return ["image"] + + monkeypatch.setattr( + "ltx_pipelines.chunks.conditionings.reference_video_conditionings_for_chunk", + fake_reference, + ) + monkeypatch.setattr("ltx_pipelines.chunks.conditionings.image_conditionings_for_chunk", fake_images) + pipe = TiledICLoraPipeline.__new__(TiledICLoraPipeline) + pipe.reference_downscale_factor = 1 + pipe.reference_temporal_scale_factor = 2 + pipe.image_conditioner = lambda build: build(object()) + color_space = object() + ctx = SimpleNamespace( + images=[], + num_frames=121, + video_conditioning=[("ref.mp4", 1.0)], + conditioning_attention_strength=0.7, + conditioning_attention_mask=None, + color_space=color_space, + ) + # 40 * 32 = 1280, 22 * 32 = 704. Exceeds one default tile at 121 frames. + chunk = SimpleNamespace( + video=torch.zeros(1, 4, 2, 40, 22), + layout=SimpleNamespace(pixel_frames=121), + ) + + make = pipe._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=True), {}) + items = make(chunk) + + # Image conditionings come first, then the reference video, in one encoder pass. + assert items == ["image", "reference"] + assert captured["downscale"] == 1 + assert captured["encode_tiling"] == TileSizeConfig.default() + assert captured["temporal"] == 2 + assert captured["strength"] == 0.7 + assert captured["color_space"] is color_space + assert captured["image_color_space"] is color_space + # Audio-only chunks carry no video, so nothing is encoded. + assert make(SimpleNamespace(video=None, layout=SimpleNamespace(pixel_frames=0))) == [] + + +def test_stage_without_ic_lora_takes_upstream_closure(monkeypatch) -> None: + """Stage 2 of the default recipe runs without the IC-LoRA, so no reference is encoded.""" + sentinel = object() + seen: dict[str, object] = {} + + def fake_parent(self, ctx, stage_config, frame_sources): # noqa: ARG001 + seen["stage_config"] = stage_config + return sentinel + + monkeypatch.setattr(ICLoraPipeline, "_video_conditionings", fake_parent) + pipe = TiledICLoraPipeline.__new__(TiledICLoraPipeline) + stage_config = SimpleNamespace(apply_ic_lora=False) + + result = pipe._video_conditionings(SimpleNamespace(), stage_config, {}) + + assert result is sentinel + assert seen["stage_config"] is stage_config + + +def _still_ctx(*images: ImageConditioningInput) -> SimpleNamespace: + return SimpleNamespace( + images=list(images), + num_frames=121, + video_conditioning=[("ref.mp4", 1.0)], + conditioning_attention_strength=1.0, + conditioning_attention_mask=None, + color_space=object(), + ) + + +def _still_pipeline(downscale: int = 1) -> TiledICLoraPipeline: + pipe = TiledICLoraPipeline.__new__(TiledICLoraPipeline) + pipe.reference_downscale_factor = downscale + pipe.reference_temporal_scale_factor = 1 + pipe.image_conditioner = lambda build: build(object()) + return pipe + + +def test_negative_frame_still_is_appended_after_the_reference_video(monkeypatch) -> None: + seen: dict[str, object] = {} + + def fake_images(chunk, **kwargs): # noqa: ARG001 + seen["frame_images"] = kwargs["images"] + return ["image"] + + def fake_reference(chunk, **kwargs): # noqa: ARG001 + return ["reference"] + + def fake_stills(**kwargs): + seen["stills"] = kwargs["images"] + seen["size"] = (kwargs["height"], kwargs["width"]) + return ["still"] + + monkeypatch.setattr("ltx_pipelines.chunks.conditionings.image_conditionings_for_chunk", fake_images) + monkeypatch.setattr( + "ltx_pipelines.chunks.conditionings.reference_video_conditionings_for_chunk", fake_reference + ) + monkeypatch.setattr( + "services.ic_lora_pipeline.tiled_ic_lora_pipeline.combined_image_conditionings", fake_stills + ) + first_frame = ImageConditioningInput("first.png", 0, 1.0) + still = ImageConditioningInput("look.png", -1, 1.0) + chunk = SimpleNamespace( + video=torch.zeros(1, 4, 2, 16, 24), + layout=SimpleNamespace(pixel_frames=9), + ) + + make = _still_pipeline()._video_conditionings( + _still_ctx(first_frame, still), SimpleNamespace(apply_ic_lora=True), {} + ) + + assert make(chunk) == ["image", "reference", "still"] + assert seen["frame_images"] == [first_frame] + assert seen["stills"] == [still] + assert seen["size"] == (16 * 32, 24 * 32) + + +def test_still_at_another_negative_index_is_rejected() -> None: + ctx = _still_ctx(ImageConditioningInput("look.png", -2, 1.0)) + + with pytest.raises(ValueError, match="frame_idx -1"): + _still_pipeline()._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=True), {}) + + +def test_still_with_a_reference_downscale_is_rejected() -> None: + ctx = _still_ctx(ImageConditioningInput("look.png", -1, 1.0)) + + with pytest.raises(ValueError, match="reference_downscale_factor 1"): + _still_pipeline(downscale=2)._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=True), {}) + + +def test_stage_without_ic_lora_rejects_a_negative_frame_still() -> None: + """The upstream closure refuses a negative index, so a still never reaches a plain stage.""" + ctx = _still_ctx(ImageConditioningInput("look.png", -1, 1.0)) + + with pytest.raises(ValueError, match="outside the planned stitched range"): + _still_pipeline()._video_conditionings(ctx, SimpleNamespace(apply_ic_lora=False), {}) + + +def test_failed_encode_closes_the_video_generator_so_the_reference_is_released(monkeypatch, tmp_path) -> None: + state = {"closed": False} + + def windows(): + try: + yield torch.zeros(1, 3, 9, 16, 16) + yield torch.zeros(1, 3, 9, 16, 16) + finally: + state["closed"] = True + + def failing_encode(*, video, **kwargs): # noqa: ARG001 + next(iter(video)) + raise RuntimeError("encoder died") + + monkeypatch.setattr("ltx_pipelines.utils.media_io.encode_video", failing_encode) + video = windows() + result = InferenceResult( + video=video, audio=None, num_frames=18, tiling_config=None, streams=(video,) + ) + + with pytest.raises(RuntimeError, match="encoder died"): + encode_result( + result, + output_path=str(tmp_path / "out.mp4"), + num_frames=18, + frame_rate=24.0, + mute_audio=True, + source_audio_path=None, + streamed=True, + device=torch.device("cpu"), + ) + + assert state["closed"] is True diff --git a/backend/tests/test_video_display_rotation.py b/backend/tests/test_video_display_rotation.py new file mode 100644 index 000000000..71ecc1ebc --- /dev/null +++ b/backend/tests/test_video_display_rotation.py @@ -0,0 +1,82 @@ +"""Display rotation comes from the clip, not an ffmpeg banner spawn.""" + +from __future__ import annotations + +import subprocess +from pathlib import Path + +import imageio_ffmpeg +from services.media_probe import probe_file + + +def _ffmpeg() -> str: + return imageio_ffmpeg.get_ffmpeg_exe() + + +def _landscape(path: Path) -> None: + subprocess.run( + [ + _ffmpeg(), + "-y", + "-f", + "lavfi", + "-i", + "color=c=black:s=32x16:r=8:d=0.2", + "-c:v", + "libx264", + "-pix_fmt", + "yuv420p", + "-movflags", + "+faststart", + str(path), + ], + check=True, + capture_output=True, + ) + + +def _with_display_rotation(src: Path, dest: Path, angle: str) -> None: + subprocess.run( + [ + _ffmpeg(), + "-y", + "-display_rotation", + angle, + "-i", + str(src), + "-c", + "copy", + str(dest), + ], + check=True, + capture_output=True, + ) + + +def test_probe_swaps_dimensions_for_a_90_degree_display_matrix(tmp_path: Path) -> None: + src = tmp_path / "src.mp4" + path = tmp_path / "rotated.mp4" + _landscape(src) + _with_display_rotation(src, path, "90") + _kind, _mime, metadata = probe_file(path) + assert metadata.mediaType == "video" + assert (metadata.metadata.width, metadata.metadata.height) == (16, 32) + + +def test_probe_keeps_coded_size_when_the_clip_has_no_rotation(tmp_path: Path) -> None: + path = tmp_path / "plain.mp4" + _landscape(path) + _kind, _mime, metadata = probe_file(path) + assert metadata.mediaType == "video" + assert (metadata.metadata.width, metadata.metadata.height) == (32, 16) + + +def test_probe_keeps_coded_size_when_rotation_cannot_be_read(tmp_path: Path) -> None: + src = tmp_path / "src.mp4" + _landscape(src) + broken = tmp_path / "broken.mp4" + data = src.read_bytes() + broken.write_bytes(data[: int(len(data) * 0.7)]) + _kind, _mime, metadata = probe_file(broken) + assert metadata.mediaType == "video" + assert (metadata.metadata.width, metadata.metadata.height) == (32, 16) diff --git a/backend/tests/test_video_job_budget.py b/backend/tests/test_video_job_budget.py new file mode 100644 index 000000000..89d1da9bd --- /dev/null +++ b/backend/tests/test_video_job_budget.py @@ -0,0 +1,669 @@ +"""Token/VRAM job budget: 5090-calibrated curve plus IC-LoRA wrapper.""" + +from __future__ import annotations + +from api_types import ( + DownloadSpec, + DownloadVariant, + IcLoraCatalogItem, + IcLoraControl, + IcLoraSettings, + InputSpec, + InstructionSection, + PreprocessingStep, +) +from frame_math import compute_num_frames +from runtime_config.ic_lora_job_budget import ( + IcLoraJobLoad, + IcLoraJobReject, + advertised_duration_options, + catalog_output_fps, + catalog_preview_stage1, + decide_ic_lora_job, + ic_lora_sequence_tokens, + with_budgeted_duration_controls, +) +from runtime_config.ic_lora_local_envelope import effective_denoise_stage1, ic_lora_output_canvas +from runtime_config.ic_lora_stage_mode import IcLoraStageMode +from runtime_config.video_job_budget import ( + OfferingCell, + VideoJobLoad, + VideoJobReject, + advertised_fast_durations, + enumerate_envelope, + estimated_giB, + fits, + decide_edit_job, + decide_video_job, + max_edit_frames_that_load, + memory_gb_for_job, + video_tokens, +) +from services.retake_pipeline.window import ( + duration_to_extend_frames, + window_for_extend, + window_for_retake, +) + + +def _source_dim_stage1(width: int, height: int) -> tuple[int, int]: + canvas_w, canvas_h, factor = ic_lora_output_canvas( + skip_stage_2=True, + resolution_factor=0, + input_width=width, + input_height=height, + resolution=None, + ) + return effective_denoise_stage1( + canvas_w, canvas_h, skip_stage_2=True, resolution_factor=factor + ) + + +def test_video_tokens_5s_540p_matches_calibration() -> None: + frames = compute_num_frames(5, 24) + tokens = video_tokens(576, 1024, frames) + assert frames == 121 + assert tokens == 16 * 18 * 32 + assert ic_lora_sequence_tokens(1024, 576, frames) == tokens * 2 + + +def test_fits_31gb_5s_540p_full_and_20s_not_full() -> None: + seq_5 = ic_lora_sequence_tokens(1024, 576, compute_num_frames(5, 24)) + seq_20 = ic_lora_sequence_tokens(1024, 576, compute_num_frames(20, 24)) + assert fits(seq_5, "full_models_loading", 31) + assert not fits(seq_20, "full_models_loading", 31) + assert fits(seq_20, "streaming_models_loading", 31) + + +def test_decide_31gb_5s_540p_full() -> None: + w, h = _source_dim_stage1(1024, 576) + decision = decide_ic_lora_job( + w, h, compute_num_frames(5, 24), memory_gb=31, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "full_models_loading" + + +def test_decide_31gb_8s_and_10s_540p_stream() -> None: + w, h = _source_dim_stage1(1024, 576) + for seconds in (8, 10): + decision = decide_ic_lora_job( + w, h, compute_num_frames(seconds, 24), memory_gb=31, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_chunked_1080p_prices_one_window() -> None: + w, h = _source_dim_stage1(1920, 1080) + frames = compute_num_frames(8, 24) + chunked = decide_ic_lora_job( + w, h, frames, memory_gb=31, process_mode="full_models_loading", stage_mode=IcLoraStageMode.SINGLE_STAGE + ) + assert isinstance(chunked, IcLoraJobLoad) + assert chunked.mode == "streaming_models_loading" + window = decide_ic_lora_job( + w, h, 97, memory_gb=31, process_mode="full_models_loading", stage_mode=IcLoraStageMode.SINGLE_STAGE + ) + assert isinstance(window, IcLoraJobLoad) + assert chunked.seq == window.seq + + +def test_decide_stage_2_ic_lora_1080p_chunks_and_fits() -> None: + decision = decide_ic_lora_job( + 960, + 544, + compute_num_frames(9, 24), + memory_gb=32, + process_mode="full_models_loading", + stage_mode=IcLoraStageMode.STAGE_2_LORA, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_1080p_single_stage_5s_on_22gb_chunks_and_loads_instead_of_rejecting() -> None: + # Whole clip: 2 x 16 x 2025 = 64800 tokens, stream estimate 23.5 GiB, over 22. + # One 97-frame window: 2 x 13 x 2025 = 52650 tokens, stream estimate 19.7 GiB. + decision = decide_ic_lora_job( + 1920, 1080, compute_num_frames(5, 24), memory_gb=22, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "streaming_models_loading" + assert decision.chunk_pixel_frames == 97 + assert decision.seq == 52650.0 + + +def test_decide_off_grid_123_frames_chunks_like_121_frames() -> None: + # Both counts are 16 latent frames, so both need the same window on a 22 GB card. + def window(frames: int) -> int | None: + decision = decide_ic_lora_job( + 1920, 1088, frames, memory_gb=22, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + return decision.chunk_pixel_frames + + assert window(121) == 97 + assert window(123) == 97 + + +def test_decide_a_longer_clip_is_never_accepted_after_a_shorter_clip_is_rejected() -> None: + # Chunking prices one window, so a long clip must not look cheaper than a short one + # that fits in no window. A card at the limit accepts up to some length and rejects after. + cases = ( + (1920, 1080, IcLoraStageMode.SINGLE_STAGE, 16), + (1920, 1080, IcLoraStageMode.SINGLE_STAGE, 22), + (960, 544, IcLoraStageMode.STAGE_2_LORA, 16), + (960, 544, IcLoraStageMode.STAGE_2_LORA, 22), + (960, 544, IcLoraStageMode.STAGE_1_LORA, 22), + ) + for width, height, mode, memory_gb in cases: + accepted = [ + isinstance( + decide_ic_lora_job( + width, height, compute_num_frames(seconds, 24), memory_gb=memory_gb, + process_mode="full_models_loading", stage_mode=mode, + ), + IcLoraJobLoad, + ) + for seconds in range(1, 21) + ] + first_reject = accepted.index(False) if False in accepted else len(accepted) + assert not any(accepted[first_reject:]), (width, height, mode, memory_gb) + + +def test_decide_does_not_chunk_two_stage_or_small_jobs() -> None: + frames = compute_num_frames(8, 24) + # A chunked job prices one 97-frame window, so an unchunked job prices above it. + for width, height, mode in ( + (960, 512, IcLoraStageMode.STAGE_1_LORA), + (1024, 576, IcLoraStageMode.SINGLE_STAGE), + ): + priced = decide_ic_lora_job( + width, height, frames, memory_gb=31, process_mode="full_models_loading", stage_mode=mode + ) + window = decide_ic_lora_job( + width, height, 97, memory_gb=31, process_mode="full_models_loading", stage_mode=mode + ) + assert priced.seq > window.seq + + +def test_decide_31gb_20s_540p_streams() -> None: + w, h = _source_dim_stage1(1024, 576) + decision = decide_ic_lora_job( + w, h, compute_num_frames(20, 24), memory_gb=31, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_31gb_5s_2160p_spatial_reject() -> None: + w, h = _source_dim_stage1(3840, 2160) + decision = decide_ic_lora_job( + w, h, compute_num_frames(5, 24), memory_gb=31, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobReject) + assert decision.reason == "spatial" + + +def test_decide_31gb_5s_2160p_two_stage_stage_1_lora_is_a_spatial_reject() -> None: + # A 3840x2160 source gives a 3840x2048 canvas, so stage 1 is 1920x1024. That is inside + # the 1920x1088 cell, but stage 2 runs at 3840x2048 and is over it. + decision = decide_ic_lora_job( + 1920, 1024, compute_num_frames(5, 24), memory_gb=32, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.STAGE_1_LORA, + ) + assert isinstance(decision, IcLoraJobReject) + assert decision.reason == "spatial" + + +def test_stage_1_lora_prices_the_stage_2_canvas_when_it_is_heavier_than_stage_1() -> None: + # Stage 1 960x544, 121 frames: 16 latent frames of 17x30 cells, times 2 for the + # reference = 16320 tokens. Stage 2 at 1920x1088 has no reference: 16 x 34 x 60 = 32640. + decision = decide_ic_lora_job( + 960, 544, 121, memory_gb=32, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.STAGE_1_LORA, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.seq == 32640.0 + + +def test_a_reference_still_adds_one_latent_frame_of_tokens_to_the_stage_2_lora_price() -> None: + # Stage 1 640x352 gives a 1280x704 canvas: 22 x 40 = 880 cells per latent frame. + # 121 frames are 16 latent frames, doubled for the reference: 2 x 16 x 880 = 28160. + # One still adds one latent frame of the canvas: 880. + def price(stills: int) -> float: + decision = decide_ic_lora_job( + 640, 352, 121, memory_gb=32, process_mode="full_models_loading", + stage_mode=IcLoraStageMode.STAGE_2_LORA, stills=stills, + ) + assert isinstance(decision, IcLoraJobLoad) + return decision.seq + + assert price(0) == 28160.0 + assert price(1) == 29040.0 + + +def test_decide_ic_lora_unsupported_beats_spatial() -> None: + w, h = _source_dim_stage1(1280, 720) + decision = decide_ic_lora_job( + w, h, compute_num_frames(5, 24), memory_gb=31, process_mode="unsupported", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobReject) + assert decision.reason == "unsupported" + + +def test_decide_ic_lora_unsupported_process_rejects() -> None: + w, h = _source_dim_stage1(1024, 576) + decision = decide_ic_lora_job( + w, h, compute_num_frames(5, 24), memory_gb=31, process_mode="unsupported", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobReject) + assert decision.reason == "unsupported" + + +def test_decide_24gb_stream_process_never_full() -> None: + w, h = _source_dim_stage1(1024, 576) + five = decide_ic_lora_job( + w, + h, + compute_num_frames(5, 24), + memory_gb=24, + process_mode="streaming_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + twenty = decide_ic_lora_job( + w, + h, + compute_num_frames(20, 24), + memory_gb=24, + process_mode="streaming_models_loading", + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(five, IcLoraJobLoad) + assert five.mode == "streaming_models_loading" + assert isinstance(twenty, IcLoraJobReject) + assert twenty.reason == "stream_over" + + +def test_decide_darwin_never_full() -> None: + w, h = _source_dim_stage1(1024, 576) + decision = decide_ic_lora_job( + w, + h, + compute_num_frames(5, 24), + memory_gb=48, + process_mode="full_models_loading", + darwin=True, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_darwin_does_not_apply_cuda_stream_over() -> None: + """Darwin skips the CUDA stream-over 422; free RAM is not 5090 reserved GiB.""" + w, h = _source_dim_stage1(1024, 576) + decision = decide_ic_lora_job( + w, + h, + compute_num_frames(20, 24), + memory_gb=20, + process_mode="full_models_loading", + darwin=True, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + ) + assert isinstance(decision, IcLoraJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_memory_gb_for_job_uses_available_ram_on_darwin() -> None: + assert memory_gb_for_job(vram_gb=31, available_ram_gb=48, darwin=True) == 48 + assert memory_gb_for_job(vram_gb=31, available_ram_gb=48, darwin=False) == 31 + + +def test_enumerate_envelope_drops_measured_no_and_over_budget() -> None: + grid = [ + OfferingCell("540p", 5, 24, 1024, 576), + OfferingCell("1080p", 10, 24, 1920, 1088), + OfferingCell("720p", 5, 24, 1280, 704), + ] + kept = enumerate_envelope( + grid, + "full_models_loading", + 31, + measured_no=lambda c: c.resolution == "720p", + ) + assert [(c.resolution, c.duration_seconds) for c in kept] == [("540p", 5)] + + +def test_ingredients_preview_stage1_is_576x960() -> None: + w, h = catalog_preview_stage1(IcLoraSettings(skip_stage_2=True, resolution_factor=1.5)) + assert sorted((w, h)) == [576, 960] + + +def test_advertised_duration_drops_20s_on_10gb() -> None: + w, h = catalog_preview_stage1(IcLoraSettings(skip_stage_2=True, resolution_factor=1.5)) + kept = advertised_duration_options( + [5, 6, 8, 10, 20], + stage1_width=w, + stage1_height=h, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + fps=24, + memory_gb=10, + process_mode="full_models_loading", + darwin=False, + ) + assert 20 not in kept + assert 5 in kept + + +def test_advertised_duration_keeps_20s_on_darwin() -> None: + w, h = catalog_preview_stage1(IcLoraSettings(skip_stage_2=True, resolution_factor=1.5)) + kept = advertised_duration_options( + [5, 6, 8, 10, 20], + stage1_width=w, + stage1_height=h, + stage_mode=IcLoraStageMode.SINGLE_STAGE, + fps=24, + memory_gb=20, + process_mode="full_models_loading", + darwin=True, + ) + assert kept == [5, 6, 8, 10, 20] + + +def test_full_estimate_is_above_stream() -> None: + seq = ic_lora_sequence_tokens(1024, 576, compute_num_frames(5, 24)) + assert estimated_giB("full_models_loading", seq) > estimated_giB("streaming_models_loading", seq) + + +def _video_job(width: int, height: int, seconds: int, **kwargs): + return decide_video_job( + width, + height, + compute_num_frames(seconds, 24), + **kwargs, + ) + + +def test_decide_video_job_31gb_540p_5s_full() -> None: + decision = _video_job(1024, 576, 5, memory_gb=31, process_mode="full_models_loading") + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "full_models_loading" + + +def test_decide_video_job_32gb_720p_20s_streams() -> None: + decision = _video_job(1280, 704, 20, memory_gb=32, process_mode="full_models_loading") + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_video_job_16gb_720p_20s_rejects() -> None: + decision = _video_job(1280, 704, 20, memory_gb=16, process_mode="streaming_models_loading") + assert isinstance(decision, VideoJobReject) + + +def test_decide_video_job_15gb_540p_5s_still_streams() -> None: + decision = _video_job(1024, 576, 5, memory_gb=15, process_mode="streaming_models_loading") + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_edit_job_31gb_720p_extend_streams() -> None: + """5090 extend 1280×704×337 estimated 27.2 GiB and reserved the whole card.""" + decision = decide_edit_job( + 1280, + 704, + 337, + memory_gb=31, + process_mode="full_models_loading", + ) + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + reported_as_32 = decide_edit_job( + 1280, 704, 337, memory_gb=32, process_mode="full_models_loading" + ) + assert isinstance(reported_as_32, VideoJobLoad) + assert reported_as_32.mode == "streaming_models_loading" + + +def test_max_edit_frames_shrinks_1080p_on_31gb_and_keeps_720p() -> None: + """1920×1088×505 streams past the 31 GB budget. The cap must load; 720p×505 already does.""" + kwargs = dict(memory_gb=31, process_mode="full_models_loading") + cap = max_edit_frames_that_load(1920, 1088, frame_cap=505, **kwargs) + assert cap < 505 + assert isinstance(decide_edit_job(1920, 1088, 505, **kwargs), VideoJobReject) + assert isinstance(decide_edit_job(1920, 1088, cap, **kwargs), VideoJobLoad) + assert isinstance(decide_edit_job(1920, 1088, cap + 1, **kwargs), VideoJobReject) + assert ( + max_edit_frames_that_load(1280, 736, frame_cap=505, **kwargs) == 505 + ) + assert ( + max_edit_frames_that_load( + 1920, 1088, frame_cap=505, darwin=True, **kwargs + ) + == 505 + ) + + extend_frames = duration_to_extend_frames(4, 25) + window = window_for_extend( + source_frames=1000, + extend_frames=extend_frames, + mode="end", + max_input_frames=cap, + ) + assert isinstance( + decide_edit_job( + 1920, 1088, window.context_frames + extend_frames, **kwargs + ), + VideoJobLoad, + ) + retake = window_for_retake( + source_frames=1000, + mask_start_frame=100, + mask_end_frame=140, + max_input_frames=cap, + fps=25, + ) + assert retake.encode_frames <= cap + assert isinstance( + decide_edit_job(1920, 1088, retake.encode_frames, **kwargs), + VideoJobLoad, + ) + + +def test_decide_edit_job_31gb_short_720p_stays_full() -> None: + decision = decide_edit_job( + 1280, + 704, + compute_num_frames(5, 24), + memory_gb=31, + process_mode="full_models_loading", + ) + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "full_models_loading" + + +def test_fast_budget_still_full_loads_the_720p_extend_clip() -> None: + decision = decide_video_job( + 1280, 704, 337, memory_gb=31, process_mode="full_models_loading" + ) + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "full_models_loading" + + +def test_decide_video_job_31gb_1080p_10s_streams() -> None: + decision = _video_job(1920, 1088, 10, memory_gb=31, process_mode="full_models_loading") + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_video_job_24gb_process_never_full() -> None: + decision = _video_job(1024, 576, 5, memory_gb=24, process_mode="streaming_models_loading") + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_video_job_darwin_never_full() -> None: + decision = _video_job( + 1024, + 576, + 5, + memory_gb=48, + process_mode="full_models_loading", + darwin=True, + ) + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_video_job_darwin_m4_loads_jobs_cuda_curve_would_reject() -> None: + """Free RAM on a 48 GB Mac is often ~20 GiB; Fast 720p/20s stream estimate is ~20.""" + for width, height, seconds in ((1280, 704, 20), (1920, 1088, 10)): + decision = _video_job( + width, + height, + seconds, + memory_gb=20, + process_mode="full_models_loading", + darwin=True, + ) + assert isinstance(decision, VideoJobLoad) + assert decision.mode == "streaming_models_loading" + + +def test_decide_video_job_stream_over_rejects() -> None: + decision = _video_job(1280, 704, 20, memory_gb=8, process_mode="full_models_loading") + assert isinstance(decision, VideoJobReject) + assert decision.reason == "stream_over" + + +def test_decide_video_job_16gb_1080p_10s_rejects() -> None: + decision = _video_job(1920, 1088, 10, memory_gb=16, process_mode="streaming_models_loading") + assert isinstance(decision, VideoJobReject) + + +def test_decide_video_job_unsupported_process_rejects() -> None: + decision = _video_job(1024, 576, 5, memory_gb=31, process_mode="unsupported") + assert isinstance(decision, VideoJobReject) + assert decision.reason == "unsupported" + + +def _fast_durations(width: int, height: int, seconds: tuple[int, ...], **kwargs) -> list[int]: + return advertised_fast_durations( + width, + height, + 24, + seconds, + **kwargs, + ) + + +def test_advertised_fast_cuda_16gb_drops_720p20_and_1080p10() -> None: + kwargs = dict(memory_gb=16, process_mode="streaming_models_loading") + assert 20 not in _fast_durations(1280, 704, (5, 6, 8, 10, 20), **kwargs) + assert 10 not in _fast_durations(1920, 1088, (5, 10), **kwargs) + assert _fast_durations(1024, 576, (5, 6, 8, 10, 20), **kwargs) == [5, 6, 8, 10, 20] + assert _fast_durations(1280, 704, (5, 6, 8, 10, 20), **kwargs) == [5, 6, 8, 10] + + +def test_advertised_fast_cuda_31gb_keeps_720p20_and_1080p10() -> None: + kwargs = dict(memory_gb=31, process_mode="full_models_loading") + assert 20 in _fast_durations(1280, 704, (5, 6, 8, 10, 20), **kwargs) + assert 10 in _fast_durations(1920, 1088, (5, 10), **kwargs) + + +def test_advertised_fast_cuda_24gb_keeps_1080p10() -> None: + kept = _fast_durations( + 1920, + 1088, + (5, 10), + memory_gb=24, + process_mode="streaming_models_loading", + ) + assert kept == [5, 10] + + +def test_advertised_fast_darwin_20gib_keeps_ceiling() -> None: + kwargs = dict(memory_gb=20, process_mode="streaming_models_loading", darwin=True) + assert 20 in _fast_durations(1280, 704, (5, 6, 8, 10, 20), **kwargs) + assert 10 in _fast_durations(1920, 1088, (5, 10), **kwargs) + + +def test_advertised_fast_never_emits_1080p20() -> None: + kept = _fast_durations( + 1920, + 1088, + (5, 10, 20), + memory_gb=31, + process_mode="full_models_loading", + ) + assert 20 not in kept + + +def test_advertised_fast_unsupported_is_empty() -> None: + assert _fast_durations(1024, 576, (5, 6, 8, 10, 20), memory_gb=31, process_mode="unsupported") == [] + + +def test_catalog_preview_two_stage_is_1080p_source_not_768_bucket() -> None: + two_stage = catalog_preview_stage1(IcLoraSettings(skip_stage_2=False, resolution_factor=1.5)) + # 1920×1088 snapped /128 → 1920×1024 canvas, stage-1 960×512. The 768×1280 + # bucket would have been 384×640 (~8 GiB optimistic on 20s). + assert sorted(two_stage) == [512, 960] + + +def _catalog_item_with_fps(fps: object) -> IcLoraCatalogItem: + return IcLoraCatalogItem( + id="fps-probe", + name="n", + description="d", + download=DownloadSpec( + repo_id="r", + variants=[DownloadVariant(id="default", label="Default", filename="f.safetensors", size_bytes=10, base_model="LTX-2.3")], + ), + requires_hf_login=False, + input=InputSpec(kind="image"), + preprocessing=[PreprocessingStep(utility="image_to_frames", params={"fps": fps})], + instructions=[InstructionSection(kind="summary", title="What it does", body="b")], + default_settings=IcLoraSettings(), + ) + + +def test_with_budgeted_duration_unsupported_clears_options() -> None: + item = _catalog_item_with_fps(24).model_copy( + update={ + "controls": [ + IcLoraControl( + id="duration", + label="Duration", + kind="int", + default=5, + options=[5, 8, 10, 20], + ) + ] + } + ) + out = with_budgeted_duration_controls( + item, memory_gb=31, process_mode="unsupported", darwin=False + ) + duration = next(control for control in out.controls if control.id == "duration") + assert duration.options == [] + + +def test_catalog_output_fps_coerces_junk_to_default() -> None: + assert catalog_output_fps(_catalog_item_with_fps(24)) == 24 + assert catalog_output_fps(_catalog_item_with_fps("12")) == 12 + assert catalog_output_fps(_catalog_item_with_fps(None)) == 24 + assert catalog_output_fps(_catalog_item_with_fps({})) == 24 + assert catalog_output_fps(_catalog_item_with_fps("nope")) == 24 + assert catalog_output_fps(_catalog_item_with_fps(True)) == 24 + assert catalog_output_fps(_catalog_item_with_fps(0)) == 24 diff --git a/backend/tests/test_video_resolution.py b/backend/tests/test_video_resolution.py index 67a25eff6..99aa81cd4 100644 --- a/backend/tests/test_video_resolution.py +++ b/backend/tests/test_video_resolution.py @@ -2,10 +2,19 @@ from __future__ import annotations +import logging + import pytest from _routes._errors import HTTPError -from handlers.video_resolution import correct_frame_count, correct_resolution +from handlers.video_resolution import ( + cap_to_1080p, + correct_frame_count, + correct_resolution, + generation_letterbox, + resolve_home_edit_size, + resolve_target_resolution, +) def test_correct_resolution_snaps_height_down_to_div32(): @@ -26,6 +35,67 @@ def test_correct_resolution_portrait(): assert correct_resolution(1080, 1920, source_width=1080, source_height=1920) == (1056, 1920) +def test_resolve_target_resolution_keeps_1080p_after_div32(caplog): + with caplog.at_level(logging.INFO, logger="handlers.video_resolution"): + assert resolve_target_resolution(None, 1920, 1080) == (1920, 1056) + assert "Downscaling" not in caplog.text + + +def test_cap_to_1080p_fits_4k_into_the_home_box(): + assert cap_to_1080p(3840, 2160) == (1920, 1080) + assert cap_to_1080p(2160, 3840) == (1080, 1920) + # Already at or below the local 1080p cell: no upscale. + assert cap_to_1080p(1920, 1088) == (1920, 1088) + assert cap_to_1080p(1280, 704) == (1280, 704) + + +def test_home_edit_size_keeps_the_picture_and_leaves_padding_to_the_letterbox(): + # No request: 4K fits the 1080p cell. Height stays 1080; the letterbox pads it. + assert resolve_home_edit_size(None, None, 3840, 2160) == (1920, 1080) + # 720p on a 1080p source stays 720. It is not snapped down to 704. + assert resolve_home_edit_size(1280, 720, 1920, 1080) == (1280, 720) + # A 4K request on a 1080p source cannot upscale past the source. + assert resolve_home_edit_size(3840, 2160, 1920, 1080) == (1920, 1080) + # A request above a small source is clamped to that source, still unsnapped. + assert resolve_home_edit_size(1280, 720, 640, 360) == (640, 360) + + +def test_queued_home_path_still_caps_then_snaps(): + # 1920×1080 snaps height to ÷32. Local 1080p (1920×1088) is already on that grid. + capped = cap_to_1080p(3840, 2160) + assert resolve_target_resolution(None, *capped) == (1920, 1056) + local = cap_to_1080p(1920, 1088) + assert resolve_target_resolution(None, *local) == (1920, 1088) + portrait = cap_to_1080p(2160, 3840) + assert resolve_target_resolution(None, *portrait) == (1056, 1920) + + +def test_resolve_target_resolution_leaves_smaller_sources(caplog): + # Below 540p: no upscale; height 360 snaps down to ÷32. + with caplog.at_level(logging.INFO, logger="handlers.video_resolution"): + assert resolve_target_resolution(None, 640, 360) == (640, 352) + assert "Downscaling" not in caplog.text + + +def test_generation_letterbox_pads_1080p_to_the_next_multiple_of_32(): + box = generation_letterbox(1920, 1080) + assert (box.canvas_width, box.canvas_height) == (1920, 1088) + assert (box.content_width, box.content_height) == (1920, 1080) + assert (box.left, box.right, box.top, box.bottom) == (0, 0, 4, 4) + + +def test_generation_letterbox_pads_portrait_on_the_sides(): + box = generation_letterbox(1080, 1920) + assert (box.canvas_width, box.canvas_height) == (1088, 1920) + assert (box.left, box.right, box.top, box.bottom) == (4, 4, 0, 0) + + +def test_generation_letterbox_is_a_no_op_when_already_aligned(): + box = generation_letterbox(1920, 1088) + assert (box.canvas_width, box.canvas_height) == (1920, 1088) + assert (box.left, box.top) == (0, 0) + + def test_correct_frame_count_trims_down_to_8k_plus_1(): assert correct_frame_count(97) == 97 assert correct_frame_count(100) == 97 diff --git a/backend/tests/test_video_trim.py b/backend/tests/test_video_trim.py new file mode 100644 index 000000000..36d28af7e --- /dev/null +++ b/backend/tests/test_video_trim.py @@ -0,0 +1,309 @@ +from __future__ import annotations + +import subprocess +from pathlib import Path + +import imageio.v2 as imageio +import imageio_ffmpeg +import numpy as np +import pytest +from starlette.testclient import TestClient + +from remote.app import create_remote_app +from services import video_trim +from services.encoded_media import derived_file_name +from services.ffmpeg import FFMPEG_TIMEOUT_SECONDS +from services.media_probe import MAX_VIDEO_BYTES +from services.video_trim import trim_video_file +from tests.http_error_assertions import assert_http_error +from tests.test_audio_trim import AUTH, _png, _store, _wav + + +def _mp4(path: Path, *, seconds: int = 3, fps: int = 8) -> Path: + writer = imageio.get_writer( + str(path), fps=fps, codec="libx264", macro_block_size=None + ) + frame = np.zeros((16, 16, 3), dtype=np.uint8) + for _ in range(seconds * fps): + writer.append_data(frame) + writer.close() + return path + + +def _mp4_with_audio(path: Path) -> Path: + video = _mp4(path.with_name(f"{path.stem}-silent.mp4")) + audio = _wav(path.with_name(f"{path.stem}.wav"), duration_seconds=3.0) + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-i", + str(video), + "-i", + str(audio), + "-c:v", + "copy", + "-c:a", + "aac", + "-shortest", + str(path), + ], + check=True, + capture_output=True, + ) + return path + + +def _ingest(client: TestClient, source: Path) -> dict[str, object]: + ingested = client.post("/api/assets", json={"path": str(source)}) + assert ingested.status_code == 200 + payload = ingested.json() + assert isinstance(payload, dict) + return payload + + +@pytest.mark.parametrize("with_audio", [True, False]) +def test_trim_video_creates_new_clip_and_leaves_original( + client, tmp_path: Path, with_audio: bool +) -> None: + source = ( + _mp4_with_audio(tmp_path / "clip.mp4") + if with_audio + else _mp4(tmp_path / "clip.mp4") + ) + original = _ingest(client, source) + original_meta = original["metadata"]["metadata"] + assert 2900 <= original_meta["durationMs"] <= 3100 + + trimmed = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 1, "endSec": 2}, + ) + assert trimmed.status_code == 200 + data = trimmed.json() + assert data["id"] != original["id"] + assert data["media_kind"] == "video" + meta = data["metadata"]["metadata"] + assert 900 <= meta["durationMs"] <= 1100 + assert meta["audioStreamCount"] == (1 if with_audio else 0) + + fetched = client.get(f"/api/assets/{original['id']}") + assert fetched.status_code == 200 + assert fetched.json()["path"] == original["path"] + assert Path(str(original["path"])).is_file() + + +def test_trim_video_rejects_end_not_after_start(client, tmp_path: Path) -> None: + original = _ingest(client, _mp4(tmp_path / "clip.mp4")) + response = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 1, "endSec": 1}, + ) + assert response.status_code == 422 + + +@pytest.mark.parametrize("make_source", [_png, _wav]) +def test_trim_video_rejects_non_video_asset( + client, tmp_path: Path, make_source +) -> None: + suffix = ".png" if make_source is _png else ".wav" + original = _ingest(client, make_source(tmp_path / f"input{suffix}")) + response = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 0, "endSec": 1}, + ) + assert response.status_code == 422 + + +def test_trim_video_rejects_missing_asset(client) -> None: + response = client.post( + "/api/assets/missing-asset/trim-video", + json={"startSec": 0, "endSec": 1}, + ) + assert_http_error(response, status_code=404, code="ASSET_NOT_FOUND") + + +def test_trim_video_output_cap_surfaces_controlled_error( + client, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("services.video_trim.MAX_VIDEO_BYTES", 64, raising=False) + original = _ingest(client, _mp4(tmp_path / "clip.mp4")) + response = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 0, "endSec": 1}, + ) + assert_http_error( + response, + status_code=400, + code="FILE_TOO_LARGE", + message="encoded video exceeds size limit", + ) + + +def _odd_size_mp4(path: Path) -> Path: + # yuv444p lets the source itself have odd dimensions. + subprocess.run( + [ + imageio_ffmpeg.get_ffmpeg_exe(), + "-y", + "-f", + "lavfi", + "-i", + "color=c=gray:s=15x17:d=3:r=8", + "-c:v", + "libx264", + "-pix_fmt", + "yuv444p", + str(path), + ], + check=True, + capture_output=True, + ) + return path + + +def test_trim_video_evens_out_odd_dimensions(client, tmp_path: Path) -> None: + original = _ingest(client, _odd_size_mp4(tmp_path / "odd.mp4")) + response = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 0, "endSec": 1}, + ) + assert response.status_code == 200, response.text + meta = response.json()["metadata"]["metadata"] + assert (meta["width"], meta["height"]) == (14, 16) + + +def test_trim_video_accepts_a_tiny_start_and_names_the_clip( + client, tmp_path: Path +) -> None: + original = _ingest(client, _mp4(tmp_path / "talk.mp4")) + response = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 0.00001, "endSec": 1}, + ) + assert response.status_code == 200, response.text + assert response.json()["name"] == "talk-trim.mp4" + + +def test_trim_video_rejects_a_start_past_the_end(client, tmp_path: Path) -> None: + original = _ingest(client, _mp4(tmp_path / "clip.mp4")) + response = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 5, "endSec": 6}, + ) + assert_http_error( + response, + status_code=422, + code="INVALID_TRIM_RANGE", + message="startSec is past the end of the video", + ) + + +def test_trim_video_reports_busy_while_another_trim_encodes( + client, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("services.video_trim.VIDEO_TRIM_QUEUE_TIMEOUT_SECONDS", 0.01) + original = _ingest(client, _mp4(tmp_path / "clip.mp4")) + with video_trim._ENCODE_SLOT: + busy = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 0, "endSec": 1}, + ) + assert_http_error( + busy, + status_code=503, + code="TRIM_BUSY", + message="another video trim is in progress", + ) + + +def test_trim_video_releases_the_slot_after_a_failed_encode( + client, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + def _fail(*_args: object, **_kwargs: object) -> None: + raise subprocess.CalledProcessError(1, "ffmpeg") + + original = _ingest(client, _mp4(tmp_path / "clip.mp4")) + monkeypatch.setattr("services.video_trim.run_ffmpeg", _fail) + failed = client.post( + f"/api/assets/{original['id']}/trim-video", + json={"startSec": 0, "endSec": 1}, + ) + assert_http_error( + failed, + status_code=400, + code="UNREADABLE_MEDIA", + message="ffmpeg failed to trim video", + ) + assert not video_trim._ENCODE_SLOT.locked() + + +@pytest.mark.parametrize( + ("source_name", "expected"), + [ + ("talk.mov", "talk-trim.mp4"), + ("a/b:c?.mp4", "b_c_-trim.mp4"), + ("...", "clip-trim.mp4"), + ], +) +def test_derived_file_name_is_safe(source_name: str, expected: str) -> None: + assert derived_file_name(source_name, "trim", ".mp4") == expected + + +def test_trim_video_ffmpeg_args_seek_accurately_and_cap_output( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + captured: list[list[str]] = [] + timeouts: list[float] = [] + + def _capture( + args: list[str], + *, + ffmpeg_exe: str | list[str] | None = None, + timeout: float = FFMPEG_TIMEOUT_SECONDS, + ) -> None: + del ffmpeg_exe + captured.append(list(args)) + timeouts.append(timeout) + + monkeypatch.setattr("services.video_trim.run_ffmpeg", _capture) + trim_video_file(tmp_path / "in.mp4", tmp_path / "out.mp4", 0.5, 1.5) + + args = captured[0] + input_index = args.index("-i") + assert args[input_index - 2 : input_index] == ["-protocol_whitelist", "file,pipe"] + assert args.index("-ss") < input_index + assert args[args.index("-ss") + 1] == "0.500000" + assert args[args.index("-t") + 1] == "1.000000" + assert "0:a:0?" in args + assert args[args.index("-vf") + 1] == "scale=trunc(iw/2)*2:trunc(ih/2)*2" + assert args[args.index("-c:v") + 1] == "libx264" + assert args[args.index("-fs") + 1] == str(MAX_VIDEO_BYTES) + assert timeouts[0] > FFMPEG_TIMEOUT_SECONDS + + +def test_phone_trim_video_returns_remote_asset_without_paths( + test_state, tmp_path: Path +) -> None: + store = _store(test_state) + video = store.ingest_upload(str(_mp4_with_audio(tmp_path / "clip.mp4"))) + app = create_remote_app(handler=test_state, remote_token="pair-token") + with TestClient(app) as client: + trimmed = client.post( + f"/api/assets/{video.id}/trim-video", + headers=AUTH, + json={"startSec": 0, "endSec": 1}, + ) + missing = client.post( + "/api/assets/missing-asset/trim-video", + headers=AUTH, + json={"startSec": 0, "endSec": 1}, + ) + + assert trimmed.status_code == 200 + asset = trimmed.json() + assert asset["media_kind"] == "video" + assert "path" not in asset + assert "thumbnail_path" not in asset + assert 900 <= asset["metadata"]["metadata"]["durationMs"] <= 1100 + assert_http_error(missing, status_code=404, code="ASSET_NOT_FOUND") diff --git a/backend/tests/test_win_dll_search.py b/backend/tests/test_win_dll_search.py index e396093a3..507225999 100644 --- a/backend/tests/test_win_dll_search.py +++ b/backend/tests/test_win_dll_search.py @@ -13,6 +13,7 @@ def test_remove_cwd_from_dll_search_path_does_not_raise() -> None: remove_cwd_from_dll_search_path() +@pytest.mark.ci_os @pytest.mark.skipif(sys.platform != "win32", reason="SetDllDirectoryW is Windows-only") def test_remove_cwd_clears_dll_directory_on_windows() -> None: import ctypes diff --git a/backend/uv.lock b/backend/uv.lock index c0d283408..a29365832 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -12,12 +12,12 @@ resolution-markers = [ [[manifest.dependency-metadata]] name = "ltx-core" -version = "1.2.0" -requires-dist = ["torch~=2.7", "torchaudio", "einops", "numpy", "av", "transformers>=5.8.0,<5.15", "safetensors", "accelerate", "scipy>=1.14", "mps-sdpa>=0.2.0 ; platform_machine == 'arm64' and sys_platform == 'darwin'"] +version = "1.4.1" +requires-dist = ["torch~=2.7", "torchaudio", "torchvision", "einops", "numpy", "colour-science", "av", "transformers>=5.8.0,<5.15", "safetensors", "accelerate", "scipy>=1.14", "mps-sdpa>=0.2.0 ; platform_machine == 'arm64' and sys_platform == 'darwin'"] [[manifest.dependency-metadata]] name = "ltx-pipelines" -version = "1.2.0" +version = "1.4.1" requires-dist = ["ltx-core", "av", "tqdm", "pillow", "openimageio", "cloudpickle>=3.1"] [[package]] @@ -210,6 +210,98 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "colour-science" +version = "0.4.7" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/f4/66/6e2216ffae6f0008118c99d6f425f7591e688671ab99f5636f7f65021395/colour_science-0.4.7.tar.gz", hash = "sha256:b34773dc4dd3f9ba99cca5297fa10e9f532134d994b3a2308dacbe970dfd5079", size = 13283171, upload-time = "2025-12-06T08:15:08.229Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6d/9e/ce54e33f383d7e1432be9fb39557477779ccb155c60033c491609936dacf/colour_science-0.4.7-py3-none-any.whl", hash = "sha256:fe2383d86e507fc11a4b5206ff31a7399031e0dce527e22ec06eeb491d45d9a7", size = 9065613, upload-time = "2025-12-06T08:15:14.908Z" }, +] + +[[package]] +name = "contourpy" +version = "1.4.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "numpy" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/83/5a/a55177dd22553a277388e8a1b3220e92de91bacb28356cdc73caa240121d/contourpy-1.4.0.tar.gz", hash = "sha256:20156f5a1ac4f8ce02656e39a61e82164a3d359796dc8026f75b062783d500e1", size = 13323726, upload-time = "2026-09-11T19:05:05.808Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/97/ba/01bde9753bdbba04a6da9d2bff3881f021bc708f654655e95fae26d3b3a3/contourpy-1.4.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:186ba929df36d61b6127da2e89cd1357e4cb79aca647381ab1a6feb0b152877b", size = 297302, upload-time = "2026-09-11T19:02:45.103Z" }, + { url = "https://files.pythonhosted.org/packages/dd/f5/c5bf67522d49a2222f3154fe46879451d26f0e35ece41770758a64ea78cb/contourpy-1.4.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:c76f3a5318164db7d9401132fc1b5364b784c613c93fa506e3b5e6d1bf353ec8", size = 284921, upload-time = "2026-09-11T19:02:48.049Z" }, + { url = "https://files.pythonhosted.org/packages/0f/cc/cb989599eec12fda312e127eb8e04a8b21a7a6c94bf7ff1bc68273334a42/contourpy-1.4.0-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:43c3ccbb32c6294b183dcc8e8c46dacf5ecef809497e3d48a5be298eef185ad0", size = 356332, upload-time = "2026-09-11T19:02:51.408Z" }, + { url = "https://files.pythonhosted.org/packages/47/fb/6f620d7602507817b0b4c21dd790ed68688f1f4ae9c29aacf21f08db5cf1/contourpy-1.4.0-cp312-cp312-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:86d05cec773c9507a3950122e0e40ce77c23c75ceeb2fc189514e71893cbb34b", size = 405878, upload-time = "2026-09-11T19:02:54.093Z" }, + { url = "https://files.pythonhosted.org/packages/32/4e/693c6d6bdece679f0953775eef3a1b66d56be55478d936e7deb1f3004422/contourpy-1.4.0-cp312-cp312-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2deb580178ca19437a84bd77e4bc2cd91a8ccad212413a83c273900868b5978c", size = 408296, upload-time = "2026-09-11T19:02:56.528Z" }, + { url = "https://files.pythonhosted.org/packages/78/f9/b6831508960d559581c448532ba4df312217072975486dbf2b24fcc5b76f/contourpy-1.4.0-cp312-cp312-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:875f42444c9cf48d56f724f2637e60d0f73b3b12c9041e1484580a233edf9591", size = 383243, upload-time = "2026-09-11T19:02:58.638Z" }, + { url = "https://files.pythonhosted.org/packages/f2/21/52903825a0ae7bb625e8bd30a09816d4c3c5d6174a469c10a616166cf780/contourpy-1.4.0-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:f863c6100bf926cf47d13f3cd75f9bb8ebd98aaab230eeb4468b91f98f39a6b3", size = 1357306, upload-time = "2026-09-11T19:03:01.036Z" }, + { url = "https://files.pythonhosted.org/packages/d8/79/d68b1ce8539e4071518fed9523f558398f34dcd078b8927b109c72dad2ef/contourpy-1.4.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3863ef2e2b13fe93f8c0ebb08ee400cb07153b8b0e91c5acb26e4537f283634f", size = 1427243, upload-time = "2026-09-11T19:03:03.866Z" }, + { url = "https://files.pythonhosted.org/packages/ac/f0/b75a10e9d0616b97a30de277b6dfe83f1879880854c7330337309530eb48/contourpy-1.4.0-cp312-cp312-win32.whl", hash = "sha256:5450f091ac1be0be3ad3a2a3b3f23b5e443e78c670ced4fd347d626f92a28fd2", size = 347345, upload-time = "2026-09-11T19:03:06.192Z" }, + { url = "https://files.pythonhosted.org/packages/50/a9/dab08786bb4d77ef9a046b3c1be923be4e73c5d07d91f5a54e8ea9b09e41/contourpy-1.4.0-cp312-cp312-win_amd64.whl", hash = "sha256:6e697d94e69f499ff6bebb899cae97a58d5d14f0e1fe9568b43a0248d2f9af8c", size = 234083, upload-time = "2026-09-11T19:03:08.122Z" }, + { url = "https://files.pythonhosted.org/packages/47/b9/3ba509755a970dbde5948e7142ac21f266be72f38017cc4087a05fdceee1/contourpy-1.4.0-cp312-cp312-win_arm64.whl", hash = "sha256:0c7a4c2716a4e98342221954416a836cca77c996c14ddbf22b5f01d5d93ca09c", size = 559521, upload-time = "2026-09-11T19:03:10.047Z" }, + { url = "https://files.pythonhosted.org/packages/b7/8b/62a6eacea08ea0b6ab0159a7783df7ed421ff9c1ff58fef7c31f58fa5e52/contourpy-1.4.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:e21d1d4a9db5b3a793649c7ab0ddb4697f2818929eec871a7b9c45fce7b2a1ea", size = 297330, upload-time = "2026-09-11T19:03:11.809Z" }, + { url = "https://files.pythonhosted.org/packages/3f/2f/103cdc5b7077cd569989d3ddb99ee3d4e96ee31bde8df2a6e426b2dc6195/contourpy-1.4.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:196759a3e4db60e1546167e361090ebb6d199aa3aafc9e34ea17a5ac3b23e814", size = 285037, upload-time = "2026-09-11T19:03:13.781Z" }, + { url = "https://files.pythonhosted.org/packages/bf/25/97001d1fdf940e6f5adfc592d4f5899fff95daf7dceead3988fe09987d2d/contourpy-1.4.0-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:9c0e07c691f3b3321913ed9b8161c50ea5f77fadd006f52f5e755359b0dcbfc5", size = 356675, upload-time = "2026-09-11T19:03:15.374Z" }, + { url = "https://files.pythonhosted.org/packages/a6/5e/9a7241a89e2f74402aefa2569e1349ad2750ff77823c04c788eaaedb7fdd/contourpy-1.4.0-cp313-cp313-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7f861af508fca2384eef392bc1d8377cfa349b2b854cb11b45d89c75780e2561", size = 406990, upload-time = "2026-09-11T19:03:17.44Z" }, + { url = "https://files.pythonhosted.org/packages/36/81/3a4fbbf6a806eada5453a6d16f6c7d96b9f4b3e57a3127368fb545986b8a/contourpy-1.4.0-cp313-cp313-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a03b32c2e7eda8b17757c022162c13c86f5c3d6f937dddf9ba3c3ff7b513953b", size = 407271, upload-time = "2026-09-11T19:03:19.523Z" }, + { url = "https://files.pythonhosted.org/packages/68/77/8f93ecbde1a4d11dfd460cd19a0c159f5487352e751fa87f5d78cc9db08e/contourpy-1.4.0-cp313-cp313-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:f1219a8898523cba821085f2da8a1b962cc696325763f09d7f93538ba43b2d70", size = 384707, upload-time = "2026-09-11T19:03:21.208Z" }, + { url = "https://files.pythonhosted.org/packages/05/07/e5cdf94d68961ee464de6b4fedd3d2f666584f59ccd124bb1290597122ab/contourpy-1.4.0-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:20da2f86bfaed60dbba729fe738c8241b1dd22b6cf7e8cbbf30df290bd04ba28", size = 1356741, upload-time = "2026-09-11T19:03:23.621Z" }, + { url = "https://files.pythonhosted.org/packages/fd/8a/2301d07accb257ac08daeb631875fada06fedd019c20ff7b00ee07e9d211/contourpy-1.4.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:6ced1670fafee703b8277ab1645072a226e74f167166eae146fb743916119b67", size = 1426793, upload-time = "2026-09-11T19:03:25.955Z" }, + { url = "https://files.pythonhosted.org/packages/7d/5d/a62648f06259d15c139b14eb8cf3c58fe53cb970a55f2bb77d1070e80a41/contourpy-1.4.0-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:abd0f7e51ecc52bf8c95713bd80b1c17c516a71fa391c54475308a4377903c2b", size = 117961, upload-time = "2026-09-11T19:03:27.713Z" }, + { url = "https://files.pythonhosted.org/packages/71/31/c5b7771ba6982f319ec90c0cf5c425b36891adfeee2d9f667f90b2d0c166/contourpy-1.4.0-cp313-cp313-win32.whl", hash = "sha256:510f7d93d94cf6ebf4e2cd0640bea16ab8affac7547230175b6745b596ce0599", size = 347438, upload-time = "2026-09-11T19:03:29.829Z" }, + { url = "https://files.pythonhosted.org/packages/68/c1/a59df0754bf83a6f3e153cc19d550a5b01f607e389b1c4d57f436f9139e0/contourpy-1.4.0-cp313-cp313-win_amd64.whl", hash = "sha256:6507a016976a75a15aee47809a34605de6244ccc056e6164bf9fb14b27eecad4", size = 234084, upload-time = "2026-09-11T19:03:31.657Z" }, + { url = "https://files.pythonhosted.org/packages/41/48/97224f5decb1efa5a610f912195deb45321f73ec9b9dac485cd6fe2d5a6a/contourpy-1.4.0-cp313-cp313-win_arm64.whl", hash = "sha256:423bd5f4b3f11d54a8c597234e513382e3454bb106b8ec7ae32ba4ed63f8d99b", size = 559559, upload-time = "2026-09-11T19:03:33.528Z" }, + { url = "https://files.pythonhosted.org/packages/75/b0/b548628c8dddf6e5e0a981b7fa8e4c008024df09c7d17c6a9e271edfa0b3/contourpy-1.4.0-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:a3e67bc1a6a4618a1dac7c3053a9ffece5ddfa2046b2670b342cf430bb0b87d1", size = 297354, upload-time = "2026-09-11T19:03:35.017Z" }, + { url = "https://files.pythonhosted.org/packages/04/5a/513484208742f65af2648c519f0b7ab034616e183c4403538024c136a1ab/contourpy-1.4.0-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:072a702e2e178f4fcf96f04775d0c059e4c917925abf0d3208ebb6865df3c23d", size = 283729, upload-time = "2026-09-11T19:03:36.818Z" }, + { url = "https://files.pythonhosted.org/packages/35/da/5a6562febc994b2c4bf9d01e57a50458ef8a2051bb3e7b35a00333e0fc26/contourpy-1.4.0-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:404dbcd9233513dfd1323b66ea593fef90e899f658f6b8a9ed8e93bd0ca669db", size = 357819, upload-time = "2026-09-11T19:03:39.058Z" }, + { url = "https://files.pythonhosted.org/packages/6d/99/7b358ce888aaa426f755daa096c99c59d17c352037344e836f20e5d3b957/contourpy-1.4.0-cp314-cp314-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:61624f6722480aa7e168fd746164e7bfdf48f8ccb6542f1613741200dc37e2b1", size = 407795, upload-time = "2026-09-11T19:03:41.293Z" }, + { url = "https://files.pythonhosted.org/packages/be/02/34d7548adf08c60967435d79d7a90882eacc84f5093435287974c7e99943/contourpy-1.4.0-cp314-cp314-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2e741a39dfc96babe1722561e81351aeec104526c57dbe91c167c1db606c2d55", size = 408552, upload-time = "2026-09-11T19:03:42.728Z" }, + { url = "https://files.pythonhosted.org/packages/cf/8c/9677dad226e5aaac5b823d5b09d881ebc32ff1648af417597649841e516c/contourpy-1.4.0-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e439ab450c93455feb0218532ded3e946ec7a9b5f459069f122cfa44b89229f6", size = 384850, upload-time = "2026-09-11T19:03:44.402Z" }, + { url = "https://files.pythonhosted.org/packages/08/f5/e3fbeaa489c223629fbb434737cb3de4ecaca9cae4825e77b92490f640f8/contourpy-1.4.0-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:417be048f7e122cefbe2a34c51a1f2b0410f8eb35796f794d45475ddb7872d9d", size = 1357601, upload-time = "2026-09-11T19:03:46.746Z" }, + { url = "https://files.pythonhosted.org/packages/88/be/55fec293d342c222ed58a5d4056df4362e192af2e59527a3d5d822de8828/contourpy-1.4.0-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:43d80072a32299bf945de0a6dd4e034ea0162e832261de2e07a274a5adbba9c9", size = 1427340, upload-time = "2026-09-11T19:03:48.745Z" }, + { url = "https://files.pythonhosted.org/packages/86/40/0faabf453edf59b0e3633381d7ca72c3414fb9b72b5cbb08b06ed792d3e5/contourpy-1.4.0-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:fa1b787362a3856e63dd2b89449f6c384d55ee1beb8f94f4bcc871b40f02462c", size = 118355, upload-time = "2026-09-11T19:03:50.047Z" }, + { url = "https://files.pythonhosted.org/packages/38/0c/7ea75aa3559ae8a6805015e15a19c92b6480752ecc92526361e5776e88c5/contourpy-1.4.0-cp314-cp314-win32.whl", hash = "sha256:738c44fa71735a617f36da58e32810512407d283d5d1bb5b1cecb00d7eeba7cf", size = 356977, upload-time = "2026-09-11T19:04:11.401Z" }, + { url = "https://files.pythonhosted.org/packages/15/41/3df8cc14bb572c8b447f9dfbc876703f0f2f2896058285b5c87a1d4a638d/contourpy-1.4.0-cp314-cp314-win_amd64.whl", hash = "sha256:181bea01bc742734ae672fa00c717d855dd35e1f029536406538c52e7b0cd73d", size = 240101, upload-time = "2026-09-11T19:04:12.772Z" }, + { url = "https://files.pythonhosted.org/packages/66/01/ee6830a5aa4565662a345172f6f35eeeed625d20f1c9d4ecd35318fe4ade/contourpy-1.4.0-cp314-cp314-win_arm64.whl", hash = "sha256:64039341e2d8804f1a13bda8c69083eab935167bbd7e856cf096241f17d5bd45", size = 576359, upload-time = "2026-09-11T19:04:14.983Z" }, + { url = "https://files.pythonhosted.org/packages/51/af/49ee9c9cf012699e505c1b63c531cc99f19df50f205173092c4d541e3ec7/contourpy-1.4.0-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:ef47fef9a912c77e3d84b014f701e5a9340f25703e9ed3bcebe37f91fb69dc49", size = 313601, upload-time = "2026-09-11T19:03:51.452Z" }, + { url = "https://files.pythonhosted.org/packages/ad/59/ce411ab2be0f805038626d8f4ca9ce563487ff51ff6c363e7512271564ed/contourpy-1.4.0-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:96019f059bcb3774acc0104be3360a57b36d33eaaa2e1d7f77c800ca8e07618b", size = 302812, upload-time = "2026-09-11T19:03:53.022Z" }, + { url = "https://files.pythonhosted.org/packages/95/b0/390915f9af14c1e2d3b2a9ad99d85b98df4352346a51e368cbb825f813c3/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:ddf5a2596d716fd3793434844caf31abc7a40b1e8718431420c89858268fb909", size = 348996, upload-time = "2026-09-11T19:03:54.594Z" }, + { url = "https://files.pythonhosted.org/packages/c7/85/e0952576d54322f3e9983b1e049a7a31f42ce82c5c29d01821e6dd3780d7/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:dd59df9e2fb0aff8bd7fd1adb9f349b7c835245a9d0f18c2f2deeb537190f2b1", size = 400272, upload-time = "2026-09-11T19:03:56.822Z" }, + { url = "https://files.pythonhosted.org/packages/d6/7d/f13543a5e1598e4a4ad01d9d5e2d65f9c09c37660616429913d606c5977d/contourpy-1.4.0-cp314-cp314t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:b7794ea07cab575633daad8d6e963b662053391022294d3aacc1d9ba9ef54114", size = 412895, upload-time = "2026-09-11T19:03:58.487Z" }, + { url = "https://files.pythonhosted.org/packages/c5/a8/6e5eaff53507dfd2dfc428240eecda32453067277d4b3e7ca71210b2d611/contourpy-1.4.0-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a1c8a74744fa746eeaa12f0f9ed7f8b4add9d8f1b14d95e3b5e133675eac888f", size = 377060, upload-time = "2026-09-11T19:04:00.122Z" }, + { url = "https://files.pythonhosted.org/packages/16/a3/d00e44d35511b3cead5bd794ee672d4eecf30d9de4ceac57a49d6204064f/contourpy-1.4.0-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:107ec46f7aa1664266d69b1181aadc953d58d39f7d8d648fa5b795d4a060b0de", size = 1345688, upload-time = "2026-09-11T19:04:02.705Z" }, + { url = "https://files.pythonhosted.org/packages/1e/01/1e533b0cae32c8edd63fe40435ec3b29345dab87321afcd28722d7f957d1/contourpy-1.4.0-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:5a4c89c7f38a0d7a94356d74e3391073c4325c4d47ad2fd065c3fe7dbae16c0c", size = 1416140, upload-time = "2026-09-11T19:04:04.77Z" }, + { url = "https://files.pythonhosted.org/packages/6d/0c/4ee66759f00d6a5d6909782f14f441d639fa18a4a43142e334351efc47f8/contourpy-1.4.0-cp314-cp314t-win32.whl", hash = "sha256:912c6afaa106e2f74ba22b30416b77ef7eb94e3bdc5a4df51ab147845dba9b6d", size = 371982, upload-time = "2026-09-11T19:04:06.233Z" }, + { url = "https://files.pythonhosted.org/packages/e6/ac/b3e5324138c3e3741f526663f4f265f4f69dfdf26415a39428940864a5f6/contourpy-1.4.0-cp314-cp314t-win_amd64.whl", hash = "sha256:ef9440f6f8506246269a82734f5ff9e2e4c5e775b3996fc883cc491c5257eca6", size = 262907, upload-time = "2026-09-11T19:04:07.882Z" }, + { url = "https://files.pythonhosted.org/packages/19/37/c9aa45e47819dc15a38fc5c81a2fb987fde55e9d3b991fbde514e3b6b5f5/contourpy-1.4.0-cp314-cp314t-win_arm64.whl", hash = "sha256:fc9feef8f1f001c5b87decadc67c4a5d1eebb62ca39c4763d1237ff62cf2b707", size = 587071, upload-time = "2026-09-11T19:04:09.898Z" }, + { url = "https://files.pythonhosted.org/packages/cc/74/66d4e6fbea3bcb3fd4e5ae21c039ba31b8fc408b35884b4bc09b88016dce/contourpy-1.4.0-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:79b06c60d5e569ce12c5da8f0c51217cdc484386e2349fa717c30fafb56d2871", size = 297358, upload-time = "2026-09-11T19:04:16.718Z" }, + { url = "https://files.pythonhosted.org/packages/2e/8d/8f7f25e71d73f15d7859943189900d2d348e740388c9ef52a0180d284762/contourpy-1.4.0-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:6f963ea9f0d68d2b6a02d861e3c0aae09ae25ba21f243fcf281e9fed468b078d", size = 283732, upload-time = "2026-09-11T19:04:18.087Z" }, + { url = "https://files.pythonhosted.org/packages/f0/90/957549e3b03c407c670e3e191db63f4aef60dab6605bc967af3a806b543e/contourpy-1.4.0-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5545ff38229c15d11d822fc6f7415b932da9f4975f53e305b7b96ebfb01f889c", size = 357820, upload-time = "2026-09-11T19:04:20.077Z" }, + { url = "https://files.pythonhosted.org/packages/56/4c/fa8de87d907b41b05d03f4945a51675cd67319650d01b4c927d209ffa6ee/contourpy-1.4.0-cp315-cp315-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:630d32f06cedf37b7f1dd2b6a12e4492826bd477a4c9c7b2e2fee6ce3a2cea76", size = 407804, upload-time = "2026-09-11T19:04:21.781Z" }, + { url = "https://files.pythonhosted.org/packages/04/e7/96bd4f4a4ae285727befbdb4b332d53a2654cc5da4585d2525b47a063e1f/contourpy-1.4.0-cp315-cp315-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:be85d160e7c795113c2a93254dde2fc7e86b375322570eee78b420969426973c", size = 408559, upload-time = "2026-09-11T19:04:23.432Z" }, + { url = "https://files.pythonhosted.org/packages/ae/94/39660e8dc309f96bf7971eb4ec5659f272f84e42b34c9990a96ecce8442c/contourpy-1.4.0-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:018227e134b73090b06f911e773a526c77c9af426be29065500ce096a5accd4c", size = 384861, upload-time = "2026-09-11T19:04:25.198Z" }, + { url = "https://files.pythonhosted.org/packages/ab/7b/411dccbf73d5d19da49bf7735786b3baf4ddb1456412d48ae4d4ab1fc761/contourpy-1.4.0-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:4bffcb2e8cc5c0e837631acab59dd04265fdac376550e7c3e310523877c68cb7", size = 1357612, upload-time = "2026-09-11T19:04:27.614Z" }, + { url = "https://files.pythonhosted.org/packages/a0/39/bf2442130e7d5aae75a4de4504f0c8aca3ef3da3feac3940ee27ca985d83/contourpy-1.4.0-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc87f2ffa84a49a77d76cb792f28a48ff3b05a222aa0b2bddbd839ba78e1d5ca", size = 1427345, upload-time = "2026-09-11T19:04:29.646Z" }, + { url = "https://files.pythonhosted.org/packages/96/60/e5d9196dd83ccd7dd103762982b10ef19a4f72e8ef67ae7157699b9be0bb/contourpy-1.4.0-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:c8be3392b84cf43373a488874dc1ebf46f60784a70977f92586e18019d71c7ed", size = 118157, upload-time = "2026-09-11T19:04:31.091Z" }, + { url = "https://files.pythonhosted.org/packages/1a/b2/ae3d90f08ba2ed82189d93b55ffbd41e559760e89af4f9ef54d51869f41d/contourpy-1.4.0-cp315-cp315-win32.whl", hash = "sha256:618137ec5778fb76d494c9ec854b104a377fddba0d128bef7136cce2c3bf0df8", size = 356982, upload-time = "2026-09-11T19:04:52.913Z" }, + { url = "https://files.pythonhosted.org/packages/02/a0/36648fff407dcf8b8482985d33367ffc0fe90be72383869312cd0bd00a1b/contourpy-1.4.0-cp315-cp315-win_amd64.whl", hash = "sha256:ea09dc704029930cbd097f75cb0cc1db9852adbcf1a151fac7e9559f7bcbfd19", size = 240101, upload-time = "2026-09-11T19:04:54.587Z" }, + { url = "https://files.pythonhosted.org/packages/07/09/49e987a96706b8f877596cee00d558d7880793a833addc6b33f80805e5dc/contourpy-1.4.0-cp315-cp315-win_arm64.whl", hash = "sha256:a5e2bb871b90cd7a52bdee63bf80ef7acb46398d27efc66d7679240016efc5aa", size = 576375, upload-time = "2026-09-11T19:04:56.515Z" }, + { url = "https://files.pythonhosted.org/packages/e3/18/820ba24a070fe2a834af73e52245c501960746f5c1777ebc64ec0c0dec12/contourpy-1.4.0-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:432e89f835cf01f8d2123a130a3126b17ee6e0348e4d62c0973872b30aa873bf", size = 313543, upload-time = "2026-09-11T19:04:32.582Z" }, + { url = "https://files.pythonhosted.org/packages/d3/4c/f61a63d8107e0c1c3fa47d30ce45abad90b2ad48a1a9a4510332db7e0176/contourpy-1.4.0-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:3e0a2392533e5e2abdf277c951047516acc8d2f3c42b2dd9dc34c907c9ebabf2", size = 302702, upload-time = "2026-09-11T19:04:34.257Z" }, + { url = "https://files.pythonhosted.org/packages/9d/93/5af95cb5113ecc6e780ca0c6c79756a2cea8833f971bbae112dd4ad73ded/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:758e7496cec3195fc28a28945eab3ceef348c47fb95c7afc2eca2f3901209c8c", size = 354370, upload-time = "2026-09-11T19:04:36.158Z" }, + { url = "https://files.pythonhosted.org/packages/47/75/5a9942446647202beb7b4d150891bfcb78fb112c73862484bbe4cc031092/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:bee6ff96653e0807cd0f8eaef00174a031e3a2effa5c20f49a5a8d574b05af23", size = 402340, upload-time = "2026-09-11T19:04:37.914Z" }, + { url = "https://files.pythonhosted.org/packages/c3/4f/bfdb0c67775a584f957211936661289789c4d0ec3e988bca2c8c02f8090e/contourpy-1.4.0-cp315-cp315t-manylinux_2_26_s390x.manylinux_2_28_s390x.whl", hash = "sha256:a58b5f130afec61a093d743cdda435cc4047748b6791627e34a68f41ec3a9b07", size = 410721, upload-time = "2026-09-11T19:04:39.925Z" }, + { url = "https://files.pythonhosted.org/packages/65/d3/dddf13d6bb26e145c99debd1f2695018b5f3e24452dd9bfc9904c9d2ec89/contourpy-1.4.0-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b9dc493e7924e5aa32d89d0b8e50986280f3d4b284968a792787bd7bcffd3cad", size = 382604, upload-time = "2026-09-11T19:04:41.793Z" }, + { url = "https://files.pythonhosted.org/packages/37/b4/89f0a5f6c6ccd322eae2704c7e933c82a4e594a61773933b4b0a18646866/contourpy-1.4.0-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:c927ec747633e68c9920bcaad48b0bcefe648812b822f18c34e2d0e2270a3d2a", size = 1354996, upload-time = "2026-09-11T19:04:43.856Z" }, + { url = "https://files.pythonhosted.org/packages/5d/29/fc91cc1ac6f3b591a269f4357b656d6ed0c39eb17c148f41f6da2f9729b9/contourpy-1.4.0-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:80c7fc8e7ac217777ce7ba2db3cf8478652b5a4b335283111012ff9eaac9d842", size = 1425030, upload-time = "2026-09-11T19:04:45.981Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b8/bb129f524210c5d3eb8616876e02af280fba8b5554e0ac1afad80b51e06b/contourpy-1.4.0-cp315-cp315t-win32.whl", hash = "sha256:90feb8da006803a95ba573fddc9536357d0c3faddc3a4c9e22816ca49af52878", size = 371854, upload-time = "2026-09-11T19:04:48.106Z" }, + { url = "https://files.pythonhosted.org/packages/d8/b1/bc774d9d200cfc4f073bba78b1bb1cb3b55bf1c8c345eae41fc2db510459/contourpy-1.4.0-cp315-cp315t-win_amd64.whl", hash = "sha256:de503609fdb71f597634ca64fb4bd2f13d27c97f140e912b1e8ed93544840df0", size = 262450, upload-time = "2026-09-11T19:04:49.502Z" }, + { url = "https://files.pythonhosted.org/packages/54/bf/eb4ff492e1c3d027617b5a20e4e6d63a035b41b8cf77a95950159556a3a5/contourpy-1.4.0-cp315-cp315t-win_arm64.whl", hash = "sha256:78ed5c5f962b3e156109f0531b174a65ba80d13cc681a70227b12524c162e184", size = 587064, upload-time = "2026-09-11T19:04:51.148Z" }, +] + [[package]] name = "cuda-bindings" version = "12.9.4" @@ -238,6 +330,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b8/5e/db279a3bfbd18d59d0598922a3b3c1454908d0969e8372260afec9736376/cuda_pathfinder-1.3.4-py3-none-any.whl", hash = "sha256:fb983f6e0d43af27ef486e14d5989b5f904ef45cedf40538bfdcbffa6bb01fb2", size = 30878, upload-time = "2026-02-11T18:50:31.008Z" }, ] +[[package]] +name = "cycler" +version = "0.12.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a9/95/a3dbbb5028f35eafb79008e7522a75244477d2838f38cbb722248dabc2a8/cycler-0.12.1.tar.gz", hash = "sha256:88bb128f02ba341da8ef447245a9e138fae777f6a23943da4540077d3601eb1c", size = 7615, upload-time = "2023-10-07T05:32:18.335Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/e7/05/c19819d5e3d95294a6f5947fb9b9629efb316b96de511b418c53d245aae6/cycler-0.12.1-py3-none-any.whl", hash = "sha256:85cef7cff222d8644161529808465972e51340599459b8ac3ccbac5a854e0d30", size = 8321, upload-time = "2023-10-07T05:32:16.783Z" }, +] + [[package]] name = "debugpy" version = "1.8.20" @@ -313,6 +414,63 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e7/04/a94ebfb4eaaa08db56725a40de2887e95de4e8641b9e902c311bfa00aa39/filelock-3.24.2-py3-none-any.whl", hash = "sha256:667d7dc0b7d1e1064dd5f8f8e80bdac157a6482e8d2e02cd16fd3b6b33bd6556", size = 24152, upload-time = "2026-02-16T02:50:44Z" }, ] +[[package]] +name = "fonttools" +version = "4.66.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/87/b6/126c659ab7e0e03e01a5f5d223abf7b2c0691ae92718085a212a3924a2a3/fonttools-4.66.1.tar.gz", hash = "sha256:64967c6ddb0d4c610dfd8cb1485981b2d27972ddfb7d4bbbd9e199d2a089c450", size = 3694174, upload-time = "2026-09-29T16:11:53.706Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/1b/fcb22638f2f5918c855abfbab203701e4b03739953d26a59f3e6e59b8f30/fonttools-4.66.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:8526b2b7ec4db6b81efb83438be52b1264eda9a4994d867163cfe8c65581ce8d", size = 3097433, upload-time = "2026-09-29T16:10:07.869Z" }, + { url = "https://files.pythonhosted.org/packages/7f/0d/f51141407f9a64efc9fb39b94b0194c4a99c1ffff50834e7ca7a3f1cdd53/fonttools-4.66.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:6946fe7bfb28590a1fd4061a17609c9a843952deb65dcf30d1fe725070c3e7a4", size = 2587566, upload-time = "2026-09-29T16:10:10.099Z" }, + { url = "https://files.pythonhosted.org/packages/75/c0/5810d73f9102eb1a08f26b8f7a6c22498622b43e05e684cd5ec602be8ffd/fonttools-4.66.1-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:09ae73bd219e1245debd8376077a0fa6e03175e255c4f51bae5f6a271bfe384a", size = 5416460, upload-time = "2026-09-29T16:10:12.182Z" }, + { url = "https://files.pythonhosted.org/packages/a6/6e/babde908b879a3b51ffc230919d06a804912559dd4cf8c94f3fa2af69fec/fonttools-4.66.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:7b8ff9e0edbcee2fbf7dff0c41b9041c1901c26acf64e23adb67495012df11de", size = 5397326, upload-time = "2026-09-29T16:10:14.133Z" }, + { url = "https://files.pythonhosted.org/packages/e6/98/8522cc7a5e5ad64a2b2b6e9598489809ed4956c532b887c65b131b8500b7/fonttools-4.66.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:38ce8f5fbd5c17dd2153d47d7c8d4108f3deda3f2b4a79b60ddc470a58faded3", size = 5353857, upload-time = "2026-09-29T16:10:16.375Z" }, + { url = "https://files.pythonhosted.org/packages/15/f9/ab87d67c23178886e57f24397b3113b4ac35297f086467c2c4d4231671a8/fonttools-4.66.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:8aed2bbcd6216253ef1b015763593365ee8084f621dfa53bb957c19d5e05f7cd", size = 5517604, upload-time = "2026-09-29T16:10:18.791Z" }, + { url = "https://files.pythonhosted.org/packages/d4/20/e126062610aea31919310b0b3de4d0bbe73ccbdcb3d0409cc52027db93ee/fonttools-4.66.1-cp312-cp312-win32.whl", hash = "sha256:9ea6c93091cbf83161a544388746a0911550bd98cb911faca3591cf5ead166ac", size = 2435084, upload-time = "2026-09-29T16:10:21.145Z" }, + { url = "https://files.pythonhosted.org/packages/f0/af/5c245a0587e5b7b3dd209f640b9f70d8e63404ad8dc93819ba578d685985/fonttools-4.66.1-cp312-cp312-win_amd64.whl", hash = "sha256:261d8dc95845e751f975fe8d6075600593ee253470d46d1b84801688051b09f6", size = 2486987, upload-time = "2026-09-29T16:10:22.924Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f4/e410b8c913da5b3fdbb4d16db0f2d2a0952f59c4db8d52dcf2d421d82044/fonttools-4.66.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:53e5854ea8003efec34adc0863c18ce91da923018354d27366f7fee7db928d7a", size = 3095249, upload-time = "2026-09-29T16:10:25.261Z" }, + { url = "https://files.pythonhosted.org/packages/5c/6a/275108baf41d9f2f4d1d77cf5f1e22200fe47efd5099dafabc3eba0b6197/fonttools-4.66.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:60f5ea17aed4262630afa43f26997ceabd6417fa05dcedf54c665f5a29193e18", size = 2587288, upload-time = "2026-09-29T16:10:27.101Z" }, + { url = "https://files.pythonhosted.org/packages/db/e7/11e5e6beb7e336d80f0ca870ae080033a91ebfe34fd5390dbcf78f8df56f/fonttools-4.66.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1801fdad5600118327171e0e8aa79f7cc48831dd55ab36998c9de03bd5ffe6cd", size = 5389836, upload-time = "2026-09-29T16:10:28.988Z" }, + { url = "https://files.pythonhosted.org/packages/4c/1c/6ec22372362b03350fe3da7bf33491a07cc9a553a36dd2383b76ec1741eb/fonttools-4.66.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:83572afe48733bad7a4a9c11721d3a726c2e976d82b063fc9bdd049d76955abd", size = 5372059, upload-time = "2026-09-29T16:10:31.011Z" }, + { url = "https://files.pythonhosted.org/packages/4b/4a/cb7971f1c0f40f891028ee8c46dadc6897ef61e44aa925a23fba2ef06e2a/fonttools-4.66.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:08d8956e3ec990c75230d92f1630b215e8f3738c83a003421c22b31ebfd0ce15", size = 5332824, upload-time = "2026-09-29T16:10:33.563Z" }, + { url = "https://files.pythonhosted.org/packages/e0/86/563e671f1d43fa8ffb2518d7fe16630fb16c7faf0420cc39f8e80181f486/fonttools-4.66.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:fdf4afd75c643e60ef4a96fe64fc8a9def27d2a542112332371a9e5066885f9a", size = 5490659, upload-time = "2026-09-29T16:10:35.788Z" }, + { url = "https://files.pythonhosted.org/packages/79/f7/2573ddfd256be6503458f8523e2893443e66257fc17f6055d7e0f0e721b7/fonttools-4.66.1-cp313-cp313-win32.whl", hash = "sha256:dbb7b950f8c02deaffb6968994691e8589d671b7ef8396bc9d5b5c0dfbb7292f", size = 2433450, upload-time = "2026-09-29T16:10:37.738Z" }, + { url = "https://files.pythonhosted.org/packages/d1/86/68bc2be04b83535607fbb70ebb2ba02380bf4286d79597c4515b7d247187/fonttools-4.66.1-cp313-cp313-win_amd64.whl", hash = "sha256:43d1284c1964666ee833f2badd3017dc138f53d4889043ffca66c5ce4188f188", size = 2485146, upload-time = "2026-09-29T16:10:39.772Z" }, + { url = "https://files.pythonhosted.org/packages/12/83/c745b210ec49379ebfe627e166b527f44671a1f6ec5e1e219d91caa8964d/fonttools-4.66.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:b18803cbdef248e7ee1be59cb277fbbe1da1faaa6f726fa5d3557904e6a3d967", size = 3099264, upload-time = "2026-09-29T16:10:41.998Z" }, + { url = "https://files.pythonhosted.org/packages/35/af/dd698f10bf0f743873077259e8a6fce075861dde3bb01eb22b2c4f7aefe8/fonttools-4.66.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:f08ab7f8461c37ecfdd29ad97fb0c0780b50501bd664bb0f46b6e83ed2b9d2a7", size = 2588769, upload-time = "2026-09-29T16:10:43.933Z" }, + { url = "https://files.pythonhosted.org/packages/c5/65/10b5caa2aa779e62411b67949bda9741d4d7532ba0b6dea647b715131260/fonttools-4.66.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:7cf4f996f9b1cb549bff9ea4c50813988a26ec922c95cfa85c7e4f1270447e06", size = 5374278, upload-time = "2026-09-29T16:10:45.727Z" }, + { url = "https://files.pythonhosted.org/packages/6a/db/9ac5c6773feec1b40e57eac106d869886f66a1e44082d343ac1e1e1fb773/fonttools-4.66.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:9261ef507f2dd74203443a472b65b5a26429eb378f975016dec7dc7305b24898", size = 5317826, upload-time = "2026-09-29T16:10:48.056Z" }, + { url = "https://files.pythonhosted.org/packages/04/0a/69beb11f6b714ac90ee73ad4600ac91d7dd4e1ce361d087c8425bb8472de/fonttools-4.66.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:e1cde50b3ec84ca6fe63ca815de183dbecb88e8adf8ada82d8ea130ef12b2b43", size = 5316239, upload-time = "2026-09-29T16:10:50.201Z" }, + { url = "https://files.pythonhosted.org/packages/33/a8/7a77359e469d3a638df91d3e225cef4a3c1184c20e98381238042f7835fa/fonttools-4.66.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:d8f0a8f16c4f3a5a87ca971de2631792d8cb4d570951f2000acf712f157d40db", size = 5449423, upload-time = "2026-09-29T16:10:52.337Z" }, + { url = "https://files.pythonhosted.org/packages/93/cf/ea0b2f1ef90431b1879d6e6c680a7fde497129cf511ab995ade0ff8e19a7/fonttools-4.66.1-cp314-cp314-win32.whl", hash = "sha256:b878c78b2af11b879bd4f26bb0d8bda2a4c64543fdd3f28efe2c80f97f043885", size = 2437673, upload-time = "2026-09-29T16:10:54.281Z" }, + { url = "https://files.pythonhosted.org/packages/b2/53/629dbb4a40c4a7b3de61442c6b4430d36ab6e0e8cf941c547f4fd66f3337/fonttools-4.66.1-cp314-cp314-win_amd64.whl", hash = "sha256:05aeb146451f37289f782c3c861f3d0f4b86c2dd2e4620b46683544c7406640e", size = 2489763, upload-time = "2026-09-29T16:10:56.262Z" }, + { url = "https://files.pythonhosted.org/packages/0e/59/342e5fce9438f88882524128d1feb0311d4014cb6f8bdeb4607fcc00713f/fonttools-4.66.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:66fad3b7874062c2a2692f0ae6dea56d24f01b778c7f191950ca3ff997e25a88", size = 3172931, upload-time = "2026-09-29T16:10:58.563Z" }, + { url = "https://files.pythonhosted.org/packages/50/92/96196ebfd02676f28fa9b3776d85e18281bca0c8450d7e214c40e346bf92/fonttools-4.66.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:eef76d5796e604f9d6753fa6d323c4eb9f4e0e43f1dcca553f3e6914f1667b64", size = 2621937, upload-time = "2026-09-29T16:11:00.845Z" }, + { url = "https://files.pythonhosted.org/packages/e7/c3/3f4b761037ebc2e5597c52c218a9e95dbc4a2cab572828654f6004f422f5/fonttools-4.66.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c47299bca4b5acaaeb32100f77b944feea151de9ef1773365a410dc3d49b945b", size = 5546932, upload-time = "2026-09-29T16:11:03.126Z" }, + { url = "https://files.pythonhosted.org/packages/b6/d1/3f506cc79608becbc287785db8c44eb3f93079b49752266eb9f57700ecc4/fonttools-4.66.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:dfba62cc93199ba62c376f90f2a9147d92730d301e44f88e013e50ff5edf6193", size = 5353546, upload-time = "2026-09-29T16:11:05.394Z" }, + { url = "https://files.pythonhosted.org/packages/6d/27/6534d84430ba1641185f8a0c9e2c7ecd395b15ff98f96967e3fb3c728b09/fonttools-4.66.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:2c7340497cf53490293e0c2b61011e0191633022ede0a0a964a68157a98b0fb4", size = 5414313, upload-time = "2026-09-29T16:11:07.618Z" }, + { url = "https://files.pythonhosted.org/packages/27/17/831ceca06d78855b11dc203b0e3ba5e6fd8a63a71ee0343ea8bd367fda55/fonttools-4.66.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:c666fefdd5613a0e99aa4516e6ff4ef87aa86cf1c7ba12a73550f4770e46b750", size = 5449661, upload-time = "2026-09-29T16:11:09.997Z" }, + { url = "https://files.pythonhosted.org/packages/2e/e4/21dc18bcbc8d0354814f6ea58af3d76d3bcd9b0d7246df454cb9e00c1740/fonttools-4.66.1-cp314-cp314t-win32.whl", hash = "sha256:2ce4c93160535761f22c80b2afbc96cabc09855363a5d1a5554265b8a4c85901", size = 2471431, upload-time = "2026-09-29T16:11:12.237Z" }, + { url = "https://files.pythonhosted.org/packages/b5/f4/eb0489e7d58ac0d3387584afc7f3e505f60f60fe4b4f5a0274f013d444a2/fonttools-4.66.1-cp314-cp314t-win_amd64.whl", hash = "sha256:b13c8c541ce0b794add3211b3641cc0e113d707f73e06235e6fe9731bd7c45a9", size = 2521288, upload-time = "2026-09-29T16:11:14.52Z" }, + { url = "https://files.pythonhosted.org/packages/eb/95/235679d5fe4265c251418cd02321de069281a700415389e14c4cce442e3d/fonttools-4.66.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:2d637468dac23aac0e223bd52e66f8faa3b0dfcef57435460fa2107e830226cd", size = 3093646, upload-time = "2026-09-29T16:11:16.809Z" }, + { url = "https://files.pythonhosted.org/packages/ad/2b/7bcd4046b3b5644c563059cce6421b488fe57f65c59171ef01ed11b66d3a/fonttools-4.66.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:90de3477394c73481d27d2b86091c1c736053ee13ff52c42f0e151948e8578c6", size = 2587335, upload-time = "2026-09-29T16:11:18.721Z" }, + { url = "https://files.pythonhosted.org/packages/ff/b6/05a093ec04fa2ad449ecc67638aad0f8d60df380df2471b68b549fe2a4b2/fonttools-4.66.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d84ac0bf776b68396185bd919dd29e633d94300660335efc40b55b294b886903", size = 5371509, upload-time = "2026-09-29T16:11:20.742Z" }, + { url = "https://files.pythonhosted.org/packages/65/a9/55effa83e64b9ff4f379d9186236d50d03f6d4770d8346805c1b6620c370/fonttools-4.66.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:0dc6fd99cb8c30941036308b148da9432640442a6f26f36d71dad9be24cbd0e9", size = 5334853, upload-time = "2026-09-29T16:11:22.928Z" }, + { url = "https://files.pythonhosted.org/packages/af/a8/44bb4021c585b76f8e480116e1f3fca62eb7d88fe5794e2ec84c10d2da76/fonttools-4.66.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:d3b5403e82d0c7659ff1d9f956e29a3a68d094f043e9f5bc0442796fc3a4fb58", size = 5311704, upload-time = "2026-09-29T16:11:25.393Z" }, + { url = "https://files.pythonhosted.org/packages/63/dd/dd482902fb7fd8b71d3b6508431a57938b5e41b29bf6fb252ed3cfce065f/fonttools-4.66.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:b8b71db96d605784e2c5ebf0788a406018ea8fdd80338491f4c83613d5cd1fec", size = 5459477, upload-time = "2026-09-29T16:11:27.536Z" }, + { url = "https://files.pythonhosted.org/packages/3c/a5/07611ba4d4b298b90908cb15005a6d730c334e25548f5175a09907b2eea6/fonttools-4.66.1-cp315-cp315-win32.whl", hash = "sha256:668f092bc0de8902167df6a0d5c5aedc3b4f9e43cf88eea92e9b46a2bd3968f5", size = 2436532, upload-time = "2026-09-29T16:11:29.653Z" }, + { url = "https://files.pythonhosted.org/packages/42/a5/5c39a05bf7c518743c6072cd75b63cd27285c58a70b1086e923fc071fb84/fonttools-4.66.1-cp315-cp315-win_amd64.whl", hash = "sha256:7f49f2834f5d006fe0f3bb10fec73b261806c50941f0cfbc08294074ffc32210", size = 2488769, upload-time = "2026-09-29T16:11:31.967Z" }, + { url = "https://files.pythonhosted.org/packages/c0/a6/1205f7a7dd746581498457e55bfbcdfbea87105a454a7b3465259816bb79/fonttools-4.66.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:71c7ca1b5f46f5dd549f56b47d47c0b709217675c23d3a7bc6aa1a69b6d9bbae", size = 3164459, upload-time = "2026-09-29T16:11:33.897Z" }, + { url = "https://files.pythonhosted.org/packages/33/42/915ff8f3c5d3bc9877007e708774e52f7ec431f9e59f607a86e50fe1864c/fonttools-4.66.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:2d320483928c7831f0139ecb361954a26b2e2a8995681200155835dd8cd4a7d5", size = 2618183, upload-time = "2026-09-29T16:11:36.067Z" }, + { url = "https://files.pythonhosted.org/packages/0b/c6/cae2f6ebe38f8927a8d0978a349b202047268016344991a14ae978c2aee3/fonttools-4.66.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:2aeb745f2664eb811026997c95628071137a777ea2ad296deec9cb393f0b23cf", size = 5524861, upload-time = "2026-09-29T16:11:38.099Z" }, + { url = "https://files.pythonhosted.org/packages/f2/14/1941629956b526d6fb46ee764cf0942221f0238581adb94de0ac229fe67f/fonttools-4.66.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:3087a430722aba8de429c2539fd2a58a9cf05238cdfefd8626460001052ca878", size = 5346561, upload-time = "2026-09-29T16:11:40.366Z" }, + { url = "https://files.pythonhosted.org/packages/62/1f/b7e7f4757dcae74285f4ecd8453d870d63c7ba38a3d46bd9175a124c350b/fonttools-4.66.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:058cd823b80bac59e64dfad9e3b6fcd677852f9a3804971bbf6b48cc611e785c", size = 5392826, upload-time = "2026-09-29T16:11:42.653Z" }, + { url = "https://files.pythonhosted.org/packages/d9/71/76db3cbdcfac0e9b3ba26e1e6e8740040cfe5f7b5199dfb9b854bc8da2c3/fonttools-4.66.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:56d41d650cb8fc6cfe1d85ed7c62a0a56cbeed07bc65ca795475b914d401312a", size = 5439233, upload-time = "2026-09-29T16:11:45.088Z" }, + { url = "https://files.pythonhosted.org/packages/10/37/cdc6b213c9fbabdf36e9169f845e8596b419c7e0cceba48e5594b952d2cf/fonttools-4.66.1-cp315-cp315t-win32.whl", hash = "sha256:c258eba62260beb33c110b03a6912cefa3635239c4ab5615b7225fb6f7b85238", size = 2468614, upload-time = "2026-09-29T16:11:47.363Z" }, + { url = "https://files.pythonhosted.org/packages/fb/35/e2247e7e29e8da213e02691a6ada7a30592c7bc0d1db8d2786ebb9bea138/fonttools-4.66.1-cp315-cp315t-win_amd64.whl", hash = "sha256:5de5d80fbc0e50ff794c244e8fb7afd3eadfe0fa232ba8b162b8c551df22fcb4", size = 2516977, upload-time = "2026-09-29T16:11:49.425Z" }, + { url = "https://files.pythonhosted.org/packages/f6/10/d45b74135d5d642cb3a4fb0a957c1613ef93de4c8548671dfc3a5bf38299/fonttools-4.66.1-py3-none-any.whl", hash = "sha256:7234ae9e28db64273fbbfa72caebd0a97e3bdba6b05064114741b9539ef339d0", size = 1202222, upload-time = "2026-09-29T16:11:51.678Z" }, +] + [[package]] name = "fsspec" version = "2026.2.0" @@ -513,13 +671,124 @@ 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 = "kiwisolver" +version = "1.5.1" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/ba/07/bd78e6a8fae171ea041ef5bba3ed21a003522fa088834b069b1909981f30/kiwisolver-1.5.1.tar.gz", hash = "sha256:f1303ef2eec81262a4b708c3e858afe58d7c75ad91c1c05266eda7673369859a", size = 104395, upload-time = "2026-08-28T10:28:27.153Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/6b/9b/65b302742389c6f96f2956bef5decf26011309feb2fc5d79613af18adea4/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_universal2.whl", hash = "sha256:63fb7294b768f444eb4b068965f2662f28c2fd4161e23bd60fcf3ff27b74c046", size = 123876, upload-time = "2026-08-28T10:25:27.44Z" }, + { url = "https://files.pythonhosted.org/packages/71/74/c21f339956f6f691b2ed7e31d5f3ae767304df6c460192739fc830853051/kiwisolver-1.5.1-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:0ebdef3eae5336568147c39a55be6a2036ffde53faa9ca2d978989ae7c2da12c", size = 66487, upload-time = "2026-08-28T10:25:28.728Z" }, + { url = "https://files.pythonhosted.org/packages/84/e5/bdb34e21523e01dceda064d63713f3bdec91388af24fba1eca7ea5e85864/kiwisolver-1.5.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1798e83840c3f627246104c4d8a9639c60fa068adf9ce92b61791781fa8a68c1", size = 64660, upload-time = "2026-08-28T10:25:30.071Z" }, + { url = "https://files.pythonhosted.org/packages/fc/f4/dadfec469313c7f428efa7e84b4aba9732f813c13ea7131a24b7b008ef57/kiwisolver-1.5.1-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:34633ecf50d16187ab8e5528b7a2530f2feb4e23f300db4672538b51cfc5cd38", size = 1477929, upload-time = "2026-08-28T10:25:31.495Z" }, + { url = "https://files.pythonhosted.org/packages/6f/35/09c58daac34e6f6ea5c6dee0094b422118e5a7c265586008a95fd135ac5f/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d27c2123977cb9269c30a49ba45f03a4323017ef693e19db4ec9dbe1299a3002", size = 1278499, upload-time = "2026-08-28T10:25:33.375Z" }, + { url = "https://files.pythonhosted.org/packages/19/32/739765e24fbad29d13f83e546ea4abc215a78cea9d677ca09025b027724d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:6a797a1cefc8b9c93170db580337e1fe3d011ad18b1299943231279406342048", size = 1296677, upload-time = "2026-08-28T10:25:35.059Z" }, + { url = "https://files.pythonhosted.org/packages/df/32/03304d1010e2cc45e5b3b52cef7e43fed3a2a5cd6c87a89b4a88e1d85b5d/kiwisolver-1.5.1-cp312-cp312-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:2551cf9917af48ee7c4b29cc82320489508cf96fd26a51f6fc124de661cd44c7", size = 1346037, upload-time = "2026-08-28T10:25:36.705Z" }, + { url = "https://files.pythonhosted.org/packages/3e/57/4c49377bfd274450dd72ecaa13eaac32ea804a03363e4d1db0c5aa999ceb/kiwisolver-1.5.1-cp312-cp312-manylinux_2_39_riscv64.whl", hash = "sha256:38f6e0deb4d0a4615efe0c4efc5990b06ae450ab50a0b321c0b078b6d238c083", size = 988248, upload-time = "2026-08-28T10:25:38.299Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c3/38df144a08b6c5d75ca4504e5cc3141bb3bfef64c04f4ef48204f42711b6/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_aarch64.whl", hash = "sha256:bfd1de989b3330420e29de39352f5c049905c9e3ee67233a50d550e3d652c148", size = 2228722, upload-time = "2026-08-28T10:25:40.038Z" }, + { url = "https://files.pythonhosted.org/packages/e7/11/3221838a89cd64d9b386353e000cd8a296069a20fbe3584507fdfd5bebae/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_ppc64le.whl", hash = "sha256:1209042a623ddfda5497e4066c7b77651dde8e1d3a9dd97599dc7e97f3b9b78c", size = 2325216, upload-time = "2026-08-28T10:25:41.699Z" }, + { url = "https://files.pythonhosted.org/packages/83/d4/075c219230697bb5db910d37262b9bacf880f92b4811a02ab81ed073a253/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_riscv64.whl", hash = "sha256:26e8268480be5061d509e29669d59103c067a26377a56491630ece11762e3858", size = 1977689, upload-time = "2026-08-28T10:25:43.559Z" }, + { url = "https://files.pythonhosted.org/packages/bb/08/1d219c3c2dd960983d0d4da623d916e9de6385df2b0bab3d1af0e9b8fccc/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_s390x.whl", hash = "sha256:d79308fa689fac89cbcfbd4dbfc80b5f95c54c5a7fd4d194be221f9d33d026e6", size = 2491443, upload-time = "2026-08-28T10:25:45.242Z" }, + { url = "https://files.pythonhosted.org/packages/ba/d3/024208ec1079d273f1047468d1bdffbf38bb75b7b268090fd3a0301b9d9a/kiwisolver-1.5.1-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:b03af77d77e50edba2030fd5f7c352ff209314b09030a3cba7c14edf9a09a444", size = 2295200, upload-time = "2026-08-28T10:25:46.984Z" }, + { url = "https://files.pythonhosted.org/packages/6e/7c/7b210498f9f92e1cd7855f260fa69ef056881087b199ee20c208f0e4189a/kiwisolver-1.5.1-cp312-cp312-win_amd64.whl", hash = "sha256:06a6917674de9e0fe3f66f5430787f59a9f2ddb64af9b714eaec547e29ef5c19", size = 70748, upload-time = "2026-08-28T10:25:48.444Z" }, + { url = "https://files.pythonhosted.org/packages/94/61/ef0daa157c8bb23672f7423e0d14c39db1dc6ef8ed47e6bc54c9c1bef3bf/kiwisolver-1.5.1-cp312-cp312-win_arm64.whl", hash = "sha256:ad8b9671348d7c8716715652ae11f85ed0eb99e265a2df2ca490577d69860b2c", size = 68324, upload-time = "2026-08-28T10:25:49.81Z" }, + { url = "https://files.pythonhosted.org/packages/08/c1/88018321d976f53c421e379c43bc6993e70ce0c8a3ec5edc4bfe102257f6/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b6ae6a0328f0bc035741820fdeecdcd67bf4694eee03972e843663107122f450", size = 62272, upload-time = "2026-08-28T10:25:51.02Z" }, + { url = "https://files.pythonhosted.org/packages/85/d2/712bc17ea4f1d216034928069d612defbc6c95a471c55a7203a39faecb1a/kiwisolver-1.5.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:886fc26012f0e8b5f69d1cfe6d711f6b11f194621539bf8e6bb1c25c5dc82724", size = 64481, upload-time = "2026-08-28T10:25:52.22Z" }, + { url = "https://files.pythonhosted.org/packages/1b/e6/6c5380d676f43b6d918033962ea5e72360ca69e5a404154bc496b598ffdb/kiwisolver-1.5.1-cp313-cp313-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:aefe930d113798330e9462f7874542977869c0613cba3262e2de3a8d5dee8f3a", size = 66260, upload-time = "2026-08-28T10:25:53.387Z" }, + { url = "https://files.pythonhosted.org/packages/92/6a/7087f5822cc8bb272679641404b1966a42504dac9ee74e2b33840475a0aa/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_universal2.whl", hash = "sha256:a5ca5aebae78a0bc13c1943af4af615d4966c5b650b05d5aa83b50e427196fee", size = 123876, upload-time = "2026-08-28T10:25:54.644Z" }, + { url = "https://files.pythonhosted.org/packages/5c/4b/9f385087ca09ee5ab9c09c6832561a7d2f7c78d3e5661d511e669f70e439/kiwisolver-1.5.1-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:1ed0f5e49d0ceff8b72190824d9e59c062fbbc02c231b853112c78474b3f5ec2", size = 66487, upload-time = "2026-08-28T10:25:55.899Z" }, + { url = "https://files.pythonhosted.org/packages/47/8b/40d33ffd2f378094ed462e9a9a0907e59d4de9845e65a59561272da350d4/kiwisolver-1.5.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:77a4c8187a5948d7f8795adb765a3c7b553d07d86d88e43038fc32fc1fb9a3f3", size = 64673, upload-time = "2026-08-28T10:25:57.048Z" }, + { url = "https://files.pythonhosted.org/packages/ab/43/86aacc027959108b4c66eeae8b73cedb057dfa6eb3a335d05ad65197081c/kiwisolver-1.5.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:74ad5c3dad54a4641b4c28cd15ded70899d04459c6c7aeacafea716be97cce6d", size = 1477992, upload-time = "2026-08-28T10:25:58.479Z" }, + { url = "https://files.pythonhosted.org/packages/ed/40/b1d0369048c79733a32c8abb0f2718532e6630641368e33a81384246e844/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:21e46b23a2da695c364124817bc01d970effd5483147f8d66a6a7167e3f6b851", size = 1278821, upload-time = "2026-08-28T10:26:00.121Z" }, + { url = "https://files.pythonhosted.org/packages/61/a1/fa71c1792272ff9461432715ae60ffb7e11a4d7ac3bf68961b9cab6c60cf/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:75d9b1cf8258462dbdc1eeda718c96ea7f079324c09067f6daabfcf37712b7fe", size = 1296805, upload-time = "2026-08-28T10:26:01.868Z" }, + { url = "https://files.pythonhosted.org/packages/a3/49/3f0bd94af8e06ecc47eb834b195a06f05d48711ceb2352c56d6835160f0e/kiwisolver-1.5.1-cp313-cp313-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:8fca690b00c4c48f6c2a547b0160ed511357093a4e4c9b47e0fadf3128066d89", size = 1346109, upload-time = "2026-08-28T10:26:03.59Z" }, + { url = "https://files.pythonhosted.org/packages/a4/44/3afe6ef9cf06d61220953a8963e94eca978491be1d9547cb01d82a1efa08/kiwisolver-1.5.1-cp313-cp313-manylinux_2_39_riscv64.whl", hash = "sha256:876bbfd276473d3daffe30e8c975df4ed9429967b41a6cb362dbb5155b6f13ad", size = 988252, upload-time = "2026-08-28T10:26:05.306Z" }, + { url = "https://files.pythonhosted.org/packages/e4/30/a12bd7a7285a211e1747c3eec77b8c614dbfcc1dad942f7611a1a6921ae5/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:f942903fde7363d1d879057ec5de01310efda2597161784d752fa9953a01a71a", size = 2228846, upload-time = "2026-08-28T10:26:07.312Z" }, + { url = "https://files.pythonhosted.org/packages/a1/6b/233e2958abf0dab7b18d07e52f286e02e519d7651bfbbe97af9347564109/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_ppc64le.whl", hash = "sha256:c90d3022d8a94778939cda8638c6c8da8fa757b8958dad7ec868ce29c87681b8", size = 2325583, upload-time = "2026-08-28T10:26:09.093Z" }, + { url = "https://files.pythonhosted.org/packages/42/8e/7673060a27b01405b580058510adef34687069d229800239f5e44682d4d0/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_riscv64.whl", hash = "sha256:8a34616dc2521cc8dc1d7d081734da63539f021ac0450ce950908340c6e7aa2f", size = 1978221, upload-time = "2026-08-28T10:26:11.127Z" }, + { url = "https://files.pythonhosted.org/packages/3f/7b/1b882fc1a8b4a0bb8084e7d1d85004116d08c92c0705d31f2928dec607f2/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_s390x.whl", hash = "sha256:8bf4df63592c2a66b4f8edc5df2544998c288aa02f96ce0acd880cd1de8c8127", size = 2491819, upload-time = "2026-08-28T10:26:13.348Z" }, + { url = "https://files.pythonhosted.org/packages/39/9c/426deb49e62c5f69464b64bbeca064d3b758a7506b8913d986ef34f4619c/kiwisolver-1.5.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:d09037ca068d784ebc4aec290ef952ca27ac15dd9c0b5801a88c6e1096b83e6b", size = 2295520, upload-time = "2026-08-28T10:26:15.042Z" }, + { url = "https://files.pythonhosted.org/packages/f5/22/deabbb3ad6d918d74b7831b2d8ae7151b09d21c87974e5ee8a456f58c94c/kiwisolver-1.5.1-cp313-cp313-win_amd64.whl", hash = "sha256:dc23390afe9f4ef9ac3bcc72a03a56eebbde03f4c571a32cb38f859cff9a6524", size = 70758, upload-time = "2026-08-28T10:26:16.504Z" }, + { url = "https://files.pythonhosted.org/packages/b9/71/02fa5c2fd92068bb8952847e70ee6c5cb280e7febe11653d17812acc53dd/kiwisolver-1.5.1-cp313-cp313-win_arm64.whl", hash = "sha256:186884a58486651e3c217b6acea0a53eaa9498fdd472057c46f2f0fb5c25aad5", size = 68329, upload-time = "2026-08-28T10:26:17.658Z" }, + { url = "https://files.pythonhosted.org/packages/dd/87/2d5dfad0daf17dcc18d98c48ed2332fc3f051cf599e60be6182a30dd4cf1/kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:0324cd2567259b7a095f6cf18a52b0ffc6f3de9e69528ff1bc0e7a37bd43ff1a", size = 62337, upload-time = "2026-08-28T10:26:18.778Z" }, + { url = "https://files.pythonhosted.org/packages/08/c8/83e1624f15d6262b470dbcc80b09979fd4d5b2ea3ddfc6b6e3327e235726/kiwisolver-1.5.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:74ea337e0ec3f6f342a36a4f1b5cd94dd9affddcd28ba9aae2905af932ee8c6b", size = 64513, upload-time = "2026-08-28T10:26:19.909Z" }, + { url = "https://files.pythonhosted.org/packages/c9/2d/827ec30eb07f528c08d8459ffb318ae91a56d793ee8acbea8b491f0ff906/kiwisolver-1.5.1-cp314-cp314-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:ee9df1f0d77b9c6e94f4ac0fec533fbddd5ea3a327807f18d7b069ae019ded80", size = 66287, upload-time = "2026-08-28T10:26:21.078Z" }, + { url = "https://files.pythonhosted.org/packages/53/11/5c43a562529dad8def4b81e5e1877c612a7e0298105a5939b3b409d2079c/kiwisolver-1.5.1-cp314-cp314-macosx_10_15_universal2.whl", hash = "sha256:fc271a6f0a2126958f4090e5507b9da5848927dae331f8f763bd4aa642b3d2cd", size = 123940, upload-time = "2026-08-28T10:26:22.475Z" }, + { url = "https://files.pythonhosted.org/packages/64/db/9bd6c505c95128c258a55236bfbb3a7a3fb6023f863316b6d7d9f3c69052/kiwisolver-1.5.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:9b3092d8992a1d69b7a59c3e39f35e1b9be327a17f68a7c35fc17329e337d6f2", size = 66493, upload-time = "2026-08-28T10:26:23.743Z" }, + { url = "https://files.pythonhosted.org/packages/e1/f4/b3007a3ed5c9be73f81161140684cf7d9bdb9c4b632f5f484d2a1c713fb9/kiwisolver-1.5.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:c2306e8bb53601979fcb3fa09cc65e031876d9ae01eff2fcbcd7a84ef94d5bc1", size = 64720, upload-time = "2026-08-28T10:26:24.95Z" }, + { url = "https://files.pythonhosted.org/packages/a1/13/08188f0cafa3a800403e4ff62b9aad4e7a17f9c4c7e080dc8f18c64794cf/kiwisolver-1.5.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:18a0cfb124546a4c2e6087c5f3029c7f44b37c85b142e0ced71f73a7599ac208", size = 1475867, upload-time = "2026-08-28T10:26:26.393Z" }, + { url = "https://files.pythonhosted.org/packages/8a/3e/053bdc3c9abdb8f2606225eda398adca25c0c91ab90add8222a69db65ee0/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:34ec467940442c9943016fb2d4c81d1ba84351eeca2f1a78f8bc87f1ba0d414c", size = 1282865, upload-time = "2026-08-28T10:26:28.118Z" }, + { url = "https://files.pythonhosted.org/packages/5e/64/a44c341b36b610588cc2f1e89b3cae072a3119aa8be578e90987cd640751/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:a83ee7107df13abe42a54a6654670eef9bb39425cf2e27f65e0007465e1286ab", size = 1300865, upload-time = "2026-08-28T10:26:30.125Z" }, + { url = "https://files.pythonhosted.org/packages/60/5e/7e7d716dca38c714478b741257a5b4a321d9932b8d851551a136dcaf3984/kiwisolver-1.5.1-cp314-cp314-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:bebb89489b279b2f5661bbbb2abcc87bcd4a46607bb4a5c966f04f1db6b8df9a", size = 1348071, upload-time = "2026-08-28T10:26:31.829Z" }, + { url = "https://files.pythonhosted.org/packages/10/1a/2b98fdda8bf45b7be317e48ed12393d44334394d315c74b81f4a14c0e31b/kiwisolver-1.5.1-cp314-cp314-manylinux_2_39_riscv64.whl", hash = "sha256:509735237ae0d849e8a843551d423d2500d2e0a9ac1611a145658b29c0fb9f85", size = 992191, upload-time = "2026-08-28T10:26:33.544Z" }, + { url = "https://files.pythonhosted.org/packages/b6/55/d893f5ede0e50f9e3fcf01f6015f42ec7d9cd221e26772701fe4a98745f9/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:824c3d763a05ea9e9003610145186b0e9848c7584a5575c79bac5a8e7cd80bad", size = 2233854, upload-time = "2026-08-28T10:26:35.282Z" }, + { url = "https://files.pythonhosted.org/packages/b1/82/f85f6279555a6ee1639fef7bfe83adb037a03e11a6fc9eaa54b8d0380339/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_ppc64le.whl", hash = "sha256:1fff05e239575b1481b6ed1a782f6fad616efbf1f0b1f44e6e85c4dfe426e483", size = 2330621, upload-time = "2026-08-28T10:26:36.9Z" }, + { url = "https://files.pythonhosted.org/packages/56/31/e11aea078f66fc2fffcc179d38ca90d9da97652a241b64519169742ba46a/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_riscv64.whl", hash = "sha256:0627b9bceb9c3cdcf12b8a18655eedfed2692b038df27423383c120d0b7dc2d6", size = 1982848, upload-time = "2026-08-28T10:26:39.01Z" }, + { url = "https://files.pythonhosted.org/packages/af/ea/2956b63bf5140ca46aa2c2818e6aa03e2d5754dd2fa41db1c6b28922940c/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_s390x.whl", hash = "sha256:8a708a47ade1fe19e8371d5da076bac0dd4b0a5a7985ad6c637f7f7e361b6baa", size = 2494850, upload-time = "2026-08-28T10:26:40.837Z" }, + { url = "https://files.pythonhosted.org/packages/11/d1/3829542258d8b3fc0898d221e7ef0e2c83eca0d348709bb8dbe54f3d4005/kiwisolver-1.5.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:007a5553dfc4f4e8d184f588a0200e2cd4b63a59cc8796df3c39909e679dc7a0", size = 2298067, upload-time = "2026-08-28T10:26:42.803Z" }, + { url = "https://files.pythonhosted.org/packages/4e/0e/49522e1ab5788cbaf63a26fbd3b851f9028616828c961b8a31b35cb96df8/kiwisolver-1.5.1-cp314-cp314-win_amd64.whl", hash = "sha256:f4167e87b397f273dc2356fcf1eaf50a6bac51e6105f45103ef7129c8efb0255", size = 72282, upload-time = "2026-08-28T10:26:44.268Z" }, + { url = "https://files.pythonhosted.org/packages/f5/b6/22e7ca5315d363e6f81c9f37c9472e12e7b298731e77c0428e6a911a2c39/kiwisolver-1.5.1-cp314-cp314-win_arm64.whl", hash = "sha256:5c490db2168a508088f59140dd392556a54b8bd1048fc6383c8baff13c359673", size = 69855, upload-time = "2026-08-28T10:26:45.725Z" }, + { url = "https://files.pythonhosted.org/packages/30/8c/03a9cfbe871964c8758a816eb03ac96c806da2795a9a7cd9bf9648bfb594/kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_universal2.whl", hash = "sha256:4d4ca09bf13cff792b1884f64b98ee6c2467930d632233be25c56b442d99f10e", size = 126289, upload-time = "2026-08-28T10:26:47.023Z" }, + { url = "https://files.pythonhosted.org/packages/f2/e3/14ce3041ca79dff9c9d884ca00c7bf32374e76028a865a9ecd99b4f5a517/kiwisolver-1.5.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:44b8faef94f1857e77fa0238f3390ff1ac51d2ea20a487e2e452a59fd2b5f5ca", size = 67709, upload-time = "2026-08-28T10:26:48.268Z" }, + { url = "https://files.pythonhosted.org/packages/af/c4/45030471a66ec8ef042e9f96ffe1d522c9ab12da180186a0898966fc1385/kiwisolver-1.5.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:2ae70bc59790d2af72a3f76f24b272403e135070340281108b447cb77ea70819", size = 65909, upload-time = "2026-08-28T10:26:49.523Z" }, + { url = "https://files.pythonhosted.org/packages/42/73/17dce073a6ae259bb32cf9d686c4079d2e538868bc45967462bf33df914a/kiwisolver-1.5.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:43844c1a7ad6d723d5b5b4c4fc7f5bd399c40e288120d16257c7c9e8765c6e85", size = 1584907, upload-time = "2026-08-28T10:26:50.933Z" }, + { url = "https://files.pythonhosted.org/packages/8c/84/ae3c75909f507283cbfcc7e916c7e822579ef962020b97e6882b27b4478f/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:22d5e5aaad6be121f2515765e3b1c444352cb8eb4c86510801db8f2e50757316", size = 1392474, upload-time = "2026-08-28T10:26:52.638Z" }, + { url = "https://files.pythonhosted.org/packages/34/31/8bcc83caad5bce8fa4577152389848bf6bc110e51e573a2b4e7c2aa34c89/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:3fa5855898f6d3d01b72ccd48a2d65cbdee301251603fefe34e2025bddba219c", size = 1405246, upload-time = "2026-08-28T10:26:54.248Z" }, + { url = "https://files.pythonhosted.org/packages/55/72/220345537d790cf4ae54f8acfff4b5cc2468e0702a384d651cf7a771c63e/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:d66a64dd5dec136040ec2ae94aa026a912ee60fdd45bc28d3db30037fd809e88", size = 1456099, upload-time = "2026-08-28T10:26:56.042Z" }, + { url = "https://files.pythonhosted.org/packages/cd/10/3725fd2398f66d18c34b4e0f81a8d03764cd4f4f089f58a527f0b4428086/kiwisolver-1.5.1-cp314-cp314t-manylinux_2_39_riscv64.whl", hash = "sha256:9e51c119992ea8820706871c30a4642ec76de20ae82f9b50b9a45517d8e9f810", size = 1073695, upload-time = "2026-08-28T10:26:57.658Z" }, + { url = "https://files.pythonhosted.org/packages/86/cb/28d6e09e66b93e4588b2e6b7d84d020ccefea09e2f4de788510a07efeab7/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:70ed9a45c7484d2b30cdacf60d220f494a1763b9fec1ad03285c6553fa0889f2", size = 2335355, upload-time = "2026-08-28T10:26:59.202Z" }, + { url = "https://files.pythonhosted.org/packages/6a/b3/a0f31d5e4e40af7dc97c36b8a74fdd3a36cf3c8bbd098da9a23466ff6a94/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_ppc64le.whl", hash = "sha256:98b208a7cc42c803445ef551d6753cc42a5ea13e9cab1ee66cd8b9cb70195330", size = 2426524, upload-time = "2026-08-28T10:27:01.181Z" }, + { url = "https://files.pythonhosted.org/packages/2f/c9/728f63bd58c72cafdc79fc306abeeac7391bec03b757a48dadeb30906521/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_riscv64.whl", hash = "sha256:c6834b92dd2428e2dd85ef3d85f723d3c12f20aaf43a2ddd4f944ca25d833408", size = 2063430, upload-time = "2026-08-28T10:27:03.06Z" }, + { url = "https://files.pythonhosted.org/packages/84/df/ce188b96f92f9a2c958231da140768918cba53c9713dc887b82f85462118/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_s390x.whl", hash = "sha256:5d142e352eb13facc7dd047489aebdff6ba78576c239f1ea04931979caaf0567", size = 2597513, upload-time = "2026-08-28T10:27:05.072Z" }, + { url = "https://files.pythonhosted.org/packages/69/d6/76947c8203768968382e5bd74d9cc95654746703a61ea53015f2c74a2e06/kiwisolver-1.5.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:f9b1c4900736e489a812c529100de4b8fb617d4db075e931e213c57424b83d9b", size = 2394488, upload-time = "2026-08-28T10:27:07.423Z" }, + { url = "https://files.pythonhosted.org/packages/e4/d4/14b21e4eb203c4d15425e8b6a2c625a320b4a1f2f7557eead63ffc30ffb7/kiwisolver-1.5.1-cp314-cp314t-win_amd64.whl", hash = "sha256:5978c3340f16a35c30f8ab2fa7bcf559973c55f1a5ef6970e1f621acf3c4db13", size = 75404, upload-time = "2026-08-28T10:27:08.892Z" }, + { url = "https://files.pythonhosted.org/packages/cb/f5/53157899fc7f45f76421b77b99eb1639dd0f83f26ff9d76300c96bb4a3b0/kiwisolver-1.5.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ca307d6c259e5c98d3cb9ade55342b47a6839762caf2536f3d7b46ee660cc82e", size = 72946, upload-time = "2026-08-28T10:27:10.944Z" }, + { url = "https://files.pythonhosted.org/packages/75/62/f786c3a27f181fa339d851a77e266d208e776b9883cabc40a5b041a31b5a/kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:bb7c99f0673c03017a3ee01e54a5c2617a05468b11eabe513b0080e063ed95b1", size = 62420, upload-time = "2026-08-28T10:27:12.308Z" }, + { url = "https://files.pythonhosted.org/packages/02/cd/58a91ed25fbad0facdf503297b03768efab04bdf3141e5e3b49a34be7443/kiwisolver-1.5.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:0d8924877ce22e17326a99a418c3c82037da078df3c6a260b13eca677444e6e7", size = 64577, upload-time = "2026-08-28T10:27:13.502Z" }, + { url = "https://files.pythonhosted.org/packages/f6/5c/d501ef5a0958b226eac28306d24d5e5f114be0ace50e19cabae7b6b3b197/kiwisolver-1.5.1-cp315-cp315-ios_13_0_x86_64_iphonesimulator.whl", hash = "sha256:534f02c1abb31ed6dbd3515545285c330b2f12d00fdb1fdb71658b9ca5a13a6a", size = 66284, upload-time = "2026-08-28T10:27:14.813Z" }, + { url = "https://files.pythonhosted.org/packages/a3/a6/8fbecaf4fc18c02f31f05e47a84c010a80e3ec391ed2f0bdade1d62b5954/kiwisolver-1.5.1-cp315-cp315-macosx_10_15_universal2.whl", hash = "sha256:cea20da04494e662b83c872683bf4ff2345206043d036315ed0e924b652e7294", size = 124031, upload-time = "2026-08-28T10:27:16.193Z" }, + { url = "https://files.pythonhosted.org/packages/7c/c6/bf3090d2983b4204347cbdbe952116e7c3b2abf62b4e33e50167a13e75ee/kiwisolver-1.5.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:7fd82debf43c6acd0a94359d232f6bb516ee13f269a7993736a9ac9f988bb5d9", size = 66489, upload-time = "2026-08-28T10:27:17.506Z" }, + { url = "https://files.pythonhosted.org/packages/85/de/562dddef55fdd7c291da8626d6619e72b5fc0870e6ccca0e149a5731e7f3/kiwisolver-1.5.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:18170a77ddfecf40ec60d0928268dc95880c881864e015a8f34094ed18b9b9ad", size = 64806, upload-time = "2026-08-28T10:27:18.673Z" }, + { url = "https://files.pythonhosted.org/packages/89/b1/ba7b9c0164ce1cf62bf2872db63b8483289cf0f3110d6f9390eb09e409ed/kiwisolver-1.5.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ca7f6fe0f37ca978a1e5eb7a3a68e6413f417e78e838324947ffd420202b198b", size = 1482211, upload-time = "2026-08-28T10:27:20.039Z" }, + { url = "https://files.pythonhosted.org/packages/13/dc/34da54efb4976616d45c20aae32d70e89d6e7395ed908029154d1609ef22/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:5b973887ff782cfd6b67c9904ad8ca542e0bc5e4961503408b423b5a688b4d38", size = 1283739, upload-time = "2026-08-28T10:27:21.82Z" }, + { url = "https://files.pythonhosted.org/packages/5a/3a/30ffb62bee646e266e98a1b5cd276d9c75b6116fbfcb87c1190838c1b6df/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:f76fc85bd054c806960f917ec0f329e24e436f1712267d90588e4c39890caa63", size = 1301681, upload-time = "2026-08-28T10:27:23.876Z" }, + { url = "https://files.pythonhosted.org/packages/a9/8d/13c70be22a8506880b35fdc38dca36629613bc493405c79f4037f2cd2bb9/kiwisolver-1.5.1-cp315-cp315-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:828f75af2b0080c8a972e75f649ab46af008e92c6104a57a759157200b835b75", size = 1349159, upload-time = "2026-08-28T10:27:25.899Z" }, + { url = "https://files.pythonhosted.org/packages/82/0e/993972b8ec6767f47cd69818fb3a5ff14510557d29f7d1a839be7574fa1b/kiwisolver-1.5.1-cp315-cp315-manylinux_2_39_riscv64.whl", hash = "sha256:431dc224a1a92a5c8f582d96e505196a3b5997a7271076678da2dfde67b77e9a", size = 997613, upload-time = "2026-08-28T10:27:27.507Z" }, + { url = "https://files.pythonhosted.org/packages/36/82/ca26eddd2eda2420dfc56693449c1f821f78b485da9cbde9904c03af3f93/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:61e9a64c7635095a6bfe483e2ff055d437c59bd45f3617a228b37277f0185d62", size = 2235109, upload-time = "2026-08-28T10:27:30.113Z" }, + { url = "https://files.pythonhosted.org/packages/c7/84/97d920881e10840b8d7c7185620298e3e4c88820b05514e3a15a258b08a6/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_ppc64le.whl", hash = "sha256:3c24cd69455e1b00ddf770c13b6e2c33e07d6dc3f2d34add0bf9277c5c6bbd46", size = 2331207, upload-time = "2026-08-28T10:27:32.795Z" }, + { url = "https://files.pythonhosted.org/packages/e2/ce/34d74b8f25acc58800f4c09268371e8d6159cf0f1206f1e4dc7835629b48/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_riscv64.whl", hash = "sha256:27add358abe374ebaa3b8763ef380bc99051b5a4b18d94878366a9e4f59efef0", size = 1986696, upload-time = "2026-08-28T10:27:34.628Z" }, + { url = "https://files.pythonhosted.org/packages/0e/01/f892644014612527aef7031d3306a2ffc60b3cb044f802c1561f8e5e14f3/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_s390x.whl", hash = "sha256:255605693a483db7bd5c79f60437f7bf658f7f520d61aa42722e32257c941951", size = 2496400, upload-time = "2026-08-28T10:27:36.818Z" }, + { url = "https://files.pythonhosted.org/packages/32/6d/d8284e66e697026536e5f418b9cfe56567bffd3c775e3ecfbae373605854/kiwisolver-1.5.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:7d38b0c279c3032e8c9cc013b405c6df8e1668dbf15465779aa7f15f61201812", size = 2302967, upload-time = "2026-08-28T10:27:38.803Z" }, + { url = "https://files.pythonhosted.org/packages/46/0a/69a355e27f32ba50d5b6369949b6a1702e122f5277c89bc76d452b81c1c4/kiwisolver-1.5.1-cp315-cp315-win_amd64.whl", hash = "sha256:958254518717542d02d0688d0d20cbf771da5e415e6f49543f92481c850a4540", size = 72283, upload-time = "2026-08-28T10:27:40.491Z" }, + { url = "https://files.pythonhosted.org/packages/ef/d8/7a95be90c33dcdd52204d4aa6384d731443225b887283bbd8b61e7931f6c/kiwisolver-1.5.1-cp315-cp315-win_arm64.whl", hash = "sha256:da3275833be0edbaf4830fae08bae3dc7219f40ce0c37eaa6c25825957e06612", size = 69860, upload-time = "2026-08-28T10:27:41.835Z" }, + { url = "https://files.pythonhosted.org/packages/31/f8/9bc493e7f5707788ba7f621902c68f82dc3a7ba03c78fbd337b026cef1ed/kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_universal2.whl", hash = "sha256:470d420f98d368d6f010633a20659b544c5fdfa5329e6b70219f2ef08fd4a7ef", size = 126336, upload-time = "2026-08-28T10:27:43.379Z" }, + { url = "https://files.pythonhosted.org/packages/d1/82/3aea86b3f99712db825e9ac5631bf99571e818a8b8961ff98cebd798413e/kiwisolver-1.5.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:83f78128fa28705fa85d01c59771c72fe81c11bd0e6155edbb9f818983a7d761", size = 67698, upload-time = "2026-08-28T10:27:44.613Z" }, + { url = "https://files.pythonhosted.org/packages/84/7d/8daafc5d2e7f9c47a4f78f8865d86d2a9cf399c2a85f86c44a993594410c/kiwisolver-1.5.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:9506e892bcc3b409831d363c6f53e5985e1c8d1f6f6b0256d00358684ff85378", size = 65945, upload-time = "2026-08-28T10:27:45.932Z" }, + { url = "https://files.pythonhosted.org/packages/3d/c9/51dc974d9130da70a8c47a96160123443d387ffe1b6b833d6f91d9429339/kiwisolver-1.5.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:cea90547bfd93807e0013a004dc76552be44fad3bc1cc2b38610a9e889ed098f", size = 1588030, upload-time = "2026-08-28T10:27:47.678Z" }, + { url = "https://files.pythonhosted.org/packages/e6/86/f3e1a730e7a995149d8d3ff9e313b6d8a17b2cf1d98a8eff139dc30463fb/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e8e4d953faaded9ec7ede36824e9814082d22d4c7b1eafbfa079ecba8cd0d076", size = 1390760, upload-time = "2026-08-28T10:27:49.676Z" }, + { url = "https://files.pythonhosted.org/packages/4f/3b/8ba25a2b5a0d2375e046f1b72de5179513f0be95aba6e7b094c89303929f/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_ppc64le.manylinux_2_28_ppc64le.whl", hash = "sha256:7e9c01d3dd7ceba4d1d436cc021d40d592466e40b9bc7f5d83dc4e98a5c9cd8c", size = 1403279, upload-time = "2026-08-28T10:27:51.242Z" }, + { url = "https://files.pythonhosted.org/packages/18/d0/278d5cb8be812740027d5ca0a7eda0c375488a88d6dce0fa60fcc2591ad2/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_24_s390x.manylinux_2_28_s390x.whl", hash = "sha256:37f801b5d7cc0e5a548921308e059fd2b057bb42972b591cfa3049f95423c4ed", size = 1454429, upload-time = "2026-08-28T10:27:53.213Z" }, + { url = "https://files.pythonhosted.org/packages/94/37/bcbab41063ec284c1d200efe5087cf087798c2f8916960aa8a20dd303290/kiwisolver-1.5.1-cp315-cp315t-manylinux_2_39_riscv64.whl", hash = "sha256:e68e151428b5384f766cd25739bf77c7e4a3dc93b5ded7a12118d9fbfdf78ab6", size = 1073225, upload-time = "2026-08-28T10:27:55.089Z" }, + { url = "https://files.pythonhosted.org/packages/cb/c5/ab79dcdf5ae28909a51210ae0a1c579e97ff997b3466414f0d04c0994583/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:8f8fddb8e323bd6eee4e54e69a39243beab22689070f4c66b472c4cc88bb89d8", size = 2334335, upload-time = "2026-08-28T10:27:56.78Z" }, + { url = "https://files.pythonhosted.org/packages/8d/8e/71d047468a189041d9c93f3b76844b924f9793b188c44bd149fa258912da/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_ppc64le.whl", hash = "sha256:3cc210010fd2f438a3ed430b45f1b501fd13a8618bf984dc2c5ce5b69b78752e", size = 2424982, upload-time = "2026-08-28T10:27:58.639Z" }, + { url = "https://files.pythonhosted.org/packages/7d/37/1347461bbea6d0e1f0580b94ef603b18e72c2be5f667fa1653867361a00b/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_riscv64.whl", hash = "sha256:b5664603a253efd3a75716d793d1d3a6a82723b61dc6db767b2460bbbeec4c0f", size = 2062857, upload-time = "2026-08-28T10:28:00.407Z" }, + { url = "https://files.pythonhosted.org/packages/1f/87/c7f0976c9cd0d127643351bc0c9929e0b8899d7f49d4ec238cd909e39c42/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_s390x.whl", hash = "sha256:a7b85b2cc6ea45e5f7e8c9a30bc9fabd47cda09106cbb4b967335c3e6c43b69d", size = 2596022, upload-time = "2026-08-28T10:28:02.183Z" }, + { url = "https://files.pythonhosted.org/packages/e3/9a/59a6f6ae6f938c15076be2c21b6cedea973d71bb1349ec84fa485fab82cf/kiwisolver-1.5.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:ab620eb663952455271ac37f9aaad86b73c969c02f11f53cea405b38e96a4300", size = 2395634, upload-time = "2026-08-28T10:28:03.977Z" }, + { url = "https://files.pythonhosted.org/packages/e9/2d/8982c1fb7926da5bb7ed60318c3665b5c3f941447271ac982960a11b8637/kiwisolver-1.5.1-cp315-cp315t-win_amd64.whl", hash = "sha256:cb6fae641357ed2f6e533c0d3c6504a4a5703621a50c89459e46051d56b61140", size = 75379, upload-time = "2026-08-28T10:28:06.307Z" }, + { url = "https://files.pythonhosted.org/packages/07/78/ba7b6dfa1708b82b373ac056928a30c545d5c1a627df9839dcec3c6c1881/kiwisolver-1.5.1-cp315-cp315t-win_arm64.whl", hash = "sha256:b390aec180a7c054919c04898835e1c77bced23ea8383eb2c570213bf25d1a86", size = 73011, upload-time = "2026-08-28T10:28:07.578Z" }, + { url = "https://files.pythonhosted.org/packages/a9/c4/1407df7512a5b36cc79840e01710dc575733c461b13ab866cae77eaf87f3/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-macosx_11_0_arm64.whl", hash = "sha256:482676e5bd48d70ac99d9fc78863469845421e01184fa83f1f9366dc49f7e974", size = 134002, upload-time = "2026-08-28T10:28:08.881Z" }, + { url = "https://files.pythonhosted.org/packages/16/45/c37a21ad5c0ab581a93c55ad544721aaa1f0ae94edb29c6a678a23d013e6/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-manylinux_2_24_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:072bdb15a3c19a5b5dbc8f8fb1f4e1884bf4f3507eeb4cc6334401274d37a5c0", size = 194292, upload-time = "2026-08-28T10:28:11.06Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c1/69f00d627949580e43d57af0aa465df46868d7c29801c137a55374101294/kiwisolver-1.5.1-graalpy312-graalpy250_312_native-win_amd64.whl", hash = "sha256:a5a00665d1a0e26763a7338d7e911d4598fbc1d50dd0d6b7919b7dc6c5d6569f", size = 73362, upload-time = "2026-08-28T10:28:12.449Z" }, +] + [[package]] name = "ltx-core" -version = "1.2.0" -source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.2.0#d151147788a9284cca791edc6ce898007e727fe6" } +version = "1.4.1" +source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.4.1#2d6e71c88be37b55a2dd698c2dff447edfbe5898" } dependencies = [ { name = "accelerate" }, { name = "av" }, + { name = "colour-science" }, { name = "einops" }, { name = "mps-sdpa", marker = "platform_machine == 'arm64' and sys_platform == 'darwin'" }, { name = "numpy" }, @@ -530,6 +799,9 @@ dependencies = [ { name = "torch", version = "2.12.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, { name = "torchaudio", version = "2.10.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, { name = "torchaudio", version = "2.11.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'linux' and sys_platform != 'win32'" }, + { name = "torchvision", version = "0.25.0+cu128", source = { registry = "https://download.pytorch.org/whl/cu128" }, marker = "sys_platform == 'linux' or sys_platform == 'win32'" }, + { name = "torchvision", version = "0.26.0", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform == 'darwin'" }, + { name = "torchvision", version = "0.27.1", source = { registry = "https://pypi.org/simple" }, marker = "sys_platform != 'darwin' and sys_platform != 'linux' and sys_platform != 'win32'" }, { name = "transformers" }, ] @@ -538,6 +810,7 @@ name = "ltx-desktop-backend" version = "1.0.0" source = { virtual = "." } dependencies = [ + { name = "av" }, { name = "diffusers" }, { name = "fastapi" }, { name = "ftfy" }, @@ -546,6 +819,7 @@ dependencies = [ { name = "imageio-ffmpeg" }, { name = "ltx-core" }, { name = "ltx-pipelines" }, + { name = "matplotlib" }, { name = "natten", marker = "sys_platform == 'win32'" }, { name = "ninja", marker = "sys_platform == 'darwin'" }, { name = "opencv-python-headless" }, @@ -570,6 +844,7 @@ dependencies = [ { name = "transformers" }, { name = "triton", marker = "sys_platform == 'linux'" }, { name = "triton-windows", marker = "sys_platform == 'win32'" }, + { name = "tzdata" }, { name = "uvicorn", extra = ["standard"] }, ] @@ -581,11 +856,13 @@ dev = [ test = [ { name = "httpx" }, { name = "pytest" }, + { name = "pytest-split" }, { name = "requests" }, ] [package.metadata] requires-dist = [ + { name = "av", specifier = ">=16.1.0" }, { name = "debugpy", marker = "extra == 'dev'", specifier = ">=1.8" }, { name = "diffusers", specifier = ">=0.39.0" }, { name = "fastapi", specifier = ">=0.141.1" }, @@ -594,8 +871,9 @@ requires-dist = [ { name = "huggingface-hub", specifier = ">=0.23.0" }, { name = "imageio", specifier = ">=2.37.2" }, { name = "imageio-ffmpeg", specifier = ">=0.6.0" }, - { name = "ltx-core", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.2.0" }, - { name = "ltx-pipelines", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.2.0" }, + { name = "ltx-core", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-core&tag=v1.4.1" }, + { name = "ltx-pipelines", git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.4.1" }, + { name = "matplotlib", specifier = ">=3.8" }, { name = "natten", marker = "sys_platform == 'win32'", url = "https://storage.googleapis.com/ltx-desktop-artifacts/wheels/natten-0.21.6+torch2100cu128-cp313-cp313-win_amd64.whl" }, { name = "ninja", marker = "sys_platform == 'darwin'", specifier = ">=1.11" }, { name = "opencv-python-headless", specifier = ">=4.8.0" }, @@ -607,6 +885,7 @@ requires-dist = [ { name = "pynvml", marker = "sys_platform != 'darwin'", specifier = ">=11.5.0" }, { name = "pyright", marker = "extra == 'dev'", specifier = ">=1.1.380" }, { name = "pytest", marker = "extra == 'test'", specifier = ">=8.0" }, + { name = "pytest-split", marker = "extra == 'test'", specifier = ">=0.11.0" }, { name = "python-multipart", specifier = ">=0.0.32" }, { name = "requests", marker = "extra == 'test'", specifier = ">=2.34.2" }, { name = "sageattention", marker = "sys_platform != 'darwin' and sys_platform != 'win32'", specifier = ">=1.0.0" }, @@ -622,14 +901,15 @@ requires-dist = [ { name = "transformers", specifier = ">=5.14.1,<5.15" }, { name = "triton", marker = "sys_platform == 'linux'" }, { name = "triton-windows", marker = "sys_platform == 'win32'" }, + { name = "tzdata", specifier = ">=2024.1" }, { name = "uvicorn", extras = ["standard"], specifier = ">=0.30.0" }, ] provides-extras = ["test", "dev"] [[package]] name = "ltx-pipelines" -version = "1.2.0" -source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.2.0#d151147788a9284cca791edc6ce898007e727fe6" } +version = "1.4.1" +source = { git = "https://github.com/Lightricks/LTX-2.git?subdirectory=packages%2Fltx-pipelines&tag=v1.4.1#2d6e71c88be37b55a2dd698c2dff447edfbe5898" } dependencies = [ { name = "av" }, { name = "cloudpickle" }, @@ -714,6 +994,67 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/70/bc/6f1c2f612465f5fa89b95bead1f44dcb607670fd42891d8fdcd5d039f4f4/markupsafe-3.0.3-cp314-cp314t-win_arm64.whl", hash = "sha256:32001d6a8fc98c8cb5c947787c5d08b0a50663d139f1305bac5885d98d9b40fa", size = 14146, upload-time = "2025-09-27T18:37:28.327Z" }, ] +[[package]] +name = "matplotlib" +version = "3.11.2" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "contourpy" }, + { name = "cycler" }, + { name = "fonttools" }, + { name = "kiwisolver" }, + { name = "numpy" }, + { name = "packaging" }, + { name = "pillow" }, + { name = "pyparsing" }, + { name = "python-dateutil" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/e7/c8/9aa712a0afb882649424dd8de8ad9aa6235e796e84c6052e8f6dc1598d0d/matplotlib-3.11.2.tar.gz", hash = "sha256:cec596316640f2b394b8f0daa0ea61a8eae82d017b620b9f202befb972a59ea4", size = 32660610, upload-time = "2026-09-11T19:05:31.214Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/cb/ce/1bfcc4873b121597791ad74032943b123218c0613af0b97e8dd05e916fb1/matplotlib-3.11.2-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:ef752769cd962f39ea0b6ffc82d1ea43a0012c5a6157c7a075212fa509cfcff2", size = 9476466, upload-time = "2026-09-11T19:03:19.45Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c4/7f5f3601ee69baf072c0c7d3ce60c03e0618621c5a56c34a62a460e29d11/matplotlib-3.11.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:ef31985c4dedb5f1424e1aec6849a47dd37689cb7fa3c20b1b82187f26806261", size = 9305583, upload-time = "2026-09-11T19:03:22.39Z" }, + { url = "https://files.pythonhosted.org/packages/b8/90/2b3fd67ee273163faeda6d514be70b5596eaa0fd77b60ffc294ad0b34f5f/matplotlib-3.11.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:df4f7784aca81a94f254c0a2767d592ee25f407e488f5fa7203e51093fb6ca27", size = 9860353, upload-time = "2026-09-11T19:03:25.049Z" }, + { url = "https://files.pythonhosted.org/packages/f4/84/32549e7a462dc311aed2ab62e5d2538028840b5c53a8be0195c789937c3d/matplotlib-3.11.2-cp312-cp312-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:1b9a7ad579856284135e401ecc918c5f8a017ee30539298862a109f51b971710", size = 10670348, upload-time = "2026-09-11T19:03:28.108Z" }, + { url = "https://files.pythonhosted.org/packages/84/39/02e21b74f7439bd643d717ea846006d46e309e6d29b632b57751265311d6/matplotlib-3.11.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3aa4b8516fd26659e4363abbf317c703d9116496c5db2e9d0609a2866dd39dd2", size = 10810580, upload-time = "2026-09-11T19:03:31.402Z" }, + { url = "https://files.pythonhosted.org/packages/04/93/0d239bde12b308262265c2d98909b2f0ecad2b5deeae96241642e822e9c7/matplotlib-3.11.2-cp312-cp312-win_amd64.whl", hash = "sha256:c5c1c68ee401fc98271263410f0e5ce88285abacf7627132914e8adf3d70ff43", size = 9349409, upload-time = "2026-09-11T19:03:34.195Z" }, + { url = "https://files.pythonhosted.org/packages/49/a8/06baf901c02246c8a222b655cc4540ef9c15e1549a04e07927f9cde716c3/matplotlib-3.11.2-cp312-cp312-win_arm64.whl", hash = "sha256:643ff850d8e0f5b8319337f87ed3cb59506afb3df3cc48de777d85871233be7b", size = 9028084, upload-time = "2026-09-11T19:03:37.032Z" }, + { url = "https://files.pythonhosted.org/packages/bf/ce/fc58855a3d17f6cb8a87b6f9ccd100f65432a3a7ffed57309cbf14c78987/matplotlib-3.11.2-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:7d43ff8cebb50840648cb6429b2228621dbd709010f3117b3740abb20abf21c0", size = 9476987, upload-time = "2026-09-11T19:03:40.17Z" }, + { url = "https://files.pythonhosted.org/packages/a9/29/2a47b700545aca050e0ed73c89ba21e08407e11f5f42a567421b220de6c1/matplotlib-3.11.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:2a8285cea8ef4d92aa041d1c33788bcae82248503300f93f1ca2136b9049452f", size = 9306050, upload-time = "2026-09-11T19:03:43.103Z" }, + { url = "https://files.pythonhosted.org/packages/a9/df/e7c10292f348cf55178a5b3c0092a38ea68891a3945f199ae8b7b8ac9dc1/matplotlib-3.11.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:1944895967f87c84c9b4bad29a707b31f5b36df4a3a2339ea1f8ea3ce5105539", size = 9861060, upload-time = "2026-09-11T19:03:46.044Z" }, + { url = "https://files.pythonhosted.org/packages/e4/b9/b978de6d43d47f1d4d8e653fac32c16d8d2e5f46bbbb822e26d7cb1adece/matplotlib-3.11.2-cp313-cp313-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:af2661f6ac6bbd1d081996f54fdd9385715c625ace8cec0869055c0cfbf38981", size = 10670885, upload-time = "2026-09-11T19:03:48.942Z" }, + { url = "https://files.pythonhosted.org/packages/a3/80/d72f61bb2631ac15d17fada1f17e0f99fecba69d8376d34f17cf93b7eddd/matplotlib-3.11.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:7e5a90f8a707ebb6004a713b1cff091a40cc5df4c7c1cb165e5a505ebc11c292", size = 10811222, upload-time = "2026-09-11T19:03:51.665Z" }, + { url = "https://files.pythonhosted.org/packages/94/2e/6d1d33f242c705b5c6c6fb3f0fc141add51cb1abb62912e59de0835d28c4/matplotlib-3.11.2-cp313-cp313-win_amd64.whl", hash = "sha256:bc067c462a86f0e57bf52fc6e058d90171a5420007dac00c46e90153050c69a7", size = 9349539, upload-time = "2026-09-11T19:03:54.534Z" }, + { url = "https://files.pythonhosted.org/packages/bb/bb/c0aa86a7f4c0e62f1c3c0711e361f6f23f87eb9018732a5e11994bd1b7ec/matplotlib-3.11.2-cp313-cp313-win_arm64.whl", hash = "sha256:3e8576f7c47e02fd4f21f44171302d2d1d58d4471d46da3d71fe8899d19539d9", size = 9028295, upload-time = "2026-09-11T19:03:57.261Z" }, + { url = "https://files.pythonhosted.org/packages/54/b4/4facdb700bc236e4c676495ca3798d8134ab8668cbfe0f6b2e9ebf962a38/matplotlib-3.11.2-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:c9721f81275499da1feeb36a2cf8192ea086283b3bd16b7dc4c9d7aedb7396d6", size = 9478976, upload-time = "2026-09-11T19:04:00.12Z" }, + { url = "https://files.pythonhosted.org/packages/4c/a0/bba05f0a25bfeb0475c2f2a87958b31103aa6b7a5386017afb1a96212825/matplotlib-3.11.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:1a3040b209f3968b4e84161df7b174f07a9fad33b0f2d7e48ea3bbd3075e2863", size = 9307932, upload-time = "2026-09-11T19:04:02.976Z" }, + { url = "https://files.pythonhosted.org/packages/d4/42/81d5cba4bb39b41b0998efc880e129f2d7cdb94256ca49678fdcd9c21be5/matplotlib-3.11.2-cp314-cp314-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:bf3fe71fbfb8ec0e310e0bc8537c3405a01f38f25f9394ed2135e6202fed542b", size = 10674370, upload-time = "2026-09-11T19:04:06.912Z" }, + { url = "https://files.pythonhosted.org/packages/29/5e/52f56f93d5b20815ee0ae352f7a38eff25580edb180b4fa7df87cfeba68f/matplotlib-3.11.2-cp314-cp314-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8c8255de28f986d935a64c9ca71c0ec2d2f41d355691f5ea684725dc91413f71", size = 10954597, upload-time = "2026-09-11T19:04:09.948Z" }, + { url = "https://files.pythonhosted.org/packages/6e/ae/f8918a1b564db49c53cd603eb3c8748c5767e4ce0fb2cf1d7c38653e4c5d/matplotlib-3.11.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:a8756cc73d9af9a7fe0deb54ea2e75ef73b01d9e575877e72acad5458e660943", size = 10812583, upload-time = "2026-09-11T19:04:12.887Z" }, + { url = "https://files.pythonhosted.org/packages/ea/61/4315ef0d63937fe56f451887b4a0be3b8e8b22cf1d92a8d157caac54570d/matplotlib-3.11.2-cp314-cp314-win_amd64.whl", hash = "sha256:ecea603dd2fbf8242fd31a305a8b12a4ece2de28096870c65fdd0d1e35b8d9a6", size = 9505972, upload-time = "2026-09-11T19:04:15.788Z" }, + { url = "https://files.pythonhosted.org/packages/d5/00/02398b0a1a62ef73d9af0a957fe1773363eec9a6ca7e433c72ae2790fbce/matplotlib-3.11.2-cp314-cp314-win_arm64.whl", hash = "sha256:01dc8eaaab5a9fce9ff615eca82345728f289e4715b186ee10c6d85272fc26bb", size = 9184534, upload-time = "2026-09-11T19:04:18.691Z" }, + { url = "https://files.pythonhosted.org/packages/ec/c5/1e6ca10baa7e04f113c37856aadb4adc3dbb1c55fc7da6dc830bba1292d7/matplotlib-3.11.2-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:79a258f58253dfa025af80a9e9bb228d75fced007f0e93ae7423fefbde81a74d", size = 9526415, upload-time = "2026-09-11T19:04:21.39Z" }, + { url = "https://files.pythonhosted.org/packages/e0/93/7561727af07ccc84747953c6a33eee3981cc436d04f465032e707ca0e429/matplotlib-3.11.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:c0b83f044ce10a98027b105b3931548719a6e8c7ef986b4362651e0b5367c8dc", size = 9361064, upload-time = "2026-09-11T19:04:24.107Z" }, + { url = "https://files.pythonhosted.org/packages/c1/40/ce270ef2a6794d94a409fe28b8dabedffc07c07f9e5dbb89e0f605bd157d/matplotlib-3.11.2-cp314-cp314t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e43b188f0a5b75447bcc197728258166aa64365770ed1caa36595a5e1ca4bbba", size = 10684626, upload-time = "2026-09-11T19:04:27.201Z" }, + { url = "https://files.pythonhosted.org/packages/45/46/396e0307dbf1c1f2d0a3654caa6dbc780dd5379f5f11257369cf8d21d9fe/matplotlib-3.11.2-cp314-cp314t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d3304eb5a59442a8867f6920d484591c0fa09ffc29e9260be2feec3351e25869", size = 10960602, upload-time = "2026-09-11T19:04:30.254Z" }, + { url = "https://files.pythonhosted.org/packages/1c/97/4defb84695477340aa88b27c9482cc1ca4de11f36f66b6c8c0ddd685def1/matplotlib-3.11.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:02329432ae5c6af87cf208ee575b701d698bdf0b1a3bb28cc6d53c36e967e575", size = 10822603, upload-time = "2026-09-11T19:04:32.964Z" }, + { url = "https://files.pythonhosted.org/packages/7d/e7/eab54551c1ec6b72dcd678a078b6c6da8d4c85ec1ff0016e81fe52866304/matplotlib-3.11.2-cp314-cp314t-win_amd64.whl", hash = "sha256:f2ac30cf5eb5dff1b584627ae0b0e1186551a4f69ae3c75073911da497a29170", size = 9551206, upload-time = "2026-09-11T19:04:35.811Z" }, + { url = "https://files.pythonhosted.org/packages/4e/0e/04698032cb4d8fb1e30d8ffec5ded20f6f582b03c8c58b2385c95245f158/matplotlib-3.11.2-cp314-cp314t-win_arm64.whl", hash = "sha256:cf41ecd1b0c0b6f7177ed965a54c2afbe888715c7cf6054dc12d53bc1494002c", size = 9234977, upload-time = "2026-09-11T19:04:38.972Z" }, + { url = "https://files.pythonhosted.org/packages/44/a9/ca827c184b87364378964e36e7c0ae23651d146fdbc4000635205490cf82/matplotlib-3.11.2-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:894a9cbbecbe30ae6787d464df2e8fc7a8d475cfc68f87c3029f7c11152899b3", size = 9478997, upload-time = "2026-09-11T19:04:41.914Z" }, + { url = "https://files.pythonhosted.org/packages/48/60/01aaafc9c3159f3fae9a65bbcddaa4a6d4d72b0aeffdd636d7f6d00a5c8d/matplotlib-3.11.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:bbf1062991d826ed27e2144f3afa4461afbb8ff56e8f703043e191a8163b1ee9", size = 9307947, upload-time = "2026-09-11T19:04:44.834Z" }, + { url = "https://files.pythonhosted.org/packages/1e/a0/6aa72c7cd7cf4dfac652744d7a3310007cec3ce8e5ab9be607bec7096471/matplotlib-3.11.2-cp315-cp315-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:399fef672f7046ef7d6a57572b2a6f9845f3f5afcff04e7b2df7a363a9f42190", size = 10674370, upload-time = "2026-09-11T19:04:47.745Z" }, + { url = "https://files.pythonhosted.org/packages/a1/97/d7e90225ac145046787a2ee0fa4cdc7e4d5cb6772ea232130b10f8a4095a/matplotlib-3.11.2-cp315-cp315-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:cc82dde2a0d3e3ad472edce04897ad7146b8d8bfd1df8a32992eebb81af18fdc", size = 10954581, upload-time = "2026-09-11T19:04:50.712Z" }, + { url = "https://files.pythonhosted.org/packages/58/18/89cf056a9d2cae01f4b8baf01c7e809d613244fcdfa2a2acf28c1e0d79fa/matplotlib-3.11.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:930efb28f59fda124e39265d177bab302625297bb147d2910de725a2fc2aef54", size = 10812605, upload-time = "2026-09-11T19:04:53.552Z" }, + { url = "https://files.pythonhosted.org/packages/9d/4d/c61b9f4c34af802d4d84e58803e009013d626b5f468bafe1416131863b5b/matplotlib-3.11.2-cp315-cp315-win_amd64.whl", hash = "sha256:3da3bc0cbf7245e7db72cc6d29d12c5abef72cb73059c73b945f14e3545f3eb2", size = 9506068, upload-time = "2026-09-11T19:04:56.519Z" }, + { url = "https://files.pythonhosted.org/packages/03/7b/047f2fa8708d47430d8e7fa45e9fffb0aee5d4e300f978e087be2ee11fbc/matplotlib-3.11.2-cp315-cp315-win_arm64.whl", hash = "sha256:f25446b2981717dca9786bac841cb3fd7efb568e3e3c755dd980481c5cb9228d", size = 9184576, upload-time = "2026-09-11T19:04:59.318Z" }, + { url = "https://files.pythonhosted.org/packages/03/6e/ad9c5989950785a98642667df265a47c6637e924cb69b5dcf68c3299ae7c/matplotlib-3.11.2-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:fea03cf56568cc1cba08b470be6a0559e71c3a5b688d54b7179bb35ba23d0821", size = 9525988, upload-time = "2026-09-11T19:05:02.304Z" }, + { url = "https://files.pythonhosted.org/packages/a6/c3/25c61701fb655dd412428b15eee2591ce554cdd593e39a045a153373f428/matplotlib-3.11.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:254d4ddb2fa8df3b4c689c0c306063aee10521df82cfb438185e499c75fe37c1", size = 9360774, upload-time = "2026-09-11T19:05:05.092Z" }, + { url = "https://files.pythonhosted.org/packages/58/5a/4552878fce8f9d249a5e264c16f5c267c27eac08fb039fa3e207a06feff5/matplotlib-3.11.2-cp315-cp315t-manylinux_2_26_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:e60cf3047a51edecdc4535a9196bbd6a732936b8e9f8184aabf4d16165884aaf", size = 10685892, upload-time = "2026-09-11T19:05:07.686Z" }, + { url = "https://files.pythonhosted.org/packages/af/dd/b3b19ec0124fc4aafd8a4b3bae859c562a7ff0fd8ae3b2099947f78bde19/matplotlib-3.11.2-cp315-cp315t-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eb3712dc9b464793de0a4e42a7313d50293c751f94bddaf7332a1bc71bccdda9", size = 10964946, upload-time = "2026-09-11T19:05:10.943Z" }, + { url = "https://files.pythonhosted.org/packages/7b/30/687ccce22f66a57fed85942450e88062773bcbf1a42914e70c7148ec71dc/matplotlib-3.11.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:75b6d88402770e181b5d06a67dda4129c31da7d05004d63a21c310ec78d1b83c", size = 10824960, upload-time = "2026-09-11T19:05:13.9Z" }, + { url = "https://files.pythonhosted.org/packages/d3/34/117fe35a8d05054b4b34d2d29287099927c24c3841d36e06d9fa2f20c1cf/matplotlib-3.11.2-cp315-cp315t-win_amd64.whl", hash = "sha256:a6939df7567114b6bac7f4c5e06c84a67f197c1b2f2e4b234d4eecb3bfec9482", size = 9551204, upload-time = "2026-09-11T19:05:16.48Z" }, + { url = "https://files.pythonhosted.org/packages/63/5a/9f440e7bec8b80d0af2a65d1165b2f4e718982dad785531f62255d9ff19b/matplotlib-3.11.2-cp315-cp315t-win_arm64.whl", hash = "sha256:d480038c83691532ed52ff3147db51fa902fc78cb2d8349993a1cdb684435bff", size = 9233946, upload-time = "2026-09-11T19:05:19.063Z" }, +] + [[package]] name = "mdurl" version = "0.1.2" @@ -1394,6 +1735,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/43/d5/6aa84d1d976ba8b97cdc6486f09aab85f20ea6ba5079086f1de4426cbb2e/pyobjc_framework_metalperformanceshadersgraph-12.2.1-py2.py3-none-any.whl", hash = "sha256:9ac2270c573e9399c02196ea1725bd3c7ed3699d71ee70286b1f78beb8afaf5e", size = 7134, upload-time = "2026-06-19T16:14:24.104Z" }, ] +[[package]] +name = "pyparsing" +version = "3.3.3" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/11/b213bebff182584360cb8d17c72c1677fec5c5c228de439e63bcf8ab1c8f/pyparsing-3.3.3.tar.gz", hash = "sha256:928ae7e20211f3b6f3915a72f06a0cfd29ab9d24279dd6346b6b1a7146397d36", size = 1050487, upload-time = "2026-09-20T20:59:05.609Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/38/bb/d215ee7c73b61497b28a5503f9f53523f294fcc936762b7caf90e0c1c2b5/pyparsing-3.3.3-py3-none-any.whl", hash = "sha256:ece8c00a69cf01b45d0b1dedabb469c90d8caf996d4fda40f147627a122849a4", size = 126420, upload-time = "2026-09-20T20:59:04.025Z" }, +] + [[package]] name = "pyright" version = "1.1.408" @@ -1423,6 +1773,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/3b/ab/b3226f0bd7cdcf710fbede2b3548584366da3b19b5021e74f5bde2a8fa3f/pytest-9.0.2-py3-none-any.whl", hash = "sha256:711ffd45bf766d5264d487b917733b453d917afd2b0ad65223959f59089f875b", size = 374801, upload-time = "2025-12-06T21:30:49.154Z" }, ] +[[package]] +name = "pytest-split" +version = "0.11.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pytest" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/2f/16/8af4c5f2ceb3640bb1f78dfdf5c184556b10dfe9369feaaad7ff1c13f329/pytest_split-0.11.0.tar.gz", hash = "sha256:8ebdb29cc72cc962e8eb1ec07db1eeb98ab25e215ed8e3216f6b9fc7ce0ec2b5", size = 13421, upload-time = "2026-02-03T09:14:31.469Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ae/a1/d4423657caaa8be9b31e491592b49cebdcfd434d3e74512ce71f6ec39905/pytest_split-0.11.0-py3-none-any.whl", hash = "sha256:899d7c0f5730da91e2daf283860eb73b503259cb416851a65599368849c7f382", size = 11911, upload-time = "2026-02-03T09:14:33.708Z" }, +] + +[[package]] +name = "python-dateutil" +version = "2.9.0.post0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "six" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/66/c0/0c8b6ad9f17a802ee498c46e004a0eb49bc148f2fd230864601a86dcf6db/python-dateutil-2.9.0.post0.tar.gz", hash = "sha256:37dd54208da7e1cd875388217d5e00ebd4179249f90fb72437e91a35459a0ad3", size = 342432, upload-time = "2024-03-01T18:36:20.211Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ec/57/56b9bcc3c9c6a792fcbaf139543cee77261f3651ca9da0c93f5c1221264b/python_dateutil-2.9.0.post0-py2.py3-none-any.whl", hash = "sha256:a8b2bc7bffae282281c8140a97d3aa9c14da0b136dfe83f850eea9a5f7470427", size = 229892, upload-time = "2024-03-01T18:36:18.57Z" }, +] + [[package]] name = "python-dotenv" version = "1.2.1" @@ -1795,6 +2169,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/e0/f9/0595336914c5619e5f28a1fb793285925a8cd4b432c9da0a987836c7f822/shellingham-1.5.4-py2.py3-none-any.whl", hash = "sha256:7ecfff8f2fd72616f7481040475a65b2bf8af90a56c89140852d1120324e8686", size = 9755, upload-time = "2023-10-24T04:13:38.866Z" }, ] +[[package]] +name = "six" +version = "1.17.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/94/e7/b2c673351809dca68a0e064b6af791aa332cf192da575fd474ed7d6f16a2/six-1.17.0.tar.gz", hash = "sha256:ff70335d468e7eb6ec65b95b99d3a2836546063f63acc5171de367e834932a81", size = 34031, upload-time = "2024-12-04T17:35:28.174Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, +] + [[package]] name = "starlette" version = "1.6.0" @@ -2143,6 +2526,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/dc/9b/47798a6c91d8bdb567fe2698fe81e0c6b7cb7ef4d13da4114b41d239f65d/typing_inspection-0.4.2-py3-none-any.whl", hash = "sha256:4ed1cacbdc298c220f1bd249ed5287caa16f34d44ef4e9c3d0cbad5b521545e7", size = 14611, upload-time = "2025-10-01T02:14:40.154Z" }, ] +[[package]] +name = "tzdata" +version = "2026.4" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/e4/31/3d74fa778a63b98b7374323befcc0be5ab3bd94afd4096a0124e7379152c/tzdata-2026.4.tar.gz", hash = "sha256:f1b8bd365d8d210c55353f4d7f8d6d8561c0ba50d704b700d195a9424bba0d79", size = 199350, upload-time = "2026-09-12T12:56:03.251Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/f9/bc/8737e8d54cf51106118039b83f485a4783112fab49ea9d044b234978a46e/tzdata-2026.4-py2.py3-none-any.whl", hash = "sha256:c2169a8b0a7a5e9674da5a135ccdfb2b3e671b333ed9fed17b41f73c34476e81", size = 347494, upload-time = "2026-09-12T12:56:01.67Z" }, +] + [[package]] name = "urllib3" version = "2.6.3" diff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.md index 02324a0af..6f7e641bb 100644 --- a/docs/TELEMETRY.md +++ b/docs/TELEMETRY.md @@ -1,13 +1,38 @@ # Telemetry -LTX Desktop collects minimal, anonymous telemetry to help the team understand how the app is used and prioritize development. -No personal information, generated content, prompts, file paths, or IP-derived location data is collected or stored. +LTX Desktop sends a small amount of anonymous usage data so the team can see how the app is used and where it fails. That is the only purpose. The data is used to improve the app: which features people reach for, which settings they pick, and which generations fail or get cancelled. It is not used for advertising, it is not sold, and it is not linked to an account, a name, or an email address. + +No personal information, generated content, prompts, negative prompts, file paths, custom LoRA file names, or IP-derived location is collected. + +A random installation ID is created on the first event and stored on the device. It lets us tell that several events came from the same install. It is not an account, and it cannot be used to identify a person. + +## What is collected + +Every event includes the app version, a device timestamp, the installation ID, and the platform (macOS, Windows, or Linux). + +**App launch** (`launched`). Sent once per process for a packaged app. On a first install it is sent when the user clicks Install, after the opt-out on that screen has been saved. On later opens it is sent when the app starts. Also includes total system memory, and the GPU name when it is available. + +**Generation start** (`generate_started`). Sent when a generation begins, including one that is cancelled immediately after it is claimed. Also includes total system memory and the GPU name. The operational details are: + +- A random generation ID, and the attempt number when a job is retried +- Where it ran: the desktop app or a remote client on the local network, and whether it started from Home or Gen Space +- What was requested: feature (for example text-to-video, image-to-video, audio-to-video, multi-keyframe, retake, extend, or a Home LoRA recipe), image or video, local or LTX API execution, model, resolution, frames per second, and requested duration +- How many images were requested, for an image generation +- LoRA catalog IDs for built-in adapters. A custom LoRA is recorded only as a boolean, never as a file name or path +- How the prompt was passed: `raw` (sent as typed), `manually-enhanced` (the user ran Enhance), or `auto-enhanced` (the app rewrote it before generation). The prompt text is never included + +**Generation end** (`generate_ended`). Sent when that same generation succeeds, fails, or is cancelled. It does not repeat the start details. It carries only: + +- The same generation ID and attempt, so it can be joined to the start +- The outcome: succeeded, failed, or cancelled +- How long the run took, in milliseconds +- An error code when the run failed, such as a capability or executor failure. The code is a fixed label, not an error message, a prompt, or a path ## Opting out -Analytics is enabled by default. You can disable it at any time in **Settings > General > Anonymous Analytics**. When disabled, no events are sent. +Analytics is enabled by default. On the initial setup screen, **Opt out of basic analytics** is unchecked. Check it to turn collection off before you click Install. You can also turn it off or back on at any time in **Settings > General > Anonymous Analytics**. When disabled, no events are sent. -To disable telemetry before the first launch, create an `app_state.json` file in the app data folder with the following content: +To disable telemetry before the first launch, create an `app_state.json` file in the app data folder, or set the flag if that file is already there: ```json { "analyticsEnabled": false } @@ -19,8 +44,10 @@ App data folder locations: - **macOS:** `~/Library/Application Support/LTXDesktop/` - **Linux:** `$XDG_DATA_HOME/LTXDesktop/` (default: `~/.local/share/LTXDesktop/`) -Your preference is respected immediately — no restart required. +This method is relevant mainly to machines that are ineligible for local generation. Those machines skip the setup screen and so never show the checkbox. Your preference is respected immediately — no restart required. Development builds do not send events. ## Implementation -The telemetry implementation is fully contained in [`electron/analytics.ts`](../electron/analytics.ts). Events are sent to an ingestion endpoint over HTTPS. No third-party analytics SDKs are used. +Electron is the only process that builds or sends the ingest payload. [`electron/analytics-payload.ts`](../electron/analytics-payload.ts) defines the event names and the detail keys that are allowed onto a start event. [`shared/analytics-ended-details.json`](../shared/analytics-ended-details.json) is the list of keys allowed onto an end event; both the Python forwarder and Electron check that list. [`electron/analytics.ts`](../electron/analytics.ts) applies opt-out, hardware on launch and start events, retries, and the rate limit, then sends the event over HTTPS. No third-party analytics SDKs are used. + +The Python backend does not talk to the ingest host. It forwards an event name and operational details to the loopback receiver in [`electron/analytics-sink.ts`](../electron/analytics-sink.ts), which accepts generation start and end events and drops every other detail key. [`electron/main.ts`](../electron/main.ts) sends `launched` once per process: at startup when setup is already complete, when the user clicks Install on a first install, and when an API-only first run finishes setup without that screen. The renderer only signals that click, after the opt-out has been saved. It cannot attach details or choose the ingest payload. diff --git a/docs/local-compat-matrix.md b/docs/local-compat-matrix.md new file mode 100644 index 000000000..5d836aa48 --- /dev/null +++ b/docs/local-compat-matrix.md @@ -0,0 +1,28 @@ +# Local Explore compatibility matrix + +Generated from `decide_local_generation_mode` and `decide_video_job`. +A machine that cannot run a Fast cell is not offered that cell. +Regenerate: `cd backend && uv run python -m runtime_config.local_compat_matrix`. + +| Tool | CUDA unsupported | CUDA stream | CUDA full | Darwin unsupported | Darwin stream | Intel Mac / no GPU | +| --- | --- | --- | --- | --- | --- | --- | +| T2V | No | Yes | Yes | No | Yes | No | +| I2V | No | Yes | Yes | No | Yes | No | +| A2V | No | Yes | Yes | No | Yes | No | +| LoRAs | No | Yes | Yes | No | Yes | No | +| IC-LoRA | No | Yes | Yes | No | Yes | No | +| Retake | No | Yes | Yes | No | Yes | No | +| Extend | No | Yes | Yes | No | Yes | No | +| local text encoder | No | Yes | Yes | No | Yes | No | +| 2.5 download | No | Yes | Yes | No | Yes | No | + +Floors: CUDA integer **15** GiB VRAM (`total_memory // 1024**3`); +Darwin **32** GiB total RAM; ~72 GB disk for the 2.5 Fast core pack +(kitchen-sink installs with 2.3, image models, and processors are larger). + +CUDA stream (16 GB) still runs T2V/I2V/A2V; the Fast picker hides 720p/20s +and 1080p/10s because `decide_video_job` would reject them. CUDA full (31 GB) +keeps those cells (they stream). Darwin stream keeps the static Fast ceiling. + +Footnote: Darwin IC-LoRA duration is unbounded past the 540p spatial cap +(no token 422). Do not invent a CUDA-curve ceiling for Darwin. diff --git a/docs/remote-lan.md b/docs/remote-lan.md new file mode 100644 index 000000000..b9ca8b571 --- /dev/null +++ b/docs/remote-lan.md @@ -0,0 +1,222 @@ +# LAN Remote Explore + +LAN Remote lets a phone or another computer use LTX Desktop Explore over the +same local network. The remote client uses the same generation queue, SQLite +store, assets, and GPU worker as Desktop Explore. It does not create a second +generation pipeline. + +## Architecture + +```mermaid +flowchart LR + Phone["Phone browser
Remote SPA"] -->|HTTP + Bearer| Remote["Remote FastAPI
:41955"] + Desktop["Electron renderer
Desktop UI"] -->|HTTP + local auth| Local["Desktop FastAPI
:41954"] + Desktop -->|remote status/settings| Local + Remote --> Shared["Shared AppHandler"] + Local --> Shared + Shared --> Queue["Generation queue"] + Shared --> DB["SQLite store"] + Shared --> Assets["Asset files"] + Shared --> GPU["GPU worker"] +``` + +The two HTTP servers use different ports: + +| Surface | Purpose | +| --- | --- | +| `:41954` | Full Desktop backend and Desktop-only controls | +| `:41955` | Authenticated, allowlisted phone surface | +| `:41954/api/remote/status` | Desktop control-plane status for the Remote server | + +The phone opens a dedicated pairing route. The one-time grant lives in the +query string so QR scanners and macOS/`open` / Electron `openExternal` keep +it (fragments are often dropped before JavaScript runs): + +```text +http://:41955/pairing?t= +``` + +The Remote server disables uvicorn access logs. `origin_url()` strips query +and fragment before our own logs. The document sends `no-referrer`. The grant +is one-time and lasts ~5 minutes; after a successful pair the SPA `replace`s +to `/`. + +`/api/remote/status` is not the phone API. It tells Desktop whether the +separate Remote server is permitted, starting, serving, or failed. Desktop +also lists and revokes paired devices on `:41954`: + +- `GET /api/remote/devices` +- `POST /api/remote/devices/{device_id}/revoke` + +## Remote API boundary + +The Remote server exposes only the Explore surface: + +- `GET /health` — public liveness check. +- `POST /api/pairing/exchange` — public; trades the one-time grant for a + durable device session. +- `GET /api/session` — authenticated pairing check. +- T2V/I2V generation list, create, get, retry, cancel, and delete. +- `GET /api/generate/models-specs`. +- `POST /api/assets/upload` — image input upload. +- `GET /api/assets/{id}` — path-free asset metadata plus signed media URLs. +- `GET`/`HEAD /api/assets/{id}/bytes` — media playback via a short-lived + HMAC-signed URL (`bytes_url` on the asset DTO). +- `GET`/`HEAD /api/assets/{id}/thumbnail/bytes` — same, via `thumbnail_url`. +- `GET /api/prompt-enhancer` — whether Gemini and/or local Enhance are + available, plus `defaultProvider` (Gemini if a Desktop key is stored, + otherwise local Gemma when downloaded). Does not return API keys or + filesystem paths. +- `POST /api/enhance-prompt` — rewrite the prompt. Image frames are asset ids, + never paths. Body `provider` is `local` or `api`; omit it to use + `defaultProvider`. Explicit `api` without a key returns + `GEMINI_API_KEY_MISSING` (no silent fallback to Gemma). The Enhance button + follows the Desktop Auto-Enhance setting (hidden when auto-enhance is on). +- `GET`/`PATCH /api/feature-flags` — the dev feature flags shared with Desktop + (`feature_flags.json`). The Dev Panel opens in the Remote with Ctrl+Shift+D + or `?devpanel=1`, so any paired device can change them. +- Bundled Remote SPA assets. + +These stay off `:41955`: + +- Settings and shutdown. +- Desktop path ingest (`POST /api/assets`). +- Model downloads and Hugging Face auth (except the LoRA recipe preflight + already on this port). +- Image generation, IC-LoRA, Extend, and Retake. + +The separate port is the namespace boundary. Therefore the phone uses normal +paths such as `/api/generations`; adding `/api/remote/` to every phone route +would add special cases without adding security. + +## Pairing and authentication + +There are no cookies. Cookies would break when the SPA origin later becomes +`connect.ltx.io` while the API stays on the engine host. + +The Desktop controller mints a one-time grant (5 minutes, single use) and puts +it in the QR query (`/pairing?t=`). The phone: + +1. Lands on `/pairing` (Explore chrome is not mounted). It uses that token to + `POST /api/pairing/exchange`. If the phone already has a stored session, it + sends `Authorization: Bearer ` so the host reuses that row + instead of inserting another device. +2. Stores the returned device session in memory and `localStorage`. +3. `replace`s to `/`, dropping `t`. A failed pair stays on `/pairing?t=` so a + reload can retry. + +A new phone, or a phone that cleared storage / was revoked, still inserts a +row. Two different phones stay two rows. Scanning a **new** QR from an +already-paired phone keeps one row, the same session token, and the same +`device_id`. Retrying a consumed grant fails and does not unpair the phone. + +The session survives reloads and Remote restarts; turning Remote off does not +revoke devices. API calls use `Authorization: Bearer `. Media +uses host-minted `bytes_url` / `thumbnail_url` values. Those URLs are +HMAC-signed, asset-scoped, and expiry-bucketed to 5-minute windows so +generation polling does not rewrite `