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
fix: align lyric words to the vocal stem with CTC (#10611)
[._.]/ Adam Eivyef2920c9200d
diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsxindex ed889da822..36752fb3c9 100644--- a/client/src/components/musicVideo/LyricsPanel.jsx+++ b/client/src/components/musicVideo/LyricsPanel.jsx@@ -1,5 +1,6 @@import { useRef, useState } from 'react';import { ListMusic, Plus, Trash2, Upload } from 'lucide-react';+import Modal from '../ui/Modal.jsx';import { lyricSetupState } from '../../lib/musicVideoStages.js';// Client-minted ids keep a freshly added row addressable across saves without@@ -163,6 +164,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imconst [importFormat, setImportFormat] = useState('auto');const [importMode, setImportMode] = useState('replace');const [alignError, setAlignError] = useState('');+ const [separationConsent, setSeparationConsent] = useState(null);const timedCount = cues.filter((c) => typeof c.startSec === 'number').length;const hasAudio = Boolean(project.trackId || project.uploadedAudioFilename);@@ -186,10 +188,15 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imonImport({ text: importText, format: importFormat, mode: importMode }, () => setImportText(''));};- const runAlign = (cueId) => {+ const runAlign = (cueId, separateVocals = false) => {if (!onAlign || aligning) return;+ if (!project.vocalStemFilename && !separateVocals) {+ setSeparationConsent({ cueId });+ return;+ }+ setSeparationConsent(null);setAlignError('');- Promise.resolve(onAlign(cueId)).catch((err) => {+ Promise.resolve(separateVocals ? onAlign(cueId, { separateVocals: true }) : onAlign(cueId)).catch((err) => {setAlignError(err?.message || 'Could not align the words to the vocal. Try Align words again.');});};@@ -200,6 +207,19 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im};return (+ <>+ {separationConsent && (+ <Modal open onClose={() => setSeparationConsent(null)} size="sm" ariaLabel="Separate vocals before alignment">+ <div className="p-4 space-y-3">+ <h3 className="font-medium text-port-text">Separate vocals before alignment</h3>+ <p className="text-sm text-port-text-muted">Use local Demucs htdemucs_ft to create a vocal stem, then align your lyrics with MMS_FA. The first run installs their private Python environments and downloads model weights. Your audio stays on this machine.</p>+ <div className="flex flex-wrap justify-end gap-2">+ <button type="button" className="min-h-[44px] px-3 text-port-text-muted" onClick={() => setSeparationConsent(null)}>Cancel</button>+ <button type="button" className="min-h-[44px] px-3 rounded bg-port-accent text-white" onClick={() => runAlign(separationConsent.cueId, true)}>Separate and align</button>+ </div>+ </div>+ </Modal>+ )}<Shell className="mt-2 bg-port-bg border border-port-border rounded-lg p-2 text-xs"><Heading className={`${inline ? '' : 'cursor-pointer select-none '}text-port-text-muted min-h-[44px] sm:min-h-0 flex flex-wrap items-center gap-x-1`}>Lyrics & phrases — {cues.length} line{cues.length === 1 ? '' : 's'} ({timedCount} timed)@@ -264,7 +284,7 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im<span className="flex items-center gap-2">{onAlign && (<button type="button" onClick={() => runAlign()} disabled={aligning || cues.length === 0 || !hasAudio}- title={hasAudio ? 'Align each word to the vocal with local whisper.cpp (the first run downloads a 1.6 GB model)' : 'Attach a song before aligning words'}+ title={hasAudio ? 'Align the known lyrics to the vocal with local MMS_FA (model weights download on first use)' : 'Attach a song before aligning words'}className="min-h-[44px] sm:min-h-0 text-port-accent disabled:opacity-50">{aligning ? 'Aligning…' : 'Align words'}</button>@@ -344,5 +364,6 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im</section></div></Shell>+ </>);}diff --git a/client/src/components/musicVideo/LyricsPanel.test.jsx b/client/src/components/musicVideo/LyricsPanel.test.jsxindex 7dd8596257..b81306bfe9 100644--- a/client/src/components/musicVideo/LyricsPanel.test.jsx+++ b/client/src/components/musicVideo/LyricsPanel.test.jsx@@ -5,6 +5,7 @@ import LyricsPanel from './LyricsPanel.jsx';const PROJECT = {id: 'mv-1',trackId: 't1',+ vocalStemFilename: 'vocal.wav',lyricCues: [{id: 'lc-1',text: 'walking home',@@ -59,6 +60,18 @@ describe('LyricsPanel word alignment', () => {expect(await screen.findByRole('alert')).toHaveTextContent(/Settings → Voice/);});+ it('requires named model consent before separating a missing stem, and supports declining', () => {+ const { onAlign } = renderPanel({ project: { ...PROJECT, vocalStemFilename: null } });+ fireEvent.click(screen.getByRole('button', { name: 'Align words' }));+ expect(onAlign).not.toHaveBeenCalled();+ expect(screen.getByText(/Demucs htdemucs_ft/)).toHaveTextContent('MMS_FA');+ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }));+ expect(onAlign).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Re-align line 1' }));+ fireEvent.click(screen.getByRole('button', { name: 'Separate and align' }));+ expect(onAlign).toHaveBeenCalledWith('lc-1', { separateVocals: true });+ });+it('flags only measured low confidence, and clears the badge data when the lyric text changes', () => {const cues = [{ ...PROJECT.lyricCues[0], matched: 0.4 },diff --git a/client/src/hooks/useMusicVideoLyricAlign.js b/client/src/hooks/useMusicVideoLyricAlign.jsindex d6a473c48d..04e8b501f4 100644--- a/client/src/hooks/useMusicVideoLyricAlign.js+++ b/client/src/hooks/useMusicVideoLyricAlign.js@@ -10,6 +10,10 @@ import {/** Human label for the alignment job's current progress frame. */export function lyricAlignStageLabel(frame) {switch (frame?.stage) {+ case 'installing': return frame.detail || 'Installing the alignment runtime…';+ case 'separating': return 'Separating vocals with Demucs…';+ case 'emissions': return 'Reading the vocal with MMS_FA…';+ case 'aligning': return 'Aligning the lyric text with CTC…';case 'decoding': return 'Decoding the song…';case 'loading-model': return 'Loading the speech model…';case 'downloading-model': return 'Downloading the speech model (first run only)…';@@ -36,7 +40,7 @@ export default function useMusicVideoLyricAlign({ onAligned } = {}) {if (pending) fn(pending);};const slot = useSseJobSlot({- startRequest: ({ projectId, cueId }) => alignMusicVideoLyrics(projectId, cueId ? { cueId } : {}, { silent: true }),+ startRequest: ({ projectId, cueId, separateVocals }) => alignMusicVideoLyrics(projectId, { ...(cueId ? { cueId } : {}), ...(separateVocals ? { separateVocals: true } : {}) }, { silent: true }),eventsUrl: musicVideoLyricAlignEventsUrl,cancelRequest: cancelMusicVideoLyricAlign,onComplete: (frame, { projectId, cueId }) => {@@ -67,10 +71,10 @@ export default function useMusicVideoLyricAlign({ onAligned } = {}) {}, [slot.active]);useEffect(() => () => settle((pending) => pending.resolve(null)), []);- const run = (projectId, cueId = null) => new Promise((resolve, reject) => {+ const run = (projectId, cueId = null, { separateVocals = false } = {}) => new Promise((resolve, reject) => {if (slot.active) { resolve(null); return; }waiter.current = { resolve, reject, started: false };- slot.start({ projectId, cueId });+ slot.start({ projectId, cueId, ...(separateVocals ? { separateVocals } : {}) });});return {diff --git a/client/src/hooks/useMusicVideoLyricAlign.test.jsx b/client/src/hooks/useMusicVideoLyricAlign.test.jsxindex 93321f319c..36592ac504 100644--- a/client/src/hooks/useMusicVideoLyricAlign.test.jsx+++ b/client/src/hooks/useMusicVideoLyricAlign.test.jsx@@ -37,8 +37,8 @@ describe('useMusicVideoLyricAlign', () => {it('rejects run() with the server message so the panel can show it', async () => {const { result } = renderHook(() => useMusicVideoLyricAlign());let outcome;- await act(async () => { outcome = result.current.run('p-1', 'lc-1'); });- expect(alignMusicVideoLyrics).toHaveBeenCalledWith('p-1', { cueId: 'lc-1' }, { silent: true });+ await act(async () => { outcome = result.current.run('p-1', 'lc-1', { separateVocals: true }); });+ expect(alignMusicVideoLyrics).toHaveBeenCalledWith('p-1', { cueId: 'lc-1', separateVocals: true }, { silent: true });const failed = expect(outcome).rejects.toThrow('whisper missing');act(() => { lastEventSource().emit({ type: 'error', error: 'whisper missing' }); });await failed;diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 389f5181df..029de65cde 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -782,7 +782,7 @@ export default function MusicVideo() {};// Alignment is a click, never an import side effect. The panel shows the// whisper setup error itself, so this request stays silent.- const handleAlignLyrics = (cueId) => lyricAlign.run(selected.id, cueId);+ const handleAlignLyrics = (cueId, options) => lyricAlign.run(selected.id, cueId, options);// The slot is page-wide but the job belongs to one project: only that// project's Setup shows "Aligning…".const aligningLyrics = Boolean(lyricAlign.active && selected && lyricAlign.context?.projectId === selected.id);diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex d4b800dfa7..3cbb1d5d9d 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -1617,13 +1617,13 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {{ w: 'home', startSec: 1, endSec: 1.5, conf: 'interpolated' },],}];- await openProject({ ...PROJECT_ANALYZED, lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] }, 'setup');+ await openProject({ ...PROJECT_ANALYZED, vocalStemFilename: 'stem.wav', lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] }, 'setup');expect(alignMusicVideoLyrics).not.toHaveBeenCalled();alignMusicVideoLyrics.mockResolvedValue({ jobId: 'align-job-1' });fireEvent.click(screen.getByRole('button', { name: 'Align words' }));await waitFor(() => expect(alignMusicVideoLyrics).toHaveBeenCalledWith('mv-3', {}, { silent: true }));await settle();- sseState.latest = { type: 'complete', project: { id: 'mv-3', lyricCues: cues, updatedAt: 't' } };+ sseState.latest = { type: 'complete', project: { id: 'mv-3', vocalStemFilename: 'stem.wav', lyricCues: cues, updatedAt: 't' } };forceRerender();expect(await screen.findByText('walking')).toHaveClass('text-port-accent');expect(screen.getByText('home')).toHaveClass('text-port-warning');diff --git a/docs/features/product-surfaces.md b/docs/features/product-surfaces.mdindex 8d4c2832f7..796692cc6e 100644--- a/docs/features/product-surfaces.md+++ b/docs/features/product-surfaces.md@@ -110,7 +110,7 @@ An end-to-end creative production suite for authors, worldbuilders, filmmakers,| **SongBook** | `/songbook` | Interactive chord charts, guitar tablature, lyric repertoire, and auto-scrolling practice sheet music. | — || **Creative Director** | `/creative-director` | Multi-scene episodic video production orchestrator: turn briefs into treatments, storyboards, render plans, and completed episodes. | — || **Creative Commissions** | `/creative-commission` | Standing briefs and scheduled/nightly autonomous media generation aligning with personal taste profiles and feedback. A universe and/or mood board can be picked as the style source: each run loads its style tags and reference images as the Creative Director's art-direction base, attaches those images to vision scene evaluation, and conditions local image renders on them. | — |-| **Music Video Studio** | `/music-video` | A project is six deep-linked steps (`/music-video/:projectId/:stage` — Song `setup`, Look `cast-sets`, Storyboard `board`, Make `produce`, Final render `review`, Publish `publish`; an old `compose` link opens Make), listed down the left with a state word and one fact each (a bottom icon bar on a phone). Each step opens with what "done" means and an always-visible checklist, and ends with its own approval (art on Look, the timed storyboard on Storyboard; an animated proof on Make is optional and never holds the final render). Approvals never require typed notes. A sticky header gives one status line ("Step 3 of 6: Storyboard needs you"), the one next action, an Autopilot button, paid-generation spend against the cap and **Project settings** — a drawer holding the render style and services, advanced audio tools, the autopilot brief and runs, and every development file, the external handoff and the making-of export; a **Needs attention** banner under that status line lists any state a half-finished workflow left on the server — an open revision, an interrupted Cast & Sets stage, an auto-review waiting for its revised sections, a final render nobody is watching — with its Resume / Continue / Cancel / Reattach inline, derived from the saved record so it survives a reload; a preview player is docked beside every step — the final render, the live composition document, each finished draft excerpt and, before anything is rendered, a storyboard animatic (the song under each shot's frame or card), picked from the dock (`?play=`) — and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns every word with local whisper.cpp (large-v3-turbo, downloaded on first use), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A run started from the board generates its revised sections on the server too (#10014), routed from the project's saved image and video pins, so it completes with no tab open; a section that cannot be generated unattended (a synchronous image backend, a clip lane only the board can submit) parks the run as needing the director, with the reason named. A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News, Substack, DistroKid) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — |+| **Music Video Studio** | `/music-video` | A project is six deep-linked steps (`/music-video/:projectId/:stage` — Song `setup`, Look `cast-sets`, Storyboard `board`, Make `produce`, Final render `review`, Publish `publish`; an old `compose` link opens Make), listed down the left with a state word and one fact each (a bottom icon bar on a phone). Each step opens with what "done" means and an always-visible checklist, and ends with its own approval (art on Look, the timed storyboard on Storyboard; an animated proof on Make is optional and never holds the final render). Approvals never require typed notes. A sticky header gives one status line ("Step 3 of 6: Storyboard needs you"), the one next action, an Autopilot button, paid-generation spend against the cap and **Project settings** — a drawer holding the render style and services, advanced audio tools, the autopilot brief and runs, and every development file, the external handoff and the making-of export; a **Needs attention** banner under that status line lists any state a half-finished workflow left on the server — an open revision, an interrupted Cast & Sets stage, an auto-review waiting for its revised sections, a final render nobody is watching — with its Resume / Continue / Cancel / Reattach inline, derived from the saved record so it survives a reload; a preview player is docked beside every step — the final render, the live composition document, each finished draft excerpt and, before anything is rendered, a storyboard animatic (the song under each shot's frame or card), picked from the dock (`?play=`) — and scene cards seek it. Audio-reactive video creation, beat-detection synchronization, scene choreography, tempo alignment, and audience-driven pre-production treatments that direct each shot. Scenes are cutaways or lip-synced performance shots; a performance shot renders only on a verified source-audio provider (fal.ai MiniMax H3 lip-sync, 5–14.8s song slices placed at an exact edit in-point, cut from an optional full-length vocal stem when one is attached — uploaded, or separated from the song with a locally installed demucs) — Grok video is cutaway-only. The autopilot kickoff analyzes the song, imports the linked track's lyric sheet (its `[Verse]`/`[Chorus]` headers and stage directions kept as lyric markers that name the analysis sections and steer shot framing), separates the vocal, aligns the known lyrics to the vocal stem with local MMS_FA CTC (downloaded on first use, a garbage token between lines absorbs instrumental gaps; standalone alignment asks for Demucs htdemucs_ft consent before creating a missing stem), builds a Cast & Sets check-in (one creative-direction call that interprets the song, then a canonical character sheet, expression and looks sheets, one empty plate per set and in-set tests on the image queue, each later image conditioned on the character sheet; assembled into a self-contained sheet saved as a development artifact), stops for the director's review unless the brief auto-approves it, then plans against the approved references. Development artifacts (check-in sheets, animatics, treatments, storyboards; HTML/Markdown/MP4/PNG/JPG) are versioned per project, reviewed with notes and approve/request-changes, and viewed in a sandboxed viewer at `/music-video/:projectId/:stage/dev/:artifactId` (the stage-less `/music-video/:projectId/dev/:artifactId` still opens it). Draft excerpts are reviewed and selectively revised by hand, or by an opt-in auto-review run bounded by director-set review and paid-generation limits (a frame-only look never passes motion or audio sync). A run started from the board generates its revised sections on the server too (#10014), routed from the project's saved image and video pins, so it completes with no tab open; a section that cannot be generated unattended (a synchronous image backend, a clip lane only the board can submit) parks the run as needing the director, with the reason named. A server-owned production run (`/api/music-video/:id/production-runs`, #9066) plans an empty board, generates missing frames and clips only on a director-allowed image/video provider+model pool, hands the continuous draft to auto-review and dispatches its revisions — within explicit generation, review and (priced routes only) dollar limits, without the browser open, and never resuming on its own after a restart; the song is the sole audio unless a sound-design bed is explicitly chosen to mix under it. A footage or composed render can intercut (#9290): shots are re-cut on the song's section energy (every 2 beats in the loudest quarter, up to every 8 in the quietest) and on sung word onsets, alternating the host shot — a lip-synced take stays in sync — with unshown footage from a cutaway in the same section, so the edit gets faster without generating more clips; an autopilot production run defaults to it unless the director chose one cut per shot. Lyric lines sung two or more times are hooks: the treatment's text cues give them a word-by-word build (#9291) — each word lands on its sung onset in heavy caps, the newest in the accent color. Draft excerpts can be re-framed as vertical or square social cuts with faded audio edges, from suggested hook windows (#9280). The **Autonomous** entry point (`docs/features/music-video-autonomous.md`) starts from one prompt instead of a chosen track: it writes the brief, lyrics and a mood board, makes the song in Suno through the PortOS Browser, and runs the production — with optional approval checkpoints, and a `music-video-autopilot` scheduled task that turns unused Brain ideas into videos. The Publish stage (#9281) builds a release kit from the final render: an X-sized 1080p, a 720p preview, a hook teaser, thumbnail candidates, lyric captions (SRT) and YouTube chapters. It also drafts every platform's copy in one director-triggered provider call from their own making-of notes, and every field stays editable. Posting (#9282) fills each platform's post (YouTube, Suno, an X thread, Shorts, TikTok, Instagram Reels, Reddit, Stacker News, Substack, DistroKid) in a new PortOS Browser tab with the director's signed-in sessions, shows a screenshot and summary of the filled draft, and posts only when the director presses Post for that draft; the posted links are kept on the project. Reddit defaults to a native video post in r/aivideo — title and flair, no body — through the new composer's own Video button (#9307). Platforms are opt-in (#9287): a "Where you post" list turns each one on (all start off) and optionally names the account posted as — X and Reddit drafts filled while signed in as someone else are refused. Copy is drafted and posts are offered only for enabled platforms. Each post (including one recorded by hand) can be rated good, mixed or poor with notes; ratings roll up per platform across projects and are passed to later copy drafts. | — || **Sharing & Conflict Resolution** | `/sharing`, `/sharing/duplicates`, `/sharing/conflicts` | Collaborative asset exchange via cloud storage buckets (Google Drive, Dropbox, iCloud, Syncthing) with duplicate reconciliation and conflict recovery journals. | — |---diff --git a/scripts/align_lyrics_ctc.py b/scripts/align_lyrics_ctc.pynew file mode 100644index 0000000000..40008206bf--- /dev/null+++ b/scripts/align_lyrics_ctc.py@@ -0,0 +1,121 @@+#!/usr/bin/env python3+"""MMS_FA emissions + one CTC Viterbi pass, with garbage between lyric lines.++Only this CLI invocation loads/downloads weights. Input is ffmpeg's 16 kHz+mono PCM and a JSON array of word arrays; output keeps those exact word slots.+Torchaudio 2.8 is pinned by the caller because 2.9 removed forced_align.+"""+import argparse+import json+import sys+import unicodedata+import wave++SAMPLE_RATE = 16000+HOP = 320+RECEPTIVE_FIELD = 400+CHUNK_FRAMES = 1000 # 20 s; bound transformer attention memory on long songs.+CONTEXT_FRAMES = 50+++def targets_for_lines(lines, dictionary):+ tokens = [dictionary['*']]+ slots = []+ for line in lines:+ for word in line:+ normalized = ''.join(c for c in unicodedata.normalize('NFKD', word.lower())+ if not unicodedata.combining(c))+ chars = [c for c in normalized if c.isalpha() or c.isdigit()]+ if not chars or any(c not in dictionary for c in chars):+ raise ValueError('Spell lyric numbers out and use MMS_FA supported letters.')+ start = len(tokens)+ tokens.extend(dictionary[c] for c in chars)+ slots.append((start, len(tokens), word))+ # A star may absorb silence, instrumental gaps, or untranscribed vocals.+ if tokens[-1] != dictionary['*']:+ tokens.append(dictionary['*'])+ if not slots:+ raise ValueError('No lyric words to align.')+ return tokens, slots+++def word_times(lines, slots, spans, frame_sec):+ words = []+ for start, end, original in slots:+ words.append({'w': original, 'startSec': round(spans[start].start * frame_sec, 3),+ 'endSec': round(spans[end - 1].end * frame_sec, 3)})+ result, cursor = [], 0+ for line in lines:+ result.append(words[cursor:cursor + len(line)])+ cursor += len(line)+ return result+++def emissions_for_audio(model, waveform, torch, device):+ # Every inference crop starts on the encoder's global 320-sample grid.+ # Keep only owned frames, with 1 s of context on each side. Concatenation+ # preserves the song clock; alignment itself is never split into windows.+ frame_count = (waveform.shape[-1] - RECEPTIVE_FIELD) // HOP + 1+ if frame_count <= 0:+ raise ValueError('The vocal is too short to align.')+ chunks = []+ for first in range(0, frame_count, CHUNK_FRAMES):+ last = min(frame_count, first + CHUNK_FRAMES)+ left = max(0, first - CONTEXT_FRAMES)+ right = min(frame_count, last + CONTEXT_FRAMES)+ crop = waveform[:, left * HOP:(right - 1) * HOP + RECEPTIVE_FIELD]+ emission, _ = model(crop.to(device))+ chunks.append(emission[:, first - left:last - left].cpu())+ print(f'PROGRESS:emissions:{round(last / frame_count * 100)}', flush=True)+ return torch.cat(chunks, dim=1)+++def align(audio, lines):+ import torch+ import torchaudio+ from torchaudio import functional as F++ with wave.open(audio, 'rb') as source:+ if source.getframerate() != SAMPLE_RATE or source.getnchannels() != 1 or source.getsampwidth() != 2:+ raise ValueError('Expected 16 kHz mono PCM16 WAV.')+ waveform = torch.frombuffer(bytearray(source.readframes(source.getnframes())), dtype=torch.int16)+ waveform = waveform.to(torch.float32).unsqueeze(0) / 32768+ bundle = torchaudio.pipelines.MMS_FA+ dictionary = bundle.get_dict()+ tokens, slots = targets_for_lines(lines, dictionary)+ # CPU is the portable default; CUDA when present. forced_align runs on CPU+ # after bounded inference, so unsupported accelerator alignment is avoided.+ device = 'cuda' if torch.cuda.is_available() else 'cpu'+ print('PROGRESS:loading-model', flush=True)+ model = bundle.get_model().to(device).eval()+ with torch.inference_mode():+ emission = emissions_for_audio(model, waveform, torch, device)+ print('PROGRESS:aligning', flush=True)+ targets = torch.tensor([tokens], dtype=torch.int64)+ path, scores = F.forced_align(emission, targets, blank=0)+ spans = F.merge_tokens(path[0], scores[0].exp())+ if [span.token for span in spans] != tokens:+ raise ValueError('CTC alignment did not preserve the transcript.')+ return word_times(lines, slots, spans, HOP / SAMPLE_RATE)+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument('--audio', required=True)+ parser.add_argument('--lyrics', required=True)+ parser.add_argument('--output', required=True)+ args = parser.parse_args()+ with open(args.lyrics, encoding='utf-8') as source:+ lines = json.load(source)+ result = align(args.audio, lines)+ with open(args.output, 'w', encoding='utf-8') as output:+ json.dump(result, output, ensure_ascii=False)+++if __name__ == '__main__':+ try:+ main()+ except Exception:+ # Never print the transcript, project paths, or a private traceback.+ print('MMS_FA alignment failed; check runtime, lyric alphabet and audio.', file=sys.stderr)+ sys.exit(1)diff --git a/scripts/align_lyrics_ctc.test.js b/scripts/align_lyrics_ctc.test.jsnew file mode 100644index 0000000000..98da511e85--- /dev/null+++ b/scripts/align_lyrics_ctc.test.js@@ -0,0 +1,13 @@+// Exercises align_lyrics_ctc.py via its dependency-free Python boundary tests.+import { describe, expect, it } from 'vitest';+import { execFileSync } from 'node:child_process';+import { fileURLToPath } from 'node:url';+import { resolveTestPython, PY_TEST_TIMEOUT_MS, PY_SUBPROCESS_TIMEOUT_MS } from '../server/lib/testHelper.js';++const python = resolveTestPython();+describe.skipIf(!python)('CTC Python transcript and emission clock', () => {+ it('runs the production boundary checks without downloading a model', () => {+ expect(() => execFileSync(python, [fileURLToPath(new URL('./align_lyrics_ctc_test.py', import.meta.url))],+ { timeout: PY_SUBPROCESS_TIMEOUT_MS, stdio: 'pipe', env: { ...process.env, PYTHONDONTWRITEBYTECODE: '1' } })).not.toThrow();+ }, PY_TEST_TIMEOUT_MS);+});diff --git a/scripts/align_lyrics_ctc_test.py b/scripts/align_lyrics_ctc_test.pynew file mode 100644index 0000000000..6db92c9684--- /dev/null+++ b/scripts/align_lyrics_ctc_test.py@@ -0,0 +1,52 @@+"""Dependency-free checks of the production CTC transcript/timebase boundary."""+import unittest+from types import SimpleNamespace+from align_lyrics_ctc import targets_for_lines, word_times, emissions_for_audio, HOP, RECEPTIVE_FIELD+++class Tensor:+ def __init__(self, start, frames):+ self.start, self.frames = start, frames+ self.shape = (1, frames)++ def __getitem__(self, key):+ crop = key[1]+ return Tensor(self.start + crop.start, crop.stop - crop.start)++ def to(self, device):+ return self++ def cpu(self):+ return self+++class CtcContract(unittest.TestCase):+ def test_garbage_and_slots_preserve_punctuation_accents_repeated_letters_and_occurrences(self):+ dictionary = {char: i for i, char in enumerate('-*abcdefghijklmnopqrstuvwxyz')}+ lines = [['Hello,', 'café!'], ['Hello,'], []]+ targets, slots = targets_for_lines(lines, dictionary)+ self.assertEqual([i for i, token in enumerate(targets) if token == dictionary['*']], [0, 10, 16])+ self.assertEqual([word for _, _, word in slots], ['Hello,', 'café!', 'Hello,'])+ spans = [SimpleNamespace(start=i * 3, end=i * 3 + 2) for i in range(len(targets))]+ result = word_times(lines, slots, spans, 0.02)+ self.assertEqual(result[0][0], {'w': 'Hello,', 'startSec': 0.06, 'endSec': 0.34})+ self.assertEqual(result[1][0]['startSec'], 0.66)+ self.assertEqual(result[2], [])+ with self.assertRaises(ValueError):+ targets_for_lines([['123']], dictionary)++ def test_emission_chunks_keep_every_global_frame_once_across_context_seams(self):+ frames = 2055+ waveform = Tensor(0, (frames - 1) * HOP + RECEPTIVE_FIELD)+ def model(crop):+ self.assertEqual(crop.start % HOP, 0)+ return Tensor(crop.start // HOP, (crop.frames - RECEPTIVE_FIELD) // HOP + 1), None+ class Torch:+ @staticmethod+ def cat(chunks, dim):+ return [chunk.start + i for chunk in chunks for i in range(chunk.frames)]+ self.assertEqual(emissions_for_audio(model, waveform, Torch, 'cpu'), list(range(frames)))+++if __name__ == '__main__':+ unittest.main()diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 67a03829cf..d6d78c3434 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -332,6 +332,7 @@ export const musicVideoLyricsImportTrackSchema = z.object({// that line; omitted, every line is aligned.export const musicVideoLyricsAlignSchema = z.object({cueId: z.string().min(1).max(64).optional(),+ separateVocals: z.boolean().optional(),}).strict();// ---- Composition manifest (#8984, part of #8966) ---------------------------diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex 1b771b84bb..b3b6236f55 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -516,11 +516,11 @@ router.post('/:id/lyrics/import-track', asyncHandler(async (req, res) => {// transcribing window n/m) stream over SSE with cancel, and the terminal// `complete` frame carries the updated project. One job per project: a second// request returns the running job (`reused: true`). The first alignment-// downloads the music-grade whisper model; no whisper.cpp at all is an error-// frame with install steps, not an empty timing list.+// provisions MMS_FA only on demand. Explicit separateVocals consent creates+// a missing stem with Demucs first; older master-only callers retain Whisper.router.post('/:id/lyrics/align', asyncHandler(async (req, res) => {- const { cueId } = validateRequest(musicVideoLyricsAlignSchema, req.body || {});- res.status(202).json(await startLyricAlign(req.params.id, { cueId }));+ const { cueId, separateVocals } = validateRequest(musicVideoLyricsAlignSchema, req.body || {});+ res.status(202).json(await startLyricAlign(req.params.id, { cueId, separateVocals }));}));router.get('/lyrics/align/:jobId/events', (req, res) => {diff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 4c9440737b..e7e4658de4 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -492,7 +492,7 @@ describe('musicVideo routes', () => {svc.getProject.mockResolvedValue(alignable);expect(alignProjectLyrics).not.toHaveBeenCalled();const release = holdAlignment();- const first = await request(app).post('/api/music-video/mv-1/lyrics/align').send({});+ const first = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ separateVocals: true });expect(first.status).toBe(202);expect(first.body.jobId).toEqual(expect.any(String));expect(first.body.reused).toBeUndefined();@@ -500,7 +500,7 @@ describe('musicVideo routes', () => {expect(second.status).toBe(202);expect(second.body).toEqual({ jobId: first.body.jobId, reused: true });expect(alignProjectLyrics).toHaveBeenCalledTimes(1);- expect(alignProjectLyrics).toHaveBeenCalledWith('mv-1', expect.objectContaining({ cueId: null }));+ expect(alignProjectLyrics).toHaveBeenCalledWith('mv-1', expect.objectContaining({ cueId: null, separateVocals: true }));const active = await request(app).get('/api/music-video/mv-1/active-jobs');expect(active.body).toEqual({ alignment: first.body.jobId, separation: null, midi: null });release();diff --git a/server/routes/musicVideoVocalStem.test.js b/server/routes/musicVideoVocalStem.test.jsindex d926996948..7c88f4aad4 100644--- a/server/routes/musicVideoVocalStem.test.js+++ b/server/routes/musicVideoVocalStem.test.js@@ -35,6 +35,7 @@ vi.mock('../lib/cudaCapability.js', async (importOriginal) => ({const { default: musicVideoRoutes } = await import('./musicVideo.js');const projects = await import('../services/musicVideo/projects.js');const { runStreamingCommand } = await import('../lib/streamingSpawn.js');+const { separateProjectVocals } = await import('../services/musicVideo/vocalSeparation.js');const { findFfmpeg } = await import('../lib/ffmpeg.js');const app = express();@@ -206,6 +207,20 @@ describe.skipIf(!ffmpeg)('music-video vocal separation', () => {expect(libraryFiles()).toEqual(before);}, 20000);+ it('shares one separation between concurrent alignment callers and propagates attachment failures', async () => {+ const calls = demucsDouble();+ const onProgress = vi.fn();+ const [first, second] = await Promise.all([+ separateProjectVocals(project.id, { onProgress }), separateProjectVocals(project.id),+ ]);+ expect(first.vocalStemFilename).toBe(second.vocalStemFilename);+ expect((await projects.getProject(project.id)).vocalStemFilename).toBe(first.vocalStemFilename);+ expect(calls.filter((argv) => argv[2] === 'demucs')).toHaveLength(1);+ expect(onProgress).toHaveBeenCalledWith(expect.objectContaining({ stage: 'attaching' }));+ demucsDouble({ stemSeconds: 5 });+ await expect(separateProjectVocals(project.id)).rejects.toMatchObject({ code: 'MUSIC_VIDEO_VOCAL_STEM_TIMEBASE' });+ }, 20000);+it('404s for a missing project and 400s for a project with no song, before any job starts', async () => {demucsDouble();const missing = await request(app).post('/api/music-video/mv-missing/vocal-stem/separate').send({});diff --git a/server/services/musicVideo/lyricAlign.js b/server/services/musicVideo/lyricAlign.jsindex 127b6ccec0..b52b91f967 100644--- a/server/services/musicVideo/lyricAlign.js+++ b/server/services/musicVideo/lyricAlign.js@@ -1,17 +1,7 @@/**- * Music Video word-level lyric alignment (#9074).- *- * Runs when the director clicks Align words (or a line's Re-align), or as a- * step of an autopilot run the director started. ffmpeg decodes the audio to- * 16 kHz mono PCM; a whisper runner (lyricTranscriber.js — whisper-cli with a- * music-grade model, the voice STT endpoint, or a temporary whisper-server)- * returns word timings, and those timings are aligned to the director's- * spelling. With a vocal stem attached, its phrases anchor short mix windows- * so post-silence words cannot drift back into the instrumental gap. A line- * the singer skipped stays inside its own window- * and does not move the lines around it. Times the director already set are- * kept. A whole-song alignment also names the analysis sections after the- * lyric sheet's `[Verse]`/`[Chorus]` headers (lyricMarkers.js).+ * User-triggered lyric alignment. Vocal stems use known-text MMS_FA CTC;+ * legacy master-only callers retain Whisper until they consent to separation.+ * No models load at boot. Director cue boundaries and concurrent edits survive.*/import { mkdtemp, readFile, rm } from 'fs/promises';@@ -24,11 +14,7 @@ import { getProject, updateProject } from './projects.js';import {alignDirectorWords,lyricAlignFfmpegArgs,- dropNonLyricWords,mergeTranscripts,- detectVocalPhrases,- phraseWindows,- snapLineStarts,vocalPcm,wavDurationSec,pickAlignmentPath,@@ -79,9 +65,9 @@ function relabeledAnalysis(project, cues) {}/**- * Align one project's lyric cues. `cueId` re-aligns that line only: a line- * with a window is transcribed on its own slice; a line without one is placed- * against the full vocal so a repeated chorus keeps its own occurrence.+ * Align one project's lyric cues. `cueId` re-aligns that line only: a timed+ * line uses its own slice; an untimed line uses full-song CTC context so a+ * repeated chorus keeps its own occurrence.*/export async function alignProjectLyrics(projectId, options = {}) {const onProgress = options.onProgress || (() => {});@@ -94,10 +80,12 @@ export async function alignProjectLyrics(projectId, options = {}) {resolveAudio: pickAlignmentPath,decodeAudio: decodeSourceToWav,resolveTranscriber,+ forceAlign: async (...args) => (await import('./lyricForcedAlign.js')).forceAlignLyrics(...args),+ separateVocals: async (...args) => (await import('./vocalSeparation.js')).separateProjectVocals(...args),...options.deps,};const cueId = options.cueId || null;- const project = await deps.getProject(projectId);+ let project = await deps.getProject(projectId);if (!project) throw new ServerError('Project not found', { status: 404, code: 'NOT_FOUND' });const cues = Array.isArray(project.lyricCues) ? project.lyricCues : [];if (cues.length === 0) {@@ -106,10 +94,16 @@ export async function alignProjectLyrics(projectId, options = {}) {const cue = cueId ? cues.find((entry) => entry.id === cueId) : null;if (cueId && !cue) throw new ServerError('That lyric line is no longer on the project.', { status: 404, code: 'NOT_FOUND' });+ const expectedTextKey = textKey(cues);+ if (!project.vocalStemFilename && options.separateVocals === true) {+ onProgress({ stage: 'separating' });+ project = await deps.separateVocals(projectId, { onProgress, isCancelled: options.isCancelled });+ checkCancel();+ }+ const expectedAudioKey = audioKey(project);onProgress({ stage: 'decoding' });- const { path: audioPath, source, mixPath } = await deps.resolveAudio(project);+ const { path: audioPath, source } = await deps.resolveAudio(project);const wav = await deps.decodeAudio(audioPath);- const mixWav = mixPath ? await deps.decodeAudio(mixPath) : null;checkCancel();const windowed = cue&& typeof cue.startSec === 'number'@@ -120,67 +114,52 @@ export async function alignProjectLyrics(projectId, options = {}) {const region = windowed || { startSec: 0, endSec: null };const promptCues = windowed ? [cue] : cues;const prompt = alignmentPrompt(promptCues);- const phrases = mixWav ? detectVocalPhrases(vocalPcm(wav)) : [];- const windows = mixWav ? phraseWindows(phrases, wavDurationSec(mixWav)) : [];-- onProgress({ stage: 'loading-model' });- const transcriber = await deps.resolveTranscriber((download) => onProgress({ stage: 'downloading-model', percent: download.percent }));- let recognized;- try {- if (mixWav) {- recognized = [];- const inRegion = (window) => !windowed || (window.endSec > windowed.startSec && window.startSec < windowed.endSec);- const total = windows.filter(inRegion).length;- let done = 0;- // The runner already slices and offsets each result onto the song clock.- // Sequential calls bound memory/GPU use and release one runner per song.- for (const [index, window] of windows.entries()) {- if (!inRegion(window)) continue;- checkCancel();- onProgress({ stage: 'transcribing', current: done + 1, total, percent: Math.round((done / total) * 100) });- done += 1;- const startSec = Math.max(window.startSec, windowed?.startSec ?? 0);- const endSec = Math.min(window.endSec, windowed?.endSec ?? Infinity);- const words = await transcriber.transcribe(mixWav, { startSec, endSec, prompt });- const previous = windows[index - 1];- const following = windows[index + 1];- const ownStart = Math.max(startSec, previous ? (previous.endSec + window.startSec) / 2 : startSec);- const ownEnd = Math.min(endSec, following ? (window.endSec + following.startSec) / 2 : endSec);- recognized.push(...words.filter((word) => {- const midpoint = (word.startSec + word.endSec) / 2;- return midpoint >= ownStart && midpoint < ownEnd;- }));- }- recognized = dropNonLyricWords(recognized);- } else {+ let forcedWords = null;+ let recognized = [];+ let kind;+ if (source === 'vocal-stem') {+ onProgress({ stage: 'loading-model' });+ checkCancel();+ forcedWords = await deps.forceAlign(wav, promptCues, {+ ...region, onProgress, isCancelled: options.isCancelled,+ });+ kind = 'MMS_FA';+ } else {+ onProgress({ stage: 'loading-model' });+ const transcriber = await deps.resolveTranscriber((download) => onProgress({ stage: 'downloading-model', percent: download.percent }));+ kind = transcriber.kind;+ try {checkCancel();onProgress({ stage: 'transcribing', current: 1, total: 1, percent: 0 });recognized = mergeTranscripts(await transcriber.transcribe(wav, { ...region, prompt }), [], promptCues.map((entry) => entry.text).join('\n'));+ } finally {+ await Promise.resolve(transcriber.release?.()).catch((err) => console.error(`❌ Could not stop the alignment runner: ${err.message}`));+ }+ if (!windowed && recognized.length === 0) {+ throw new ServerError('Speech-to-text heard no words in this audio. Check the song has vocals, then try Align words again.',+ { status: 422, code: 'LYRIC_ALIGN_EMPTY' });}- } finally {- await Promise.resolve(transcriber.release?.()).catch((err) => console.error(`❌ Could not stop the alignment runner: ${err.message}`));}checkCancel();- if (!mixWav && !windowed && recognized.length === 0) {- throw new ServerError(- 'Speech-to-text heard no words in this audio. Check the song has vocals, then try Align words again.',- { status: 422, code: 'LYRIC_ALIGN_EMPTY' },- );- }const fresh = await deps.getProject(projectId);- if (!fresh || audioKey(fresh) !== audioKey(project)) {+ if (!fresh || audioKey(fresh) !== expectedAudioKey) {throw new ServerError('The song changed while lyrics were aligning. Run Align words again.', { status: 409, code: 'MUSIC_VIDEO_AUDIO_CHANGED' });}const freshCues = Array.isArray(fresh.lyricCues) ? fresh.lyricCues : [];- if (textKey(freshCues) !== textKey(cues)) {+ if (textKey(freshCues) !== expectedTextKey) {throw new ServerError('The lyric lines changed while they were aligning. Run Align words again.', { status: 409, code: 'LYRIC_ALIGN_TEXT_CHANGED' });}onProgress({ stage: 'saving', percent: 100 });const align = (entries) => {- const aligned = alignDirectorWords(entries, recognized, { phraseAnchored: Boolean(mixWav) });- return mixWav ? snapLineStarts(aligned, phrases.map((phrase) => phrase.startSec), entries) : aligned;+ if (!forcedWords) return alignDirectorWords(entries, recognized);+ return entries.map((entry, index) => {+ const words = forcedWords[index];+ return { ...entry, words, matched: words.length ? 1 : 0,+ startSec: entry.startSec ?? words[0]?.startSec ?? null,+ endSec: entry.endSec ?? words.at(-1)?.endSec ?? null };+ });};let nextCues;if (windowed) {@@ -191,14 +170,18 @@ export async function alignProjectLyrics(projectId, options = {}) {nextCues = cueId ? freshCues.map((entry, index) => (entry.id === cueId ? aligned[index] : entry)) : aligned;}const matched = nextCues.reduce((sum, entry) => sum + (entry.words || []).filter((word) => word.conf === 'matched').length, 0);- console.log(`🎤 Aligned lyric words from the ${source}${mixWav ? ' + mix' : ''} via ${transcriber.kind} (${matched} words matched)`);+ console.log(`🎤 Aligned lyric words from the ${source} via ${kind} (${matched} words matched)`);// Provenance is project-wide, so only a whole-song pass may change it; one// re-aligned line leaves the other lines' timings as stale as they were.const patch = { lyricCues: nextCues, ...(cueId ? {} : { lyricAlignSource: source }) };- if (mixWav) {+ if (source === 'vocal-stem') {const silentWords = findSilentWords(nextCues, vocalPcm(wav)).length;patch.lyricAlignSilentWords = silentWords;- if (silentWords > 0) console.warn(`⚠️ ${silentWords} aligned lyric words sit in silence in the vocal stem; their timing is suspect`);+ const checkedCues = cueId ? nextCues.filter((entry) => entry.id === cueId) : nextCues;+ if (findSilentWords(checkedCues, vocalPcm(wav)).length > 0) {+ throw new ServerError('Some lyric words aligned to silence. Check that the lyrics match the vocal, then re-align.',+ { status: 422, code: 'LYRIC_ALIGN_SILENT_WORDS' });+ }}if (!cueId) {const analysis = relabeledAnalysis(fresh, nextCues);diff --git a/server/services/musicVideo/lyricAlign.test.js b/server/services/musicVideo/lyricAlign.test.jsindex e793ed014f..d5da355fc4 100644--- a/server/services/musicVideo/lyricAlign.test.js+++ b/server/services/musicVideo/lyricAlign.test.js@@ -199,12 +199,12 @@ describe('lyric alignment audio', () => {expect(() => sliceWav(stereo, 0, 0.01)).toThrow(/16-bit mono/);});- it('uses the vocal stem with the mix beside it, and does not fall back when the stem file is missing', async () => {+ it('uses the vocal stem without needing the mix, and does not fall back when the stem file is missing', async () => {const resolveMaster = vi.fn(async () => '/library/mix.wav');await expect(pickAlignmentPath({ vocalStemFilename: 'v.wav' }, {resolveStem: () => '/library/v.wav',resolveMaster,- })).resolves.toEqual({ path: '/library/v.wav', source: 'vocal-stem', mixPath: '/library/mix.wav' });+ })).resolves.toEqual({ path: '/library/v.wav', source: 'vocal-stem', mixPath: null });await expect(pickAlignmentPath({}, {resolveStem: () => null,@@ -273,6 +273,7 @@ describe('alignProjectLyrics', () => {resolveAudio: resolveAudio || (async () => ({ path: 'song.wav', source: 'master', mixPath: null })),decodeAudio,resolveTranscriber: async () => ({ kind: 'test', transcribe, release }),+ ...opts.deps,},}),};@@ -318,56 +319,97 @@ describe('alignProjectLyrics', () => {expect(stopped.release).toHaveBeenCalledOnce();});- it('anchors a post-silence line to the stem while transcribing only sequential mix windows', async () => {- const record = { ...project, lyricCues: [+ it('uses CTC word slots for repeated lines after silence, without Whisper or mix decoding', async () => {+ const record = { ...project, vocalStemFilename: 'stem.wav', lyricCues: [{ id: 'a', text: 'hello morning', startSec: null, endSec: null },- { id: 'b', text: 'gently awaken', startSec: null, endSec: null },- { id: 'c', text: 'absent lyric', startSec: 8, endSec: 9 },+ { id: 'b', text: 'hello morning', startSec: null, endSec: null },] };const stem = encodePcm16Wav(16000 * 10);for (const [start, end] of [[1, 2], [4, 5]]) {for (let i = start * 16000; i < end * 16000; i++) stem.writeInt16LE(5000, 44 + i * 2);}- const mix = encodePcm16Wav(16000 * 10);- let active = false;- const transcribe = vi.fn(async (wav, region) => {- expect(wav).toBe(mix);- expect(active).toBe(false);- active = true;- await Promise.resolve();- active = false;- // Mimic whisper's bias: first word starts at the slice's beginning.- const text = region.startSec < 2 ? ['hello', 'morning'] : region.startSec < 5 ? ['gently', 'awaken'] : [];- return text.map((word, i) => ({ text: word, startSec: region.startSec + i * 0.4, endSec: region.startSec + (i + 1) * 0.4 }));- });+ const transcribe = vi.fn();const h = harness(transcribe, record, {- resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem', mixPath: 'song.wav' }),+ resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem', mixPath: null }),});- h.decodeAudio.mockImplementation(async (path) => path === 'stem.wav' ? stem : mix);- const saved = await h.run();- expect(h.decodeAudio.mock.calls.map(([path]) => path)).toEqual(['stem.wav', 'song.wav']);- expect(Math.abs(saved.lyricCues[1].startSec - 4)).toBeLessThanOrEqual(0.06);- expect(saved.lyricCues[1].matched).toBe(1);- expect(saved.lyricCues[1].words[0].startSec).toBe(saved.lyricCues[1].startSec);- expect(saved.lyricCues[2]).toEqual({ ...record.lyricCues[2], matched: 0 });- expect(transcribe.mock.calls.every(([, window]) => window.endSec - window.startSec <= 11)).toBe(true);- expect(h.release).toHaveBeenCalledOnce();+ h.decodeAudio.mockResolvedValue(stem);+ const forceAlign = vi.fn(async (_wav, cues) => {+ expect(cues).toEqual(record.lyricCues);+ return [1, 4].map((start) => [+ { w: 'hello', startSec: start, endSec: start + 0.4, conf: 'matched' },+ { w: 'morning', startSec: start + 0.4, endSec: start + 1, conf: 'matched' },+ ]);+ });+ const saved = await h.run({ deps: { forceAlign } });+ expect(h.decodeAudio.mock.calls.map(([path]) => path)).toEqual(['stem.wav']);+ expect(forceAlign).toHaveBeenCalledOnce();+ expect(transcribe).not.toHaveBeenCalled();+ expect(saved.lyricCues.map((cue) => cue.startSec)).toEqual([1, 4]);+ expect(saved.lyricAlignSilentWords).toBe(0);+ expect(saved.lyricAlignSource).toBe('vocal-stem');});- it('keeps current director times on a stem re-alignment, including edits made during transcription', async () => {- const record = { ...project, lyricCues: [{ id: 'a', text: 'walking home', startSec: 1, endSec: 2 }] };- const transcribe = vi.fn(async () => {- record.lyricCues = [{ ...record.lyricCues[0], startSec: 1.2, endSec: 2.5 }];- return [{ text: 'walking', startSec: 1, endSec: 1.5 }, { text: 'home', startSec: 1.5, endSec: 2 }];- });- const h = harness(transcribe, record, {- resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem', mixPath: 'song.wav' }),+ it('re-aligns one stem line preserving current director edits and the other occurrence', async () => {+ const record = { ...project, vocalStemFilename: 'stem.wav', lyricCues: [+ { id: 'a', text: 'walking home', startSec: 1, endSec: 2 },+ { id: 'b', text: 'walking home', startSec: 4, endSec: 5 },+ ] };+ const h = harness(vi.fn(), record, {+ resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem' }),});- const stem = encodePcm16Wav(16000 * 3);+ const stem = encodePcm16Wav(16000 * 6);for (let i = 16000; i < 32000; i++) stem.writeInt16LE(5000, 44 + i * 2);h.decodeAudio.mockResolvedValue(stem);- const saved = await h.run({ cueId: 'a' });+ const forceAlign = vi.fn(async () => {+ record.lyricCues = [{ ...record.lyricCues[0], startSec: 1.2, endSec: 2.5 }, record.lyricCues[1]];+ return [[{ w: 'walking', startSec: 1.2, endSec: 1.5, conf: 'matched' }, { w: 'home', startSec: 1.5, endSec: 2, conf: 'matched' }]];+ });+ const saved = await h.run({ cueId: 'a', deps: { forceAlign } });+ expect(forceAlign).toHaveBeenCalledWith(stem, [expect.objectContaining({ id: 'a' })], expect.objectContaining({ startSec: 1, endSec: 2 }));expect(saved.lyricCues[0]).toMatchObject({ startSec: 1.2, endSec: 2.5, matched: 1 });+ expect(saved.lyricCues[1]).toEqual(record.lyricCues[1]);+ expect(saved.lyricAlignSource).toBeUndefined();+ });++ it('saves nothing when CTC lands in silence, the song or text changes, or alignment is cancelled', async () => {+ for (const outcome of ['silence', 'audio', 'text', 'cancel']) {+ const record = { ...project, vocalStemFilename: 'stem.wav', lyricCues: [{ id: 'a', text: 'walking', startSec: null, endSec: null }] };+ const h = harness(vi.fn(), record, { resolveAudio: async () => ({ path: 'stem.wav', source: 'vocal-stem' }) });+ const stem = encodePcm16Wav(16000 * 3);+ if (outcome !== 'silence') for (let i = 16000; i < 32000; i++) stem.writeInt16LE(5000, 44 + i * 2);+ h.decodeAudio.mockResolvedValue(stem);+ let cancelled = false;+ const forceAlign = async () => {+ if (outcome === 'audio') record.trackId = 'changed';+ if (outcome === 'text') record.lyricCues = [{ ...record.lyricCues[0], text: 'changed' }];+ if (outcome === 'cancel') cancelled = true;+ return [[{ w: 'walking', startSec: 1, endSec: 2, conf: 'matched' }]];+ };+ await expect(h.run({ deps: { forceAlign }, isCancelled: () => cancelled })).rejects.toMatchObject(+ outcome === 'cancel' ? { canceled: true } : { code: { silence: 'LYRIC_ALIGN_SILENT_WORDS', audio: 'MUSIC_VIDEO_AUDIO_CHANGED', text: 'LYRIC_ALIGN_TEXT_CHANGED' }[outcome] });+ expect(h.updateProject).not.toHaveBeenCalled();+ }+ });++ it('separates a missing stem only with explicit consent, then aligns that stem', async () => {+ const record = { ...project, lyricCues: [{ id: 'a', text: 'walking', startSec: null, endSec: null }] };+ const separated = { ...record, vocalStemFilename: 'stem.wav' };+ const updateProject = vi.fn(async (_id, patch) => ({ ...separated, ...patch }));+ const separateVocals = vi.fn(async () => separated);+ const forceAlign = vi.fn(async () => [[{ w: 'walking', startSec: 1, endSec: 2, conf: 'matched' }]]);+ const stem = encodePcm16Wav(16000 * 3);+ for (let i = 16000; i < 32000; i++) stem.writeInt16LE(5000, 44 + i * 2);+ const saved = await alignProjectLyrics('mv-1', { separateVocals: true, deps: {+ getProject: vi.fn().mockResolvedValueOnce(record).mockResolvedValue(separated), updateProject, separateVocals, forceAlign,+ resolveAudio: async (project) => { expect(project.vocalStemFilename).toBe('stem.wav'); return { path: 'stem.wav', source: 'vocal-stem' }; },+ decodeAudio: async () => stem,+ } });+ expect(separateVocals).toHaveBeenCalledOnce();+ expect(forceAlign).toHaveBeenCalledOnce();+ expect(saved.lyricAlignSilentWords).toBe(0);+ const legacy = harness(vi.fn(async () => [{ text: 'walking', startSec: 1, endSec: 2 }]), record);+ await legacy.run({ deps: { separateVocals } });+ expect(separateVocals).toHaveBeenCalledOnce();});it('names the analysis sections after the lyric sheet once the lines are timed', async () => {diff --git a/server/services/musicVideo/lyricAlignCore.js b/server/services/musicVideo/lyricAlignCore.jsindex 78399f42b1..9abbea5cdf 100644--- a/server/services/musicVideo/lyricAlignCore.js+++ b/server/services/musicVideo/lyricAlignCore.js@@ -823,8 +823,8 @@ export async function pickAlignmentPath(project, io = {}) {return resolveMasterAudioPath(record);});const stem = resolveStem(project);- // The stem supplies phrase onsets; the mix supplies recognized words.- if (stem) return { path: stem, source: 'vocal-stem', mixPath: await resolveMaster(project) };+ // CTC aligns the known text directly to the stem, without decoding the mix.+ if (stem) return { path: stem, source: 'vocal-stem', mixPath: null };return { path: await resolveMaster(project), source: 'master', mixPath: null };}diff --git a/server/services/musicVideo/lyricAlignJob.js b/server/services/musicVideo/lyricAlignJob.jsindex cb79e73dc6..b2527b2264 100644--- a/server/services/musicVideo/lyricAlignJob.js+++ b/server/services/musicVideo/lyricAlignJob.js@@ -1,8 +1,8 @@/*** Lyric word alignment as a job (#10155).*- * `alignProjectLyrics` can take minutes (audio decode, a ~1.6 GB first-use- * model download, one whisper pass per phrase window), so the route starts it+ * `alignProjectLyrics` can take minutes (audio decode, first-use model downloads+ * and a CTC pass over the known lyric text), so the route starts it* here and returns a job id; stages stream over SSE with cancel. One job per* project at a time — a second request returns the running job, so a double* click or a reloaded page never starts a duplicate run.@@ -44,7 +44,7 @@ export function cancelLyricAlign(jobId) {* line while one runs also reuses it: the client reattaches rather than* queueing a second whisper run over the same song.*/-export async function startLyricAlign(projectId, { cueId = null, align = alignProjectLyrics } = {}) {+export async function startLyricAlign(projectId, { cueId = null, separateVocals = false, align = alignProjectLyrics } = {}) {const running = getActiveLyricAlignJobId(projectId);if (running) return { jobId: running, reused: true };// Fail with a real status before a job exists, as the blocking route did.@@ -69,6 +69,7 @@ export async function startLyricAlign(projectId, { cueId = null, align = alignPrbroadcastSse(job, { type: 'progress', stage: 'preparing' });const project = await align(projectId, {cueId,+ separateVocals,isCancelled: () => job.cancelRequested,onProgress: (frame) => broadcastSse(job, { type: 'progress', ...frame }),});diff --git a/server/services/musicVideo/lyricForcedAlign.js b/server/services/musicVideo/lyricForcedAlign.jsnew file mode 100644index 0000000000..8f3ffeda6f--- /dev/null+++ b/server/services/musicVideo/lyricForcedAlign.js@@ -0,0 +1,113 @@+/** User-triggered MMS_FA alignment in a private, version-pinned Python venv. */+import { existsSync } from 'fs';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { homedir, tmpdir } from 'os';+import { dirname, join } from 'path';+import { fileURLToPath } from 'url';+import { ServerError } from '../../lib/errorHandler.js';+import { whichFirst } from '../../lib/processEnv.js';+import { runStreamingCommand } from '../../lib/streamingSpawn.js';+import { lyricTokens } from './timedText.js';+import { sliceWav, wavDurationSec } from './lyricAlignCore.js';++const SCRIPT = fileURLToPath(new URL('../../../scripts/align_lyrics_ctc.py', import.meta.url));+// forced_align was removed in 2.9. Keep matching wheels in this venv only.+const INTEL_MAC = process.platform === 'darwin' && process.arch === 'x64';+// 2.2 was the last release with official Intel Mac wheels.+const TORCH_VERSION = INTEL_MAC ? '2.2.2' : '2.8.0';+const MAX_PYTHON_MINOR = INTEL_MAC ? 12 : 13;+const PYTHON_RANGE = `Python 3.10–3.${MAX_PYTHON_MINOR}`;+const PACKAGES = [`torch==${TORCH_VERSION}`, `torchaudio==${TORCH_VERSION}`, ...(INTEL_MAC ? ['numpy<2'] : [])];+const PROBE = `import torch, torchaudio; assert torch.__version__.split("+")[0] == "${TORCH_VERSION}"; assert torchaudio.__version__.split("+")[0] == "${TORCH_VERSION}"; assert callable(torchaudio.functional.forced_align); assert torchaudio.pipelines.MMS_FA`;+let provisioning = null;++const canceled = () => Object.assign(new Error('cancelled'), { canceled: true });+const failure = (message, code = 'LYRIC_ALIGN_CTC_FAILED') => new ServerError(message, { status: 503, code });++async function basePython() {+ const { classifyVenvBases, probePythonVersion } = await import('../../lib/pythonSetup.js');+ const { supported } = await classifyVenvBases().catch(() => ({ supported: [] }));+ const candidates = [...supported];+ for (const name of ['python3.13', 'python3.12', 'python3.11', 'python3.10', process.platform === 'win32' ? 'python' : 'python3']) {+ const found = await whichFirst(name);+ if (found && !candidates.includes(found)) candidates.push(found);+ }+ for (const candidate of candidates) {+ const version = await probePythonVersion(candidate);+ if (version?.major === 3 && version.minor >= 10 && version.minor <= MAX_PYTHON_MINOR) return candidate;+ }+ return null;+}++async function ensureRuntime({ run, onProgress, resolveBasePython, dir }) {+ const python = process.platform === 'win32' ? join(dir, 'Scripts', 'python.exe') : join(dir, 'bin', 'python');+ if (existsSync(python) && (await run(python, ['-c', PROBE], null, { timeoutMs: 120_000 })).success) return python;+ if (!provisioning) {+ provisioning = (async () => {+ const exists = existsSync(python);+ const compatible = exists && (await run(python, ['-c', `import sys; assert (3, 10) <= sys.version_info[:2] <= (3, ${MAX_PYTHON_MINOR})`], null, { timeoutMs: 120_000 })).success;+ if (!compatible) {+ const base = await resolveBasePython();+ if (!base) throw failure(`MMS_FA lyric alignment needs ${PYTHON_RANGE}.`, 'LYRIC_ALIGN_CTC_PYTHON_MISSING');+ await mkdir(dirname(dir), { recursive: true });+ onProgress({ stage: 'installing', detail: 'Creating the MMS_FA environment (first run only)' });+ const result = await run(base, ['-m', 'venv', ...(exists ? ['--clear'] : []), dir], null, { timeoutMs: 300_000 });+ if (!result.success) throw failure('Could not create the MMS_FA environment.', 'LYRIC_ALIGN_CTC_INSTALL_FAILED');+ }+ onProgress({ stage: 'installing', detail: 'Installing MMS_FA dependencies (first run only)' });+ const result = await run(python, ['-m', 'pip', 'install', ...PACKAGES], null, { timeoutMs: 45 * 60_000 });+ if (!result.success || !(await run(python, ['-c', PROBE], null, { timeoutMs: 120_000 })).success) {+ throw failure(`Could not install MMS_FA dependencies. Use ${PYTHON_RANGE} with compatible PyTorch wheels.`, 'LYRIC_ALIGN_CTC_INSTALL_FAILED');+ }+ })().finally(() => { provisioning = null; });+ }+ await provisioning;+ return python;+}++/** Returns one word list per supplied cue, preserving occurrence and spelling. */+export async function forceAlignLyrics(wav, cues, {+ startSec = 0, endSec = wavDurationSec(wav), onProgress = () => {}, isCancelled = () => false,+ run = runStreamingCommand, resolveBasePython = basePython,+ dir = process.env.PORTOS_LYRIC_ALIGN_VENV_DIR || join(homedir(), '.portos', 'venvs', 'lyric-align'),+} = {}) {+ const checkCancel = () => { if (isCancelled()) throw canceled(); };+ checkCancel();+ const duration = wavDurationSec(wav);+ const from = Math.max(0, startSec);+ const to = Math.min(duration, endSec ?? duration);+ if (!(to > from)) throw failure('That lyric line has no audio window to align.');+ const lines = cues.map((cue) => lyricTokens(cue.text).map((token) => token.w));+ const python = await ensureRuntime({ run, onProgress, resolveBasePython, dir });+ checkCancel();+ const scratch = await mkdtemp(join(tmpdir(), 'portos-ctc-align-'));+ try {+ const audio = join(scratch, 'vocal.wav');+ const transcript = join(scratch, 'lyrics.json');+ const output = join(scratch, 'words.json');+ await writeFile(audio, sliceWav(wav, from, to));+ await writeFile(transcript, JSON.stringify(lines), { mode: 0o600 });+ const result = await run(python, [SCRIPT, '--audio', audio, '--lyrics', transcript, '--output', output], (line) => {+ const match = /^PROGRESS:(loading-model|aligning|emissions)(?::(\d+))?$/.exec(line);+ if (match) onProgress({ stage: match[1], ...(match[2] ? { percent: Number(match[2]) } : {}) });+ }, { timeoutMs: 60 * 60_000, isCancelled });+ checkCancel();+ if (!result.success) throw failure('MMS_FA could not align these lyrics. Check that lyrics match the vocal, spell numbers out, and allow the first-use model download.');+ const raw = await readFile(output, 'utf8').catch(() => null);+ const parsed = raw ? (() => { try { return JSON.parse(raw); } catch { return null; } })() : null;+ let previousEnd = 0;+ if (!Array.isArray(parsed) || parsed.length !== lines.length || parsed.some((words, i) => !Array.isArray(words)+ || words.length !== lines[i].length || words.some((word, j) => {+ const invalid = word?.w !== lines[i][j] || !Number.isFinite(word.startSec) || !Number.isFinite(word.endSec)+ || word.startSec < previousEnd || word.endSec <= word.startSec || word.endSec > to - from + 0.001;+ previousEnd = word?.endSec;+ return invalid;+ }))) throw failure('MMS_FA returned invalid word timings.');+ return parsed.map((words) => words.map((word) => ({+ w: word.w, startSec: Math.round((word.startSec + from) * 1000) / 1000,+ endSec: Math.round((word.endSec + from) * 1000) / 1000, conf: 'matched',+ })));+ } finally {+ await rm(scratch, { recursive: true, force: true });+ }+}diff --git a/server/services/musicVideo/lyricForcedAlign.test.js b/server/services/musicVideo/lyricForcedAlign.test.jsnew file mode 100644index 0000000000..e2c6b3f5ab--- /dev/null+++ b/server/services/musicVideo/lyricForcedAlign.test.js@@ -0,0 +1,84 @@+import { afterEach, describe, expect, it, vi } from 'vitest';+import { mkdir, mkdtemp, readFile, rm, writeFile } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { forceAlignLyrics } from './lyricForcedAlign.js';+import { encodePcm16Wav, wavDurationSec } from './lyricAlignCore.js';++const roots = [];+afterEach(async () => { await Promise.all(roots.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))); });++async function harness(transform = (words) => words) {+ const root = await mkdtemp(join(tmpdir(), 'ctc-contract-'));+ roots.push(root);+ let runDir;+ const run = vi.fn(async (_bin, args, onLine, options) => {+ if (args[0] !== '-m' && args[0] !== '-c') {+ runDir = args[args.indexOf('--output') + 1];+ expect(wavDurationSec(await readFile(args[args.indexOf('--audio') + 1]))).toBe(2);+ expect(JSON.parse(await readFile(args[args.indexOf('--lyrics') + 1], 'utf8'))).toEqual([['Hello,', 'café!'], ['Hello,']]);+ expect(options.isCancelled).toEqual(expect.any(Function));+ onLine('PROGRESS:emissions:50');+ onLine('unstructured output is ignored');+ await writeFile(runDir, JSON.stringify(transform([+ [{ w: 'Hello,', startSec: 0.1, endSec: 0.4 }, { w: 'café!', startSec: 0.4, endSec: 0.8 }],+ [{ w: 'Hello,', startSec: 1.4, endSec: 1.8 }],+ ])));+ }+ return { success: true };+ });+ return { root, run, runDir: () => runDir, align: (options = {}) => forceAlignLyrics(encodePcm16Wav(16000 * 8),+ [{ text: 'Hello, café!' }, { text: 'Hello,' }], { startSec: 4, endSec: 6, dir: join(root, 'venv'),+ resolveBasePython: async () => 'test-python', run, ...options }) };+}++describe('MMS_FA process contract', () => {+ it('provisions compatible wheels on demand, preserves word occurrences and offsets the cropped song clock', async () => {+ const h = await harness();+ expect(h.run).not.toHaveBeenCalled();+ const onProgress = vi.fn();+ const words = await h.align({ onProgress });+ expect(words).toEqual([+ [{ w: 'Hello,', startSec: 4.1, endSec: 4.4, conf: 'matched' }, { w: 'café!', startSec: 4.4, endSec: 4.8, conf: 'matched' }],+ [{ w: 'Hello,', startSec: 5.4, endSec: 5.8, conf: 'matched' }],+ ]);+ const intelMac = process.platform === 'darwin' && process.arch === 'x64';+ const version = intelMac ? '2.2.2' : '2.8.0';+ expect(h.run.mock.calls[1][1]).toEqual(['-m', 'pip', 'install', `torch==${version}`, `torchaudio==${version}`, ...(intelMac ? ['numpy<2'] : [])]);+ expect(onProgress).toHaveBeenCalledWith({ stage: 'emissions', percent: 50 });+ await expect(readFile(h.runDir())).rejects.toMatchObject({ code: 'ENOENT' });+ });++ it('repairs a venv created from an incompatible interpreter before installing pinned wheels', async () => {+ const h = await harness();+ const dir = join(h.root, 'venv');+ const bin = join(dir, process.platform === 'win32' ? 'Scripts' : 'bin');+ await mkdir(bin, { recursive: true });+ await writeFile(join(bin, process.platform === 'win32' ? 'python.exe' : 'python'), '');+ const implementation = h.run.getMockImplementation();+ let installed = false;+ h.run.mockImplementation(async (...args) => {+ if (args[1][0] === '-c' && !installed) return { success: false };+ if (args[1][1] === 'pip') installed = true;+ return implementation(...args);+ });+ await h.align();+ expect(h.run.mock.calls.some(([, args]) => args.join(' ') === `-m venv --clear ${dir}`)).toBe(true);+ });++ it('rejects missing, foreign, overlapping and out-of-window results instead of publishing invented words', async () => {+ for (const mutate of [() => null, (w) => w.slice(1), (w) => { w[1][0].w = 'foreign'; return w; },+ (w) => { w[1][0].startSec = 0.5; return w; }, (w) => { w[1][0].endSec = 3; return w; }]) {+ const h = await harness(mutate);+ await expect(h.align()).rejects.toMatchObject({ code: 'LYRIC_ALIGN_CTC_FAILED' });+ await expect(readFile(h.runDir())).rejects.toMatchObject({ code: 'ENOENT' });+ }+ });++ it('never starts a canceled alignment and fails closed on runtime installation failure', async () => {+ const h = await harness();+ await expect(h.align({ isCancelled: () => true })).rejects.toMatchObject({ canceled: true });+ expect(h.run).not.toHaveBeenCalled();+ await expect(h.align({ run: async () => ({ success: false }) })).rejects.toMatchObject({ code: 'LYRIC_ALIGN_CTC_INSTALL_FAILED' });+ });+});diff --git a/server/services/musicVideo/vocalSeparation.js b/server/services/musicVideo/vocalSeparation.jsindex 1967f32df1..ceacb5acb6 100644--- a/server/services/musicVideo/vocalSeparation.js+++ b/server/services/musicVideo/vocalSeparation.js@@ -167,7 +167,7 @@ const canceledRun = () => Object.assign(new Error('cancelled'), { canceled: true* `reused: true` when a separation for this project is already running).* Throws before a job exists when the project or its audio is missing.*/-export async function startVocalSeparation(projectId, { deps = {} } = {}) {+export async function startVocalSeparation(projectId, { deps = {}, onProgress = null, isCancelled = () => false } = {}) {const d = {getProject,attachVocalStem,@@ -184,16 +184,24 @@ export async function startVocalSeparation(projectId, { deps = {} } = {}) {return { jobId: running, reused: true };}const audioPath = await d.resolveMaster(project);+ // Source resolution yields; an alignment and a standalone click may race.+ const raced = getActiveVocalSeparationJobId(projectId);+ if (raced) return { jobId: raced, reused: true };const jobId = randomUUID();- const job = { id: jobId, clients: [], settled: false, cancelRequested: false };+ const job = { id: jobId, clients: [], settled: false, cancelRequested: false, observers: new Set(onProgress ? [onProgress] : []) };separationJobs.set(jobId, job);activeByProject.set(projectId, jobId);console.log(`🎙️ Vocal separation ${shortId(jobId)} started for ${projectId}`);- (async () => {+ job.completion = (async () => {let outDir = null;- const progress = (frame) => broadcastSse(job, { type: 'progress', ...frame });- const checkCancel = () => { if (job.cancelRequested) throw canceledRun(); };+ const progress = (frame) => {+ broadcastSse(job, { type: 'progress', ...frame });+ for (const observer of job.observers) {+ try { observer(frame); } catch (err) { console.error(`❌ Vocal separation progress observer failed: ${err.message}`); }+ }+ };+ const checkCancel = () => { if (job.cancelRequested || isCancelled()) throw canceledRun(); };try {progress({ stage: 'preparing' });const python = await ensureDemucsRuntime({ onProgress: progress, run: d.run, resolveBasePython: d.resolveBasePython });@@ -212,7 +220,7 @@ export async function startVocalSeparation(projectId, { deps = {} } = {}) {timeoutMs: SEPARATE_TIMEOUT_MS,splitRe: /[\r\n]+/,env: { ...process.env, PYTORCH_ENABLE_MPS_FALLBACK: '1' },- isCancelled: () => job.cancelRequested,+ isCancelled: () => job.cancelRequested || isCancelled(),});};const device = pickDemucsDevice({ cudaAvailable: await d.cudaAvailable() });@@ -236,6 +244,7 @@ export async function startVocalSeparation(projectId, { deps = {} } = {}) {const updated = await d.attachVocalStem(projectId, { tempPath: vocals, originalName: stemName(project) });console.log(`✅ Vocal separation ${shortId(jobId)} attached ${updated?.vocalStemFilename} to ${projectId}`);broadcastSse(job, { type: 'complete', project: updated });+ return { project: updated };} catch (err) {if (err?.canceled || job.cancelRequested) {console.log(`🛑 Vocal separation ${shortId(jobId)} cancelled`);@@ -244,6 +253,7 @@ export async function startVocalSeparation(projectId, { deps = {} } = {}) {console.error(`❌ Vocal separation ${shortId(jobId)} failed: ${err?.message || err}`);broadcastSse(job, { type: 'error', error: err?.message || String(err), ...(err?.code ? { code: err.code } : {}) });}+ return { error: err };} finally {job.settled = true;if (activeByProject.get(projectId) === jobId) activeByProject.delete(projectId);@@ -254,3 +264,28 @@ export async function startVocalSeparation(projectId, { deps = {} } = {}) {return { jobId };}++/** Await the existing separation job; consent is checked by the alignment caller. */+export async function separateProjectVocals(projectId, { onProgress = () => {}, isCancelled = () => false, deps } = {}) {+ const { jobId, reused } = await startVocalSeparation(projectId, { onProgress, isCancelled, deps });+ const job = separationJobs.get(jobId);+ if (reused) job.observers.add(onProgress);+ let cancelTimer;+ try {+ const result = await Promise.race([+ job.completion,+ new Promise((resolve) => {+ cancelTimer = setInterval(() => {+ try {+ if (isCancelled()) resolve({ error: canceledRun() });+ } catch (error) { resolve({ error }); }+ }, 1000);+ }),+ ]);+ if (result.error) throw result.error;+ return result.project;+ } finally {+ clearInterval(cancelTimer);+ job.observers.delete(onProgress);+ }+}