Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat(music-video): align lyric cues to the vocal for word timings (#9074)
[._.]/ Adam Eivy330ec94d4ae0
diff --git a/client/src/components/musicVideo/LyricsPanel.jsx b/client/src/components/musicVideo/LyricsPanel.jsxindex 3f43a97657..2bda2f3951 100644--- a/client/src/components/musicVideo/LyricsPanel.jsx+++ b/client/src/components/musicVideo/LyricsPanel.jsx@@ -1,4 +1,4 @@-import { useState } from 'react';+import { useRef, useState } from 'react';import { Plus, Trash2, Upload } from 'lucide-react';// Client-minted ids keep a freshly added row addressable across saves without@@ -15,6 +15,72 @@ const PACING_FIELDS = [];const inputCls = 'bg-port-bg border border-port-border rounded px-1.5 py-1 text-xs';+const round3 = (n) => Math.round(n * 1000) / 1000;+const MIN_WORD_SEC = 0.02;++/** Move the boundary after `index` by deltaSec. The next word's start follows. */+export function nudgeWordBoundary(words, index, deltaSec) {+ const next = words.map((word) => ({ ...word }));+ const word = next[index];+ if (!word || !Number.isFinite(deltaSec)) return words;+ const following = next[index + 1];+ const ceiling = following ? following.endSec - MIN_WORD_SEC : word.endSec + Math.abs(deltaSec) + 1;+ const boundary = round3(Math.min(ceiling, Math.max(word.startSec + MIN_WORD_SEC, word.endSec + deltaSec)));+ word.endSec = boundary;+ if (following) following.startSec = boundary;+ return next;+}++function WordTimingRow({ cue, onPreview, onCommit }) {+ const words = cue.words || [];+ const drag = useRef(null);+ if (words.length === 0) return null;+ const apply = (index, delta, commit) => {+ const next = nudgeWordBoundary(drag.current?.words || words, index, delta);+ if (commit) onCommit(next);+ else onPreview(next);+ };+ return (+ <div className="flex flex-wrap items-center gap-1 pl-1">+ {words.map((word, index) => (+ <span key={`${word.w}-${index}`} className="inline-flex items-center gap-0.5">+ <span+ className={word.conf === 'interpolated' ? 'text-port-warning' : 'text-port-accent'}+ title={word.conf === 'interpolated' ? 'Interpolated — the vocal did not match this word' : 'Matched to the vocal'}+ >{word.w}</span>+ <button type="button" aria-label={`Nudge the end of ${word.w} earlier`}+ onClick={() => onCommit(nudgeWordBoundary(words, index, -0.05))}+ className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 px-1 text-port-text-muted">−</button>+ <span+ role="separator"+ aria-orientation="vertical"+ aria-label={`Drag the end of ${word.w}`}+ title="Drag this word boundary"+ className="inline-block w-1.5 h-4 cursor-ew-resize touch-none rounded bg-port-border"+ onPointerDown={(event) => {+ event.currentTarget.setPointerCapture(event.pointerId);+ drag.current = { index, origin: event.clientX, words: words.map((entry) => ({ ...entry })) };+ }}+ onPointerMove={(event) => {+ if (!drag.current || drag.current.index !== index) return;+ apply(index, (event.clientX - drag.current.origin) * 0.01, false);+ }}+ onPointerUp={(event) => {+ if (!drag.current || drag.current.index !== index) return;+ const delta = (event.clientX - drag.current.origin) * 0.01;+ const base = drag.current.words;+ drag.current = null;+ onCommit(nudgeWordBoundary(base, index, delta));+ }}+ />+ <button type="button" aria-label={`Nudge the end of ${word.w} later`}+ onClick={() => onCommit(nudgeWordBoundary(words, index, 0.05))}+ className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 px-1 text-port-text-muted">+</button>+ </span>+ ))}+ </div>+ );+}/*** Timed lyric cues, musical-phrase annotations and shot pacing for the AI@@ -22,19 +88,30 @@ const inputCls = 'bg-port-bg border border-port-border rounded px-1.5 py-1 text-* board immediately (`onEditLocal`) and persist on blur (`onSave`, a project* PATCH that replaces the list whole). Import parses pasted LRC, SRT/WebVTT or* plain lines server-side; plain lines arrive untimed and are timed here.- * Changing the project's audio clears every timing (the text stays) — those- * rows show as untimed until they are re-timed against the new track.+ * Align words runs only from its button: matched words use the accent colour+ * and interpolated words use the warning colour. Drag or nudge a boundary to+ * correct it. Changing a line's text drops its word timings. Changing the+ * project's audio clears every timing (the text stays).*/-export default function LyricsPanel({ project, onEditLocal, onSave, onImport, importing }) {+export default function LyricsPanel({ project, onEditLocal, onSave, onImport, importing, onAlign, aligning = false }) {const cues = project.lyricCues || [];const phrases = project.phrases || [];const pacing = project.pacing || {};const [importText, setImportText] = useState('');const [importFormat, setImportFormat] = useState('auto');const [importMode, setImportMode] = useState('replace');+ const [alignError, setAlignError] = useState('');const timedCount = cues.filter((c) => typeof c.startSec === 'number').length;+ const hasAudio = Boolean(project.trackId || project.uploadedAudioFilename);- const editCue = (id, patch) => onEditLocal({ lyricCues: cues.map((c) => (c.id === id ? { ...c, ...patch } : c)) });+ const editCue = (id, patch) => onEditLocal({+ lyricCues: cues.map((c) => {+ if (c.id !== id) return c;+ const next = { ...c, ...patch };+ if (Object.hasOwn(patch, 'words') && patch.words == null) delete next.words;+ return next;+ }),+ });const editPhrase = (id, patch) => onEditLocal({ phrases: phrases.map((p) => (p.id === id ? { ...p, ...patch } : p)) });const saveCues = (next = cues) => onSave({ lyricCues: next });const savePhrases = (next = phrases) => onSave({ phrases: next });@@ -58,6 +135,19 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, imonImport({ text: importText, format: importFormat, mode: importMode }, () => setImportText(''));};+ const runAlign = (cueId) => {+ if (!onAlign || aligning) return;+ setAlignError('');+ Promise.resolve(onAlign(cueId)).catch((err) => {+ setAlignError(err?.message || 'Speech-to-text is not running. Enable the local whisper server in Settings → Voice, then try Align words again.');+ });+ };+ const editWords = (id, words, save) => {+ const next = cues.map((cue) => (cue.id === id ? { ...cue, words } : cue));+ onEditLocal({ lyricCues: next });+ if (save) onSave({ lyricCues: next });+ };+return (<details className="mt-2 bg-port-bg border border-port-border rounded-lg p-2 text-xs"><summary className="cursor-pointer select-none text-port-text-muted">@@ -118,24 +208,47 @@ export default function LyricsPanel({ project, onEditLocal, onSave, onImport, im<section className="space-y-1 min-w-0"><div className="flex items-center justify-between"><h4 className="font-medium text-port-text">Lyric lines</h4>- <button type="button" onClick={() => replaceCues([...cues, { id: mintId('lc'), text: 'New line', startSec: null, endSec: null }])}- className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0"><Plus size={13} /> Line</button>+ <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' : '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>+ )}+ <button type="button" onClick={() => replaceCues([...cues, { id: mintId('lc'), text: 'New line', startSec: null, endSec: null }])}+ className="flex items-center gap-1 text-port-accent min-h-[44px] sm:min-h-0"><Plus size={13} /> Line</button>+ </span></div>+ {alignError && <p role="alert" className="text-port-error">{alignError}</p>}{cues.length === 0 && <p className="text-port-text-muted">No lyrics — instrumental tracks plan from sections and beats alone.</p>}<div className="max-h-64 overflow-y-auto space-y-1 pr-1">{cues.map((cue, i) => (- <div key={cue.id} className="flex flex-wrap items-center gap-1">- <input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} start (s)`} placeholder="start"- value={cue.startSec ?? ''} onChange={(e) => editCue(cue.id, { startSec: toSec(e.target.value) })}- onBlur={() => saveCues()} className={`${inputCls} w-16`} />- <input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} end (s)`} placeholder="end"- value={cue.endSec ?? ''} onChange={(e) => editCue(cue.id, { endSec: toSec(e.target.value) })}- onBlur={() => saveCues()} className={`${inputCls} w-16`} />- <input type="text" maxLength={500} aria-label={`Line ${i + 1} text`}- value={cue.text} onChange={(e) => editCue(cue.id, { text: e.target.value })}- onBlur={() => saveCues()} className={`${inputCls} min-w-0 flex-1 basis-40`} />- <button type="button" onClick={() => replaceCues(cues.filter((c) => c.id !== cue.id))}- aria-label={`Delete line ${i + 1}`} className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 text-port-error"><Trash2 size={12} /></button>+ <div key={cue.id} className="space-y-1 border-b border-port-border/50 pb-1">+ <div className="flex flex-wrap items-center gap-1">+ <input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} start (s)`} placeholder="start"+ value={cue.startSec ?? ''} onChange={(e) => editCue(cue.id, { startSec: toSec(e.target.value) })}+ onBlur={() => saveCues()} className={`${inputCls} w-16`} />+ <input type="number" min={0} step={0.01} aria-label={`Line ${i + 1} end (s)`} placeholder="end"+ value={cue.endSec ?? ''} onChange={(e) => editCue(cue.id, { endSec: toSec(e.target.value) })}+ onBlur={() => saveCues()} className={`${inputCls} w-16`} />+ <input type="text" maxLength={500} aria-label={`Line ${i + 1} text`}+ value={cue.text} onChange={(e) => {+ const text = e.target.value;+ editCue(cue.id, cue.words && text !== cue.text ? { text, words: undefined } : { text });+ }}+ onBlur={() => saveCues()} className={`${inputCls} min-w-0 flex-1 basis-40`} />+ {onAlign && (+ <button type="button" onClick={() => runAlign(cue.id)} disabled={aligning}+ aria-label={`Re-align line ${i + 1}`}+ className="min-h-[44px] sm:min-h-0 text-port-accent disabled:opacity-50">Re-align</button>+ )}+ <button type="button" onClick={() => replaceCues(cues.filter((c) => c.id !== cue.id))}+ aria-label={`Delete line ${i + 1}`} className="min-h-[44px] min-w-[44px] sm:min-h-0 sm:min-w-0 p-1 text-port-error"><Trash2 size={12} /></button>+ </div>+ <WordTimingRow cue={cue}+ onPreview={(words) => editWords(cue.id, words, false)}+ onCommit={(words) => editWords(cue.id, words, true)} /></div>))}</div>diff --git a/client/src/components/musicVideo/LyricsPanel.test.jsx b/client/src/components/musicVideo/LyricsPanel.test.jsxnew file mode 100644index 0000000000..f9a604e089--- /dev/null+++ b/client/src/components/musicVideo/LyricsPanel.test.jsx@@ -0,0 +1,62 @@+import { describe, it, expect, vi } from 'vitest';+import { render, screen, fireEvent } from '@testing-library/react';+import LyricsPanel from './LyricsPanel.jsx';++const PROJECT = {+ id: 'mv-1',+ trackId: 't1',+ lyricCues: [{+ id: 'lc-1',+ text: 'walking home',+ startSec: 1,+ endSec: 2,+ words: [+ { w: 'walking', startSec: 1, endSec: 1.4, conf: 'matched' },+ { w: 'home', startSec: 1.4, endSec: 2, conf: 'interpolated' },+ ],+ }],+};++function renderPanel(overrides = {}) {+ const props = {+ project: PROJECT,+ onEditLocal: vi.fn(),+ onSave: vi.fn(),+ onImport: vi.fn(),+ onAlign: vi.fn(),+ ...overrides,+ };+ render(<LyricsPanel {...props} />);+ return props;+}++describe('LyricsPanel word alignment', () => {+ it('does not align until Align words is clicked, and shows the whisper setup error', async () => {+ const onAlign = vi.fn().mockRejectedValue(new Error(+ 'Speech-to-text is not running. Enable the local whisper server in Settings → Voice, then try Align words again.',+ ));+ renderPanel({ onAlign });+ expect(onAlign).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole('button', { name: 'Align words' }));+ expect(onAlign).toHaveBeenCalledWith(undefined);+ expect(await screen.findByRole('alert')).toHaveTextContent(/Settings → Voice/);+ });++ it('re-aligns one line and nudges a word boundary into the save', () => {+ const { onAlign, onSave } = renderPanel();+ fireEvent.click(screen.getByRole('button', { name: 'Re-align line 1' }));+ expect(onAlign).toHaveBeenCalledWith('lc-1');+ expect(screen.getByText('home').className).toMatch(/text-port-warning/);+ expect(screen.getByText('walking').className).toMatch(/text-port-accent/);+ fireEvent.click(screen.getByRole('button', { name: 'Nudge the end of walking later' }));+ expect(onSave).toHaveBeenCalledWith({+ lyricCues: [{+ ...PROJECT.lyricCues[0],+ words: [+ { w: 'walking', startSec: 1, endSec: 1.45, conf: 'matched' },+ { w: 'home', startSec: 1.45, endSec: 2, conf: 'interpolated' },+ ],+ }],+ });+ });+});diff --git a/client/src/pages/MusicVideo.jsx b/client/src/pages/MusicVideo.jsxindex 97eacb57af..0713c41cf5 100644--- a/client/src/pages/MusicVideo.jsx+++ b/client/src/pages/MusicVideo.jsx@@ -19,6 +19,7 @@ import {splitMusicVideoScene,reorderMusicVideoScenes,importMusicVideoLyrics,+ alignMusicVideoLyrics,} from '../services/apiMusicVideo.js';import useFieldDraft from '../hooks/useFieldDraft.js';import useMusicVideoYoutubeImport from '../hooks/useMusicVideoYoutubeImport.js';@@ -106,6 +107,7 @@ export default function MusicVideo() {const [planning, setPlanning] = useState(false);const [cloning, setCloning] = useState(false);const [importingLyrics, setImportingLyrics] = useState(false);+ const [aligningLyrics, setAligningLyrics] = useState(false);const [createOpen, setCreateOpen] = useState(false);const [creating, setCreating] = useState(false);const [form, setForm] = useState(emptyCreateForm);@@ -450,6 +452,18 @@ export default function MusicVideo() {.catch((err) => toast.error(err?.message || 'Lyric import failed')).finally(() => setImportingLyrics(false));};+ // 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) => {+ const projectId = selected.id;+ setAligningLyrics(true);+ return alignMusicVideoLyrics(projectId, cueId ? { cueId } : {}, { silent: true })+ .then((project) => {+ patchProject(projectId, { lyricCues: project.lyricCues, updatedAt: project.updatedAt });+ toast.success(cueId ? 'Re-aligned that line' : 'Aligned words to the vocal');+ })+ .finally(() => setAligningLyrics(false));+ };// Buffered so a concept/style keystroke doesn't fire a round-trip per character,// and a focus-without-edit blur doesn't re-PATCH an unchanged value.const conceptDraft = useFieldDraft(selected?.concept?.prompt, (v) => commitConcept({ prompt: v }));@@ -815,6 +829,8 @@ export default function MusicVideo() {onSave={saveProjectFields}onImport={handleImportLyrics}importing={importingLyrics}+ onAlign={handleAlignLyrics}+ aligning={aligningLyrics}/><TypographyPanelproject={selected}diff --git a/client/src/pages/MusicVideo.test.jsx b/client/src/pages/MusicVideo.test.jsxindex f3a48794dd..9a983e7162 100644--- a/client/src/pages/MusicVideo.test.jsx+++ b/client/src/pages/MusicVideo.test.jsx@@ -53,6 +53,7 @@ vi.mock('../services/apiMusicVideo.js', () => ({reorderMusicVideoScenes: vi.fn(),splitMusicVideoScene: vi.fn(),importMusicVideoLyrics: vi.fn(),+ alignMusicVideoLyrics: vi.fn(),renderMusicVideoProject: vi.fn(async () => ({ jobId: 'job-1' })),musicVideoRenderEventsUrl: (jobId) => `/api/music-video/render/${jobId}/events`,cancelMusicVideoRender: vi.fn(async () => ({ ok: true })),@@ -159,7 +160,7 @@ import MusicVideo from './MusicVideo.jsx';import {listMusicVideoProjects, createMusicVideoProject, cloneMusicVideoProject, renderMusicVideoProject, planMusicVideoProject, updateMusicVideoProject,deleteMusicVideoProject, transcribeMusicVideoMidi, cancelMusicVideoRender, analyzeMusicVideoProject,- importMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,+ importMusicVideoLyrics, alignMusicVideoLyrics, updateMusicVideoScene, splitMusicVideoScene,selectMusicVideoSceneTake, reviewMusicVideoSceneTake, importMusicVideoHandoff,addMusicVideoSceneTake, getMusicVideoHandoffBundle,renderMusicVideoExcerpt, deleteMusicVideoExcerpt, addMusicVideoExcerptNote,@@ -979,6 +980,7 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {expect(screen.getByLabelText('Lyrics to import')).toHaveValue('');fireEvent.change(line, { target: { value: 'second line, retold' } });+ expect(alignMusicVideoLyrics).not.toHaveBeenCalled();fireEvent.blur(line);await waitFor(() => expect(updateMusicVideoProject).toHaveBeenCalledWith('mv-3',@@ -987,6 +989,25 @@ describe('MusicVideo lyrics and shot coverage (#8964)', () => {));});+ it('aligns words only after the button click and shows the returned timings', async () => {+ const cues = [{+ id: 'lc-1', text: 'walking home', startSec: 0.5, endSec: 1.5,+ words: [+ { w: 'walking', startSec: 0.5, endSec: 1, conf: 'matched' },+ { w: 'home', startSec: 1, endSec: 1.5, conf: 'interpolated' },+ ],+ }];+ await openProject({ ...PROJECT_ANALYZED, lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: null, endSec: null }] });+ expect(alignMusicVideoLyrics).not.toHaveBeenCalled();+ alignMusicVideoLyrics.mockResolvedValue({ id: 'mv-3', lyricCues: cues, updatedAt: 't' });+ fireEvent.click(screen.getByRole('button', { name: 'Align words' }));+ await waitFor(() => expect(alignMusicVideoLyrics).toHaveBeenCalledWith('mv-3', {}, { silent: true }));+ expect(await screen.findByText('walking')).toHaveClass('text-port-accent');+ expect(screen.getByText('home')).toHaveClass('text-port-warning');+ fireEvent.click(screen.getByRole('button', { name: 'Re-align line 1' }));+ await waitFor(() => expect(alignMusicVideoLyrics).toHaveBeenLastCalledWith('mv-3', { cueId: 'lc-1' }, { silent: true }));+ });+it('flags a non-looping shot longer than its clip and trims it; a legacy scene is left alone', async () => {const project = {...PROJECT_WITH_CLIP,diff --git a/client/src/services/apiMusicVideo.js b/client/src/services/apiMusicVideo.jsindex 04c36f4b1e..0ded93f1e5 100644--- a/client/src/services/apiMusicVideo.js+++ b/client/src/services/apiMusicVideo.js@@ -48,6 +48,13 @@ export const importMusicVideoLyrics = (id, body, options = {}) => request(`/musimethod: 'POST', body: JSON.stringify(body), ...options,});+// Align director lyric lines to the vocal (#9074). Body `{}` aligns every line;+// `{ cueId }` re-aligns one line. Resolves to the updated project. Runs only+// when the caller invokes it — there is no boot or import hook.+export const alignMusicVideoLyrics = (id, body = {}, options = {}) => request(`/music-video/${encodeURIComponent(id)}/lyrics/align`, {+ method: 'POST', body: JSON.stringify(body), ...options,+});+// ---- Director scene board ----export const addMusicVideoScene = (id, scene, options = {}) => request(`/music-video/${encodeURIComponent(id)}/scenes`, {method: 'POST', body: JSON.stringify(scene), ...options,diff --git a/server/lib/musicVideoValidation.js b/server/lib/musicVideoValidation.jsindex 14b61dd152..3854dad0ec 100644--- a/server/lib/musicVideoValidation.js+++ b/server/lib/musicVideoValidation.js@@ -70,12 +70,23 @@ export const musicVideoVideoSettingsSchema = z.object({// null means "not yet timed" (plain pasted lyrics, or timings invalidated by an// audio-source change — see projectsLogic.applyProjectPatch). The id is// optional on input; the server mints one so edits stay addressable.+// `words` (#9074) is derived karaoke timing. Absent on older records and on+// peers that have not aligned; cleared with the line times when the audio changes.const timedSec = z.number().min(0).max(36000).nullable().optional();+const lyricWordSchema = z.object({+ w: z.string().min(1).max(80),+ startSec: z.number().min(0).max(36000),+ endSec: z.number().min(0).max(36000),+ conf: z.enum(['matched', 'interpolated']),+}).strict().refine((word) => word.endSec >= word.startSec, {+ message: 'word endSec must be >= startSec',+});export const musicVideoLyricCueSchema = z.object({id: z.string().min(1).max(64).optional(),text: z.string().max(500),startSec: timedSec,endSec: timedSec,+ words: z.array(lyricWordSchema).max(400).optional(),}).strict();// A musical-phrase annotation: a span of the song with an optional visual@@ -205,6 +216,12 @@ export const musicVideoLyricsImportSchema = z.object({mode: z.enum(['replace', 'append']).optional(),}).strict();+// Word alignment (#9074) runs only when the director clicks. `cueId` re-aligns+// that line; omitted, every line is aligned.+export const musicVideoLyricsAlignSchema = z.object({+ cueId: z.string().min(1).max(64).optional(),+}).strict();+// ---- Composition manifest (#8984, part of #8966) ---------------------------// A composed render lays timed text cues over the cut footage; `concat` (and adiff --git a/server/lib/schemaVersions.js b/server/lib/schemaVersions.jsindex 2b9f23398c..232726e08d 100644--- a/server/lib/schemaVersions.js+++ b/server/lib/schemaVersions.js@@ -604,7 +604,13 @@ export const PORTOS_SCHEMA_VERSIONS = Object.freeze({// `shotMode` = cutaway; takes without an instruction render as before).// v5 = authored universe style and cast/place/object snapshots in concept.// Older peers ignore these when generating, losing character continuity.- musicVideoProjects: 5,+ // v6 = word-level lyric timings (`lyricCues[].words`, #9074). A v5 receiver+ // stores the body verbatim but mis-executes it: an audio-source change clears+ // startSec/endSec and leaves `words` aligned to the OLD vocal, and that edit+ // wins LWW onto the upgraded peer. Gating makes a v5 receiver reject the+ // ahead-version transfer until it upgrades. Records without `words` need no+ // rewrite.+ musicVideoProjects: 6,// v1 = Creative Commission FEEDBACK federation (PostgreSQL `commission_feedback`)// via the per-record peer-sync push pipeline (record kind `commissionFeedback`,// sync category `commissionFeedback`, #2686 — split-record follow-up to #2657).diff --git a/server/routes/musicVideo.js b/server/routes/musicVideo.jsindex c911eaa6d9..8d10c8c9bf 100644--- a/server/routes/musicVideo.js+++ b/server/routes/musicVideo.js@@ -23,6 +23,7 @@ import {musicVideoManualAnalysisSchema,musicVideoTranscribeMidiRequestSchema,musicVideoLyricsImportSchema,+ musicVideoLyricsAlignSchema,musicVideoTakeInputSchema,musicVideoTakeReviewSchema,musicVideoHandoffImportSchema,@@ -85,6 +86,7 @@ import {} from '../services/musicVideo/autoReviewService.js';import { planProject } from '../services/musicVideo/planner.js';import { parseLyricCues } from '../services/musicVideo/timedText.js';+import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';import {updateTreatment,compileTreatment,@@ -293,6 +295,14 @@ router.post('/:id/lyrics/import', asyncHandler(async (req, res) => {res.json({ project: updated, imported: cues.length, format: detected });}));+// Word-level alignment (#9074). Nothing here runs until the director clicks+// Align words or a line's Re-align. An unreachable whisper server is an error,+// not an empty timing list.+router.post('/:id/lyrics/align', asyncHandler(async (req, res) => {+ const { cueId } = validateRequest(musicVideoLyricsAlignSchema, req.body || {});+ res.json(await alignProjectLyrics(req.params.id, { cueId }));+}));+// --- Audio → MIDI transcription (MuScriptor) ---// Transcribe the project's source audio into a .mid via the local MuScriptor// sidecar. Kickoff returns 202 + a jobId (503 with the install hint when thediff --git a/server/routes/musicVideo.test.js b/server/routes/musicVideo.test.jsindex 594f7fd5c2..a08b61c791 100644--- a/server/routes/musicVideo.test.js+++ b/server/routes/musicVideo.test.js@@ -71,6 +71,10 @@ vi.mock('../services/audioMidiTranscription.js', () => ({cancelMidiTranscription: vi.fn(() => true),}));+vi.mock('../services/musicVideo/lyricAlign.js', () => ({+ alignProjectLyrics: vi.fn(async (id, opts) => ({ id, lyricCues: [], cueId: opts?.cueId || null })),+}));+vi.mock('../services/musicVideo/planner.js', () => ({planProject: vi.fn(async (id) => ({project: { id, scenes: [{ sceneId: 'mvs-1' }] },@@ -88,6 +92,7 @@ import * as excerptRenderSvc from '../services/musicVideo/excerptRender.js';import * as excerptSvc from '../services/musicVideo/excerptService.js';import * as midiSvc from '../services/audioMidiTranscription.js';import { planProject } from '../services/musicVideo/planner.js';+import { alignProjectLyrics } from '../services/musicVideo/lyricAlign.js';import musicVideoRoutes from './musicVideo.js';describe('musicVideo routes', () => {@@ -295,6 +300,48 @@ describe('musicVideo routes', () => {});});+ describe('POST /:id/lyrics/align (#9074)', () => {+ it('aligns only when the route is called, and accepts a single-line re-align', async () => {+ expect(alignProjectLyrics).not.toHaveBeenCalled();+ const all = await request(app).post('/api/music-video/mv-1/lyrics/align').send({});+ expect(all.status).toBe(200);+ expect(alignProjectLyrics).toHaveBeenCalledWith('mv-1', { cueId: undefined });+ const one = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ cueId: 'lc-1' });+ expect(one.status).toBe(200);+ expect(alignProjectLyrics).toHaveBeenLastCalledWith('mv-1', { cueId: 'lc-1' });+ });++ it('rejects an unknown body and a cue id the schema cannot store', async () => {+ const extra = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ force: true });+ expect(extra.status).toBe(400);+ const blank = await request(app).post('/api/music-video/mv-1/lyrics/align').send({ cueId: '' });+ expect(blank.status).toBe(400);+ expect(alignProjectLyrics).not.toHaveBeenCalled();+ });++ it('accepts a lyric cue with word timings and a cue that has none', async () => {+ const words = [+ { w: 'walking', startSec: 0.2, endSec: 0.6, conf: 'matched' },+ { w: 'home', startSec: 0.6, endSec: 1, conf: 'interpolated' },+ ];+ const timed = await request(app).patch('/api/music-video/mv-1').send({+ lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 0.2, endSec: 1, words }],+ });+ expect(timed.status).toBe(200);+ expect(svc.updateProject).toHaveBeenCalledWith('mv-1', expect.objectContaining({+ lyricCues: [expect.objectContaining({ words })],+ }));+ const legacy = await request(app).patch('/api/music-video/mv-1').send({+ lyricCues: [{ text: 'walking home', startSec: null, endSec: null }],+ });+ expect(legacy.status).toBe(200);+ const bad = await request(app).patch('/api/music-video/mv-1').send({+ lyricCues: [{ text: 'walking home', words: [{ w: 'walking', startSec: 1, endSec: 0.2, conf: 'guessed' }] }],+ });+ expect(bad.status).toBe(400);+ });+ });+it('DELETE /:id soft-deletes', async () => {const r = await request(app).delete('/api/music-video/mv-1');expect(r.status).toBe(200);diff --git a/server/services/musicVideo/lyricAlign.js b/server/services/musicVideo/lyricAlign.jsnew file mode 100644index 0000000000..7cd04a3a90--- /dev/null+++ b/server/services/musicVideo/lyricAlign.js@@ -0,0 +1,505 @@+/**+ * Music Video word-level lyric alignment (#9074).+ *+ * Runs only when the director clicks Align words (or a line's Re-align).+ * The vocal stem is the audio when one is attached; otherwise the master.+ * ffmpeg decodes that file to 16 kHz mono PCM, the local whisper.cpp server+ * returns word timings, and those timings are aligned to the director's+ * spelling. 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.+ */++import { mkdtemp, readFile, rm } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { ServerError } from '../../lib/errorHandler.js';+import { findFfmpeg, runFfmpegProcess } from '../../lib/ffmpeg.js';+import { STT_TIMEOUT_MS, transcribe } from '../voice/stt.js';+import { getProject, updateProject } from './projects.js';+import { lyricTokens } from './timedText.js';+import { resolveVocalStemPath } from './vocalStem.js';++export const LYRIC_ALIGN_SAMPLE_RATE = 16000;+export const LYRIC_ALIGN_CHUNK_SEC = 20;+export const LYRIC_ALIGN_OVERLAP_SEC = 2;++const round3 = (n) => Math.round(n * 1000) / 1000;++/**+ * Audio seconds per whisper request. The wall-clock budget is STT_TIMEOUT_MS;+ * eight seconds of that stay free for the model to start, and a chunk never+ * grows past LYRIC_ALIGN_CHUNK_SEC.+ */+export function lyricAlignChunkSec(timeoutMs = STT_TIMEOUT_MS) {+ const budgetSec = (Number(timeoutMs) || STT_TIMEOUT_MS) / 1000;+ return Math.max(8, Math.min(LYRIC_ALIGN_CHUNK_SEC, budgetSec - 8));+}++export function lyricAlignFfmpegArgs(sourcePath, outPath) {+ return ['-v', 'error', '-i', sourcePath, '-ac', '1', '-ar', String(LYRIC_ALIGN_SAMPLE_RATE), '-c:a', 'pcm_s16le', '-y', outPath];+}++export function explainSttFailure(err) {+ const msg = String(err?.message || '');+ if (/whisper inference failed:/i.test(msg)) {+ return 'Speech-to-text rejected the audio. Enable the local whisper server in Settings → Voice and try Align words again.';+ }+ if (/timed out|timeout|aborted/i.test(msg)) {+ return 'Speech-to-text did not answer in time. Enable the local whisper server in Settings → Voice and try Align words again.';+ }+ return 'Speech-to-text is not running. Enable the local whisper server in Settings → Voice, then try Align words again.';+}++/** Chunk a song so each whisper call fits the timeout, overlapping the seams. */+export function planAudioChunks(durationSec, { chunkSec = lyricAlignChunkSec(), overlapSec = LYRIC_ALIGN_OVERLAP_SEC } = {}) {+ if (!(durationSec > 0)) return [];+ const overlap = Math.min(overlapSec, chunkSec / 4);+ if (durationSec <= chunkSec + 0.05) return [{ startSec: 0, endSec: round3(durationSec) }];+ const stride = Math.max(0.5, chunkSec - overlap);+ const chunks = [];+ for (let start = 0; start < durationSec - 0.05; start += stride) {+ const end = Math.min(durationSec, start + chunkSec);+ chunks.push({ startSec: round3(start), endSec: round3(end) });+ if (end >= durationSec - 0.001) break;+ }+ return chunks;+}++/**+ * Join overlapped chunk transcripts. Each word is kept by the chunk that owns+ * its midpoint, and chunk-relative times are shifted onto the song clock.+ */+export function mergeChunkWords(chunks) {+ const list = Array.isArray(chunks) ? chunks : [];+ const owned = [];+ for (let i = 0; i < list.length; i++) {+ const chunk = list[i];+ const prev = list[i - 1];+ const next = list[i + 1];+ const ownStart = prev ? (chunk.startSec + prev.endSec) / 2 : chunk.startSec;+ const ownEnd = next ? (next.startSec + chunk.endSec) / 2 : chunk.endSec;+ for (const word of chunk.words || []) {+ const startSec = Number(word.startSec) + chunk.startSec;+ const endSec = Number(word.endSec) + chunk.startSec;+ if (!Number.isFinite(startSec) || !Number.isFinite(endSec)) continue;+ const mid = (startSec + endSec) / 2;+ if (mid < ownStart || (next && mid >= ownEnd)) continue;+ owned.push({ text: String(word.text || ''), startSec, endSec });+ }+ }+ return owned;+}++/** Glue a contraction fragment ("'s") onto the previous recognized word. */+export function glueContractions(words) {+ const out = [];+ for (const word of words || []) {+ const text = String(word?.text ?? '').trim();+ const startSec = Number(word?.startSec);+ const endSec = Number(word?.endSec);+ if (!text || !Number.isFinite(startSec) || !Number.isFinite(endSec)) continue;+ if (out.length && /^['’]/.test(text)) {+ const prev = out[out.length - 1];+ prev.text += text;+ prev.endSec = Math.max(prev.endSec, endSec);+ continue;+ }+ out.push({ text, startSec, endSec });+ }+ return out;+}++function recognizedTokens(words) {+ const out = [];+ for (const word of glueContractions(words)) {+ const tokens = lyricTokens(word.text);+ if (tokens.length === 0) continue;+ if (tokens.length === 1) {+ out.push({ key: tokens[0].key, startSec: word.startSec, endSec: word.endSec });+ continue;+ }+ const weights = tokens.map((token) => Math.max(1, token.key.length));+ const total = weights.reduce((sum, n) => sum + n, 0);+ const span = Math.max(0, word.endSec - word.startSec);+ let cursor = word.startSec;+ tokens.forEach((token, index) => {+ const dur = span * (weights[index] / total);+ const endSec = index === tokens.length - 1 ? word.endSec : cursor + dur;+ out.push({ key: token.key, startSec: cursor, endSec });+ cursor = endSec;+ });+ }+ return out;+}++// Earliest still-available equal token. Repeated choruses stay in order+// because a match consumes that recognizer word.+function alignTokenIndexes(director, recognized) {+ const matchOf = new Array(director.length).fill(-1);+ let cursor = 0;+ for (let i = 0; i < director.length; i++) {+ for (let j = cursor; j < recognized.length; j++) {+ if (recognized[j].key !== director[i].key) continue;+ matchOf[i] = j;+ cursor = j + 1;+ break;+ }+ }+ return matchOf;+}++function distribute(tokens, left, right) {+ const span = Math.max(0, right - left);+ const weights = tokens.map((token) => Math.max(1, token.w.length));+ const total = weights.reduce((sum, n) => sum + n, 0);+ let cursor = left;+ return tokens.map((token, index) => {+ const dur = total ? span * (weights[index] / total) : 0;+ const startSec = round3(cursor);+ const endSec = round3(index === tokens.length - 1 ? left + span : cursor + dur);+ cursor += dur;+ return {+ w: token.w,+ startSec,+ endSec: endSec < startSec ? startSec : endSec,+ conf: 'interpolated',+ };+ });+}++function cueWindow(cue) {+ if (typeof cue?.startSec === 'number' && typeof cue?.endSec === 'number' && cue.endSec > cue.startSec) {+ return { startSec: cue.startSec, endSec: cue.endSec };+ }+ return null;+}++function matchedWord(token) {+ const startSec = round3(token.match.startSec);+ return {+ w: token.w,+ startSec,+ endSec: round3(Math.max(token.match.startSec, token.match.endSec)),+ conf: 'matched',+ };+}++function writeSegment(placed, cue, segment, left, right) {+ const windowed = !segment.entireCue ? cueWindow(cue) : null;+ let segLeft = left;+ let segRight = right;+ if (windowed) {+ segLeft = Math.min(windowed.endSec, Math.max(windowed.startSec, segLeft));+ segRight = Math.max(segLeft, Math.min(windowed.endSec, segRight));+ }+ if (!(segRight >= segLeft)) segRight = segLeft;+ const words = distribute(segment.tokens, segLeft, segRight);+ words.forEach((word, index) => {+ const token = segment.tokens[index];+ placed[token.cueIndex][token.wordIndex] = word;+ });+}++// One pass over the whole lyric, so an unmatched run that crosses lines shares+// the gap between the matched words around it. A line the singer skipped, and+// that already has a window, takes that window instead of the gap.+function placeAll(cues, byCue, recognized) {+ const flat = [];+ byCue.forEach((tokens, cueIndex) => {+ const entireCue = tokens.length > 0 && tokens.every((token) => !token.match);+ tokens.forEach((token, wordIndex) => flat.push({ ...token, cueIndex, wordIndex, entireCue }));+ });+ const placed = byCue.map((tokens) => new Array(tokens.length));+ const timelineStart = recognized[0]?.startSec ?? 0;+ const timelineEnd = recognized.length ? recognized[recognized.length - 1].endSec : timelineStart;+ let i = 0;+ while (i < flat.length) {+ if (flat[i].match) {+ placed[flat[i].cueIndex][flat[i].wordIndex] = matchedWord(flat[i]);+ i += 1;+ continue;+ }+ let j = i;+ while (j < flat.length && !flat[j].match) j += 1;+ const prev = i > 0 ? placed[flat[i - 1].cueIndex][flat[i - 1].wordIndex] : null;+ const next = j < flat.length ? flat[j].match : null;+ const left = prev ? prev.endSec : timelineStart;+ const right = next ? next.startSec : timelineEnd;+ const segments = [];+ for (const token of flat.slice(i, j)) {+ const last = segments[segments.length - 1];+ if (!last || last.cueIndex !== token.cueIndex) {+ segments.push({ cueIndex: token.cueIndex, tokens: [token], entireCue: token.entireCue });+ } else last.tokens.push(token);+ }+ const flex = [];+ for (const segment of segments) {+ const windowed = segment.entireCue ? cueWindow(cues[segment.cueIndex]) : null;+ if (windowed) writeSegment(placed, cues[segment.cueIndex], { ...segment, entireCue: true }, windowed.startSec, windowed.endSec);+ else flex.push(segment);+ }+ if (flex.length) {+ const weights = flex.map((segment) => segment.tokens.reduce((sum, token) => sum + Math.max(1, token.w.length), 0));+ const total = weights.reduce((sum, n) => sum + n, 0);+ let cursor = left;+ const span = Math.max(0, right - left);+ flex.forEach((segment, index) => {+ const segRight = index === flex.length - 1 ? left + span : cursor + span * (weights[index] / total);+ writeSegment(placed, cues[segment.cueIndex], segment, cursor, segRight);+ cursor = segRight;+ });+ }+ i = j;+ }+ return placed;+}++function applyWordTimes(cue, words) {+ const next = { ...cue, words };+ if (next.startSec == null && words.length) next.startSec = words[0].startSec;+ if (next.endSec == null && words.length) next.endSec = words[words.length - 1].endSec;+ if (typeof next.startSec === 'number' && typeof next.endSec === 'number' && next.endSec <= next.startSec) {+ if (cue.endSec == null) next.endSec = null;+ if (cue.startSec == null) next.startSec = null;+ }+ return next;+}++/**+ * Align director cue text to recognized words.+ * Matched words take the recognizer's times. Unmatched runs are interpolated+ * by character count between their matched neighbours, and a line that has a+ * window keeps a fully unmatched run inside that window.+ * A cue's startSec/endSec is filled from its words only when that side is null.+ */+export function alignDirectorWords(cues, recognizedWords) {+ const list = Array.isArray(cues) ? cues : [];+ const director = [];+ list.forEach((cue, cueIndex) => {+ for (const token of lyricTokens(cue?.text)) director.push({ ...token, cueIndex });+ });+ const recognized = recognizedTokens(recognizedWords);+ const matchOf = alignTokenIndexes(director, recognized);+ const byCue = list.map(() => []);+ director.forEach((token, index) => {+ const recIndex = matchOf[index];+ byCue[token.cueIndex].push({+ w: token.w,+ match: recIndex >= 0 ? recognized[recIndex] : null,+ });+ });+ const placed = placeAll(list, byCue, recognized);+ return list.map((cue, cueIndex) => {+ const words = (placed[cueIndex] || []).filter(Boolean);+ if (words.length === 0) {+ const cleared = { ...cue };+ delete cleared.words;+ return cleared;+ }+ return applyWordTimes(cue, words);+ });+}++export function encodePcm16Wav(sampleCount, sampleRate = LYRIC_ALIGN_SAMPLE_RATE) {+ const count = Math.max(0, sampleCount | 0);+ const dataBytes = count * 2;+ const buf = Buffer.alloc(44 + dataBytes);+ buf.write('RIFF', 0);+ buf.writeUInt32LE(36 + dataBytes, 4);+ buf.write('WAVE', 8);+ buf.write('fmt ', 12);+ buf.writeUInt32LE(16, 16);+ buf.writeUInt16LE(1, 20);+ buf.writeUInt16LE(1, 22);+ buf.writeUInt32LE(sampleRate, 24);+ buf.writeUInt32LE(sampleRate * 2, 28);+ buf.writeUInt16LE(2, 32);+ buf.writeUInt16LE(16, 34);+ buf.write('data', 36);+ buf.writeUInt32LE(dataBytes, 40);+ return buf;+}++export function wavInfo(buf) {+ if (!Buffer.isBuffer(buf) || buf.length < 44) return null;+ if (buf.toString('ascii', 0, 4) !== 'RIFF' || buf.toString('ascii', 8, 12) !== 'WAVE') return null;+ let offset = 12;+ let sampleRate = 0;+ let blockAlign = 2;+ let dataOffset = 0;+ let dataBytes = 0;+ while (offset + 8 <= buf.length) {+ const id = buf.toString('ascii', offset, offset + 4);+ const size = buf.readUInt32LE(offset + 4);+ const body = offset + 8;+ if (id === 'fmt ' && body + 16 <= buf.length) {+ sampleRate = buf.readUInt32LE(body + 4);+ blockAlign = buf.readUInt16LE(body + 12) || 2;+ } else if (id === 'data') {+ dataOffset = body;+ dataBytes = Math.min(size, Math.max(0, buf.length - body));+ break;+ }+ offset = body + size + (size % 2);+ if (size < 0) break;+ }+ if (!sampleRate || !dataOffset) return null;+ return { sampleRate, blockAlign, dataOffset, dataBytes, sampleCount: Math.floor(dataBytes / blockAlign) };+}++export function wavDurationSec(buf) {+ const info = wavInfo(buf);+ if (!info?.sampleRate) return null;+ return info.sampleCount / info.sampleRate;+}++export function sliceWav(buf, startSec, endSec) {+ const info = wavInfo(buf);+ if (!info) throw new ServerError('Decoded audio was not a PCM WAV.', { status: 422, code: 'LYRIC_ALIGN_DECODE_FAILED' });+ const start = Math.max(0, Math.min(info.sampleCount, Math.round(startSec * info.sampleRate)));+ const end = Math.max(start, Math.min(info.sampleCount, Math.round(endSec * info.sampleRate)));+ const out = encodePcm16Wav(end - start, info.sampleRate);+ buf.copy(out, 44, info.dataOffset + start * info.blockAlign, info.dataOffset + end * info.blockAlign);+ return out;+}++async function decodeSourceToWav(sourcePath) {+ const ffmpeg = await findFfmpeg();+ if (!ffmpeg) {+ throw new ServerError('ffmpeg is required to align lyrics to the vocal.', { status: 500, code: 'FFMPEG_MISSING' });+ }+ const dir = await mkdtemp(join(tmpdir(), 'lyric-align-'));+ const outPath = join(dir, 'vocal.wav');+ try {+ const result = await runFfmpegProcess({ bin: ffmpeg, args: lyricAlignFfmpegArgs(sourcePath, outPath) });+ if (!result.ok) {+ console.error(`❌ Lyric alignment could not decode audio: ${result.reason}`);+ throw new ServerError('Could not decode the song for lyric alignment.', { status: 422, code: 'LYRIC_ALIGN_DECODE_FAILED' });+ }+ return await readFile(outPath);+ } finally {+ await rm(dir, { recursive: true, force: true }).catch(() => {});+ }+}++export async function pickAlignmentPath(project, io = {}) {+ const resolveStem = io.resolveStem || resolveVocalStemPath;+ const resolveMaster = io.resolveMaster || (async (record) => {+ const { resolveMasterAudioPath } = await import('./render.js');+ return resolveMasterAudioPath(record);+ });+ const stem = resolveStem(project);+ if (stem) return { path: stem, source: 'vocal-stem' };+ return { path: await resolveMaster(project), source: 'master' };+}++const audioKey = (project) => `${project?.trackId ?? ''}\u0000${project?.uploadedAudioFilename ?? ''}`;+const textKey = (cues) => (cues || []).map((cue) => `${cue.id ?? ''}\u0000${cue.text ?? ''}`).join('\n');++function alignmentPrompt(cues) {+ return (cues || []).map((cue) => cue?.text || '').filter(Boolean).join('\n').slice(0, 800);+}++async function recognizeRegion(wav, region, transcribeFn, prompt) {+ const duration = wavDurationSec(wav);+ if (!(duration > 0)) {+ throw new ServerError('Could not read the decoded vocal.', { status: 422, code: 'LYRIC_ALIGN_DECODE_FAILED' });+ }+ const regionStart = Math.max(0, region.startSec || 0);+ const regionEnd = Math.min(duration, region.endSec ?? duration);+ if (!(regionEnd > regionStart)) {+ throw new ServerError('That lyric line has no audio window to align.', { status: 422, code: 'LYRIC_ALIGN_NO_WINDOW' });+ }+ const span = regionEnd - regionStart;+ const chunks = planAudioChunks(span).map((chunk) => ({+ startSec: regionStart + chunk.startSec,+ endSec: regionStart + chunk.endSec,+ }));+ console.log(`🎤 Aligning lyric words (${chunks.length} whisper ${chunks.length === 1 ? 'chunk' : 'chunks'})`);+ const results = [];+ for (const chunk of chunks) {+ const slice = sliceWav(wav, chunk.startSec, chunk.endSec);+ let result;+ try {+ result = await transcribeFn(slice, {+ verbose: true,+ mimeType: 'audio/wav',+ filename: 'lyric-align.wav',+ prompt,+ });+ } catch (err) {+ console.error(`❌ Lyric alignment speech-to-text failed: ${err.message}`);+ throw new ServerError(explainSttFailure(err), { status: 503, code: 'LYRIC_ALIGN_STT_UNAVAILABLE' });+ }+ results.push({+ startSec: chunk.startSec,+ endSec: chunk.endSec,+ words: (result?.words || []).map((word) => ({+ text: word.text,+ startSec: word.startSec,+ endSec: word.endSec,+ })),+ });+ }+ return mergeChunkWords(results);+}++/**+ * 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.+ */+export async function alignProjectLyrics(projectId, options = {}) {+ const deps = {+ getProject,+ updateProject,+ resolveAudio: pickAlignmentPath,+ decodeAudio: decodeSourceToWav,+ transcribe,+ ...options.deps,+ };+ const cueId = options.cueId || null;+ const 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) {+ throw new ServerError('Add lyric lines before aligning words.', { status: 400, code: 'NO_LYRICS' });+ }+ 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 { path: audioPath, source } = await deps.resolveAudio(project);+ const wav = await deps.decodeAudio(audioPath);+ const duration = wavDurationSec(wav);+ const windowed = cue && cueWindow(cue);+ const region = windowed+ ? { startSec: windowed.startSec, endSec: Math.min(windowed.endSec, duration || windowed.endSec) }+ : { startSec: 0, endSec: duration };+ const recognized = await recognizeRegion(wav, region, deps.transcribe, alignmentPrompt(windowed ? [cue] : cues));+ if (!windowed && recognized.length === 0) {+ throw new ServerError(+ 'Speech-to-text returned no words for this audio. Enable the local whisper server in Settings → Voice and try Align words again.',+ { status: 422, code: 'LYRIC_ALIGN_EMPTY' },+ );+ }++ const fresh = await deps.getProject(projectId);+ if (!fresh || audioKey(fresh) !== audioKey(project)) {+ 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)) {+ throw new ServerError('The lyric lines changed while they were aligning. Run Align words again.', { status: 409, code: 'LYRIC_ALIGN_TEXT_CHANGED' });+ }++ let nextCues;+ if (windowed) {+ const [aligned] = alignDirectorWords([cue], recognized);+ nextCues = freshCues.map((entry) => (entry.id === cue.id ? { ...entry, ...aligned, id: entry.id } : entry));+ } else {+ const aligned = alignDirectorWords(freshCues, recognized);+ nextCues = cueId ? freshCues.map((entry, index) => (entry.id === cueId ? aligned[index] : entry)) : aligned;+ }+ console.log(`🎤 Aligned lyric words from the ${source}`);+ return deps.updateProject(projectId, { lyricCues: nextCues });+}diff --git a/server/services/musicVideo/lyricAlign.test.js b/server/services/musicVideo/lyricAlign.test.jsnew file mode 100644index 0000000000..f48e0f0014--- /dev/null+++ b/server/services/musicVideo/lyricAlign.test.js@@ -0,0 +1,259 @@+import { describe, it, expect, vi } from 'vitest';+import { ServerError } from '../../lib/errorHandler.js';+import {+ alignDirectorWords,+ alignProjectLyrics,+ encodePcm16Wav,+ explainSttFailure,+ lyricAlignChunkSec,+ lyricAlignFfmpegArgs,+ mergeChunkWords,+ pickAlignmentPath,+ planAudioChunks,+ sliceWav,+ wavDurationSec,+} from './lyricAlign.js';+import { STT_TIMEOUT_MS } from '../voice/stt.js';++const round3 = (n) => Math.round(n * 1000) / 1000;++function groundWords(count, origin = 0.2) {+ return Array.from({ length: count }, (_, i) => {+ const startSec = round3(origin + i * 0.5);+ return { w: `w${i}`, startSec, endSec: round3(startSec + 0.4) };+ });+}++function within80(word, truth) {+ return Math.abs(word.startSec - truth.startSec) <= 0.08 && Math.abs(word.endSec - truth.endSec) <= 0.08;+}++describe('alignDirectorWords', () => {+ it('places at least 90% of a synthetic phrase within 80ms and flags the interpolated word', () => {+ const ground = groundWords(20);+ const duration = 12;+ const dropped = 'w7';+ const chunks = planAudioChunks(duration, { chunkSec: 8, overlapSec: 2 });+ expect(chunks.length).toBeGreaterThan(1);+ const recognized = mergeChunkWords(chunks.map((chunk) => ({+ ...chunk,+ words: ground+ .filter((word) => word.w !== dropped)+ .filter((word) => {+ const mid = (word.startSec + word.endSec) / 2;+ return mid >= chunk.startSec && mid < chunk.endSec;+ })+ .map((word) => ({+ text: word.w,+ startSec: word.startSec - chunk.startSec,+ endSec: word.endSec - chunk.startSec,+ })),+ })));+ const [aligned] = alignDirectorWords(+ [{ id: 'lc-1', text: ground.map((word) => word.w).join(' '), startSec: null, endSec: null }],+ recognized,+ );+ const hits = aligned.words.filter((word, index) => within80(word, ground[index]));+ expect(hits.length / aligned.words.length).toBeGreaterThanOrEqual(0.9);+ expect(aligned.words).toHaveLength(ground.length);+ expect(aligned.words.find((word) => word.w === dropped).conf).toBe('interpolated');+ expect(aligned.words.filter((word) => word.w !== dropped).every((word) => word.conf === 'matched')).toBe(true);+ // The line had no director times, so the cue takes its first and last word.+ expect(aligned.startSec).toBe(aligned.words[0].startSec);+ expect(aligned.endSec).toBe(aligned.words.at(-1).endSec);+ });++ it('keeps a skipped line inside its window and leaves the sung lines on the vocal', () => {+ const cues = [+ { id: 'a', text: 'walking home', startSec: 0.4, endSec: 1.6 },+ { id: 'b', text: 'not sung here', startSec: 3, endSec: 4 },+ { id: 'c', text: 'under neon', startSec: 5, endSec: 6.2 },+ ];+ const aligned = alignDirectorWords(cues, [+ { text: 'walking', startSec: 0.5, endSec: 1 },+ { text: 'home', startSec: 1, endSec: 1.5 },+ { text: 'under', startSec: 5.1, endSec: 5.4 },+ { text: 'neon', startSec: 5.4, endSec: 5.9 },+ ]);+ expect(aligned[1].words.every((word) => word.conf === 'interpolated')).toBe(true);+ expect(aligned[1].words.every((word) => word.startSec >= 3 && word.endSec <= 4)).toBe(true);+ expect(aligned[0].words.map((word) => [word.startSec, word.conf])).toEqual([+ [0.5, 'matched'],+ [1, 'matched'],+ ]);+ expect(aligned[2].words[0]).toMatchObject({ w: 'under', startSec: 5.1, conf: 'matched' });+ // Director-set line times stay put.+ expect(aligned[0].startSec).toBe(0.4);+ expect(aligned[2].endSec).toBe(6.2);+ });++ it('matches a repeated chorus to its own occurrence', () => {+ const aligned = alignDirectorWords([+ { id: 'a', text: 'we go', startSec: null, endSec: null },+ { id: 'b', text: 'we go', startSec: null, endSec: null },+ ], [+ { text: 'we', startSec: 1, endSec: 1.2 },+ { text: 'go', startSec: 1.2, endSec: 1.5 },+ { text: 'we', startSec: 8, endSec: 8.2 },+ { text: 'go', startSec: 8.2, endSec: 8.6 },+ ]);+ expect(aligned[0].words.map((word) => word.startSec)).toEqual([1, 1.2]);+ expect(aligned[1].words.map((word) => word.startSec)).toEqual([8, 8.2]);+ });++ it('divides an unmatched run between its matched neighbours by character count', () => {+ const [aligned] = alignDirectorWords(+ [{ id: 'a', text: 'hi ab abcd yo', startSec: null, endSec: null }],+ [+ { text: 'hi', startSec: 0, endSec: 1 },+ { text: 'yo', startSec: 7, endSec: 8 },+ ],+ );+ expect(aligned.words[1]).toMatchObject({ w: 'ab', startSec: 1, endSec: 3, conf: 'interpolated' });+ expect(aligned.words[2]).toMatchObject({ w: 'abcd', startSec: 3, endSec: 7, conf: 'interpolated' });+ expect(aligned.words[0].startSec).toBe(0);+ expect(aligned.words[3].startSec).toBe(7);+ });++ it('fills only the cue times the director left empty', () => {+ const [aligned] = alignDirectorWords(+ [{ id: 'a', text: 'walking home', startSec: 1, endSec: null }],+ [+ { text: 'walking', startSec: 1.2, endSec: 1.5 },+ { text: 'home', startSec: 1.5, endSec: 1.9 },+ ],+ );+ expect(aligned.startSec).toBe(1);+ expect(aligned.endSec).toBe(1.9);+ });+});++describe('lyric alignment audio', () => {+ it('decodes to 16 kHz mono PCM and slices a window without shifting the clock', () => {+ expect(lyricAlignFfmpegArgs('/songs/mix.wav', '/tmp/vocal.wav')).toEqual([+ '-v', 'error', '-i', '/songs/mix.wav', '-ac', '1', '-ar', '16000', '-c:a', 'pcm_s16le', '-y', '/tmp/vocal.wav',+ ]);+ expect(lyricAlignChunkSec(STT_TIMEOUT_MS)).toBeLessThanOrEqual(STT_TIMEOUT_MS / 1000 - 8);+ const wav = encodePcm16Wav(16000 * 4);+ expect(wavDurationSec(wav)).toBeCloseTo(4, 3);+ expect(wavDurationSec(sliceWav(wav, 1, 2.5))).toBeCloseTo(1.5, 3);+ });++ it('uses the vocal stem when one is attached, and does not fall back when that 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' });+ expect(resolveMaster).not.toHaveBeenCalled();++ await expect(pickAlignmentPath({}, {+ resolveStem: () => null,+ resolveMaster,+ })).resolves.toEqual({ path: '/library/mix.wav', source: 'master' });++ const missing = new ServerError('missing', { status: 404, code: 'MUSIC_VIDEO_VOCAL_STEM_MISSING' });+ await expect(pickAlignmentPath({ vocalStemFilename: 'gone.wav' }, {+ resolveStem: () => { throw missing; },+ resolveMaster,+ })).rejects.toMatchObject({ code: 'MUSIC_VIDEO_VOCAL_STEM_MISSING' });+ });+});++describe('alignProjectLyrics', () => {+ const project = {+ id: 'mv-1',+ trackId: 't1',+ lyricCues: [+ { id: 'lc-1', text: 'walking home', startSec: 1, endSec: null },+ { id: 'lc-2', text: 'not sung here', startSec: 2, endSec: 2.8 },+ ],+ };++ function harness(transcribe, record = project) {+ const updateProject = vi.fn(async (id, patch) => ({ id, ...record, ...patch }));+ const decodeAudio = vi.fn(async () => encodePcm16Wav(16000 * 3));+ const getProject = vi.fn(async () => record);+ return {+ updateProject,+ decodeAudio,+ transcribe,+ run: (opts = {}) => alignProjectLyrics(record.id, {+ ...opts,+ deps: {+ getProject,+ updateProject,+ resolveAudio: async () => ({ path: 'song.wav', source: 'master' }),+ decodeAudio,+ transcribe,+ },+ }),+ };+ }++ it('writes matched and interpolated words, and does not replace a time the director set', async () => {+ const transcribe = vi.fn(async () => ({+ text: 'walking home',+ words: [+ { text: 'walking', startSec: 0.5, endSec: 1 },+ { text: 'home', startSec: 1, endSec: 1.5 },+ ],+ latencyMs: 4,+ }));+ const { run, updateProject } = harness(transcribe);+ const saved = await run();+ expect(transcribe).toHaveBeenCalledWith(expect.any(Buffer), expect.objectContaining({ verbose: true }));+ expect(saved.lyricCues[0]).toMatchObject({+ startSec: 1,+ endSec: 1.5,+ words: [+ { w: 'walking', startSec: 0.5, endSec: 1, conf: 'matched' },+ { w: 'home', startSec: 1, endSec: 1.5, conf: 'matched' },+ ],+ });+ expect(saved.lyricCues[1].words.every((word) => word.conf === 'interpolated')).toBe(true);+ expect(saved.lyricCues[1].words.every((word) => word.startSec >= 2 && word.endSec <= 2.8)).toBe(true);+ expect(updateProject).toHaveBeenCalledOnce();+ });++ it('re-aligns one windowed line without moving the other line', async () => {+ const record = {+ ...project,+ lyricCues: [+ {+ id: 'lc-1', text: 'walking home', startSec: 0.5, endSec: 1.5,+ words: [+ { w: 'walking', startSec: 0.5, endSec: 1, conf: 'matched' },+ { w: 'home', startSec: 1, endSec: 1.5, conf: 'matched' },+ ],+ },+ { id: 'lc-2', text: 'not sung here', startSec: 2, endSec: 2.8 },+ ],+ };+ const transcribe = vi.fn(async () => ({ text: '', words: [], latencyMs: 1 }));+ const saved = await harness(transcribe, record).run({ cueId: 'lc-2' });+ expect(saved.lyricCues[0].words).toEqual(record.lyricCues[0].words);+ expect(saved.lyricCues[1].words.every((word) => word.conf === 'interpolated')).toBe(true);+ expect(saved.lyricCues[1].words.every((word) => word.startSec >= 2 && word.endSec <= 2.8)).toBe(true);+ });++ it('reports an unreachable speech-to-text server instead of saving empty timings', async () => {+ const transcribe = vi.fn(async () => { throw new Error('fetch failed'); });+ const { run, updateProject } = harness(transcribe);+ await expect(run()).rejects.toMatchObject({+ status: 503,+ code: 'LYRIC_ALIGN_STT_UNAVAILABLE',+ message: expect.stringMatching(/Settings → Voice/),+ });+ expect(updateProject).not.toHaveBeenCalled();+ expect(explainSttFailure(new Error('fetch failed'))).toMatch(/not running/);+ });++ it('does not transcribe when the project has no lyric lines', async () => {+ const transcribe = vi.fn();+ const { run, decodeAudio } = harness(transcribe, { ...project, lyricCues: [] });+ await expect(run()).rejects.toMatchObject({ code: 'NO_LYRICS' });+ expect(transcribe).not.toHaveBeenCalled();+ expect(decodeAudio).not.toHaveBeenCalled();+ });+});diff --git a/server/services/musicVideo/projectsFile.test.js b/server/services/musicVideo/projectsFile.test.jsindex fae7c5ce84..fa7e429267 100644--- a/server/services/musicVideo/projectsFile.test.js+++ b/server/services/musicVideo/projectsFile.test.js@@ -170,6 +170,36 @@ describe('projectsFile federation (#1770)', () => {expect(swapped.phrases).toEqual([{ ...saved.phrases[0], startSec: null, endSec: null }]);});+ it('keeps a nudged word boundary through reload and clone, and drops words when the audio changes (#9074)', async () => {+ const p = await file.createProject({ name: 'Karaoke', trackId: 't1' });+ const nudged = [+ { w: 'walking', startSec: 1, endSec: 1.55, conf: 'matched' },+ { w: 'home', startSec: 1.55, endSec: 2, conf: 'matched' },+ ];+ await file.updateProject(p.id, {+ lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 1, endSec: 2, words: nudged }],+ });+ const saved = await file.getProject(p.id);+ expect(saved.lyricCues[0].words).toEqual(nudged);+ expect(saved.lyricCues[0].text).toBe('walking home');+ expect((await file.cloneProject(p.id)).lyricCues[0].words).toEqual(nudged);++ const retitled = await file.updateProject(p.id, {+ lyricCues: [{ id: 'lc-1', text: 'walking house', startSec: 1, endSec: 2, words: nudged }],+ });+ expect(retitled.lyricCues[0]).toMatchObject({ text: 'walking house', startSec: 1, endSec: 2 });+ expect(retitled.lyricCues[0].words).toBeUndefined();++ await file.updateProject(p.id, {+ lyricCues: [{ id: 'lc-1', text: 'walking home', startSec: 1, endSec: 2, words: nudged }],+ });+ const swapped = await file.updateProject(p.id, { trackId: 't2' });+ expect(swapped.lyricCues[0].text).toBe('walking home');+ expect(swapped.lyricCues[0].words).toBeUndefined();+ expect(swapped.lyricCues[0].startSec).toBeNull();+ expect(swapped.lyricCues[0].endSec).toBeNull();+ });+// #8984 — the composition manifest is editable record state like the lyric// cues: normalized on save, carried by clone and peer sync, and its timings// (cue times, poster frame) cleared with the audio source, text kept.diff --git a/server/services/musicVideo/projectsLogic.js b/server/services/musicVideo/projectsLogic.jsindex 41adce2d39..9e730addd6 100644--- a/server/services/musicVideo/projectsLogic.js+++ b/server/services/musicVideo/projectsLogic.js@@ -310,8 +310,8 @@ export function applyProjectPatch(project, patch) {// The MIDI transcription was produced from the OLD audio too — clear it with// the analysis so a stale .mid can't masquerade as the new track's score.// Lyric-cue and phrase timings were aligned to the OLD audio as well: keep the- // director's text but clear the times (#8964), unless this same patch supplied- // fresh lists of its own.+ // director's text but clear the times and word timings (#8964, #9074), unless+ // this same patch supplied fresh lists of its own.return touch(project, {...invalidateTimedText(project),// Composition cue times and the poster frame were set against the olddiff --git a/server/services/musicVideo/timedText.js b/server/services/musicVideo/timedText.jsindex 7ad6825bed..8e8ddb2ff0 100644--- a/server/services/musicVideo/timedText.js+++ b/server/services/musicVideo/timedText.js@@ -10,9 +10,9 @@** Timings are alignment DERIVED from one specific audio file; the text is the* director's own. So an audio-source change keeps every line and label but- * clears their times (`startSec`/`endSec` → null) — the planner then ignores- * them until they are re-timed against the new track, instead of cutting the- * new song on the old song's lyric positions.+ * clears their times (`startSec`/`endSec` → null) and any word timings — the+ * planner then ignores them until they are re-timed against the new track,+ * instead of cutting the new song on the old song's lyric positions.*/import { randomUUID } from 'crypto';@@ -23,6 +23,14 @@ const MAX_SEC = 36000;const round3 = (n) => Math.round(n * 1000) / 1000;+/** One sung word: the director's spelling plus a key with punctuation stripped. */+export function lyricTokens(text) {+ return String(text || '').split(/\s+/).filter(Boolean).map((w) => {+ const key = w.toLowerCase().replace(/[^a-z0-9']+/g, '');+ return key ? { w, key } : null;+ }).filter(Boolean);+}+function toTime(value) {return typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= MAX_SEC? round3(value)@@ -56,10 +64,30 @@ function normalizeList(list, prefix, shape) {return out;}+// Word timings belong to the current spelling. A text edit drops them; a+// boundary nudge (same words, new times) keeps them. One bad entry drops the+// list rather than persisting a partial karaoke line.+function normalizeWords(text, words) {+ const tokens = lyricTokens(text);+ if (!Array.isArray(words) || words.length === 0 || words.length !== tokens.length) return null;+ const out = [];+ for (let i = 0; i < words.length; i++) {+ const word = words[i];+ const startSec = toTime(word?.startSec);+ const endSec = toTime(word?.endSec);+ const conf = word?.conf === 'matched' || word?.conf === 'interpolated' ? word.conf : null;+ if (!conf || startSec == null || endSec == null || endSec < startSec || word.w !== tokens[i].w) return null;+ out.push({ w: tokens[i].w, startSec, endSec, conf });+ }+ return out;+}+/** Normalize an edited cue list: keep ids, trim text, drop empty lines. Order is kept (lyric order). */export const normalizeLyricCues = (cues) => normalizeList(cues, 'lc', (cue) => {const text = trimTo(cue.text, MAX_CUE_TEXT);- return text ? { text } : null;+ if (!text) return null;+ const words = normalizeWords(text, cue.words);+ return words ? { text, words } : { text };});/** Normalize an edited phrase list: keep ids, trim label/intent. */@@ -70,10 +98,17 @@ export const normalizePhrases = (phrases) => normalizeList(phrases, 'mp', (phras/** Clear the audio-derived timings on every cue/phrase, keeping the authored text. */export function invalidateTimedText(project) {- const clear = (list) => (Array.isArray(list) ? list.map((e) => ({ ...e, startSec: null, endSec: null })) : list);+ const clearTimes = (list) => (Array.isArray(list) ? list.map((e) => ({ ...e, startSec: null, endSec: null })) : list);+ // `words` is derived from the same audio as the line times. Drop the key so+ // a later sync does not treat stale karaoke timings as still current.+ const clearCues = (list) => (Array.isArray(list) ? list.map((e) => {+ const next = { ...e, startSec: null, endSec: null };+ delete next.words;+ return next;+ }) : list);return {- ...(Array.isArray(project.lyricCues) ? { lyricCues: clear(project.lyricCues) } : {}),- ...(Array.isArray(project.phrases) ? { phrases: clear(project.phrases) } : {}),+ ...(Array.isArray(project.lyricCues) ? { lyricCues: clearCues(project.lyricCues) } : {}),+ ...(Array.isArray(project.phrases) ? { phrases: clearTimes(project.phrases) } : {}),};}diff --git a/server/services/voice/stt.js b/server/services/voice/stt.jsindex 9f9bbeefb2..67e0316359 100644--- a/server/services/voice/stt.js+++ b/server/services/voice/stt.js@@ -4,7 +4,7 @@import { getVoiceConfig } from './config.js';import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';-const STT_TIMEOUT_MS = 30_000;+export const STT_TIMEOUT_MS = 30_000;// Vocabulary bias: whisper.cpp's `prompt` field seeds the decoder with context// so proper nouns and PortOS-specific terms are transcribed correctly instead@@ -19,7 +19,9 @@ const DEFAULT_STT_PROMPT = 'PortOS, Chief of Staff, brain inbox, brain capture,* @param {string} [opts.mimeType='audio/wav']* @param {string} [opts.endpoint] override default endpoint* @param {AbortSignal} [opts.signal] upstream abort (barge-in) — cancels STT mid-flight- * @returns {Promise<{ text: string, latencyMs: number }>}+ * @param {boolean} [opts.verbose] word timestamps via verbose_json (lyric alignment)+ * @param {string} [opts.prompt] decoder prompt; empty string disables the vocabulary bias+ * @returns {Promise<{ text: string, latencyMs: number, words?: Array<{ text: string, startSec: number, endSec: number }> }>}*/export const transcribe = async (audio, opts = {}) => {const cfg = await getVoiceConfig();@@ -30,14 +32,24 @@ export const transcribe = async (audio, opts = {}) => {const language = opts.language || cfg.stt.language || 'en';const mimeType = opts.mimeType || 'audio/wav';const filename = opts.filename || 'audio.wav';+ const verbose = opts.verbose === true;+ // Lyric alignment passes the director's line. An absent prompt keeps the+ // voice vocabulary; a present string, including '', replaces it.+ const prompt = opts.prompt != null ? String(opts.prompt) : (cfg.stt.vocabularyPrompt || DEFAULT_STT_PROMPT);const blob = new Blob([audio], { type: mimeType });const form = new FormData();form.append('file', blob, filename);- form.append('response_format', 'json');+ form.append('response_format', verbose ? 'verbose_json' : 'json');+ if (verbose) {+ // whisper.cpp splits the verbose_json `words` array on word boundaries+ // only when this flag is set; otherwise tokens break mid-word.+ form.append('split_on_word', 'true');+ form.append('token_timestamps', 'true');+ }form.append('language', language);form.append('temperature', '0');- form.append('prompt', cfg.stt.vocabularyPrompt || DEFAULT_STT_PROMPT);+ form.append('prompt', prompt);const started = Date.now();// fetchWithTimeout composes our timeout with the caller's abort signal so@@ -57,5 +69,82 @@ export const transcribe = async (audio, opts = {}) => {}const data = await res.json();- return { text: (data.text || '').trim(), latencyMs: Date.now() - started };+ const text = (data.text || '').trim();+ const latencyMs = Date.now() - started;+ if (!verbose) return { text, latencyMs };+ return { text, latencyMs, words: extractVerboseWords(data) };};++const SPECIAL_TOKEN = /^(?:\[.*?\]|<\|.*?\|>)$/;++/** Parse a whisper timestamp: seconds, or `hh:mm:ss,mmm` / `mm:ss.mmm`. */+export function asSeconds(value) {+ if (typeof value === 'number' && Number.isFinite(value)) return value;+ if (typeof value !== 'string') return null;+ const text = value.trim();+ const hms = text.match(/^(\d+):(\d{2}):(\d{2})[.,](\d{1,3})$/);+ if (hms) {+ return Number(hms[1]) * 3600 + Number(hms[2]) * 60 + Number(hms[3]) + Number(hms[4]) / 10 ** hms[4].length;+ }+ const ms = text.match(/^(\d+):(\d{2})[.,](\d{1,3})$/);+ if (ms) return Number(ms[1]) * 60 + Number(ms[2]) + Number(ms[3]) / 10 ** ms[3].length;+ const parsed = Number(text);+ return Number.isFinite(parsed) ? parsed : null;+}++function pushWord(out, text, start, end) {+ const trimmed = String(text || '').trim();+ if (!trimmed || SPECIAL_TOKEN.test(trimmed) || start == null || end == null || end < start) return;+ out.push({ text: trimmed, startSec: start, endSec: end });+}++function wordsFromList(list) {+ const out = [];+ if (!Array.isArray(list)) return out;+ for (const item of list) {+ if (!item || typeof item !== 'object') continue;+ const start = asSeconds(item.start ?? item.startSec ?? item.timestamps?.from);+ const end = asSeconds(item.end ?? item.endSec ?? item.timestamps?.to);+ pushWord(out, item.word ?? item.text, start, end);+ }+ return out;+}++// Subword tokens (" Hel" + "lo") become one word. A leading space, which is+// how whisper marks a word boundary, starts a new word.+function wordsFromTokens(tokens) {+ if (!Array.isArray(tokens) || tokens.length === 0 || typeof tokens[0] === 'number') return [];+ const out = [];+ let current = null;+ for (const token of tokens) {+ const raw = typeof token === 'string' ? token : String(token?.text ?? token?.word ?? '');+ if (!raw || SPECIAL_TOKEN.test(raw.trim())) continue;+ const start = asSeconds(token?.timestamps?.from ?? token?.start ?? token?.startSec);+ const end = asSeconds(token?.timestamps?.to ?? token?.end ?? token?.endSec);+ if (start == null || end == null) continue;+ const text = raw.trim();+ if (!text) continue;+ if (!current || /^\s/.test(raw)) {+ current = { text, startSec: start, endSec: end };+ out.push(current);+ } else {+ current.text += text;+ current.endSec = end;+ }+ }+ return out;+}++/**+ * Word timings from a whisper.cpp `verbose_json` body. Prefers the `words`+ * array (word-split tokens) and falls back to grouping subword tokens.+ * @returns {Array<{ text: string, startSec: number, endSec: number }>}+ */+export function extractVerboseWords(data) {+ const segments = Array.isArray(data?.segments) ? data.segments : [];+ const segmented = segments.some((segment) => Array.isArray(segment?.words) && segment.words.length);+ if (segmented) return segments.flatMap((segment) => wordsFromList(segment.words));+ const top = wordsFromList(data?.words);+ if (top.length) return top;+ return segments.flatMap((segment) => wordsFromTokens(segment?.tokens));+}diff --git a/server/services/voice/stt.test.js b/server/services/voice/stt.test.jsnew file mode 100644index 0000000000..c8d900b050--- /dev/null+++ b/server/services/voice/stt.test.js@@ -0,0 +1,77 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++vi.mock('./config.js', () => ({+ getVoiceConfig: vi.fn(async () => ({+ stt: { endpoint: 'http://127.0.0.1:9', language: 'en', vocabularyPrompt: 'bias terms' },+ })),+}));++vi.mock('../../lib/fetchWithTimeout.js', () => ({+ fetchWithTimeout: vi.fn(),+}));++import { fetchWithTimeout } from '../../lib/fetchWithTimeout.js';+import { extractVerboseWords, transcribe } from './stt.js';++const ok = (data) => ({+ ok: true,+ status: 200,+ statusText: 'OK',+ json: async () => data,+ text: async () => JSON.stringify(data),+});++describe('transcribe verbose word timings', () => {+ beforeEach(() => vi.clearAllMocks());++ it('keeps the plain json path for voice turns', async () => {+ fetchWithTimeout.mockResolvedValue(ok({ text: ' hello ' }));+ await expect(transcribe(Buffer.from('x'))).resolves.toMatchObject({ text: 'hello' });+ const form = fetchWithTimeout.mock.calls[0][1].body;+ expect(form.get('response_format')).toBe('json');+ expect(form.get('split_on_word')).toBeNull();+ expect(form.get('prompt')).toBe('bias terms');+ });++ it('asks whisper for word-split verbose json and returns those words', async () => {+ fetchWithTimeout.mockResolvedValue(ok({+ text: " That's one",+ segments: [{+ words: [+ { word: ' That', start: 0.16, end: 0.31 },+ { word: "'s", start: 0.38, end: 0.49 },+ { word: ' one', start: 0.5, end: 0.8 },+ ],+ }],+ }));+ const result = await transcribe(Buffer.from('x'), { verbose: true, prompt: 'walking home' });+ expect(result.words).toEqual([+ { text: 'That', startSec: 0.16, endSec: 0.31 },+ { text: "'s", startSec: 0.38, endSec: 0.49 },+ { text: 'one', startSec: 0.5, endSec: 0.8 },+ ]);+ const form = fetchWithTimeout.mock.calls[0][1].body;+ expect(form.get('response_format')).toBe('verbose_json');+ expect(form.get('split_on_word')).toBe('true');+ expect(form.get('token_timestamps')).toBe('true');+ expect(form.get('prompt')).toBe('walking home');+ });+});++describe('extractVerboseWords', () => {+ it('groups subword tokens on whisper word boundaries and drops special tokens', () => {+ expect(extractVerboseWords({+ segments: [{+ tokens: [+ { text: '[_BEG_]', timestamps: { from: '00:00:00,000', to: '00:00:00,000' } },+ { text: ' Hel', timestamps: { from: '00:00:01,000', to: '00:00:01,200' } },+ { text: 'lo', timestamps: { from: '00:00:01,200', to: '00:00:01,450' } },+ { text: ' there', timestamps: { from: '00:00:01,500', to: '00:00:01,900' } },+ ],+ }],+ })).toEqual([+ { text: 'Hello', startSec: 1, endSec: 1.45 },+ { text: 'there', startSec: 1.5, endSec: 1.9 },+ ]);+ });+});