Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: dgrauet/ltx-2-mlx runtime for true keyframe interpolation
Adam Eivyef5d9081bd56
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 6539fe1a8d..c204f920bc 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -7,6 +7,7 @@## Added- Video Gen "Chunks" control (1–8) chains multiple LTX renders into a single longer clip. Each chunk's last frame seeds the next, then ffmpeg stitches them into one output. The individual chunks land in history hidden by default, so the gallery shows just the stitched result.+- Two new LTX-2.3 video models — "dgrauet Q4" and "dgrauet Q8" — running on a more capable runtime that supports true keyframe interpolation (proper FFLF that respects both start AND end frames), native video extend, and audio-to-video. Install with `INSTALL_LTX2=1 bash scripts/setup-image-video.sh`. The existing notapalindrome models keep working unchanged; pick the new "dgrauet" entries from the model dropdown to use the new pipeline. FFLF on these models has a stage-2 OOM ceiling — the server auto-clamps frame count to a memory-safe budget (override via `FFLF_LTX2_PIXEL_BUDGET` env var if you have more RAM than 48 GB).## Changeddiff --git a/scripts/generate_ltx2.py b/scripts/generate_ltx2.pynew file mode 100644index 0000000000..379e4b8b63--- /dev/null+++ b/scripts/generate_ltx2.py@@ -0,0 +1,254 @@+#!/usr/bin/env python3+"""PortOS bridge to dgrauet/ltx-2-mlx pipelines.++Translates the PortOS spawn-protocol used by `mlx_video.generate_av` into the+dgrauet `ltx_pipelines_mlx` Python API. Lives in the ltx-2-mlx venv (see+scripts/setup-image-video.sh INSTALL_LTX2 path) and is invoked by the Node+videoGen service when the selected model has `runtime: 'ltx2'` in+data/media-models.json.++Why a wrapper at all (vs. spawning `ltx-2-mlx <subcommand>` directly):+ - The dgrauet CLI uses bare `print(...)` and `tqdm` for progress; PortOS's+ queue dispatcher parses `STAGE:`, `STATUS:`, `DOWNLOAD:` prefixed lines+ out of stderr to drive SSE. We translate by emitting our prefixes around+ pipeline boundaries (load_models / encode / denoise / decode / save).+ - PortOS already has FFLF / extend / image / text mode semantics that map+ to different pipeline classes here. Putting the dispatch in Python keeps+ the Node side simple — one helper, four subcommands, identical contract+ to the existing `python -m mlx_video.generate_av` invocation.++Modes:+ text → TextToVideoPipeline.generate_and_save+ image → ImageToVideoPipeline.generate_and_save (--image)+ fflf → KeyframeInterpolationPipeline.generate_and_save (--image start, --last-image end)+ extend → ExtendPipeline.extend_from_video (--extend-from-video, --extend-frames, --direction)++Output: writes the rendered .mp4 to --output. Emits a final JSON line on+stdout ({"video_path": "<output>"}) so the Node parent can read the result+metadata, mirroring the contract used by mlx_video.generate_av.+"""+from __future__ import annotations++import argparse+import json+import os+import sys+from pathlib import Path+++def emit_status(msg: str) -> None:+ """STATUS: line — single status update routed to PortOS SSE as `status`."""+ print(f"STATUS:{msg}", file=sys.stderr, flush=True)+++def emit_stage(stage: int, step: int, total: int, label: str) -> None:+ """STAGE: line — structured progress, parsed as `progress` (step/total) by PortOS."""+ print(f"STAGE:{stage}:STEP:{step}:{total}:{label}", file=sys.stderr, flush=True)+++def emit_download(msg: str) -> None:+ """DOWNLOAD: line — first-use HF download status routed to SSE as `status`."""+ print(f"DOWNLOAD:{msg}", file=sys.stderr, flush=True)+++def parse_args() -> argparse.Namespace:+ p = argparse.ArgumentParser(description="PortOS ltx-2-mlx bridge")+ p.add_argument("--mode", required=True, choices=["text", "image", "fflf", "extend"])+ p.add_argument("--prompt", required=True)+ p.add_argument("--negative-prompt", default="")+ p.add_argument("--output", required=True, help="Output .mp4 path")+ p.add_argument("--model", required=True, help="HF repo id or local path (e.g. dgrauet/ltx-2.3-mlx-q4)")+ p.add_argument("--gemma", default="mlx-community/gemma-3-12b-it-4bit")+ p.add_argument("--height", type=int, default=480)+ p.add_argument("--width", type=int, default=704)+ p.add_argument("--num-frames", type=int, default=97)+ p.add_argument("--fps", type=float, default=24.0)+ p.add_argument("--seed", type=int, default=42)+ p.add_argument("--steps", type=int, default=None,+ help="One-stage steps; for fflf this maps to stage1-steps")+ p.add_argument("--stage2-steps", type=int, default=None)+ p.add_argument("--cfg-scale", type=float, default=None)+ p.add_argument("--dev-transformer", default=None,+ help="Filename of the non-distilled (dev) transformer inside the model repo. "+ "Required for fflf mode — KeyframeInterpolationPipeline rejects pure-distilled "+ "models because they hallucinate unrelated content during interpolation. "+ "Default for fflf: transformer-dev.safetensors (matches dgrauet/ltx-2.3-mlx-q4 + q8 layouts).")+ p.add_argument("--distilled-lora", default=None,+ help="Filename of the distilled LoRA inside the model repo, fused on top of the "+ "dev transformer for stage 2. Default for fflf: "+ "ltx-2.3-22b-distilled-lora-384.safetensors.")+ p.add_argument("--lora-strength", type=float, default=1.0,+ help="Distilled-LoRA fusion strength (default 1.0, matches dgrauet's CLI).")+ p.add_argument("--image", default=None, help="Source/start frame (image, fflf modes)")+ p.add_argument("--last-image", default=None, help="End frame (fflf mode)")+ p.add_argument("--extend-from-video", default=None, help="Source video path (extend mode)")+ p.add_argument("--extend-frames", type=int, default=2,+ help="Number of latent frames to add (extend mode); 1 latent ≈ 8 pixel frames")+ p.add_argument("--extend-direction", choices=["before", "after"], default="after")+ p.add_argument("--no-audio", action="store_true",+ help="Strip audio from output. The dgrauet pipeline always generates A/V; "+ "we re-mux without the audio stream when requested.")+ return p.parse_args()+++def run_text(args: argparse.Namespace) -> str:+ from ltx_pipelines_mlx import TextToVideoPipeline+ emit_status(f"Loading T2V pipeline ({args.model})…")+ emit_stage(1, 0, 1, "Loading model")+ pipe = TextToVideoPipeline(model_dir=args.model, gemma_model_id=args.gemma)+ emit_stage(1, 1, 1, "Loaded")+ emit_status("Generating T2V…")+ return pipe.generate_and_save(+ prompt=args.prompt,+ output_path=args.output,+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ seed=args.seed,+ num_steps=args.steps,+ )+++def run_image(args: argparse.Namespace) -> str:+ from ltx_pipelines_mlx import ImageToVideoPipeline+ if not args.image:+ raise SystemExit("--image is required for image mode")+ emit_status(f"Loading I2V pipeline ({args.model})…")+ emit_stage(1, 0, 1, "Loading model")+ pipe = ImageToVideoPipeline(model_dir=args.model, gemma_model_id=args.gemma)+ emit_stage(1, 1, 1, "Loaded")+ emit_status("Generating I2V…")+ return pipe.generate_and_save(+ prompt=args.prompt,+ output_path=args.output,+ image=args.image,+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ seed=args.seed,+ num_steps=args.steps,+ )+++def run_fflf(args: argparse.Namespace) -> str:+ """Keyframe interpolation — true FFLF (start + end frame conditioning).++ Pixel frame indices: keyframe 0 anchors at frame 0, keyframe 1 at the+ LAST pixel frame (num_frames - 1). num_frames must be 8k+1 (LTX latent+ boundary) — the panel UI already enforces this via FRAME_OPTIONS.+ """+ from ltx_pipelines_mlx import KeyframeInterpolationPipeline+ if not args.image or not args.last_image:+ raise SystemExit("--image and --last-image are required for fflf mode")+ # Keyframe interpolation needs the dev (non-distilled) transformer ++ # the distilled LoRA fused on top for stage 2. Defaults match the file+ # names in dgrauet/ltx-2.3-mlx-q4 and dgrauet/ltx-2.3-mlx-q8 — caller+ # can override via --dev-transformer / --distilled-lora when a future+ # repo renames them.+ dev_transformer = args.dev_transformer or "transformer-dev.safetensors"+ distilled_lora = args.distilled_lora or "ltx-2.3-22b-distilled-lora-384.safetensors"+ emit_status(f"Loading Keyframe pipeline ({args.model}, dev+lora)…")+ emit_stage(1, 0, 1, "Loading model")+ pipe = KeyframeInterpolationPipeline(+ model_dir=args.model,+ gemma_model_id=args.gemma,+ dev_transformer=dev_transformer,+ distilled_lora=distilled_lora,+ distilled_lora_strength=args.lora_strength,+ )+ emit_stage(1, 1, 1, "Loaded")+ emit_status("Interpolating between keyframes…")+ last_pixel_frame = args.num_frames - 1+ return pipe.generate_and_save(+ prompt=args.prompt,+ output_path=args.output,+ keyframe_images=[args.image, args.last_image],+ keyframe_indices=[0, last_pixel_frame],+ height=args.height,+ width=args.width,+ num_frames=args.num_frames,+ fps=args.fps,+ seed=args.seed,+ stage1_steps=args.steps,+ stage2_steps=args.stage2_steps,+ cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,+ )+++def run_extend(args: argparse.Namespace) -> str:+ from ltx_pipelines_mlx import ExtendPipeline+ if not args.extend_from_video:+ raise SystemExit("--extend-from-video is required for extend mode")+ emit_status(f"Loading Extend pipeline ({args.model})…")+ emit_stage(1, 0, 1, "Loading model")+ pipe = ExtendPipeline(model_dir=args.model, gemma_model_id=args.gemma)+ emit_stage(1, 1, 1, "Loaded")+ emit_status(f"Extending video {args.extend_direction} by {args.extend_frames} latent frames…")+ video_latent, audio_latent = pipe.extend_from_video(+ prompt=args.prompt,+ video_path=args.extend_from_video,+ extend_frames=args.extend_frames,+ direction=args.extend_direction,+ seed=args.seed,+ num_steps=args.steps if args.steps is not None else 30,+ cfg_scale=args.cfg_scale if args.cfg_scale is not None else 3.0,+ )+ return pipe._decode_and_save_video(video_latent, audio_latent, args.output)+++def maybe_strip_audio(output_path: str) -> None:+ """Remux the output without the audio stream when --no-audio is set.++ Caller already wrote `<output_path>` containing both video + audio; we+ swap it for a video-only mp4 in place. ffmpeg's `-an` drops the audio+ stream, `-c:v copy` skips re-encoding so this is fast and lossless.+ """+ import shutil+ import subprocess+ import tempfile+ if not Path(output_path).exists():+ return+ if not shutil.which("ffmpeg"):+ emit_status("ffmpeg not on PATH — leaving audio in output despite --no-audio")+ return+ fd, tmp = tempfile.mkstemp(suffix=".mp4", dir=os.path.dirname(output_path))+ os.close(fd)+ try:+ proc = subprocess.run(+ ["ffmpeg", "-y", "-loglevel", "error", "-i", output_path, "-c:v", "copy", "-an", tmp],+ check=False,+ )+ if proc.returncode == 0 and Path(tmp).stat().st_size > 0:+ os.replace(tmp, output_path)+ emit_status("Stripped audio (--no-audio)")+ else:+ os.unlink(tmp)+ emit_status(f"ffmpeg audio-strip failed (exit {proc.returncode}); keeping A/V")+ except OSError as e:+ emit_status(f"ffmpeg audio-strip skipped: {e}")+++def main() -> int:+ args = parse_args()+ Path(args.output).parent.mkdir(parents=True, exist_ok=True)++ runners = {+ "text": run_text,+ "image": run_image,+ "fflf": run_fflf,+ "extend": run_extend,+ }+ runner = runners[args.mode]+ saved_path = runner(args)+ if args.no_audio:+ maybe_strip_audio(saved_path)++ # Final JSON line on stdout — matches the contract mlx_video.generate_av+ # provides, so videoGen/local.js can pick up `result.video_path` from+ # job.resultJson without a separate parser branch per runtime.+ print(json.dumps({"video_path": saved_path}), flush=True)+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/scripts/setup-image-video.sh b/scripts/setup-image-video.shindex 98739b3f42..2ec2a24faa 100755--- a/scripts/setup-image-video.sh+++ b/scripts/setup-image-video.sh@@ -9,6 +9,7 @@# PYTHON_BIN Python 3 binary to use (default: python3)# PORTOS_DATA Path to PortOS data dir (default: ./data, resolved from $REPO_ROOT)# INSTALL_VIDEO '1' to also install mlx_video for LTX video generation (default: 1 on macOS, 0 on Windows)+# INSTALL_LTX2 '1' to also clone + uv-sync dgrauet/ltx-2-mlx at ~/.portos/ltx-2-mlx for the second-gen LTX-2.3 pipeline (proper keyframe interpolation, true video extend, audio-to-video). Default: 1 on macOS, 0 elsewhere.# INSTALL_FLUX2 '1' to also bootstrap a separate venv at ~/.portos/venv-flux2 for FLUX.2-klein (default: 1 on macOS, 0 elsewhere)set -euo pipefail@@ -71,6 +72,60 @@ if [[ "$INSTALL_VIDEO" == "1" ]]; thenfifi+INSTALL_LTX2="${INSTALL_LTX2:-$(is_macos && echo 1 || echo 0)}"++if [[ "$INSTALL_LTX2" == "1" ]]; then+ # dgrauet/ltx-2-mlx: a more capable community port of LTX-2.3 with+ # proper KeyframeInterpolationPipeline (true FFLF), video Extend (not+ # last-frame conditioning), retake, ic-lora, audio-to-video.+ # Requires Python 3.11+ and ships as a multi-package monorepo we sync+ # via `uv sync --all-extras` from a local clone. Lives at+ # ~/.portos/ltx-2-mlx/ (sibling to the FLUX.2 venv pattern).+ #+ # The notapalindrome `mlx-video-with-audio` install above is unaffected+ # — both pipelines coexist; dispatch is per-model via media-models.json's+ # `runtime` field (`mlx_video` vs `ltx2`).+ if ! have uv; then+ echo "❌ INSTALL_LTX2=1 requires the 'uv' Python installer. Install with:" >&2+ echo " curl -LsSf https://astral.sh/uv/install.sh | sh" >&2+ exit 1+ fi+ if ! have git; then+ echo "❌ INSTALL_LTX2=1 requires git." >&2+ exit 1+ fi+ LTX2_DIR="${HOME}/.portos/ltx-2-mlx"+ LTX2_PY="${LTX2_DIR}/.venv/bin/python3"+ mkdir -p "${HOME}/.portos"+ if [[ ! -d "${LTX2_DIR}/.git" ]]; then+ echo "📦 Cloning dgrauet/ltx-2-mlx into ${LTX2_DIR}..."+ git clone --depth=1 https://github.com/dgrauet/ltx-2-mlx.git "${LTX2_DIR}"+ else+ echo "ℹ️ ltx-2-mlx clone exists at ${LTX2_DIR}; skipping clone."+ fi+ # Force Python 3.11 — ltx-core-mlx pins requires-python>=3.11 and the+ # macOS bundled python3 is sometimes 3.10. uv resolves this for us when+ # the env doesn't already exist.+ if [[ ! -x "${LTX2_PY}" ]]; then+ echo "📦 Creating ltx-2-mlx venv with Python 3.11..."+ (cd "${LTX2_DIR}" && uv venv --python 3.11)+ fi+ # `uv sync` is idempotent — already-installed packages are no-ops. The+ # repo's uv.lock pins mlx==0.31.1, which is the safe version (mlx 0.31.2+ # silently regressed audio peaks by ~22 dB; phosphene hit this and ships+ # the same pin). Skip --all-extras — we don't need the trainer or dev+ # extras for inference, and the trainer extra pulls another package we+ # have no use for.+ echo "📦 Syncing ltx-2-mlx packages (uv sync, no extras)..."+ (cd "${LTX2_DIR}" && uv sync)+ if ! "${LTX2_PY}" -c "import ltx_pipelines_mlx" 2>/dev/null; then+ echo "❌ ltx-2-mlx synced but 'import ltx_pipelines_mlx' failed." >&2+ echo " Re-run with: rm -rf ${LTX2_DIR}/.venv && bash $0" >&2+ exit 1+ fi+ echo "✅ ltx-2-mlx venv ready: ${LTX2_PY}"+fi+INSTALL_FLUX2="${INSTALL_FLUX2:-$(is_macos && echo 1 || echo 0)}"if [[ "$INSTALL_FLUX2" == "1" ]]; then@@ -138,6 +193,9 @@ echo " Python: $PYTHON_PATH"echo " HF cache: ~/.cache/huggingface (HF default)"echo " LoRAs: ${PORTOS_DATA}/loras"echo " Videos: ${PORTOS_DATA}/videos"+if [[ "$INSTALL_LTX2" == "1" ]]; then+ echo " LTX-2.3: ${HOME}/.portos/ltx-2-mlx/.venv/bin/python3 (separate venv, dgrauet pipeline)"+fiif [[ "$INSTALL_FLUX2" == "1" ]]; thenecho " FLUX.2: ${HOME}/.portos/venv-flux2/bin/python3 (separate venv)"echo ""diff --git a/server/lib/mediaModels.js b/server/lib/mediaModels.jsindex 6ca21addfe..4bc12b8980 100644--- a/server/lib/mediaModels.js+++ b/server/lib/mediaModels.js@@ -32,12 +32,19 @@ const DEFAULT_REGISTRY = {_doc: 'PortOS media model registry. Edit to add models, tune defaults, or switch the text encoder. Restart the server to apply changes.',video: {macos: [- { id: 'ltx2_unified', name: 'LTX-2 Unified (~42 GB)', repo: 'notapalindrome/ltx2-mlx-av', steps: 30, guidance: 3.0 },- { id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta (~48 GB)', repo: 'notapalindrome/ltx23-mlx-av', steps: 25, guidance: 3.0 },- { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4 (~22 GB)', repo: 'notapalindrome/ltx23-mlx-av-q4', steps: 25, guidance: 3.0 },+ // notapalindrome's mlx-video-with-audio runtime — single PyPI package,+ // T2V/I2V only, FFLF degrades to last-frame conditioning (one --image arg).+ { id: 'ltx2_unified', name: 'LTX-2 Unified (~42 GB)', repo: 'notapalindrome/ltx2-mlx-av', runtime: 'mlx_video', steps: 30, guidance: 3.0 },+ { id: 'ltx23_unified', name: 'LTX-2.3 Unified Beta (~48 GB)', repo: 'notapalindrome/ltx23-mlx-av', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ { id: 'ltx23_distilled_q4', name: 'LTX-2.3 Distilled Q4 (~22 GB)', repo: 'notapalindrome/ltx23-mlx-av-q4', runtime: 'mlx_video', steps: 25, guidance: 3.0 },+ // dgrauet's ltx-2-mlx runtime — true KeyframeInterpolationPipeline,+ // native video Extend, audio→video. Requires a separate venv synced+ // via `INSTALL_LTX2=1 bash scripts/setup-image-video.sh`.+ { id: 'ltx23_dgrauet_q4', name: 'LTX-2.3 dgrauet Q4 (~16 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q4', runtime: 'ltx2', steps: 8, guidance: 3.0 },+ { id: 'ltx23_dgrauet_q8', name: 'LTX-2.3 dgrauet Q8 (~25 GB, true keyframes)', repo: 'dgrauet/ltx-2.3-mlx-q8', runtime: 'ltx2', steps: 8, guidance: 3.0 },],windows: [- { id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', steps: 25, guidance: 3.0 },+ { id: 'ltx_video', name: 'LTX-Video 0.9.5 — T2V + I2V (~9.5 GB, auto-downloads)', runtime: 'mlx_video', steps: 25, guidance: 3.0 },],defaultMacos: 'ltx23_distilled_q4',defaultWindows: 'ltx_video',@@ -152,6 +159,35 @@ const upgradeImageEntries = (list) => {export const isFlux2 = (model) => model?.runner === 'flux2';+// Append video models whose id is in DEFAULT_REGISTRY but missing from the+// user's saved list. Lets us roll out new pipelines (e.g. the dgrauet ltx2+// runtime) to existing installs without forcing users to hand-edit+// data/media-models.json. Preserves any user customisations for ids they+// already have (we only ADD new entries; we don't overwrite existing).+const appendMissingVideoEntries = (userList, defaults) => {+ if (!Array.isArray(userList)) return defaults;+ if (!Array.isArray(defaults)) return userList;+ const haveIds = new Set(userList.map((e) => e?.id).filter((id) => typeof id === 'string'));+ const missing = defaults.filter((e) => typeof e?.id === 'string' && !haveIds.has(e.id));+ if (!missing.length) return userList;+ return [...userList, ...missing];+};++// Existing installs predate the `runtime` field on video entries — fill it+// with 'mlx_video' (the legacy default) for known-legacy ids so the+// dispatch in videoGen/local.js routes them through `python -m+// mlx_video.generate_av` rather than treating undefined as ltx2.+const LEGACY_MLX_VIDEO_IDS = new Set(['ltx2_unified', 'ltx23_unified', 'ltx23_distilled_q4', 'ltx_video']);+const backfillRuntime = (list) => {+ if (!Array.isArray(list)) return list;+ return list.map((entry) => {+ if (!isPlainObject(entry) || typeof entry.id !== 'string') return entry;+ if (typeof entry.runtime === 'string' && entry.runtime.length > 0) return entry;+ if (LEGACY_MLX_VIDEO_IDS.has(entry.id)) return { ...entry, runtime: 'mlx_video' };+ return entry;+ });+};+const normalizeRegistry = (parsed) => {const safe = isPlainObject(parsed) ? parsed : {};const safeVideo = isPlainObject(safe.video) ? safe.video : {};@@ -163,8 +199,8 @@ const normalizeRegistry = (parsed) => {video: {...DEFAULT_REGISTRY.video,...safeVideo,- macos: arrayOrDefault(safeVideo.macos, DEFAULT_REGISTRY.video.macos),- windows: arrayOrDefault(safeVideo.windows, DEFAULT_REGISTRY.video.windows),+ macos: backfillRuntime(appendMissingVideoEntries(safeVideo.macos, DEFAULT_REGISTRY.video.macos)),+ windows: backfillRuntime(appendMissingVideoEntries(safeVideo.windows, DEFAULT_REGISTRY.video.windows)),},};};diff --git a/server/services/videoGen/local.js b/server/services/videoGen/local.jsindex cf28ba70d8..e9879ace75 100644--- a/server/services/videoGen/local.js+++ b/server/services/videoGen/local.js@@ -14,7 +14,7 @@ import { execFile, spawn } from 'child_process';import { existsSync, statSync } from 'fs';import { unlink, writeFile, copyFile } from 'fs/promises';import { join, basename } from 'path';-import { tmpdir } from 'os';+import { homedir, tmpdir } from 'os';import { randomUUID } from 'crypto';import { promisify } from 'util';import { ensureDir, PATHS, readJSONFile, atomicWrite, UUID_RE } from '../../lib/fileUtils.js';@@ -24,6 +24,14 @@ import { broadcastSse, attachSseClient as attachSse, closeJobAfterDelay, PYTHON_import { getVideoModels, getDefaultVideoModelId, getTextEncoderRepo } from '../../lib/mediaModels.js';import { findFfmpeg, safeUnder, generateThumbnail, optimizeForStreaming, upscaleVideo2x } from '../../lib/ffmpeg.js';+// Path to the dgrauet/ltx-2-mlx venv populated by `INSTALL_LTX2=1+// scripts/setup-image-video.sh`. Used when a model entry has+// `runtime: 'ltx2'`. The companion helper at scripts/generate_ltx2.py+// imports `ltx_pipelines_mlx` from this venv and emits the same SSE+// progress protocol (STAGE:/STATUS:/DOWNLOAD:) as the mlx_video CLI.+const LTX2_VENV_PYTHON = join(homedir(), '.portos', 'ltx-2-mlx', '.venv', 'bin', 'python3');+const LTX2_HELPER_SCRIPT = join(PATHS.root, 'scripts', 'generate_ltx2.py');+const execFileAsync = promisify(execFile);const IS_WIN = process.platform === 'win32';@@ -75,7 +83,90 @@ export const cancel = () => {export const loadHistory = () => readJSONFile(HISTORY_FILE, []);export const saveHistory = (h) => atomicWrite(HISTORY_FILE, h);+// Build the spawn args for dgrauet's ltx-2-mlx runtime via our Python helper.+// The helper lives in the ltx-2-mlx venv (so its `import ltx_pipelines_mlx`+// resolves) but the script file lives in the PortOS repo so updates ship+// with PortOS releases instead of the user's HF cache.+const buildLtx2Args = ({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, mode, disableAudio, outputPath, textEncoderRepo }) => {+ if (!existsSync(LTX2_VENV_PYTHON)) {+ throw new ServerError(+ `ltx-2-mlx venv not found at ${LTX2_VENV_PYTHON}. Run \`INSTALL_LTX2=1 bash scripts/setup-image-video.sh\` to install.`,+ { status: 500, code: 'LTX2_VENV_MISSING' },+ );+ }+ // Map PortOS UI modes to the helper's subcommand. Extend isn't reachable+ // from the current videoGen.generateVideo signature — that mode runs as+ // a chain of i2v renders today (see generateChainedVideo). Native extend+ // is a future enhancement; we route 'extend' to 'image' for now since+ // the chain orchestrator already handed us a frame.+ const helperMode = mode === 'fflf' ? 'fflf'+ : mode === 'image' || mode === 'extend' ? 'image'+ : 'text';+ if (helperMode === 'fflf' && (!sourceImagePath || !lastImagePath)) {+ throw new ServerError(+ 'FFLF mode on the ltx2 runtime requires BOTH a start image (sourceImagePath) and an end image (lastImagePath).',+ { status: 400, code: 'LTX2_FFLF_MISSING_KEYFRAMES' },+ );+ }+ // Stage-2 OOM clamp on the keyframe pipeline.+ //+ // The KeyframeInterpolationPipeline runs a 2× spatial upscale + full-res+ // refinement after stage 1, and memory pressure scales with both+ // (width × height) AND latent-frame count = 1 + (numFrames - 1) / 8.+ // Phosphene's panel notes the same path OOMs even on 64 GB Macs at full+ // resolution and clamps to 768×432 in their UI. We empirically verified+ // 25 frames @ 704×448 fits 48 GB; 97 frames @ 704×448 OOMs in stage 2.+ //+ // Approach: cap the pixel-frame budget (width × height × numFrames) at a+ // value that fit on the test box, then back-solve numFrames. Round down+ // to the LTX 8k+1 latent-boundary so the model doesn't silently snap.+ // FFLF_LTX2_PIXEL_BUDGET env var lets users with more RAM raise the cap.+ if (helperMode === 'fflf') {+ const envBudget = Number(process.env.FFLF_LTX2_PIXEL_BUDGET);+ const pixelBudget = Number.isFinite(envBudget) && envBudget > 0+ ? envBudget+ : 704 * 448 * 25; // ≈7.9M pixel-frames, confirmed to fit 48 GB unified RAM+ const requested = Number(width) * Number(height) * Number(numFrames);+ if (requested > pixelBudget) {+ const safeRaw = Math.floor(pixelBudget / (Number(width) * Number(height)));+ const safeLatent = Math.max(1, Math.floor((safeRaw - 1) / 8));+ const safeFrames = safeLatent * 8 + 1;+ console.log(`⚠️ FFLF/ltx2 numFrames clamped ${numFrames} → ${safeFrames} to fit pixel budget ${pixelBudget} (export FFLF_LTX2_PIXEL_BUDGET=<n> to raise)`);+ numFrames = safeFrames;+ }+ }+ const args = [+ LTX2_HELPER_SCRIPT,+ '--mode', helperMode,+ '--prompt', prompt,+ '--output', outputPath,+ '--model', model.repo,+ '--gemma', textEncoderRepo,+ '--width', String(width),+ '--height', String(height),+ '--num-frames', String(numFrames),+ '--fps', String(fps),+ '--seed', String(seed),+ '--steps', String(steps),+ '--cfg-scale', String(guidance),+ ];+ if (negativePrompt) args.push('--negative-prompt', negativePrompt);+ if (disableAudio) args.push('--no-audio');+ if (helperMode === 'image' && sourceImagePath) args.push('--image', sourceImagePath);+ if (helperMode === 'fflf') {+ args.push('--image', sourceImagePath);+ args.push('--last-image', lastImagePath);+ }+ return { bin: LTX2_VENV_PYTHON, args };+};+const buildArgs = ({ pythonPath, modelId, model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, tiling, disableAudio, sourceImagePath, lastImagePath, mode, imageStrength, textEncoderRepo, outputPath }) => {+ // Route to the dgrauet/ltx-2-mlx helper when the model declares the new+ // runtime. Existing notapalindrome models default to runtime: 'mlx_video'+ // (or undefined in legacy registries — see backfillRuntime in mediaModels.js).+ if (model.runtime === 'ltx2') {+ return buildLtx2Args({ model, prompt, negativePrompt, width, height, numFrames, fps, steps, guidance, seed, sourceImagePath, lastImagePath, mode, disableAudio, outputPath, textEncoderRepo });+ }if (IS_WIN) {const scriptPath = join(PATHS.root, 'scripts', 'generate_win.py');const args = [scriptPath, '--model', modelId, '--prompt', prompt, '--height', String(height), '--width', String(width), '--num-frames', String(numFrames), '--fps', String(fps), '--steps', String(steps), '--guidance', String(guidance), '--seed', String(seed), '--output', outputPath];