Ship live translations
with confidence
A production-ready full-stack Node.js + React application for seamless EN↔RU↔UK live auto-detect translation with voice synthesis.
⚙
Installation
Set up the project locally with Docker, Redis, and LibreTranslate in minutes.
▦
Architecture
Understand the STT → Translation → TTS pipeline and real-time Socket.io communication.
▶
Live Translation
Stream from YouTube or microphone with automatic EN/RU/UK language detection and voice output.
📜
Biblical Simulator
Test the full pipeline with AI-generated biblical passages in King James, Church Slavonic, or Ukrainian style.
🎤
Voice Training
Clone custom voices from microphone recordings or YouTube videos using ElevenLabs IVC.
Prerequisites
●
Node.js 20+
Runtime for backend and build tools
●
Docker + Docker Compose
For Redis and LibreTranslate services
●
yt-dlp + ffmpeg
Required for YouTube audio extraction
●
ElevenLabs API Key
For speech-to-text and text-to-speech
Clone & Configure
git clone https://github.com/Pzharyuk/live-translator-node.git && cd live-translator-node
cp .env.example .env
Edit .env and set your API key:
ELEVENLABS_API_KEY=sk-your-key-here
ADMIN_PASSWORD=your-secure-password
Start Infrastructure
# Start Redis + LibreTranslate
docker compose -f docker-compose.local.yml up -d
# Wait for LibreTranslate to download language models (~500 MB)
docker logs -f $(docker ps -qf "name=libretranslate") 2>&1 | grep -i "running"
Start Backend
cd backend
npm install
npm run dev # nodemon watches for changes
Start Frontend
cd frontend
npm install
npm run dev # Vite hot-reload on localhost:5173
✓
You're all set!
Open http://localhost:5173 — log in with user / changeme and you will be redirected to /translate. Admin panel: http://localhost:5173/admin (admin password: admin123).
System Overview
Frontend
React 19 + Vite
Socket.io Client
Web Audio API
↔
Backend
Express + Socket.io
TypeScript
Service Layer
ElevenLabs
Scribe v2 (STT)
TTS Streaming
Voice Cloning
Translation
Google Translate (Cloud API)
LibreTranslate (self-hosted)
DeepL (premium API)
Claude / Anthropic (AI)
Redis
Feature Flags
Settings Store
Google Gemini
Biblical Simulator
Sermon Generation
Voice Training Text
DeepL
Free & Pro tiers
Auto endpoint detection
Data Flow
1 Audio Input (Mic / YouTube / Simulator)
↓
2 PCM 16-bit LE @ 16kHz via Socket.io chunks
↓
3 ElevenLabs Scribe v2 WebSocket STT
↓
4 Commit Merge Buffer 2.5s VAD aggregation
↓
5 Translation Provider Google / LibreTranslate / DeepL / Claude
↓
6 ElevenLabs TTS Voice synthesis streaming
↓
7 Audio Playback Queued with 600ms pause
Key Architecture Decisions
Two-layer Language Detection
LibreTranslate's /detect endpoint returns 0-confidence for short Cyrillic phrases. The app uses script-based pre-detection (Unicode 0x0400–0x04FF = Cyrillic) combined with ElevenLabs Scribe's language_code output for reliable EN/RU/UK auto-detection.
VAD Commit Merging
Voice Activity Detection can fire aggressively on speaker breathing. Commits are buffered for 2.5 seconds before translation to merge fragments into meaningful phrases.
Feature Flag Merging
YAML config defaults are merged with Redis runtime overrides. Redis values take priority, falling back to YAML if Redis is unavailable.
API Key Hierarchy
Keys resolve in order: Runtime Cache → Redis → Config File → Empty. This allows hot-swapping keys without restarts.
Connection Lifecycle
- Client sends
start_session with source type (mic or youtube) and optional voiceId
- Backend opens a WebSocket to
wss://api.elevenlabs.io/v1/speech-to-text/realtime
- For YouTube: spawns
yt-dlp | ffmpeg child processes to extract PCM audio
- For Microphone: awaits
audio_chunk events from the frontend
Audio Streaming
Audio chunks are sent to Scribe as JSON messages:
{
"message_type": "input_audio_chunk",
"audio_base_64": "UklGR..." // PCM 16-bit LE, 16kHz, mono
}
Scribe Responses
| Response Type | Meaning | Action |
partial_transcript |
Live partial text (speculative) |
Emitted as non-final transcript event |
committed_transcript |
VAD fired — complete phrase |
Buffered for commit merge window |
Commit Merge Buffer
After receiving a committed_transcript, the backend waits 2.5 seconds (COMMIT_MERGE_MS) to collect additional commits before translating. This prevents fragmented translations from aggressive VAD.
Stability Timeout
If VAD stalls (no new commits), a 3.5 second fallback timer (STABILITY_TIMEOUT_MS) fires to translate whatever new text has accumulated, preventing indefinite silence.
Text Validation
Before translation, text is validated against EN/RU/UK character regex patterns. This filters out hallucinated text from the STT model (common with silence or background noise).
Provider Chain
The system supports three translation providers with automatic fallback:
Default
LibreTranslate
Self-hosted, no API key required. Runs in Docker alongside the app. Best for privacy and cost.
Premium
DeepL
High-quality translations. Supports both free and paid API tiers. Auto-detects endpoint.
AI
Claude
Anthropic's Claude for context-aware translations. Uses claude-haiku-4-5 for speed.
Fallback Logic
1. Try primary provider (admin-selected)
2. If primary fails → try configured fallback
3. If fallback fails → try LibreTranslate (last resort)
4. If all fail → emit error event
Language Detection
The app uses a two-layer auto-detection approach:
Layer 1: Script-based Pre-detection
Before calling any translation API, the backend checks Unicode character scripts:
- Cyrillic characters (Unicode 0x0400–0x04FF) → if >50% of matched letters are Cyrillic, detected as Russian
- Latin characters → detected as English
- This avoids low-confidence results from LibreTranslate's
/detect endpoint on short text
Layer 2: STT Language Code
When the auto_language_detect flag is enabled, ElevenLabs Scribe returns a language_code with each transcript commit. The backend uses this to correctly route EN/RU/UK without relying solely on script detection.
Note: For LibreTranslate, both Russian and Ukrainian Cyrillic text is passed with source ru since LibreTranslate handles Ukrainian text acceptably via the Russian model. DeepL and Claude providers distinguish Ukrainian natively and handle uk as a proper source language.
Language Gating
Detected languages are checked against the admin-approved pool. If a detected language isn't in the allowed set, the translation is rejected to prevent hallucinated language outputs.
TTS Pipeline
After translation, the text is sent to ElevenLabs TTS:
const stream = await client.textToSpeech.stream(voiceId, {
text: translatedText,
model_id: "eleven_multilingual_v2",
output_format: "mp3_44100_128",
voice_settings: {
stability: 0.5,
similarity_boost: 0.75,
style: 0.0,
speed: 1.0,
use_speaker_boost: true
}
});
Audio Delivery
TTS audio is streamed to a Buffer, then emitted as a base64-encoded MP3 via the tts_audio Socket.io event.
Frontend Playback Queue
The frontend maintains an audio queue to prevent overlapping playback:
- Received
tts_audio events are queued
- Each segment plays to completion before the next starts
- A configurable pause (600ms default) is inserted between segments
- The pause duration is controlled by
tts_segment_pause_ms (adjustable in admin)
Microphone Input
- User selects "Mic" tab and chooses a TTS voice
- Browser captures audio via Web Audio API's
ScriptProcessor
- PCM 16-bit LE at 16kHz sample rate sent to backend via Socket.io
- Backend pipes audio to ElevenLabs Scribe v2 Realtime WebSocket
- Language auto-detected (EN/RU/UK), text translated and synthesized
- TTS audio returned and played back with inter-segment pauses
YouTube Input
- User pastes a YouTube URL (live stream or video)
- Backend spawns
yt-dlp | ffmpeg child processes
- Audio extracted as PCM stream (16kHz, 16-bit LE, mono)
- Piped to Scribe v2, same pipeline as microphone
- Stream ends when YouTube content ends or user stops
User Interface
The user view features a dark cavern theme with:
- Waveform visualizer — Canvas-based bar chart with orange gradient and cyan tips
- Transcript display — White translated text scrolls upward with fade masks
- Partial transcript — Shown in italic orange while STT is processing
- Source tabs — Toggle between Mic and YouTube (controlled by feature flags)
How It Works
The backend uses yt-dlp and ffmpeg as child processes to extract audio from YouTube URLs:
yt-dlp (best audio) → ffmpeg (PCM 16kHz 16-bit LE mono) → Scribe v2
Supported Sources
- Live streams — Translates in real-time as the stream progresses
- Regular videos — Processes the full audio track
- Any URL supported by yt-dlp (YouTube, etc.)
Requirements
Both yt-dlp and ffmpeg must be installed and available in the system PATH. On macOS:
brew install yt-dlp ffmpeg
⚠
Feature Flag Required
YouTube input is controlled by the youtube_input feature flag. Enable it in the admin panel to show the YouTube tab in the user view.
Overview
The Biblical Transcript Simulator is an admin-only feature that generates biblical text passages using Google's Gemini API (gemini-2.5-flash), then routes them through the full translation pipeline. This provides a hands-free way to test STT → Translation → TTS without a live audio source.
Language Styles
| Language | Style | Example |
en |
King James English |
"In the beginning was the Word..." |
ru |
Church Slavonic Russian |
"В начале было Слово..." |
uk |
Traditional Ukrainian |
"На початку було Слово..." |
Flow
- Admin selects language (EN/RU/UK)
- Backend calls Gemini 2.5 Flash with streaming
- Gemini generates 6-8 biblical passages, 3-5 sentences each
- Stream is buffered until 140+ characters AND complete sentences
- Chunks emitted with 1800ms smooth pacing between them
- Each chunk flows through the standard pipeline:
- Emitted as
transcript (isFinal: true)
- Auto-translated via configured provider
- TTS synthesized and audio returned
- Frontend plays audio with standard inter-segment pause
💡
Feature Flag
Enable biblical_simulator in the admin feature flags panel. The Gemini API key is configured via the GEMINI_API_KEY environment variable or set at runtime in the admin API Keys panel.
Overview
Voice Training uses ElevenLabs' Instant Voice Cloning (IVC) API to create custom voices from audio samples. Once cloned, the voice appears in the voice selector immediately.
From Microphone
- Open the Voice Training section in the admin panel
- Click Generate Text to get an AI-generated reading passage (via Gemini) — gives the speaker natural, phonetically diverse text to read aloud
- Record multiple audio clips using your browser microphone while reading the generated text
- Provide a name for the voice
- Clips are uploaded to ElevenLabs IVC API
- Cloned voice is available for TTS immediately
- Click Preview Voice to hear the cloned voice speak a sample sentence via TTS
From YouTube
- Paste a YouTube URL in the Voice Training section
- Backend extracts N × 30-second clips via
yt-dlp + ffmpeg
- Clips are uploaded to ElevenLabs IVC API
- Resulting voice is stored in your ElevenLabs account
⚠
ElevenLabs Account
Cloned voices are stored in your ElevenLabs account, not locally. Ensure your plan supports voice cloning.
Concepts
| Concept | Description |
| Active Language Pair |
The current pair used for translation (e.g., EN ↔ RU, EN ↔ UK, or RU ↔ UK). Set by admin. |
| Available Languages |
The pool of languages viewers can select from (if user_language_selector is enabled). |
Admin Controls
- Change the active language pair via the admin panel
- Changes broadcast to all connected clients in real-time
- Manage the available languages pool for viewer selection
Viewer Selection
When the user_language_selector feature flag is enabled, viewers can override the admin-set language pair by selecting their own preferred languages from the available pool.
Overview
Two people can video call each other through the app, each speaking their own language. The app transcribes, translates, and synthesizes speech in real-time so each participant hears the other in their language.
Feature flag: Video call is gated behind the video_translation flag. Enable it in the admin panel or set video_translation: true in your YAML config.
How It Works
- Create a room — Person A selects their language, picks a TTS voice, and clicks "Create Room". A 6-character room code is generated.
- Share the code — Person A shares the room code with Person B (copy button provided).
- Join the room — Person B enters the code, selects their language and TTS voice, and clicks "Join".
- WebRTC connection — The app establishes a peer-to-peer video connection via WebRTC (signaled through Socket.io). Video flows directly between browsers.
- Audio translation — Each participant's microphone audio is simultaneously:
- Sent to the peer via WebRTC (but muted on their end)
- Captured as PCM chunks and sent to the backend via Socket.io for STT
- Translation pipeline — Each participant has their own independent Scribe STT session. Transcribed text is translated to the other participant's language, then synthesized via ElevenLabs TTS and sent back to the peer.
- Playback — The peer hears the TTS translation instead of the raw audio. Translated transcript is displayed below the video.
Architecture
Person A (Browser) Server Person B (Browser)
├─ getUserMedia ├─ Socket.io ├─ getUserMedia
├─ WebRTC P2P ═══video═══►│ (signaling) ◄═══ ├─ WebRTC P2P
│ │ │
├─ PCM chunks ──Socket.io─►├─ ScribeA(STT) │
│ │ ↓ translate │
│ │ ↓ TTS ───────────►├─ Plays TTS
│ │ │
│ Plays TTS ◄─────────────├─ ScribeB(STT) ◄───├─ PCM chunks
│ (remote video muted) │ ↓ translate │ (remote video muted)
└──────────────────────────┴────────────────────┘
Socket Events
| Event | Direction | Purpose |
video_create_room | C→S | Create a new room with language + voice |
video_room_created | S→C | Returns the 6-char room code |
video_join_room | C→S | Join an existing room |
video_room_joined | S→C | Sent to both participants, triggers WebRTC |
video_signal_offer/answer/ice | C↔S | WebRTC signaling relay |
video_audio_chunk | C→S | PCM audio for STT processing |
video_transcript | S→C | Transcript sent to the speaker |
video_translation | S→C | Translation sent to the listener |
video_tts_audio | S→C | TTS audio sent to the listener |
video_leave_room | C→S | Leave the room |
video_room_closed | S→C | Notify peer when other leaves |
Room Lifecycle
- Rooms are stored in Redis with key
video_room:{code} and a 4-hour TTL
- Maximum 2 participants per room
- When one participant disconnects, the other is notified and the call ends
- Scribe sessions are automatically cleaned up on disconnect
Feature Flags
Feature flags control which routes and UI features are accessible. Defaults are set in config/application.yaml under the feature_flags section. At runtime, administrators can override any flag via the GET /admin/flags and POST /admin/flags/:flag endpoints, with overrides stored in Redis. All connected clients receive real-time updates via Socket.IO feature_flags event.
| Flag |
Default |
Description |
youtube_input |
true |
Enable YouTube audio streaming as an input source. |
mic_input |
true |
Enable microphone audio input for live translation. |
auto_language_detect |
true |
Automatically detect source language instead of requiring user selection. |
user_language_selector |
false |
Allow end users to manually select source and target languages. |
audio_device_selector |
true |
Show audio input device selector in UI. |
video_translation |
true |
Enable /video route for real-time video call translation. |
video_voice_cloning |
false |
Premium feature: show Clone Voice button in /video lobby. |
remote_audio_source |
false |
Enable /audio-source route for headless remote audio relay to broadcast. |
broadcast |
false |
Enable /broadcast route for public broadcast viewer page. |
translate |
false |
Enable /translate route for live translator with personal session. |
Storage & Runtime Behavior
Feature flags are stored in two layers: config/application.yaml provides the defaults, and Redis (key pattern: flag:*) stores runtime overrides. The GET /admin/flags endpoint merges both sources, with Redis values taking precedence. When an administrator updates a flag via POST /admin/flags/:flag, the new value is persisted to Redis and broadcasted to all connected clients via Socket.IO, ensuring real-time synchronization across the application.
API Endpoints
GET /admin/flags
→ Returns merged flags (YAML defaults + Redis overrides)
→ Response: { flags: { youtube_input: true, mic_input: true, ... } }
GET /admin/flags/:flag
→ Retrieve a single flag value
→ Response: { flag: "broadcast", value: false }
POST /admin/flags/:flag
→ Set a flag to a new value (persists to Redis)
→ Body: { value: true }
→ Broadcasts 'feature_flags' event to all Socket.IO clients
→ Response: { flag: "broadcast", value: true }
File Structure
| File | Purpose |
config/application.yaml |
Base defaults for all environments |
config/application-local.yaml |
Local development overrides (localhost URLs) |
config/application-prod.yaml |
Production overrides (Docker service names) |
The APP_ENV environment variable (local or prod) determines which overlay file is loaded on top of the base config.
Full Configuration Reference
server:
port: 3001
cors_origin: "http://localhost:5173"
elevenlabs:
api_key: "${ELEVENLABS_API_KEY}"
default_voice_id: "kxj9qk6u5PfI0ITgJwO0"
tts_model: "eleven_multilingual_v2"
tts_settings:
stability: 0.5
similarity_boost: 0.75
style: 0.0
speed: 1.0
use_speaker_boost: true
stt_model: "scribe_v2"
anthropic:
api_key: "${ANTHROPIC_API_KEY}"
deepl:
api_key: "${DEEPL_API_KEY}"
libretranslate:
url: "http://libretranslate:5000"
api_key: ""
redis:
host: "redis"
port: 6379
password: ""
feature_flags:
youtube_input: true
mic_input: true
auto_language_detect: true
user_language_selector: false
audio_device_selector: true
video_translation: false
video_voice_cloning: false
broadcast: false
audio:
sample_rate: 16000
channels: 1
chunk_duration_ms: 250
translation:
source_lang: "auto"
target_lang_en: "en"
target_lang_ru: "ru"
provider: "libretranslate"
fallback: "libretranslate"
Environment Variable Interpolation
YAML values using ${VAR_NAME} syntax are automatically replaced with the corresponding environment variable at startup.
TTS Settings
Configure text-to-speech behavior and voice parameters via the admin API.
curl -X GET http://localhost:3001/admin/tts-settings \
-H "Cookie: auth=<jwt_token>"
{
"settings": {
"stability": 0.5,
"similarity_boost": 0.75,
"style": 0.0,
"speed": 1.0,
"use_speaker_boost": true
}
}
curl -X POST http://localhost:3001/admin/tts-settings \
-H "Cookie: auth=<jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"stability": 0.6,
"similarity_boost": 0.8,
"speed": 1.1
}'
{
"settings": {
"stability": 0.6,
"similarity_boost": 0.8,
"style": 0.0,
"speed": 1.1,
"use_speaker_boost": true
}
}
TTS Settings Reference
| Setting |
Range |
Default |
Description |
stability |
0.0 – 1.0 |
0.5 |
Lower values increase variability; higher values make speech more consistent & monotone. |
similarity_boost |
0.0 – 1.0 |
0.75 |
Boost speaker similarity; higher values adhere more closely to the voice profile. |
style |
0.0 – 1.0 |
0.0 |
Exaggerate style; higher values add more expressiveness & dramatic delivery. |
speed |
0.5 – 2.0 |
1.0 |
Playback speed multiplier; 1.0 = normal, < 1.0 = slower, > 1.0 = faster. |
use_speaker_boost |
true / false |
true |
Enable speaker optimization for clearer, more natural voice output. |
STT Timing Settings
Control speech-to-text transcription timing, buffering, and word dispatch thresholds.
curl -X GET http://localhost:3001/admin/stt-timing \
-H "Cookie: auth=<jwt_token>"
{
"settings": {
"commit_merge_ms": 1500,
"stability_timeout_ms": 2000,
"tts_segment_pause_ms": 0,
"max_accumulation_ms": 8000,
"vad_threshold": 0.5,
"vad_silence_threshold_secs": 1.0,
"min_speech_duration_ms": 100,
"min_silence_duration_ms": 100,
"flush_on_sentence_boundary": true,
"min_chars_before_dispatch": 40
}
}
curl -X POST http://localhost:3001/admin/stt-timing \
-H "Cookie: auth=<jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"max_accumulation_ms": 10000,
"min_chars_before_dispatch": 50
}'
{
"settings": {
"commit_merge_ms": 1500,
"stability_timeout_ms": 2000,
"tts_segment_pause_ms": 0,
"max_accumulation_ms": 10000,
"vad_threshold": 0.5,
"vad_silence_threshold_secs": 1.0,
"min_speech_duration_ms": 100,
"min_silence_duration_ms": 100,
"flush_on_sentence_boundary": true,
"min_chars_before_dispatch": 50
}
}
| Setting |
Range |
Default |
Description |
commit_merge_ms |
50 – 5000 |
1500 |
Buffer VAD commits for this duration (ms) before flushing to translation; merges speech fragments. |
stability_timeout_ms |
500 – 5000 |
2000 |
Translate partial text if unchanged for this duration (ms); fallback when VAD doesn’t commit. |
tts_segment_pause_ms |
0 – 2000 |
0 |
Pause between consecutive TTS audio segments (ms); used by frontend playback timing. |
max_accumulation_ms |
2000 – 15000 |
8000 |
Force dispatch of accumulated words after this duration (ms) during continuous speech; prevents long delays. |
vad_threshold |
0.0 – 1.0 |
0.5 |
Voice Activity Detection sensitivity; higher = stricter noise filter, fewer false positives. |
vad_silence_threshold_secs |
0.5 – 3.0 |
1.0 |
Seconds of silence required before VAD commits a transcription segment. |
min_speech_duration_ms |
50 – 500 |
100 |
Ignore speech shorter than this duration (ms); filters out noise & clicks. |
min_silence_duration_ms |
50 – 500 |
100 |
Minimum silence gap (ms) required between speech segments; prevents mid-word breaks. |
flush_on_sentence_boundary |
true / false |
true |
When true, dispatch at sentence boundaries (.?!;) instead of waiting for timers; improves punctuation handling. |
min_chars_before_dispatch |
10 – 500 |
40 |
Minimum characters accumulated before a chunk is sent for translation; prevents tiny fragments. |
Video Call Settings
Separate STT/TTS parameters for real-time video translation calls (faster timings, dedicated provider).
curl -X GET http://localhost:3001/admin/video-settings \
-H "Cookie: auth=<jwt_token>"
{
"stability_ms": 500,
"commit_merge_ms": 50,
"translation_provider": "claude"
}
curl -X POST http://localhost:3001/admin/video-settings \
-H "Cookie: auth=<jwt_token>" \
-H "Content-Type: application/json" \
-d '{
"stability_ms": 600,
"translation_provider": "google"
}'
{
"stability_ms": 600,
"commit_merge_ms": 50,
"translation_provider": "google"
}
| Setting |
Range |
Default |
Description |
stability_ms |
200 – 2000 |
500 |
Wait for stable partial text before translating (ms); shorter = snappier response in video calls. |
commit_merge_ms |
10 – 500 |
50 |
Buffer VAD commits (ms); lower value merges fewer fragments for tighter real-time performance. |
translation_provider |
libretranslate / claude / deepl / google |
claude |
Translation provider dedicated to video calls; overrides global provider setting for this mode. |
Notes
- Persistence: All TTS & STT settings are persisted to Redis and survive server restarts.
- Live Updates: Changes apply immediately to new sessions; existing sessions continue with their cached copy.
- ElevenLabs Model: TTS settings are used by the configured
tts_model (default: eleven_multilingual_v2).
- Scribe Model: STT timing is applied to the configured
stt_model (default: scribe_v2_realtime).
- VAD Parameters: Voice Activity Detection settings (
vad_threshold, vad_silence_threshold_secs, etc.) are sent to ElevenLabs Scribe as WebSocket query params on session creation.
- Word-Count Dedup: The STT pipeline uses word-count slicing to deduplicate Scribe revisions & prevent full-utterance re-translation when earlier words change.
- Sentence Boundary Flushing: When
flush_on_sentence_boundary is enabled, complete sentences are dispatched immediately for snappier translation without waiting for timers.
STT Timing Settings
Configure how long the speech recognition system waits before translating audio segments. Lower values = snappier response; higher values = larger, more complete sentences.
| Setting |
Default |
Description |
commit_merge_ms |
1500 ms |
Buffer VAD commits for this duration before translating — merges short pauses into complete sentences. |
stability_timeout_ms |
2000 ms |
Dispatch partial text if unchanged for this duration — fallback when VAD doesn't fire. |
tts_segment_pause_ms |
0 ms |
Pause between consecutive TTS audio segments — frontend uses this value to manage playback gaps. |
max_accumulation_ms |
8000 ms |
Force-dispatch accumulated words after this duration even during continuous speech — prevents long gaps while speaker talks non-stop. |
vad_threshold |
0.5 |
Voice Activity Detection strictness (0–1: higher = stricter noise filter) — passed to ElevenLabs Scribe. |
vad_silence_threshold_secs |
1.0 sec |
Seconds of silence before VAD triggers a commit — passed to ElevenLabs Scribe. |
min_speech_duration_ms |
100 ms |
Ignore speech shorter than this — filters noise bursts; passed to ElevenLabs Scribe. |
min_silence_duration_ms |
100 ms |
Minimum silence gap between speech segments — passed to ElevenLabs Scribe. |
flush_on_sentence_boundary |
true |
Dispatch at sentence boundaries (.?!) instead of waiting for full buffer — keeps sentences whole and responsive. |
min_chars_before_dispatch |
40 chars |
Minimum text length before dispatching for translation — prevents tiny fragments. |
Tuning Guide
- Snappier response (sermon, teaching): Lower
max_accumulation_ms (4000–6000), commit_merge_ms (800–1200), and min_chars_before_dispatch (20–30). Accept shorter sentence fragments.
- Complete sentences (natural conversation): Increase
max_accumulation_ms (10000–15000) and commit_merge_ms (2000–3000) to let the speaker finish thoughts. Ideal for interview or discussion formats.
- Noisy environment: Raise
vad_threshold (0.7–0.9) to ignore background noise. Increase vad_silence_threshold_secs (1.5–2.0) to require more silence before commit.
- Quiet environment: Lower
vad_threshold (0.3–0.4) to catch soft speech. Lower vad_silence_threshold_secs (0.5–1.0) for faster commits.
- Long pauses in speech: Increase
stability_timeout_ms (3000–5000) or max_accumulation_ms to avoid premature dispatch during breath pauses.
- Real-time video calls: Video call settings are separate — see
GET /admin/video-settings.
API Endpoints
GET /admin/stt-timing
Retrieve current STT timing settings.
curl -X GET http://localhost:3001/admin/stt-timing \
-H "Cookie: auth=YOUR_JWT_COOKIE"
Response:
{
"settings": {
"commit_merge_ms": 1500,
"stability_timeout_ms": 2000,
"tts_segment_pause_ms": 0,
"max_accumulation_ms": 8000,
"vad_threshold": 0.5,
"vad_silence_threshold_secs": 1.0,
"min_speech_duration_ms": 100,
"min_silence_duration_ms": 100,
"flush_on_sentence_boundary": true,
"min_chars_before_dispatch": 40
}
}
POST /admin/stt-timing
Update one or more STT timing settings. Unspecified fields retain their current values.
curl -X POST http://localhost:3001/admin/stt-timing \
-H "Content-Type: application/json" \
-H "Cookie: auth=YOUR_JWT_COOKIE" \
-d '{
"max_accumulation_ms": 6000,
"commit_merge_ms": 1000,
"min_chars_before_dispatch": 30
}'
Response:
{
"settings": {
"commit_merge_ms": 1000,
"stability_timeout_ms": 2000,
"tts_segment_pause_ms": 0,
"max_accumulation_ms": 6000,
"vad_threshold": 0.5,
"vad_silence_threshold_secs": 1.0,
"min_speech_duration_ms": 100,
"min_silence_duration_ms": 100,
"flush_on_sentence_boundary": true,
"min_chars_before_dispatch": 30
}
}
Notes
- All timing values are persisted to Redis and survive server restarts.
- Changes take effect immediately for new sessions; active broadcasts are not affected mid-session.
- The Scribe STT WebSocket automatically passes VAD parameters (
vad_threshold, vad_silence_threshold_secs, etc.) to ElevenLabs on connection.
tts_segment_pause_ms is emitted to the frontend via the stt_timing Socket.IO event and controls playback pause duration in the browser.
- Sentence boundary detection uses regex
/[.?!;]\s+/g — requires visible punctuation followed by whitespace.
Authentication: All endpoints require JWT cookie authentication via adminAuth middleware. Users must have is_admin=true OR possess at least one role with permissions. Some endpoints further restrict access with requirePermission().
API Keys
Retrieve status of all configured API keys (elevenlabs, anthropic, deepl, libretranslate, google).
Update one or more API keys by name.
Body: {
"elevenlabs": "string (optional)",
"anthropic": "string (optional)",
"deepl": "string (optional)",
"libretranslate": "string (optional)",
"google": "string (optional)"
}
Retrieve the currently configured Gemini API key.
Voice Management
Scan ElevenLabs & return all available voices with category & preview URL.
Get the list of voice IDs allowed for user selection (null = all allowed).
Set the list of allowed voice IDs & broadcast to all connected clients.
Body: {
"voiceIds": ["string", "string", ...]
}
Feature Flags
Retrieve all feature flags merged from YAML config & Redis overrides.
Get the value of a single feature flag by name.
Set a feature flag value & broadcast to all connected clients via Socket.IO.
Body: {
"value": boolean
}
TTS & STT Settings
Retrieve TTS parameters (stability, similarity_boost, style, speed, use_speaker_boost).
Update TTS settings (partial updates allowed).
Body: {
"stability": number (0-1, optional),
"similarity_boost": number (0-1, optional),
"style": number (0-1, optional),
"speed": number (optional),
"use_speaker_boost": boolean (optional)
}
Retrieve STT timing configuration (VAD thresholds, silence timeouts, accumulation limits).
Update STT timing settings (commit merge delay, stability timeout, VAD parameters).
Body: {
"commit_merge_ms": number (optional),
"stability_timeout_ms": number (optional),
"tts_segment_pause_ms": number (optional),
"max_accumulation_ms": number (optional),
"vad_threshold": number (0-1, optional),
"vad_silence_threshold_secs": number (optional),
"min_speech_duration_ms": number (optional),
"min_silence_duration_ms": number (optional),
"flush_on_sentence_boundary": boolean (optional),
"min_chars_before_dispatch": number (optional)
}
Languages
Get the current active language pair (source & target).
Set the active language pair & broadcast to all connected clients.
Body: {
"languages": ["en", "ru"] // exactly 2 language codes
}
Get the pool of languages users can select from.
Set the available language pool & broadcast to all connected clients.
Body: {
"languages": ["en", "ru", "uk", ...]
}
Translation Provider
Get the currently active translation provider & list of available providers.
Switch the active translation provider (google, deepl, claude, libretranslate).
Body: {
"provider": "google" | "deepl" | "claude" | "libretranslate"
}
Get the currently selected Claude model & list of available Claude models.
Switch the Claude model used for translation.
Body: {
"model": "claude-3-5-sonnet-20241022" (or other available model)
}
Audio Device
Get the admin-selected audio input device (overrides viewer's local choice).
Set admin audio device & broadcast to all viewers via Socket.IO.
Body: {
"deviceId": "string (optional)",
"label": "string (optional)"
}
Video Call Settings
Get video call STT/TTS configuration (stability, commit merge, per-call provider).
Update video call translation settings.
Body: {
"stability_ms": number (optional),
"commit_merge_ms": number (optional),
"translation_provider": "libretranslate" | "claude" | "deepl" | "google" (optional)
}
Broadcast Schedule
Retrieve the upcoming broadcast event schedule.
Update the broadcast schedule with upcoming events.
Body: {
"events": [
{
"id": "string",
"title": "string",
"datetime": "ISO 8601 string",
"description": "string (optional)"
}
]
}
TTS Preview
Generate audio preview for text with a selected voice — returns MP3 buffer.
Body: {
"text": "string (required)",
"voiceId": "string (optional, uses default if omitted)"
}
Voice Training
Clone a custom voice from base64-encoded browser mic recordings.
Body: {
"name": "string (required)",
"clips": ["base64 audio", "base64 audio", ...] (required),
"mimeType": "string (optional, e.g., 'audio/webm')"
}
Clone a voice from a YouTube URL — server extracts N×30s clips via yt-dlp & ffmpeg.
Body: {
"name": "string (required)",
"youtubeUrl": "string (required)",
"clipCount": number (optional, default 3, max 25),
"startOffset": number (optional, seconds to skip before extraction)"
}
Monitoring & Diagnostics
Get statistics & log of detected hallucinations in transcription.
Clear the hallucination detection log.
Retrieve log of all translated segments (text, timing, provider).
Clear the translation log.
Get real-time snapshot of broadcast queue depth & Redis Streams stats.
Session History
Retrieve all broadcast session records from PostgreSQL.
Get detailed transcript & timing data for a specific broadcast session.
Export session transcript in JSON, CSV, or TXT format — supports ?format=json|csv|txt query param.
User Management
List all users (requires user_management permission). Password hashes stripped before response.
Update a user's admin status &/or assigned roles (requires user_management permission).
Body: {
"isAdmin": boolean (optional),
"roleId": "string | null" (optional, legacy single-role),
"roleIds": ["string", ...] (optional, multi-role)
}
Admin-initiated password reset for a user (requires user_management permission).
Body: {
"password": "string (required, min 6 characters)"
}
Delete a user account (requires user_management permission). Cannot delete your own account.
Roles & Permissions
List all available permissions (requires user_management permission).
List all roles & their assigned permissions (requires user_management permission).
Create a new role with a set of permissions (requires user_management permission).
Body: {
"name": "string (required)",
"permissions": ["permission_name", ...] (required)
}
Update an existing role's name & permissions (requires user_management permission).
Body: {
"name": "string (required)",
"permissions": ["permission_name", ...] (required)
}
Delete a role (requires user_management permission).
Content Generation
Generate a biblical sermon snippet using Gemini Flash (2.5-flash model).
Body: {
"apiKey": "string (optional, uses stored key if omitted)",
"language": "en" | "ru" | "uk" (optional),
"sentences": number (optional, 1-20, default 3)
}
SDK
Uses the official @elevenlabs/elevenlabs-js SDK (v2). The client is lazy-loaded on first use.
Speech-to-Text (Scribe v2 Realtime)
Connects via native WebSocket to wss://api.elevenlabs.io/v1/speech-to-text/realtime. Handles:
- VAD-based commit buffering with configurable merge window
- Stability timeout fallback for stalled VAD
- Text validation (EN/RU/UK character regex filtering)
- Partial and final transcript emission
Text-to-Speech
Uses client.textToSpeech.stream() with the eleven_multilingual_v2 model. Audio is collected into a Buffer and emitted as base64 MP3.
Voice Management
client.voices.getAll() — fetches all voices from account
- Admin can filter which voices are available to viewers
- Voice cloning via IVC API (from recordings or YouTube)
Key File
backend/src/services/elevenlabs.service.ts
Provider Details
Google Translate
Google Cloud Translation API v2. Fast (~200ms), deterministic, and reliable. Requires GOOGLE_TRANSLATE_API_KEY with the Cloud Translation API enabled in Google Cloud Console. Ensure the API key has no HTTP referrer restrictions (server-side requests have no referrer).
File: backend/src/services/google-translate.service.ts
LibreTranslate
Self-hosted in Docker. No API key required by default. Provides language detection and translation via REST API.
File: backend/src/services/libretranslate.service.ts
DeepL
Premium translation API. Auto-detects free vs. paid endpoint based on the API key format.
File: backend/src/services/deepl.service.ts
Claude (Anthropic)
AI-powered translation using claude-haiku-4-5 for speed. Includes language detection and auto-flip logic.
File: backend/src/services/claude-translate.service.ts
Routing
Provider routing is handled by backend/src/services/translation.provider.ts:
- Try admin-selected primary provider
- On failure, try configured fallback provider
- LibreTranslate is always the last-resort fallback
Connection
Uses ioredis with automatic retry strategy. Falls back to in-memory/YAML defaults if Redis is unavailable.
Key Patterns
| Pattern | Example | Purpose |
flag:<name> |
flag:youtube_input |
Feature flag boolean values |
setting:<name> |
setting:tts_settings |
JSON settings objects |
Key File
backend/src/services/redis.service.ts
Local Development
Use docker-compose.local.yml for Redis and LibreTranslate only (backend/frontend run natively):
docker compose -f docker-compose.local.yml up -d
Production
Use docker-compose.yml for all services:
docker compose up -d --build
Services
| Service | Image | Port | Notes |
| frontend |
node:24-alpine + Nginx |
80 (exposed) |
Serves React build, proxies API/WS to backend |
| backend |
node:24-alpine |
3001 (internal) |
Express + Socket.io server |
| redis |
redis:7-alpine |
6379 (internal) |
Feature flags and settings store |
| libretranslate |
libretranslate/libretranslate |
5000 (internal) |
Self-hosted translation engine |
Configuration
ELEVENLABS_API_KEY=sk-your-production-key
ADMIN_PASSWORD=strong-secure-password
FRONTEND_URL=https://translate.example.com
APP_ENV=prod
REDIS_PASSWORD=redis-secret
Deploy
docker compose up -d --build
Reverse Proxy
When running behind Nginx or another reverse proxy:
- Set
LISTEN_PORT in .env (e.g., 8080)
- Proxy pass to
localhost:8080
- Important: Ensure WebSocket upgrades are forwarded for the
/socket.io/ path
server {
listen 443 ssl;
server_name translate.example.com;
location / {
proxy_pass http://localhost:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_set_header Host $host;
}
}
Monitoring
# Check all services
docker compose ps
# View backend logs
docker compose logs -f backend
# Health check
curl http://localhost:3001/api/health