mirror of
https://github.com/mudler/LocalAI.git
synced 2026-07-02 20:37:03 -04:00
* feat(realtime): EOU-driven semantic_vad turn detection Add a `semantic_vad` turn-detection mode to the realtime API that feeds the transcription model live and decides "the user finished speaking" from the `<EOU>` end-of-utterance token rather than from silence alone. When EOU fires the turn commits immediately (~0.3s); otherwise it falls back to an eagerness-scaled silence threshold (low/med/high = 8/4/2s). Plumbing, bottom to top: - proto: `AudioTranscriptionLive` bidirectional RPC (config-first oneof, mono float PCM @16k, ready-ack / Unimplemented degrade signal) plus `TranscriptResult.eou` for the unary retranscribe gate. - pkg/grpc: client/server/base/embed scaffolding for the bidi stream, modeled on AudioTransformStream; release stream conns on terminal Recv. - parakeet-cpp: live transcription RPC with per-C-call engine locking (one live stream per turn, finalize+free at commit); bump parakeet.cpp to ABI v5 — incremental StreamingMel (no more quadratic per-feed mel recompute that delayed EOU on long turns) and the <EOU>/<EOB> split; strip the literal <EOU>/<EOB> from offline text and set Eou. - core/backend: LiveTranscriptionSession wrapper + pipeline `turn_detection:` config block (type/eagerness/retranscribe). - realtime: semantic_vad integration — live input captions streamed as transcription deltas while the user speaks, EOU-immediate commit with eagerness fallback, optional retranscribe gate (batch re-decode must also end in <EOU> to confirm), clause synthesis off the LLM token callback, and per-turn live-transcription / model_load telemetry. - UI: show the realtime pipeline components as a vertical list. Docs and tests included; opt-in via the pipeline YAML or per-session `session.update`. Non-streaming STT backends degrade to silence-only. Assisted-by: Claude Code:claude-opus-4-8 [Read] [Edit] [Write] [Bash] Assisted-by: Claude Code:claude-fable-5 [Read] [Edit] [Bash] Signed-off-by: Richard Palethorpe <io@richiejp.com> * feat(realtime): explicit formally-verified state machines + parakeet streaming driver The realtime API had several implicit state machines whose state was inferred from scattered booleans, channels, and five separate mutexes, leaving illegal/inconsistent states reachable. Make them explicit and keep the implementation in step with a formal design; rework the parakeet streaming backend along the same lines. Realtime state machines (M1-M5). Each is a sealed sum-type State/Event/Effect with a total, pure Next(state,event)->(state,[]effect) behind a single-writer Coordinator: M1 conncoord connection lifecycle: VAD toggle + once-only teardown (replaces vadServerStarted + a `done` channel closed from two sites). M2 turncoord turn detection: collapses speechStarted and the live-stream "turn open" flag into one state, so discardTurn can no longer desync them and suppress the next onset. M3 respcoord response coordination: serializes the dual-writer start/cancel so at most one response is live; one response.done per response.create. M4 compactcoord conversation compaction: single-flight (replaces the `compacting atomic.Bool` CAS). M5 ttscoord TTS pipeline: open->closing->closed, idempotent wait(), rejects enqueue-after-close (was a silent drop). The Coordinator/Sink/Next plumbing — only the sealed types and Next differed per machine — is extracted once into core/http/endpoints/openai/coordinator as a generic Coordinator[S,E,F]; each machine keeps its public API via type aliases, so no sink, call-site, or test moved. Hierarchy. session_lifecycle.fizz models M1 as the parent region with its children (M2/M3/M4) as one statechart and asserts ChildrenDieWithParent (conn torn => all children terminal, none start after teardown). respcoord and compactcoord gain an absorbing Terminated state + Shutdown event; conncoord's teardown drives the children terminal. This closes a compaction teardown gap: a fire-and-forget compaction could outlive a torn session — compactionSink now takes a session-scoped cancellable context + WaitGroup and joins the in-flight summarize+evict on shutdown. Formal verification. formal-verification/ holds one authoritative FizzBee spec per machine plus the composition spec, each with an always-assertion and a documented one-line edit that makes the checker fail (verified non-vacuous). scripts/realtime-conformance.sh is fail-closed: all Go conformance suites under -race AND a model-check of every .fizz spec; a missing FizzBee is a hard error (only the loud REALTIME_CONFORMANCE_SKIP_FIZZBEE=1 bypasses it, never in CI). FizzBee is pinned by sha256 and installed via scripts/install-fizzbee.sh into .tools/ (gitignored). Wired as make test-realtime-conformance, a CI workflow, and a pre-commit path filter. Go conformance tests are Ginkgo/Gomega (per the repo's forbidigo lint): transition tables + fixed-seed property walks + concurrent/-race specs, no rapid dependency. Design map: docs/design/realtime-state-machines.md. Parakeet streaming backend. The same treatment applied to the parakeet-cpp streaming paths: - AudioTranscriptionStream returns codes.Unimplemented for non-streaming models instead of decoding offline and emitting it as one delta + final. A client that asked for streaming learns the model cannot stream rather than receiving a batch result shaped like a stream. New grpcerrors.StreamTranscriptionUnsupported carries that signal; the HTTP /v1/audio/transcriptions stream path surfaces it as an SSE error event. Mirrors AudioTranscriptionLive, which already did this. - utteranceBoundary (boundary.go): a single definition of the end-of-utterance latch, replacing three open-coded finalEou toggles. Modelled as a two-valued type so illegal states are unrepresentable. - Shared decode driver (driver.go): streamFeedResult (one per-feed event) + feedChunk (hides the ABI v4 JSON vs text-only split) + feedSlices + flushTail. The feed loop is written once. - AudioTranscriptionLive becomes a bidi adapter: it streams the per-feed {delta,eou,eob,words} the realtime turn detector consumes and a terminal FinalResult carrying only Text. Segments/duration/eou are offline-only and no longer produced (nor read) on the live path; liveTraceState drops the terminal eou and keeps the per-feed eou_events count. - AudioTranscriptionStream + streamJSON merge into one driver-based function; streamSegmenter is generalized to the unified event with a text-only fallback that preserves the legacy (no-words) library's per-utterance segmentation. Verified: build/vet/gofumpt clean, golangci-lint 0 issues, all coordinator and parakeet packages under -race, the fail-closed conformance gate green, and make test-realtime (12 e2e WS+WebRTC). Assisted-by: Claude:claude-opus-4-8 [Claude Code] Signed-off-by: Richard Palethorpe <io@richiejp.com> --------- Signed-off-by: Richard Palethorpe <io@richiejp.com>
88 lines
3.3 KiB
JavaScript
88 lines
3.3 KiB
JavaScript
import { test, expect } from './coverage-fixtures.js'
|
|
|
|
// Audio snippets on the Traces page must play through a blob: object URL —
|
|
// the CSP's connect-src allows blob: but not data:, and the waveform peaks
|
|
// renderer fetch()es the player src — and must degrade to a readable note
|
|
// (not a broken player) when the stored payload is the "<truncated: N bytes>"
|
|
// marker an older server stamped into oversized fields.
|
|
|
|
// Minimal valid 16 kHz mono 16-bit PCM WAV (0.1s 440 Hz sine), base64-encoded.
|
|
function wavBase64(samples = 1600, rate = 16000) {
|
|
const dataSize = samples * 2
|
|
const buf = Buffer.alloc(44 + dataSize)
|
|
buf.write('RIFF', 0)
|
|
buf.writeUInt32LE(36 + dataSize, 4)
|
|
buf.write('WAVE', 8)
|
|
buf.write('fmt ', 12)
|
|
buf.writeUInt32LE(16, 16)
|
|
buf.writeUInt16LE(1, 20) // PCM
|
|
buf.writeUInt16LE(1, 22) // mono
|
|
buf.writeUInt32LE(rate, 24)
|
|
buf.writeUInt32LE(rate * 2, 28)
|
|
buf.writeUInt16LE(2, 32)
|
|
buf.writeUInt16LE(16, 34)
|
|
buf.write('data', 36)
|
|
buf.writeUInt32LE(dataSize, 40)
|
|
for (let i = 0; i < samples; i++) {
|
|
buf.writeInt16LE(Math.round(8000 * Math.sin((2 * Math.PI * 440 * i) / rate)), 44 + i * 2)
|
|
}
|
|
return buf.toString('base64')
|
|
}
|
|
|
|
function transcriptionTrace(audioWavBase64) {
|
|
return {
|
|
type: 'transcription',
|
|
timestamp: Date.now() * 1_000_000,
|
|
model_name: 'parakeet-test',
|
|
summary: 'transcribed utterance',
|
|
duration: 500_000_000,
|
|
error: null,
|
|
data: {
|
|
audio_wav_base64: audioWavBase64,
|
|
audio_duration_s: 0.1,
|
|
audio_snippet_s: 0.1,
|
|
audio_sample_rate: 16000,
|
|
audio_samples: 1600,
|
|
audio_rms_dbfs: -12.0,
|
|
audio_peak_dbfs: -6.0,
|
|
audio_dc_offset: 0,
|
|
},
|
|
}
|
|
}
|
|
|
|
async function openBackendTraceRow(page, traces) {
|
|
await page.route('**/api/traces', (route) => {
|
|
route.fulfill({ contentType: 'application/json', body: JSON.stringify([]) })
|
|
})
|
|
await page.route('**/api/backend-traces', (route) => {
|
|
route.fulfill({ contentType: 'application/json', body: JSON.stringify(traces) })
|
|
})
|
|
await page.goto('/app/traces')
|
|
await expect(page.locator('text=Tracing is')).toBeVisible({ timeout: 10_000 })
|
|
await page.locator('button', { hasText: 'Backend Traces' }).click()
|
|
await page.locator('td', { hasText: 'parakeet-test' }).first().click()
|
|
}
|
|
|
|
test.describe('Traces - Audio Snippets', () => {
|
|
test('plays a clip through a blob: URL, not a CSP-blocked data: URL', async ({ page }) => {
|
|
await openBackendTraceRow(page, [transcriptionTrace(wavBase64())])
|
|
|
|
// The expanded row carries the snippet metrics and a player whose source
|
|
// is an object URL (connect-src allows blob:, so the peaks fetch works).
|
|
await expect(page.locator('text=Audio Snippet')).toBeVisible()
|
|
const audio = page.locator('audio')
|
|
await expect(audio).toHaveCount(1)
|
|
const src = await audio.getAttribute('src')
|
|
expect(src).toMatch(/^blob:/)
|
|
await expect(page.getByTestId('audio-snippet-unavailable')).toHaveCount(0)
|
|
})
|
|
|
|
test('shows a readable note instead of a broken player for truncated payloads', async ({ page }) => {
|
|
await openBackendTraceRow(page, [transcriptionTrace('<truncated: 281660 bytes>')])
|
|
|
|
await expect(page.locator('text=Audio Snippet')).toBeVisible()
|
|
await expect(page.getByTestId('audio-snippet-unavailable')).toBeVisible()
|
|
await expect(page.locator('audio')).toHaveCount(0)
|
|
})
|
|
})
|