Free, open-source AI video generator for Mac. Run LTX-2.5 and MiniMax H3 (Hailuo) locally on Apple Silicon: text-to-video and image-to-video with sound, lip-sync, character LoRA training, songs from lyrics (YuE2) and image editing (Qwen-Image-Edit). One-click install via Pinokio. Offline: no cloud, no API key, no NVIDIA GPU.
Python ai-filmmakingai-videoai-video-generatorapple-siliconhailuoimage-to-videolip-synclocal-ailora-trainingltx-2ltx-2-5ltx-videomacosminimax-h3mlxmusic-generationoffline-aipinokiotext-to-videovideo-generation
feat: Audio-to-Video tab + TeaCache wired through A2V Stage 1
mrbizarro17be2a79c48d
diff --git a/mlx_ltx_panel.py b/mlx_ltx_panel.pyindex 8609012..8280a9c 100644--- a/mlx_ltx_panel.py+++ b/mlx_ltx_panel.py@@ -5557,7 +5557,7 @@ def run_job_inner(job: dict) -> None:quality = p.get("quality", "standard")if p.get("accel") not in ("off", "boost", "turbo"):p["accel"] = "off"- if quality == "high" or mode in ("extend", "keyframe"):+ if quality == "high" or mode in ("extend", "keyframe", "a2v"):p["accel"] = "off"# Guard: Q4 distilled hardcoded 9-sigma schedule needs the full walk to@@ -5567,7 +5567,8 @@ def run_job_inner(job: dict) -> None:# Modes that don't use the distilled `steps` field skip this check:# - extend / keyframe use stage1_steps + stage2_steps via two-stage path# - high quality uses two-stage HQ with its own schedule- if mode not in ("extend", "keyframe") and quality != "high" and int(p.get("steps", 8)) < 8:+ # - a2v uses A2VidPipelineTwoStage's stage1/stage2 walks+ if mode not in ("extend", "keyframe", "a2v") and quality != "high" and int(p.get("steps", 8)) < 8:raise RuntimeError(f"steps={p.get('steps')} is below the 8-step minimum for the Q4 distilled ""schedule. Fewer steps truncates the sigma walk and leaves >70% noise in "@@ -5848,6 +5849,104 @@ def run_job_inner(job: dict) -> None:subprocess.run(["open", str(out_path)], check=False)return+ # Audio → Video (A2VidPipelineTwoStage).+ # Pipeline drives generation FROM the input audio waveform. Optional+ # reference image conditions frame 0 (single picture; pipeline cover-+ # crops to target). Original audio is muxed onto the output by the+ # pipeline itself — no panel-side mux needed (unlike i2v_clean_audio).+ # Always Q8 dev + distilled LoRA stage 2 (the pipeline requires both).+ if mode == "a2v":+ if not SYSTEM_CAPS["allows_q8"]:+ raise RuntimeError(+ f"Audio → Video isn't supported on the {SYSTEM_CAPS['label']} "+ f"hardware tier — the Q8 dev transformer + audio VAE peak "+ f"doesn't fit. Bump to 64+ GB."+ )+ a2v_missing = q8_missing_files()+ if a2v_missing:+ raise RuntimeError(+ f"Audio → Video requires the full Q8 model at {Q8_LOCAL_PATH}. "+ f"Missing {len(a2v_missing)} file(s): {', '.join(a2v_missing[:3])}"+ f"{' …' if len(a2v_missing) > 3 else ''}. "+ f"Run: hf download {MODEL_ID_HQ} --local-dir {Q8_LOCAL_PATH}"+ )+ audio_src = (p.get("audio") or "").strip()+ if not audio_src or not Path(audio_src).exists():+ raise RuntimeError(f"audio file not found: {audio_src}")+ width, height = int(p["width"]), int(p["height"])+ frames = int(p["frames"])+ desc_stem = _descriptive_filename(+ p.get("label") or "", p.get("prompt") or "", fallback="a2v"+ )+ out_path = _unique_output_path(OUTPUT, desc_stem)+ job["raw_path"] = str(out_path)+ # Optional reference image — when present the pipeline anchors+ # frame 0 the same way I2V does. When absent it's pure A2V.+ ref_image_path = p.get("image") if p.get("image") else None+ # The panel ships the reference path defaulted to examples/reference.png+ # via AUDIO_DEFAULT-style fallback; only treat as a "real" image if+ # the user actually picked something distinct from the inert default.+ if ref_image_path and not Path(ref_image_path).exists():+ ref_image_path = None+ # LoRAs flow through unchanged — useful for character A2V.+ a2v_loras = list(p.get("loras") or [])+ if p.get("hdr"):+ a2v_loras.append({+ "path": CURATED_LORAS["hdr"]["repo_id"],+ "strength": float(CURATED_LORAS["hdr"]["default_strength"]),+ })+ job_spec = {+ "action": "generate_a2v",+ "id": job["id"],+ "params": {+ "model_dir": str(Q8_LOCAL_PATH),+ "prompt": p["prompt"],+ "negative_prompt": p.get("negative_prompt", ""),+ "output_path": str(out_path),+ "audio_path": audio_src,+ "image": ref_image_path,+ "height": height,+ "width": width,+ "frames": frames,+ "frame_rate": float(FPS),+ "seed": p["seed"],+ "stage1_steps": int(p.get("stage1_steps", 20)),+ "stage2_steps": int(p.get("stage2_steps", 3)),+ "cfg_scale": float(p.get("cfg_scale", 3.0)),+ "stg_scale": float(p.get("stg_scale", 1.0)),+ "loras": a2v_loras,+ },+ }+ push(+ f"Run A2V via helper: id={job['id']} {width}x{height} {frames}f · "+ f"audio={Path(audio_src).name}"+ f"{' image=' + Path(ref_image_path).name if ref_image_path else ''} · "+ f"{len(a2v_loras)} LoRA"+ f"{'s' if len(a2v_loras) != 1 else ''}"+ )+ result = HELPER.run(job_spec)+ if "seed_used" in result:+ push(f"seed used: {result['seed_used']}")+ p["seed_used"] = result["seed_used"]+ sidecar = {+ "output": str(out_path), "raw_output": str(out_path),+ "params": {**p, "command": "generate_a2v", "audio": audio_src,+ "image": ref_image_path},+ "started": job.get("started_at"),+ "elapsed_sec": round(time.time() - job["started_ts"], 2)+ if job.get("started_ts") else None,+ "video_duration_sec": video_duration(frames),+ "fps": FPS, "model": str(Q8_LOCAL_PATH), "queue_id": job["id"],+ "helper_elapsed_sec": result.get("elapsed_sec"),+ "output_codec": output_codec_settings(),+ }+ write_sidecar(out_path.with_suffix(out_path.suffix + ".json"), sidecar)+ job["output_path"] = str(out_path)+ push(f"A2V done in {sidecar['elapsed_sec']}s → {out_path.name}")+ if p.get("open_when_done"):+ subprocess.run(["open", str(out_path)], check=False)+ return+# T2V / I2V / I2V+clean_audiowidth, height = p["width"], p["height"]frames = p["frames"]@@ -10995,9 +11094,22 @@ HTML = r"""<!doctype html>body[data-workflow="train"] #modeGroup,body[data-workflow="train"] aside.form-pane > h2,body[data-workflow="train"] #genForm,- body[data-workflow="train"] #studioSection { display: none !important; }+ body[data-workflow="train"] #studioSection,+ body[data-workflow="train"] #audioSectionTab { display: none !important; }body[data-workflow="train"] #trainSection { display: block; }+ /* Audio → Video is its own workflow tier alongside Video / Images / Train.+ Pure A2V (audio + prompt) and Image + Audio (audio + still + prompt)+ both live here, behind one audio drop-zone + optional image picker.+ Hides the manual-only chrome the same way Train / Studio do. */+ body[data-workflow="audio"] #modelsInline,+ body[data-workflow="audio"] #modeGroup,+ body[data-workflow="audio"] aside.form-pane > h2,+ body[data-workflow="audio"] #genForm,+ body[data-workflow="audio"] #studioSection,+ body[data-workflow="audio"] #trainSection { display: none !important; }+ body[data-workflow="audio"] #audioSectionTab { display: block; }+/* =========================================================CAPABILITY TIER (Q4 vs Q8) — Codex C+ recommendation, 2026-05-17=========================================================@@ -11922,7 +12034,8 @@ HTML = r"""<!doctype html>body[data-workflow="studio"] aside.form-pane > h2,body[data-workflow="studio"] #genForm,body[data-workflow="studio"] #trainSection,- body[data-workflow="studio"] #charactersSection { display: none !important; }+ body[data-workflow="studio"] #charactersSection,+ body[data-workflow="studio"] #audioSectionTab { display: none !important; }body[data-workflow="studio"] #studioSection { display: block; }/* ============================================================@@ -16460,7 +16573,8 @@ HTML = r"""<!doctype html><nav class="workflow-tabs" id="workflowTabs"><button data-workflow="manual" class="active"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-film-strip"/></svg>Video</button><button data-workflow="studio"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-image"/></svg>Images</button>- <button data-workflow="train"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-user-plus"/></svg>Train Character<span class="new-badge">NEW</span></button>+ <button data-workflow="audio"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-music-notes"/></svg>Audio<span class="new-badge">NEW</span></button>+ <button data-workflow="train"><svg class="ph wf-icon" aria-hidden="true"><use href="#ph-user-plus"/></svg>Train Character</button></nav><!-- The original manual form is unchanged; it sits below in the DOMand is shown/hidden by JS as the workflow tab toggles. -->@@ -17866,6 +17980,109 @@ HTML = r"""<!doctype html></div></div>++ <!-- ============== AUDIO → VIDEO (own workflow tab) ==============+ Routes to the helper's `generate_a2v` action which loads+ A2VidPipelineTwoStage (Q8 dev + distilled LoRA stage 2). The+ pipeline writes the original input audio onto the output MP4+ itself — no panel-side mux. Reference image is optional; when+ present the pipeline anchors frame 0 (same shape as I2V), so+ the same surface covers both pure A2V (audio only) and+ Image + Audio (audio + still). -->+ <div id="audioSectionTab" style="display:none">+ <div class="composer-card">+ <div class="composer-refs">+ <div class="show">+ <h2>Audio+ <span class="h2-hint">drives the generation · WAV / MP3 / M4A / FLAC</span>+ </h2>+ <div class="studio-ref-grid" style="grid-template-columns:1fr;">+ <div class="studio-ref-slot" id="audioStudioAudioSlot" data-slot="audio" style="aspect-ratio:auto;min-height:96px;">+ <span class="ref-tag">Audio</span>+ <div class="hint" style="padding:24px 12px;text-align:center;color:var(--muted);font-size:12px;">+ Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.+ </div>+ </div>+ </div>+ <input type="file" id="audioStudioAudioInput" accept=".wav,.mp3,.m4a,.flac,audio/*" style="display:none">+ </div>+ </div>++ <div class="composer-refs">+ <div class="show">+ <h2>Reference image+ <span class="h2-hint">optional · anchors frame 0 like I2V</span>+ </h2>+ <div class="studio-ref-grid" style="grid-template-columns:1fr;">+ <div class="studio-ref-slot" id="audioStudioImageSlot" data-slot="image">+ <span class="ref-tag">Image</span>+ </div>+ </div>+ <input type="file" id="audioStudioImageInput" accept="image/*" style="display:none">+ <div class="hint" style="margin-top:6px">+ Leave empty for pure Audio → Video. Add an image to open the clip on that frame (e.g. a portrait for a talking-head shot).+ </div>+ </div>+ </div>++ <textarea id="audioStudioPrompt" class="composer-prompt" rows="4"+ placeholder="A photoreal medium close-up of a woman speaking to camera, soft daylight, shallow depth of field, natural skin pores"></textarea>+ </div>++ <div class="studio-status-row" style="margin: 6px 0 -4px;">+ <span id="audioStudioStatus" class="hint"></span>+ </div>++ <!-- Quick settings: aspect / duration / seed / quality.+ Aspect maps to the same width/height table the Characters tab+ uses (1024×576 high, 736×416 draft). Duration → frames at+ 8k+1 cadence the model expects. -->+ <div class="quick-settings">+ <div>+ <div class="mini-fields">+ <div class="mf-cell">+ <span class="mf-label">Aspect</span>+ <select id="audioStudioAspect" style="padding:7px 9px;font-size:13px;">+ <option value="16:9" selected>16:9 — 1024×576</option>+ <option value="9:16">9:16 — 576×1024</option>+ <option value="1:1">1:1 — 768×768</option>+ <option value="4:3">4:3 — 832×608</option>+ </select>+ </div>+ <div class="mf-cell">+ <span class="mf-label">Duration</span>+ <select id="audioStudioDuration" style="padding:7px 9px;font-size:13px;">+ <option value="5">5 s</option>+ <option value="7" selected>7 s</option>+ <option value="10">10 s</option>+ </select>+ </div>+ <div class="mf-cell">+ <span class="mf-label">Seed</span>+ <input type="number" id="audioStudioSeed" value="-1" placeholder="-1 = random">+ </div>+ </div>+ </div>+ </div>++ <div class="hint" style="margin-top:8px">+ Audio → Video uses the Q8 dev transformer with audio conditioning.+ Wall time is similar to High-quality I2V (~7–9 min on a 64 GB M-Max+ for a 7 s 1024×576 clip).+ </div>++ <div class="form-action-footer" id="audioStudioFooter">+ <div class="queue-strip">+ <span class="qchip-spacer"></span>+ <span class="qchip-derived" id="audioStudioEstimate"></span>+ </div>+ <div class="actions">+ <button type="button" class="primary" id="audioStudioGenBtn" onclick="audioStudioGenerate()">Generate</button>+ <button type="button" class="danger" onclick="api('/stop', 'POST').then(poll)">Stop</button>+ </div>+ </div>+ </div>+</aside><!-- ============== STAGE PANE: PLAYER + CAROUSEL ============== -->@@ -19304,6 +19521,249 @@ function imgStudioCopyPath(path) {navigator.clipboard.writeText(path).then(() => flash('Path copied.')).catch(() => legacy());}+// ====== Audio → Video pane ===================================================+// State for the Audio workflow tab. Routes to make_job with mode='a2v'.+// One drop-zone for audio (required), one for an optional reference image.+const AUDIO_STUDIO = {+ busy: false,+ audioPath: null, // server-side path returned by /upload+ audioName: null, // display name for the drop-zone tag+ audioDuration: null, // probed duration (seconds) if ffprobe returns it+ imagePath: null,+ imageName: null,+ wired: false, // init() runs once+};++function audioStudioInit() {+ if (AUDIO_STUDIO.wired) return;+ AUDIO_STUDIO.wired = true;+ const audioSlot = document.getElementById('audioStudioAudioSlot');+ const audioInput = document.getElementById('audioStudioAudioInput');+ const imageSlot = document.getElementById('audioStudioImageSlot');+ const imageInput = document.getElementById('audioStudioImageInput');++ // Audio drop-zone wiring — click to pick, drag-and-drop, paste.+ if (audioSlot && audioInput) {+ audioSlot.addEventListener('click', () => audioInput.click());+ audioSlot.addEventListener('dragover', (e) => {+ e.preventDefault();+ audioSlot.classList.add('drop-active');+ });+ audioSlot.addEventListener('dragleave', () => audioSlot.classList.remove('drop-active'));+ audioSlot.addEventListener('drop', (e) => {+ e.preventDefault();+ audioSlot.classList.remove('drop-active');+ if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]) {+ audioStudioUploadAudio(e.dataTransfer.files[0]);+ }+ });+ audioInput.addEventListener('change', () => {+ if (audioInput.files && audioInput.files[0]) {+ audioStudioUploadAudio(audioInput.files[0]);+ }+ });+ }++ // Image drop-zone wiring (optional reference frame 0).+ if (imageSlot && imageInput) {+ imageSlot.addEventListener('click', () => imageInput.click());+ imageSlot.addEventListener('dragover', (e) => {+ e.preventDefault();+ imageSlot.classList.add('drop-active');+ });+ imageSlot.addEventListener('dragleave', () => imageSlot.classList.remove('drop-active'));+ imageSlot.addEventListener('drop', (e) => {+ e.preventDefault();+ imageSlot.classList.remove('drop-active');+ if (e.dataTransfer && e.dataTransfer.files && e.dataTransfer.files[0]) {+ audioStudioUploadImage(e.dataTransfer.files[0]);+ }+ });+ imageInput.addEventListener('change', () => {+ if (imageInput.files && imageInput.files[0]) {+ audioStudioUploadImage(imageInput.files[0]);+ }+ });+ }+ audioStudioRenderSlots();+}++async function audioStudioUploadAudio(file) {+ const status = document.getElementById('audioStudioStatus');+ if (status) status.textContent = 'Uploading audio…';+ try {+ const fd = new FormData();+ // /upload accepts both `image` and `audio` field names.+ fd.append('audio', file);+ const r = await fetch('/upload', { method: 'POST', body: fd });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const data = await r.json();+ if (data.error) throw new Error(data.error);+ AUDIO_STUDIO.audioPath = data.path || null;+ AUDIO_STUDIO.audioName = file.name;+ AUDIO_STUDIO.audioDuration = (data.duration_sec != null) ? Number(data.duration_sec) : null;+ audioStudioRenderSlots();+ if (status) status.textContent = '';+ } catch (e) {+ if (status) status.textContent = 'Audio upload failed: ' + (e.message || 'unknown');+ }+}++async function audioStudioUploadImage(file) {+ const status = document.getElementById('audioStudioStatus');+ if (status) status.textContent = 'Uploading image…';+ try {+ const fd = new FormData();+ fd.append('image', file);+ const r = await fetch('/upload', { method: 'POST', body: fd });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const data = await r.json();+ if (data.error) throw new Error(data.error);+ AUDIO_STUDIO.imagePath = data.path || null;+ AUDIO_STUDIO.imageName = file.name;+ audioStudioRenderSlots();+ if (status) status.textContent = '';+ } catch (e) {+ if (status) status.textContent = 'Image upload failed: ' + (e.message || 'unknown');+ }+}++function audioStudioClearImage() {+ AUDIO_STUDIO.imagePath = null;+ AUDIO_STUDIO.imageName = null;+ audioStudioRenderSlots();+}++function audioStudioClearAudio() {+ AUDIO_STUDIO.audioPath = null;+ AUDIO_STUDIO.audioName = null;+ AUDIO_STUDIO.audioDuration = null;+ audioStudioRenderSlots();+}++function audioStudioRenderSlots() {+ const audioSlot = document.getElementById('audioStudioAudioSlot');+ const imageSlot = document.getElementById('audioStudioImageSlot');+ if (audioSlot) {+ if (AUDIO_STUDIO.audioPath) {+ const dur = (AUDIO_STUDIO.audioDuration != null)+ ? ' · ' + AUDIO_STUDIO.audioDuration.toFixed(1) + ' s'+ : '';+ audioSlot.innerHTML =+ '<span class="ref-tag">Audio</span>' ++ '<div style="padding:18px 12px;text-align:center;font-size:12px;color:var(--text);overflow:hidden;text-overflow:ellipsis;">' ++ '<svg class="ph" aria-hidden="true" style="width:18px;height:18px;vertical-align:-3px;margin-right:6px;"><use href="#ph-music-notes"/></svg>' ++ (AUDIO_STUDIO.audioName || 'audio') + dur ++ '<div class="hint" style="margin-top:8px;">' ++ '<a href="#" onclick="event.stopPropagation();audioStudioClearAudio();return false;">Remove</a>' ++ '</div>' ++ '</div>';+ } else {+ audioSlot.innerHTML =+ '<span class="ref-tag">Audio</span>' ++ '<div class="hint" style="padding:24px 12px;text-align:center;color:var(--muted);font-size:12px;">' ++ 'Drop a WAV / MP3 / M4A / FLAC here, or click to pick a file.' ++ '</div>';+ }+ }+ if (imageSlot) {+ if (AUDIO_STUDIO.imagePath) {+ imageSlot.innerHTML =+ '<span class="ref-tag">Image</span>' ++ '<img src="/uploads/' + encodeURIComponent(AUDIO_STUDIO.imagePath.split(/[/\\\\]/).pop()) + '" ' ++ ' alt="" style="max-width:100%;max-height:240px;border-radius:6px;display:block;margin:8px auto;">' ++ '<div class="hint" style="text-align:center;">' ++ '<a href="#" onclick="event.stopPropagation();audioStudioClearImage();return false;">Remove</a>' ++ '</div>';+ } else {+ imageSlot.innerHTML =+ '<span class="ref-tag">Image</span>' ++ '<div class="hint" style="padding:24px 12px;text-align:center;color:var(--muted);font-size:12px;">' ++ 'Optional · click to add an image that anchors frame 0.' ++ '</div>';+ }+ }+}++async function audioStudioGenerate() {+ if (AUDIO_STUDIO.busy) return;+ const status = document.getElementById('audioStudioStatus');+ const btn = document.getElementById('audioStudioGenBtn');+ const prompt = (document.getElementById('audioStudioPrompt').value || '').trim();+ if (!AUDIO_STUDIO.audioPath) {+ if (status) status.textContent = 'Audio file is required.';+ return;+ }+ if (!prompt) {+ if (status) status.textContent = 'Prompt is required.';+ return;+ }+ // Aspect → width/height map. Snapped to multiples of 32 so the latent+ // grid is exact (LTX requires HW % 32 == 0; the panel checks this in+ // make_job too but we pre-snap to keep the user's chosen ratio).+ const aspect = (document.getElementById('audioStudioAspect').value || '16:9');+ const aspectMap = {+ '16:9': [1024, 576],+ '9:16': [576, 1024],+ '1:1': [768, 768],+ '4:3': [832, 608],+ };+ const [w, h] = aspectMap[aspect] || aspectMap['16:9'];+ // Duration → frames at 8k+1 cadence the model expects.+ const dur = parseInt(document.getElementById('audioStudioDuration').value || '7', 10);+ // 24 fps → frames per second; snap to nearest 8k+1.+ const targetFrames = Math.max(1, Math.round(dur * 24));+ const frames = ((targetFrames - 1 + 7) >> 3 << 3) + 1; // round up to 8k+1+ const seed = parseInt(document.getElementById('audioStudioSeed').value || '-1', 10);++ AUDIO_STUDIO.busy = true;+ if (btn) btn.disabled = true;+ if (status) status.textContent = 'Queueing…';+ try {+ const fd = new URLSearchParams();+ fd.set('mode', 'a2v');+ fd.set('prompt', prompt);+ fd.set('audio', AUDIO_STUDIO.audioPath);+ if (AUDIO_STUDIO.imagePath) fd.set('image', AUDIO_STUDIO.imagePath);+ fd.set('width', String(w));+ fd.set('height', String(h));+ fd.set('frames', String(frames));+ fd.set('seed', String(seed));+ fd.set('quality', 'high'); // A2V is always Q8 dev-class+ // No accel, no enhance — A2V uses A2VidPipelineTwoStage's own walks.+ fd.set('accel', 'off');+ fd.set('enhance', 'off');+ // Forward picked LoRAs if any are active in the unified picker.+ if (typeof _activeLoras !== 'undefined' && Array.isArray(_activeLoras) && _activeLoras.length) {+ const slim = _activeLoras.map(l => ({ path: l.path, strength: l.strength }));+ fd.set('loras', JSON.stringify(slim));+ }+ const r = await fetch('/queue/add', { method: 'POST', body: fd });+ if (!r.ok) {+ const txt = await r.text();+ throw new Error('HTTP ' + r.status + ' ' + txt);+ }+ if (status) status.textContent = 'Submitted. Watch Now / Recent.';+ if (typeof phosToast === 'function') {+ phosToast('Queued Audio → Video clip · watch Now', { kind: 'success' });+ }+ const nowTab = document.querySelector('.tabs button[data-tab="now"]');+ if (nowTab) {+ nowTab.classList.add('flash');+ setTimeout(() => nowTab.classList.remove('flash'), 1200);+ }+ } catch (e) {+ if (status) status.textContent = 'Submit failed: ' + (e.message || 'unknown');+ if (typeof phosToast === 'function') {+ phosToast('A2V submit failed: ' + (e.message || 'unknown'),+ { kind: 'danger', duration: 5000 });+ }+ } finally {+ AUDIO_STUDIO.busy = false;+ if (btn) btn.disabled = false;+ }+}+// ====== Train Character pane ================================================// In-progress dataset state. The job_id is minted by the server on the FIRST// upload of a session and echoed back on every subsequent /train/upload so@@ -26283,12 +26743,14 @@ function workflowSwitch(name) {const manual = document.getElementById('genForm');const studio = document.getElementById('studioSection');const train = document.getElementById('trainSection');+ const audioTab = document.getElementById('audioSectionTab');const characters = document.getElementById('charactersSection'); // dead HTML; hide defensively// Set body data attribute so CSS can switch the layout per workflow.document.body.setAttribute('data-workflow', name);// All non-Manual panes start hidden; the active branch re-shows its own.if (studio) studio.classList.remove('show');if (train) train.classList.remove('show');+ if (audioTab) audioTab.style.display = 'none';if (characters) characters.classList.remove('show');if (name === 'studio') {// Studio is its own top-level tab now (was a mode chip inside@@ -26304,6 +26766,14 @@ function workflowSwitch(name) {if (manual) manual.style.display = 'none';if (train) train.classList.add('show');if (typeof trainInit === 'function') trainInit();+ } else if (name === 'audio') {+ // Audio → Video — own workflow tab. Pure A2V (audio + prompt) and+ // Image + Audio (audio + still + prompt) both live here, behind a+ // single drop-zone + optional image picker. Routes to make_job+ // with mode='a2v'.+ if (manual) manual.style.display = 'none';+ if (audioTab) audioTab.style.display = 'block';+ if (typeof audioStudioInit === 'function') audioStudioInit();} else {// Manual — show the video form, restore the previous video mode.if (manual) manual.style.display = '';@@ -26321,7 +26791,8 @@ try {const saved = localStorage.getItem('phos_workflow');// 2026-05-17 — Characters tab removed; 'characters' now snaps to// 'manual' (workflowSwitch handles the alias). 'studio' is new.- if (saved === 'studio' || saved === 'train' || saved === 'characters') {+ // 2026-05-18 — 'audio' is the Audio → Video workflow tab.+ if (saved === 'studio' || saved === 'train' || saved === 'characters' || saved === 'audio') {workflowSwitch(saved);}// Clear any stale agent-fullscreen flag from the removed chat surface.diff --git a/mlx_warm_helper.py b/mlx_warm_helper.pyindex 84661eb..c21e1bb 100644--- a/mlx_warm_helper.py+++ b/mlx_warm_helper.py@@ -4,10 +4,14 @@Reads JSON-line jobs from stdin, emits JSON-line events to stdout.Actions:- generate — T2V or I2V (auto-resizes images to target dims via PIL cover-crop)- extend — chain a clip by N latent frames (uses ExtendPipeline)- ping — returns pong- exit — graceful shutdown+ generate — T2V or I2V (auto-resizes images to target dims via PIL cover-crop)+ generate_hq — Q8 dev transformer + res_2s sampler + CFG (TwoStageHQPipeline)+ generate_keyframe — FFLF / multi-keyframe interpolation (KeyframeInterpolationPipeline)+ generate_a2v — Audio-to-Video, optional image conditioning (A2VidPipelineTwoStage)+ extend — chain a clip by N latent frames (uses ExtendPipeline)+ enhance_prompt — Gemma rewriting for T2V / I2V prompts+ ping — returns pong+ exit — graceful shutdownAuto-exits after LTX_IDLE_TIMEOUT seconds idle."""@@ -176,6 +180,9 @@ _i2v_pipe = None_extend_pipe = None_hq_pipe = None # TwoStageHQPipeline (Q8, res_2s + CFG, optional TeaCache)_hq_model_dir = None # remember which model the HQ pipe was built against+_a2v_pipe = None # A2VidPipelineTwoStage (Q8 dev + distilled LoRA stage 2)+_a2v_model_dir = None # which model the A2V pipe was built against+_a2v_lora_key: tuple | None = None # LoRA fingerprint for current A2V cache_pipe_lock = threading.Lock()@@ -201,11 +208,14 @@ _pipe_lock = threading.Lock()# 1.2× speedup with ~22% skip rate. Aggressive users can pass higher values# in the job spec (1.0 → ~2×, 1.5 → ~3× per the upstream comment)._EXTEND_TC_CONFIG: dict | None = None+_A2V_TC_CONFIG: dict | None = None # mirror gate for A2V (2026-05-18 PM)try:import ltx_pipelines_mlx.retake as _ltx_retake_mod+ import ltx_pipelines_mlx.a2vid_two_stage as _ltx_a2v_modfrom ltx_pipelines_mlx.ti2vid_two_stages import _build_teacache_controller as _build_stage1_teacache_orig_guided_denoise_loop_for_retake = _ltx_retake_mod.guided_denoise_loop+ _orig_guided_denoise_loop_for_a2v = _ltx_a2v_mod.guided_denoise_loopdef _guided_denoise_loop_with_extend_teacache(*args, teacache=None, **kwargs):cfg = _EXTEND_TC_CONFIG@@ -219,11 +229,30 @@ try:teacache = Nonereturn _orig_guided_denoise_loop_for_retake(*args, teacache=teacache, **kwargs)+ def _guided_denoise_loop_with_a2v_teacache(*args, teacache=None, **kwargs):+ # Mirror of the extend wrapper, scoped to the a2vid_two_stage import+ # site. A2V's Stage 1 is the same dev-transformer Euler loop the+ # standard two-stages pipeline runs (same calibration applies). The+ # distilled Stage 2 uses denoise_loop (no guidance) which we don't+ # touch — it's already fast and TeaCache wasn't designed for it.+ cfg = _A2V_TC_CONFIG+ if teacache is None and cfg and cfg.get("enable"):+ sigmas = kwargs.get("sigmas")+ n_steps = len(sigmas) - 1 if sigmas else cfg.get("num_steps", 10)+ try:+ teacache = _build_stage1_teacache(n_steps, cfg.get("thresh"))+ except Exception:+ teacache = None+ return _orig_guided_denoise_loop_for_a2v(*args, teacache=teacache, **kwargs)+_ltx_retake_mod.guided_denoise_loop = _guided_denoise_loop_with_extend_teacache+ _ltx_a2v_mod.guided_denoise_loop = _guided_denoise_loop_with_a2v_teacache_EXTEND_TC_PATCH_OK = True+ _A2V_TC_PATCH_OK = Trueexcept Exception as _tc_patch_exc:- print(f"[warm-helper] Extend TeaCache patch skipped: {_tc_patch_exc}", flush=True)+ print(f"[warm-helper] TeaCache patch skipped: {_tc_patch_exc}", flush=True)_EXTEND_TC_PATCH_OK = False+ _A2V_TC_PATCH_OK = Falsedef release_pipelines(keep_kind=None):@@ -234,10 +263,11 @@ def release_pipelines(keep_kind=None):family stays resident at a time — switching mode reloads, but rendersactually finish instead of getting SIGKILL'd by macOS.- keep_kind ∈ {'t2v', 'i2v', 'extend', 'hq', 'keyframe'} or None (free all).+ keep_kind ∈ {'t2v', 'i2v', 'extend', 'hq', 'keyframe', 'a2v'} or None (free all).Caller must hold _pipe_lock."""global _t2v_pipe, _i2v_pipe, _extend_pipe, _hq_pipe, _kf_pipe, _hq_model_dir, _kf_model_dir+ global _a2v_pipe, _a2v_model_dirglobal _gemma_lmtry:from ltx_core_mlx.utils.memory import aggressive_cleanup@@ -255,6 +285,8 @@ def release_pipelines(keep_kind=None):_hq_pipe = None; _hq_model_dir = None; freed.append("HQ")if keep_kind != "keyframe" and _kf_pipe is not None:_kf_pipe = None; _kf_model_dir = None; freed.append("Keyframe")+ if keep_kind != "a2v" and _a2v_pipe is not None:+ _a2v_pipe = None; _a2v_model_dir = None; freed.append("A2V")# Always free Gemma LanguageModel when releasing for any pipeline —# ~6 GB persistent that competes with the dev transformer's headroom.# Re-loaded on demand by the next enhance call (one-time ~10s cost).@@ -842,6 +874,60 @@ def get_kf_pipe(model_dir: str):return _kf_pipe+# Audio-to-Video (A2V) pipeline — drives video from an input audio waveform.+# Stage 1: Q8 dev transformer + CFG at half resolution, audio frozen.+# Stage 2: dev + distilled LoRA fused, refine video at full resolution.+# Image is OPTIONAL — passing it conditions frame 0 the same way I2V does, so+# the same pipeline serves both "pure A2V" (audio + prompt → video) and+# "Image + Audio" (audio + still + prompt → audio-driven video that opens on+# the reference frame). The upstream pipeline writes the original audio (not+# VAE-decoded) onto the final mp4, so no panel-side mux is needed.+def get_a2v_pipe(model_dir: str, loras: list[dict] | None = None):+ """Returns A2VidPipelineTwoStage lazily.++ A2V REQUIRES dev_transformer + distilled_lora at init time (same pattern+ as Keyframe). The pipeline inherits from TI2VidTwoStagesPipeline so LoRA+ fusion goes through the same `_pending_loras` hook the patched load()+ consumes. Cached on (model_dir, lora_fingerprint) so a LoRA swap or a+ model-dir flip rebuilds; otherwise reuses.+ """+ global _a2v_pipe, _a2v_model_dir, _a2v_lora_key+ from ltx_pipelines_mlx.a2vid_two_stage import A2VidPipelineTwoStage++ _install_lora_fusion_patches()+ _install_video_decoder_patch()+ fp = _lora_fingerprint(loras)++ try:+ from ltx_core_mlx.utils.memory import aggressive_cleanup as _ac+ except Exception:+ _ac = lambda: None+ with _pipe_lock:+ release_pipelines(keep_kind="a2v")+ if (_a2v_pipe is None+ or _a2v_model_dir != model_dir+ or _a2v_lora_key != fp):+ if _a2v_pipe is not None:+ why = "LoRA set changed" if _a2v_lora_key != fp else "model_dir changed"+ emit({"event": "log", "line": f"{why}; reloading A2V pipeline."})+ _a2v_pipe = None+ _ac()+ emit({"event": "log",+ "line": f"Loading A2V pipeline (Q8 dev + distilled LoRA — {model_dir})..."})+ _a2v_pipe = A2VidPipelineTwoStage(+ model_dir=model_dir,+ gemma_model_id=GEMMA_PATH,+ low_memory=LOW_MEMORY,+ dev_transformer="transformer-dev.safetensors",+ distilled_lora="ltx-2.3-22b-distilled-lora-384.safetensors",+ distilled_lora_strength=1.0,+ )+ _attach_loras(_a2v_pipe, loras)+ _a2v_model_dir = model_dir+ _a2v_lora_key = fp+ return _a2v_pipe++# ---- prompt enhancement (Gemma language model) ------------------------------# Separate from the pipeline's TextEncoder wrapper — same weights file, but# the LanguageModel class supports `.enhance_t2v(prompt, seed)` /@@ -1866,6 +1952,114 @@ for line in sys.__stdin__:_is_busy = Falsecontinue+ if action == "generate_a2v":+ # Audio-to-Video. Drives generation from an input audio waveform+ # plus prompt. Optional `image` conditions frame 0 (acts as I2V on+ # top of audio-driven generation). Pipeline writes the original+ # input audio onto the output mp4 — no panel-side mux needed.+ job_id = msg.get("id", "?")+ p = msg.get("params", {}) or {}+ model_dir = p.get("model_dir") or MODEL_ID+ seed = int(p.get("seed", -1))+ if seed == -1:+ seed = random.randint(0, 2**31 - 1)+ _is_busy = True+ try:+ t0 = time.time()+ configure_acceleration("off")+ audio_path = p.get("audio_path") or ""+ if not audio_path:+ raise RuntimeError("audio_path is required for A2V")+ if not os.path.exists(audio_path):+ raise RuntimeError(f"audio file not found: {audio_path}")+ num_frames = int(p["frames"])+ loras = p.get("loras") or []+ pipe = get_a2v_pipe(model_dir, loras=loras)+ _apply_vae_streaming_decision(num_frames)+ kwargs = dict(+ prompt=p["prompt"],+ output_path=p["output_path"],+ audio_path=audio_path,+ height=int(p["height"]),+ width=int(p["width"]),+ num_frames=num_frames,+ frame_rate=float(p.get("frame_rate", 24.0)),+ seed=seed,+ stage1_steps=int(p.get("stage1_steps", 20)),+ stage2_steps=int(p.get("stage2_steps", 3)),+ cfg_scale=float(p.get("cfg_scale", 3.0)),+ stg_scale=float(p.get("stg_scale", 1.0)),+ audio_start_time=float(p.get("audio_start_time", 0.0)),+ )+ # Optional reference image — when present, conditions frame 0+ # so the audio-driven generation opens on the user's still.+ ref_image = p.get("image") or None+ if ref_image:+ if not os.path.exists(ref_image):+ raise RuntimeError(f"reference image not found: {ref_image}")+ kwargs["image"] = ref_image+ # audio_max_duration defaults inside the pipeline to+ # num_frames / frame_rate when omitted. The form may pin a+ # tighter clamp (e.g. user dragged a 30 s mp3 but only wants 5 s).+ amd = p.get("audio_max_duration")+ if amd is not None:+ try:+ kwargs["audio_max_duration"] = float(amd)+ except (TypeError, ValueError):+ pass+ # TeaCache for A2V (2026-05-18 PM). The Stage-1 dev-Euler loop+ # is exactly what LTX2_TEACACHE_COEFFICIENTS was calibrated for —+ # same model, same scheduler, same sigma layout. Default ON;+ # opt-out via job spec `enable_teacache=false`. The wrapper at+ # the top of this file reads _A2V_TC_CONFIG and constructs a+ # controller; we clear it in `finally` so a future non-a2v+ # call doesn't inherit a stale state.+ enable_tc = bool(p.get("enable_teacache", True)) and _A2V_TC_PATCH_OK+ tc_thresh = p.get("teacache_thresh")+ if tc_thresh is not None:+ try:+ tc_thresh = float(tc_thresh)+ except (TypeError, ValueError):+ tc_thresh = None+ _A2V_TC_CONFIG = {+ "enable": enable_tc,+ "thresh": tc_thresh,+ "num_steps": kwargs["stage1_steps"],+ }+ if enable_tc:+ emit({"event": "log",+ "line": f"TeaCache active on A2V Stage 1 (thresh={tc_thresh if tc_thresh is not None else 'default 0.5'})."})+ emit({+ "event": "log",+ "line": (+ f"step:generate_a2v {kwargs['width']}x{kwargs['height']} "+ f"{kwargs['num_frames']}f @{kwargs['frame_rate']:.1f}fps "+ f"stage1={kwargs['stage1_steps']} stage2={kwargs['stage2_steps']} "+ f"cfg={kwargs['cfg_scale']} audio={os.path.basename(audio_path)}"+ f"{' image=' + os.path.basename(ref_image) if ref_image else ''}"+ ),+ })+ with _override_default_negative_prompt(p.get("negative_prompt")) as neg_active:+ if neg_active:+ emit({"event": "log", "line": "Avoid terms active via native CFG negative prompt."})+ kwargs = _filter_unsupported_kwargs(pipe.generate_and_save, kwargs)+ out_path = pipe.generate_and_save(**kwargs)+ elapsed = round(time.time() - t0, 2)+ _last_activity = time.time()+ emit({+ "event": "done", "id": job_id,+ "output": str(out_path), "elapsed_sec": elapsed,+ "seed_used": seed,+ })+ except Exception as exc:+ _last_activity = time.time()+ emit({"event": "error", "id": job_id, "error": str(exc), "trace": traceback.format_exc()})+ finally:+ # Clear so the next non-A2V action doesn't inherit a stale gate.+ _A2V_TC_CONFIG = None+ _is_busy = False+ continue+if action == "enhance_prompt":# Gemma-driven prompt rewriting. Same model file as the pipeline's# text encoder, but loaded as a `GemmaLanguageModel` (the wrapper