# Live EN-ES Conference Subtitles with Groq Real-time bilingual subtitles for conference talks, translating between English and Spanish using Groq's Whisper-large-v3 and LLM APIs. ## Features - **Live Transcription**: Uses Groq's Whisper-large-v3 for maximum accuracy (not turbo) - **Live Translation**: Bilingual translation between English and Spanish **ONLY** - **Manual Language Switch**: Force output to English (`--target-lang en`) or Spanish (`--target-lang es`) - **Automatic Language Detection**: Input language is auto-detected, output is always in target language (EN or ES) - **Strict Hallucination Filtering**: Blocks Whisper hallucinations like "thank you for watching", "the train is...", etc. - **Robust Against Noise**: Configurable RMS threshold and minimum segment length block background noise; tune them per device/room with `--calibrate` - **Calibration Mode**: `--calibrate` measures your room's noise floor vs. your speech level and saves optimal parameters to `calibration.json` - **Any Audio Device**: External webcams/USB interfaces are opened at their native sample rate (e.g. 48 kHz) and resampled to 16 kHz in software; `--agc` compensates quiet built-in mics - **Guided Startup**: `./start.sh` sets up the venv, asks which audio device to use, offers calibration, gates live mode behind a passing end-to-end `--test`, and opens the subtitles in a kiosk-mode browser - **Professional Output**: Only outputs when valid speech is detected, completely silent otherwise - **Clean Port Management**: Automatically frees the port when the app is closed (Ctrl-C) - **Low Latency**: Optimized for minimal delay - **Web Interface**: Clean, fullscreen-capable web page for displaying subtitles - **Cost Effective**: A multi-day conference costs only a few dollars - **Clean Console Output**: Only shows actual transcriptions and translations, no clutter ## Requirements - Python 3.7+ - Microphone or audio input device - Groq API key (free account available at [groq.com](https://groq.com)) ## Installation 1. Clone this repository: ```bash git clone cd live-en-es-conference-subtitles-with-groq ``` 2. Install dependencies into a virtualenv (this is what `start.sh` does automatically on first run): ```bash python3 -m venv .venv .venv/bin/pip install -r requirements.txt # sounddevice, numpy, requests, python-dotenv ``` On Debian/Ubuntu you may also need the PortAudio system library: ```bash sudo apt install libportaudio2 # plus python3-venv if venv creation fails ``` 3. Create a `.env` file with your Groq API key (get one free at [groq.com](https://groq.com)): ```bash echo "GROQ_API_KEY=your_api_key_here" > .env ``` 4. Optional but recommended: a Chromium-based browser (`google-chrome`, `chromium`) or `firefox` for the automatic kiosk-mode subtitle display. ## Running ### Guided start (recommended): `./start.sh` ```bash ./start.sh # extra args are passed to the python program, e.g.: ./start.sh --target-lang es # force Spanish output PORT=5000 ./start.sh # use a different web port (default 8080) ``` `start.sh` walks you through the whole setup: 1. **Virtualenv** — creates `.venv` and installs `requirements.txt` if missing. 2. **Device selection** — lists all audio input devices with their supported sample rates (from `--list-devices-json`) and asks which one to use (e.g. your webcam). Devices that don't support 16 kHz are handled automatically via resampling. 3. **Calibration (optional)** — runs `--calibrate`: stay silent for the first 60 % of the time, then speak. Saves tuned thresholds to `calibration.json`. 4. **Test gate** — runs `--test`: captures audio while you speak and verifies that speech is detected, Groq Whisper transcribes it, and the LLM translates it. **Live transcription only starts if this test passes** (exit code 0); otherwise you can retry or abort. 5. **Live mode** — starts the subtitle server in the background. 6. **Kiosk browser** — opens `http://127.0.0.1:8080` fullscreen in `chrome/chromium --kiosk` (or `firefox --kiosk`). If no `DISPLAY` is set (e.g. over SSH), it tells you the URL to open manually. Ctrl-C stops everything. ### Manual start ```bash .venv/bin/python live-en-es-conference-subtitles-with-groq.py --list-devices # pick a device index .venv/bin/python live-en-es-conference-subtitles-with-groq.py --device 4 --calibrate 20 # optional but recommended .venv/bin/python live-en-es-conference-subtitles-with-groq.py --device 4 --test 10 # optional gate .venv/bin/python live-en-es-conference-subtitles-with-groq.py --device 4 # live mode ``` Then open `http://:8080` on the subtitle screen (or let `start.sh` do it in kiosk mode). ### Options - `--list-devices`: List available audio input devices ```bash python3 live-en-es-conference-subtitles-with-groq.py --list-devices ``` - `--device N`: Use specific audio device (replace N with device index) ```bash python3 live-en-es-conference-subtitles-with-groq.py --device 4 ``` - `--port PORT`: Change HTTP server port (default: 8080) ```bash python3 live-en-es-conference-subtitles-with-groq.py --port 5000 ``` Common alternatives: 5000, 8000, 8888, 9000. If port is in use, the script will show an error with the conflicting process. - `--target-lang LANG`: Force output language to English (`en`) or Spanish (`es`) ```bash python3 live-en-es-conference-subtitles-with-groq.py --target-lang es # Force Spanish output python3 live-en-es-conference-subtitles-with-groq.py --target-lang en # Force English output ``` Useful when mentioning mixed terms like "Instituto Politécnico Nacional" or "Sociedad Mexicana de Proteómica" - the output will stay in the target language. ### Audio devices, sample rates, and calibration - The input device is opened at a sample rate it actually supports. Webcams and USB interfaces often only support 44100/48000 Hz, so the audio is captured at the native rate and resampled to 16 kHz in software — no more "invalid sample rate" errors with external devices. `--list-devices` now also shows the supported sample rates of every input device. - `--samplerate HZ`: Request a specific input sample rate (default: 16000). If the device does not support it, its native rate is used automatically. - `--list-devices-json`: Print input devices (index, name, supported rates) as JSON. Used by `start.sh` for the interactive device picker. - `--test [SECONDS]`: End-to-end test (default 10 s): capture audio while you speak, then check that (a) speech is detected above the silence threshold, (b) Groq Whisper returns a transcription, and (c) the LLM returns a translation. Exits 0 only if all pass. `start.sh` runs this before going live and aborts if it fails. - `--calibrate [SECONDS]`: Calibration mode (default 20 s). Stay **silent** for the first 60 % of the time (measures the room noise floor), then **speak a few sentences** for the last 40 % (measures speech level). It then recommends a silence threshold between the two, probes the supported sample rates, and saves everything to `calibration.json`: ```bash python3 live-en-es-conference-subtitles-with-groq.py --device 4 --calibrate 20 ``` Run it once per machine/device/room (silent office vs. noisy conference give very different thresholds). The file is loaded automatically on the next start (`--no-config` ignores it; CLI flags override it). - Manual tuning overrides (all optional, defaults shown): ```bash python3 live-en-es-conference-subtitles-with-groq.py --silence-rms 800 # RMS threshold (int16) for speech detection python3 live-en-es-conference-subtitles-with-groq.py --min-send 2.0 # minimum segment seconds sent to the API python3 live-en-es-conference-subtitles-with-groq.py --silence-flush 0.5 # trailing silence that cuts a segment python3 live-en-es-conference-subtitles-with-groq.py --max-segment 3.5 # maximum segment length python3 live-en-es-conference-subtitles-with-groq.py --block-ms 20 # audio callback block size ``` A too-high `--silence-rms` (the old default of 1500) makes quiet built-in laptop mics produce no output at all — lower it, or use `--calibrate`. - `--agc`: Normalize the level of each segment before sending it to Groq. Useful for quiet built-in microphones. Calibration enables it automatically when your speech level is low. ### Access Subtitles Open a web browser and navigate to (default port is 8080): ``` http://:8080 ``` Press **'f'** key to enter fullscreen mode. ## Keyboard Controls (in the web page) - **SPACE**: Cycle through states: **EN → ES → MUTED → EN...** - **F**: Toggle fullscreen mode The current state is clearly displayed in the top status bar: - `[→ EN]` - Unmuted, auto-detect input language, translate to English - `[→ ES]` - Unmuted, auto-detect input language, translate to Spanish - `[MUTED]` - Muted (no transcription or translation) **Yes! Mute and language selection work with a single key (SPACE)** - just press it to cycle through all states. ## Single-Screen Display (No Second Monitor) If you don't have a second screen, you can display the subtitles in a **frameless, borderless window** on your main screen: ### Option 1: Chrome/Chromium Kiosk Mode (Recommended) ```bash # Open in a frameless window with custom size and position google-chrome --kiosk --window-size=800,200 --window-position=0,800 http://localhost:8080 # or chromium-browser --kiosk --window-size=800,200 --window-position=0,800 http://localhost:8080 ``` **Flags**: - `--kiosk`: Fullscreen without browser chrome (no address bar, buttons, etc.) - `--window-size=WIDTH,HEIGHT`: Set window dimensions (e.g., 800x200 pixels) - `--window-position=X,Y`: Position on screen (e.g., x=0, y=800 places it at bottom) ### Option 2: Firefox Kiosk Mode ```bash firefox --kiosk --width=800 --height=200 http://localhost:8080 ``` **To position Firefox window**: Use your window manager or tools like `wmctrl`: ```bash wmctrl -r :ACTIVE: -e 0,0,800,800,200 # x=0, y=800, width=800, height=200 ``` ### Option 3: Use Existing Browser with Fullscreen Press **'f'** in the subtitle page to enter fullscreen mode. Press ESC to exit. ### Scaling Without Modifying Text Size The subtitle page **automatically scales** based on window size: - Text size is **viewport-relative** (uses `vmin` units) - Font size: `6.2vmin` for translation, `3.4vmin` for original - This means text **automatically adjusts** to window size while remaining readable - No need to modify CSS or text size manually ### Example for Conference Setup ```bash # Open subtitles in a bar at the bottom of your 1920x1080 screen chromium-browser --kiosk --window-size=1920,200 --window-position=0,880 http://localhost:8080 ``` This creates a **1920x200 pixel bar** at the bottom (y=880) of your screen, displaying subtitles with perfect readability. ## Console Output (Clean Mode) The console displays minimal information - only actual transcriptions and state changes: ``` [15:34:19.987] Subtitles page: http://:8080 [15:34:19.987] Press Ctrl-C to stop and free the port. [15:34:19.987] Initial state: [MUTED] [15:34:19.987] Controls: SPACE=cycle (EN->ES->MUTED) [15:34:19.988] Audio: device=None, rate=16000Hz, 1ch [15:34:19.988] Config: max_seg=3.5s, silence_flush=0.50s, rms=2500 [15:34:19.988] Transcript: transcript-20261102-153419.tsv ------------------------------------------------------------ [15:34:19.988] Listening... [15:34:23.200] State changed: [→ ES] [15:34:25.500] [→ ES] Hello everyone -> Hola a todos [15:34:30.100] State changed: [MUTED] ``` **Information displayed**: - **Timestamps**: Every message has a precise timestamp (HH:MM:SS.mmm) - **Startup info**: Port, state, controls, audio configuration - **State labels**: `[→ EN]`, `[→ ES]`, `[MUTED]` - **State changes**: Notified when you press SPACE to cycle states - **Translations**: Color-coded output (original in yellow, translation in green) - **Silent operation**: NO output when muted or when no valid speech is detected ## Important Notes 1. **Starts MUTED**: The program starts in **MUTED** mode by default for privacy. Press SPACE to cycle through: **EN → ES → MUTED → EN...** 2. **When MUTED**: No audio is transcribed or translated at all - this ensures sensitive or irrelevant speech is not processed or saved. The program is completely silent. 3. **Language Behavior**: - Input language is **automatically detected** (English, Spanish, German, etc.) - Output is **ALWAYS** in the target language (EN or ES) based on current state - If you speak German, it will be translated to the target language - Proper names and technical terms are preserved exactly 4. **Hallucination Filtering**: Blocks common Whisper hallucinations including: - "thank you for watching", "thanks for watching" - "the train is...", "moving towards the station" - "subtitles by", "amara.org" - "Kämpen", "Kärleksplatsen", and other known patterns 5. **Audio Filtering**: - RMS=1500 (blocks most background noise while accepting normal speech) - Minimum segment length=2.5 seconds (filters out short noise bursts) - Minimum word count=2 words (allows short phrases while filtering noise) - Temperature=0 (minimizes LLM creativity and reduces hallucinations) 6. **State persists**: The current state is synced across all connected clients and displayed in console. ## Language Behavior ### All Modes (EN and ES) Both EN and ES modes work identically - **language is always auto-detected**: 1. **Input**: Any language (English, Spanish, German, French, etc.) 2. **Detection**: Whisper detects the input language automatically 3. **Translation**: Translated to the **target language** (EN or ES) 4. **Output**: Translation in the target language ### Examples **In EN mode (→ EN)**: - English input "Hello" → Cleaned English "Hello" - Spanish input "Hola" → English translation "Hello" - German input "Guten Tag" → English translation "Good day" - French input "Bonjour" → English translation "Hello" **In ES mode (→ ES)**: - English input "Hello" → Spanish translation "Hola" - Spanish input "Hola" → Cleaned Spanish "Hola" - German input "Guten Tag" → Spanish translation "Buenos días" - French input "Bonjour" → Spanish translation "Hola" ### What Gets Blocked - **Whisper hallucination patterns**: "thank you for watching", "the train is...", "subtitles by", etc. - **Very short segments** (< 0.8s - background noise) - **Very quiet audio** (RMS < 500 - background noise) - **Empty or all-punctuation text** ### What Gets Through - **All languages**: English, Spanish, German, French, Chinese, etc. - **All valid speech**: Any language will be transcribed and translated - **Proper names and technical terms**: Preserved exactly as spoken - **Mixed language phrases**: Each phrase translated appropriately - **All Unicode characters**: Preserved in output ## Audio Configuration The system is optimized for **academic presentations** with **whisper-large-v3** (accuracy > speed): - **Audio buffering**: 20ms blocks for low latency capture - **Silence detection**: 500ms (waits for natural pauses) - **Max segment length**: 3.5 seconds (captures full phrases) - **Minimum segment**: 2.5 seconds (filters out short noise bursts) - **Noise threshold**: RMS=1500 (high enough to block noise, low enough for normal speech) - **Minimum words**: 2 words per segment (allows short phrases while filtering noise) ### Calibrating for Your Microphone The default settings work for most microphones, but you may need to adjust them for your specific setup: #### If you get NO output (too strict): - **Decrease RMS**: Lower `SILENCE_RMS` from 1500 to 1000 or 800 - **Decrease min segment**: Lower `MIN_SEND_S` from 2.5 to 2.0 or 1.5 - **Decrease min words**: Lower `MIN_WORDS` from 2 to 1 #### If you get TOO MUCH noise/hallucinations (too lenient): - **Increase RMS**: Raise `SILENCE_RMS` from 1500 to 2000 or 2500 - **Increase min segment**: Raise `MIN_SEND_S` from 2.5 to 3.0 or 4.0 - **Increase min words**: Raise `MIN_WORDS` from 2 to 3 or 4 #### How to test and calibrate: 1. **Check your microphone RMS level**: Add this temporary debug code to the `_append` method in `Segmenter` class (around line 122): ```python rms = float(np.sqrt(np.mean(block.astype(np.float64) ** 2))) if int(self._total_s * 10) % 20 == 0: # Print every ~2 seconds print(f"[DEBUG] RMS: {rms:.0f} (threshold: {SILENCE_RMS})") ``` 2. **Speak normally and observe RMS values**: - If your speech RMS is consistently below `SILENCE_RMS`, lower the threshold - If background noise RMS is above `SILENCE_RMS`, raise the threshold 3. **Adjust the three key parameters** in the script: ```python SILENCE_RMS = 1500 # Line 88 - RMS threshold for speech detection MIN_SEND_S = 2.5 # Line 89 - Minimum segment length in seconds MIN_WORDS = 2 # Line 90 - Minimum words per segment ``` 4. **Test with real speech**: - Speak normal sentences - Verify transcriptions appear - Verify background noise is ignored 5. **Remove debug code** after calibration #### Recommended starting points: | Environment | RMS | MIN_SEND_S | MIN_WORDS | |------------|-----|------------|-----------| | Quiet office | 1000-1500 | 2.0 | 2 | | Conference room | 1500-2000 | 2.5 | 2 | | Noisy environment | 2000-2500 | 3.0 | 3 | | Very noisy | 2500-3000 | 4.0 | 4 | This ensures **complete, accurate phrases** are captured with minimal delay for academic use. ### Dynamic Parameter Optimization The system **automatically adapts** to your audio environment with the current settings: - **Silence threshold (RMS=1500)**: Filters segments below this noise level - **Segment length (2.5s - 3.5s)**: Balanced for responsive subtitles and complete phrases - **Silence flush (0.50s)**: Waits for natural pauses before finalizing a segment **Note**: For adjustment during a session, you can: 1. Stop the program (Ctrl-C) 2. Modify the parameters at the top of the script 3. Restart with your new settings 4. The current configuration works well for typical conference settings ### Port Usage - **Default port**: 8080 (can be changed with `--port PORT`) - **Port conflict resolution**: If a port is already in use, the script will: - Show an error message with the conflicting process - Suggest alternative ports (5000, 8000, 8888, 9000) - Exit cleanly without starting - **Port cleanup**: When you press Ctrl-C, the port is **immediately freed** - **Common free ports**: 5000, 8000, 8080, 8888, 9000, 9090 - **How to check**: `ss -tulnp | grep LISTEN` or `netstat -tulnp | grep LISTEN` ## Latency Considerations With the default settings, expect **~3-5 seconds end-to-end latency**: - Audio capture: ~2.5s (minimum segment length) - Whisper API: ~1-2s (Groq's fast response) - Translation API: ~0.5-1s - Display update: ~0.2s **Note**: The Groq API response time is the dominant factor. For lower latency at the cost of some noise filtering, you can reduce `MIN_SEND_S` in the script. For example, setting it to 1.5s reduces latency but may accept more background noise. ## Use Cases - **Mixed language terms**: When presenting about "Instituto Politécnico Nacional" or "Sociedad Mexicana de Proteómica", use `--target-lang` to ensure consistent output language. - **Noisy environments**: The system automatically filters out background noise like keyboard typing. - **Non-speech audio**: Only valid human language (English or Spanish) will be displayed; non-speech audio is silently ignored. ## How It Works 1. Audio is captured from the selected input device 2. Speech is segmented at natural pauses (0.45s silence) or after 8 seconds maximum 3. Each segment is transcribed using Groq's Whisper-large-v3 4. Transcription is translated to the opposite language (EN ↔ ES) 5. Results are displayed on the web page with a 15-second TTL 6. Transcripts are saved to `transcript-YYYYMMDD-HHMMSS.tsv` ## Configuration Edit the script to customize: - `ASR_MODEL`: Speech-to-text model (currently `whisper-large-v3`) - `LLM_MODEL`: Translation model (currently `openai/gpt-oss-20b`) - `HTTP_PORT`: Web server port (default: 8000) - `SUBTITLE_TTL_S`: How long subtitles stay visible (default: 15 seconds) - Audio parameters: `SAMPLE_RATE`, `SILENCE_FLUSH_S`, `SILENCE_RMS`, etc. ## Cost Estimate - Whisper-large-v3: $0.111/hour of audio - 10-second billing minimum per request - Translation: < $0.01/hour - **Total for a multi-day conference: ~$5-10** ## Publishing & Version Control ### Initial Setup This project is ready for Git. The `.gitignore` file already excludes: - `.env` (API keys) - `__pycache__/` (Python cache) - `transcript-*.tsv` (transcript files) - Virtual environments - IDE files ### First Commit & Publish ```bash # Navigate to project directory cd live-en-es-conference-subtitles-with-groq # Initialize git (if not already done) git init # Add all files git add . # Commit GIT_COMMITTER_NAME="Your Name" GIT_COMMITTER_EMAIL="robsi@duck.com" \ git commit -m "Initial commit: Live EN-ES conference subtitles with Groq Features: - Real-time transcription with whisper-large-v3 - Bilingual EN/ES translation - Manual language switching (SPACE key) - Robust noise filtering - Hallucination blocking - Web interface for subtitles - Clean console output Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe " # Add remote (replace with your repository URL) git remote add origin https://github.com/yourusername/live-en-es-conference-subtitles-with-groq.git # Push to main branch git push -u origin main # Tag as alpha version git tag -a alpha-0.1 -m "Alpha 0.1: Initial public release" git push origin alpha-0.1 ``` ### Publishing to GitHub 1. Create a new repository on GitHub 2. Follow the instructions above to add the remote and push 3. Enable GitHub Pages (optional) for documentation 4. Add a release for the alpha version ### Versioning This project uses semantic versioning for the alpha stage: - `alpha-0.1`: Initial public release - `alpha-0.2`: Bug fixes and improvements - Future: `beta-1.0`, `1.0.0` (stable) ## Contact For questions or issues, contact: **robsi@duck.com** ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.