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 (RMS=1500)
- Hallucination blocking
- Web interface for subtitles
- Clean console output

Generated by Mistral Vibe.
Co-Authored-By: Mistral Vibe <vibe@mistral.ai>
This commit is contained in:
robertwinkler@posteo.net
2026-11-02 18:13:46 -06:00
commit c5128f0d31
4 changed files with 1225 additions and 0 deletions
+39
View File
@@ -0,0 +1,39 @@
# Environment variables
.env
# Python
__pycache__/
*.py[cod]
*$py.class
*.so
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
# Virtual environments
.venv/
venv/
ENV/
env/
# IDE
.idea/
.vscode/
*.swp
*.swo
# Transcript files
transcript-*.tsv
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 rob
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+425
View File
@@ -0,0 +1,425 @@
# 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**: High thresholds (RMS=1500, min 2.5 seconds) to block background noise while accepting normal speech
- **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 <repository-url>
cd live-en-es-conference-subtitles-with-groq
```
2. Install dependencies:
```bash
pip install sounddevice numpy requests python-dotenv
```
3. Create a `.env` file with your Groq API key:
```bash
echo "GROQ_API_KEY=your_api_key_here" > .env
```
## Usage
### Quick Start
```bash
python3 live-en-es-conference-subtitles-with-groq.py
```
### 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.
### Access Subtitles
Open a web browser and navigate to (default port is 8080):
```
http://<this-machine>: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://<this-machine>: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 <vibe@mistral.ai>"
# 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.
@@ -0,0 +1,740 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
groq-live-subs — Live bilingual (EN <-> ES) subtitles for a conference room.
Pipeline:
mixer/mic audio -> this Linux box -> Groq Whisper (speech-to-text)
-> Groq LLM (translation) -> web page with live subtitles.
The subtitle page is served on http://<this-machine>:8080 (configurable via --port) — open it:
* fullscreen on the venue's second projector/screen, or
* on a tablet placed in front of the host-institution director.
Note: The program starts MUTED by default. Press SPACE to cycle through states.
Keyboard controls (on the web page):
* SPACE: Cycle through states (EN -> ES -> MUTED -> EN...)
* F: Fullscreen
Status bar shows: [-> EN], [-> ES], or [MUTED]
When MUTED: No transcription/translation occurs for privacy.
When EN or ES: Language is AUTO-DETECTED, then translated to the target.
Temperature is set to 0 to minimize hallucinations.
Audio filtering (RMS=500, min_length=0.8s) reduces background noise.
Usage
-----
pip install sounddevice numpy requests python-dotenv
Create a .env file with: GROQ_API_KEY="gsk_..."
python3 live-en-es-conference-subtitles-with-groq.py # default: port 8080, auto-detect language
python3 live-en-es-conference-subtitles-with-groq.py --list-devices # pick your audio interface
python3 live-en-es-conference-subtitles-with-groq.py --device 4 # e.g. USB interface from the mixer
python3 live-en-es-conference-subtitles-with-groq.py --port 5000 # use alternative port
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
Latency: Groq has no streaming Whisper endpoint, so audio is cut into segments
at natural speech pauses (~0.2 s of silence) or after 3 s max. Expect subtitles
to appear roughly 1-3 s after the words are spoken (optimized for minimal delay).
Cost (2026): whisper-large-v3 = $0.111/h of audio, with a 10-second billing
minimum per request (short pause-cut chunks are therefore billed as 10 s).
Translation with a small LLM adds well under one cent per hour. A multi-day
conference costs a few dollars total.
"""
import argparse
import datetime
import io
import json
import os
import queue
import re
import subprocess
import sys
import threading
import time
import wave
from dotenv import load_dotenv
load_dotenv() # Load GROQ_API_KEY from .env file
import numpy as np
import requests
import sounddevice as sd
# Timestamp helper for console output
def ts():
from datetime import datetime
return datetime.now().strftime('%H:%M:%S.%f')[:-3]
# --------------------------------------------------------------------------
# Configuration
# --------------------------------------------------------------------------
GROQ_API_KEY = None # or hardcode here; env var GROQ_API_KEY takes precedence
ASR_MODEL = "whisper-large-v3" # max accuracy
LLM_MODEL = "openai/gpt-oss-20b" # any Groq chat model works (e.g. "qwen/qwen3.8-27b")
SAMPLE_RATE = 16000 # Whisper native rate
CHANNELS = 1
BLOCK_MS = 20 # audio callback block (reduced from 30ms for lower latency)
MAX_SEGMENT_S = 3.5 # force a flush after this much continuous speech
SILENCE_FLUSH_S = 0.50 # cut a segment after this much trailing silence
SILENCE_RMS = 1500 # RMS threshold (int16) - High enough to block noise, low enough for speech
MIN_SEND_S = 2.5 # ignore tiny blips - minimum segment to send to API
MIN_WORDS = 2 # Minimum words in transcription to accept
HTTP_PORT = 8080 # Changed from 8000 to avoid common conflicts
SUBTITLE_TTL_S = 10 # a line disappears from the page after this (reduced from 15s)
# Target language: None = auto-detect, 'en' = force English output, 'es' = force Spanish output
TARGET_LANG = None
GROQ_ASR_URL = "https://api.groq.com/openai/v1/audio/transcriptions"
GROQ_CHAT_URL = "https://api.groq.com/openai/v1/chat/completions"
# --------------------------------------------------------------------------
# Audio segmentation: collect blocks, flush on pauses or max length
# --------------------------------------------------------------------------
class Segmenter:
def __init__(self):
self.blocks = queue.Queue()
self._reset()
def _reset(self):
self._audio = [] # list of np.ndarray blocks
self._speech_seen = False
self._silence_run = 0.0
self._total_s = 0.0
self._segment_len = 0.0
def callback(self, indata, frames, time_info, status):
if status:
print(f"[audio] {status}", )
self.blocks.put(indata.copy())
def _append(self, block):
self._audio.append(block)
self._total_s += len(block) / SAMPLE_RATE
rms = float(np.sqrt(np.mean(block.astype(np.float64) ** 2)))
if rms > SILENCE_RMS:
self._speech_seen = True
self._silence_run = 0.0
elif self._speech_seen:
self._silence_run += len(block) / SAMPLE_RATE
def next_segment(self):
"""Blocking. Returns WAV bytes for one utterance segment, or None."""
while True:
block = self.blocks.get() # waits for audio
self._append(block)
if self._speech_seen and (
self._silence_run >= SILENCE_FLUSH_S or self._total_s >= MAX_SEGMENT_S
):
wav = self._wav_bytes()
keep = self._segment_len >= MIN_SEND_S
self._reset()
if keep:
return wav
elif not self._speech_seen and self._total_s >= MAX_SEGMENT_S:
# long silence: drop it (don't burn API requests on room noise)
self._reset()
def _wav_bytes(self):
self._segment_len = self._total_s
audio = np.concatenate(self._audio)
buf = io.BytesIO()
with wave.open(buf, "wb") as w:
w.setnchannels(CHANNELS)
w.setsampwidth(2)
w.setframerate(SAMPLE_RATE)
w.writeframes(audio.astype(np.int16).tobytes())
return buf.getvalue()
# --------------------------------------------------------------------------
# Groq calls with simple 429 handling
# --------------------------------------------------------------------------
def _headers():
key = os.environ.get("GROQ_API_KEY") or GROQ_API_KEY
if not key:
sys.exit("Set GROQ_API_KEY in the environment or edit GROQ_API_KEY in this file.")
return {"Authorization": f"Bearer {key}"}
def transcribe(wav_bytes):
for attempt in range(4):
r = requests.post(
GROQ_ASR_URL,
headers=_headers(),
files={"file": ("chunk.wav", wav_bytes, "audio/wav")},
data={"model": ASR_MODEL, "temperature": "0"},
timeout=30,
)
if r.status_code == 429:
wait = float(r.headers.get("retry-after", 2 ** attempt))
print(f"[groq] rate limited, waiting {wait}s", )
time.sleep(wait)
continue
r.raise_for_status()
return r.json().get("text", "").strip()
return ""
def _is_english_or_spanish(text):
"""No language filtering - accept all languages."""
return True
def _is_real_speech(text):
"""Check if text looks like real human speech (not Whisper hallucination)."""
stripped = text.strip()
if not stripped or len(stripped) < 3:
return False
# Check minimum word count
words = stripped.split()
if len(words) < MIN_WORDS:
return False
text_lower = text.lower()
# Check for Whisper hallucination patterns (very specific)
hallucination_patterns = [
r'thank you',
r'thanks for watching',
r'thank you for',
r'thanks\.?$',
r'the train is now',
r'the train is coming',
r'the bus is now',
r'the car is now',
r'the plane is now',
r'the vehicle is now',
r'moving towards the',
r'moving to the next',
r'departing for the',
r'now departing',
r'coming to the end',
r'of the track',
r'for the next station',
r'for the next stop',
r'station\b',
r'airport\b',
r'platform\b',
r'texte?',
r'texting',
r'teksting',
r'subtitling',
r'subtitles by',
r'subtítulos de la',
r'comunidad amara',
r'amara\.org',
r'nicolai winther',
r'kjelland',
r'kjell ',
r'kjellandeskog',
r'kronholm',
r'kanskje',
r'nettopp',
r'stjålstjålene',
r'skjermen',
r'godelag',
r'roden',
r'ropsten',
r'kämpen',
r'kärleksplatsen',
r'takk for',
r'hallo, hallo',
r'kannst du mich hören',
r'kannst du mich',
r'kannst du',
r'exzellente',
r'entschlossenheit',
r'verstehst du',
r'das ist',
r'das ist auch',
r'auch gut',
r'kann noch',
r'optimieren',
]
for pattern in hallucination_patterns:
if re.search(pattern, text_lower):
return False
# Check for text with too many short words (typical of background noise)
words = text_lower.split()
if len(words) >= 3:
short_words = sum(1 for w in words if len(w) <= 3)
# If more than 80% of words are 3 letters or shorter, it's likely background noise
if short_words > len(words) * 0.8:
return False
# Check for very low word diversity (many repeated words)
unique_words = len(set(words))
if unique_words < len(words) * 0.4 and len(words) >= 5:
# Less than 40% unique words = many repetitions = likely background noise
return False
return True
def _is_valid_text(text):
"""Check if text contains valid human language (EN or ES), not just noise/garbage."""
if not text or len(text.strip()) < 3:
return False
# First check if it's valid text at all
# Common non-speech artifacts from Whisper
noise_patterns = [
r'^[\s\-\._\,]+$', # Just punctuation
r'^[\d\s]+$', # Just numbers
r'[\x00-\x1f\x7f]', # Control characters
]
for pattern in noise_patterns:
if re.match(pattern, text):
return False
# Check if it looks like real speech
if not _is_real_speech(text):
return False
# Then check if it's English or Spanish
return _is_english_or_spanish(text)
def _get_translation_prompt(target_lang=None):
"""Generate translation prompt based on target language setting."""
if target_lang == 'en':
return (
"You are a live simultaneous translator. ALWAYS translate to clear, natural English. "
"If the input is not English, translate it to English. "
"Output ONLY the English translation - no explanations, quotes, or original text. "
"If the text is unclear or not speech, output an empty string. "
"Keep technical terms, acronyms, and proper names exactly as they appear."
)
elif target_lang == 'es':
return (
"You are a live simultaneous translator. ALWAYS translate to natural, formal "
"Latin-American Spanish. "
"If the input is not Spanish, translate it to Spanish. "
"Output ONLY the Spanish translation - no explanations, quotes, or original text. "
"If the text is unclear or not speech, output an empty string. "
"Keep technical terms, acronyms, and proper names exactly as they appear."
)
else: # auto-detect
return (
"You are a live simultaneous translator. "
"If the text is in English, translate to natural Latin-American Spanish. "
"If the text is in Spanish, translate to clear English. "
"If the text is unclear or not speech, output an empty string. "
"Output ONLY the translation - no explanations, quotes, or original text. "
"Keep technical terms, acronyms, and proper names exactly as they appear."
)
def _is_sensible_translation(input_text, output_text, target_lang=None):
"""Check if translation makes sense - very permissive."""
# Only block completely empty or clearly broken outputs
if not output_text or len(output_text.strip()) < 2:
return False
# Don't filter based on content - Whisper is good
# Don't block repetitions - might be correct text in target language
return True
def translate(text, target_lang=None):
if not _is_valid_text(text):
return ""
try:
r = requests.post(
GROQ_CHAT_URL,
headers=_headers(),
json={
"model": LLM_MODEL,
"temperature": 0,
"messages": [
{"role": "system", "content": _get_translation_prompt(target_lang)},
{"role": "user", "content": text},
],
},
timeout=30,
)
r.raise_for_status()
result = r.json()["choices"][0]["message"]["content"].strip()
# Validate that the translation makes sense
if not _is_sensible_translation(text, result, target_lang):
return ""
# Double-check: if we forced a language but got empty or invalid result, return empty
if target_lang and not result:
return ""
return result
except Exception as e:
print(f"[groq] translation failed: {e}", )
return ""
# --------------------------------------------------------------------------
# Shared state for the subtitle web page
# --------------------------------------------------------------------------
class SubtitleState:
# States for space key cycling: EN -> ES -> MUTED -> EN
STATES = [
{'muted': False, 'target_lang': 'en', 'label': '→ EN'},
{'muted': False, 'target_lang': 'es', 'label': '→ ES'},
{'muted': True, 'target_lang': None, 'label': 'MUTED'}
]
def __init__(self):
self.lock = threading.Lock()
self.seq = 0
self.original = ""
self.translation = ""
self.updated_at = 0.0
self.transcript_path = datetime.datetime.now().strftime("transcript-%Y%m%d-%H%M%S.tsv")
self.current_state_idx = 2 # Start MUTED by default (index 2 = MUTED)
@property
def muted(self):
return self.STATES[self.current_state_idx]['muted']
@property
def current_target_lang(self):
return self.STATES[self.current_state_idx]['target_lang']
@property
def state_label(self):
return self.STATES[self.current_state_idx]['label']
def cycle_state(self):
"""Cycle to next state: EN -> ES -> MUTED -> EN"""
with self.lock:
self.current_state_idx = (self.current_state_idx + 1) % len(self.STATES)
new_state = self.STATES[self.current_state_idx]['label']
print(f"[{ts()}] State changed: [{new_state}]")
return self.current_state_idx
def publish(self, original, translation):
with self.lock:
self.seq += 1
self.original = original
self.translation = translation
self.updated_at = time.time()
with open(self.transcript_path, "a", encoding="utf-8") as f:
f.write(f"{time.strftime('%H:%M:%S')}\t{original}\t{translation}\n")
def snapshot(self):
with self.lock:
if self.updated_at > 0 and time.time() - self.updated_at > SUBTITLE_TTL_S:
result = {
"seq": self.seq,
"original": "",
"translation": "",
"muted": self.muted,
"targetLang": self.current_target_lang,
"stateLabel": self.state_label
}
else:
result = {
"seq": self.seq,
"original": self.original,
"translation": self.translation,
"muted": self.muted,
"targetLang": self.current_target_lang,
"stateLabel": self.state_label
}
return result
PAGE = """<!DOCTYPE html>
<html lang="es"><head><meta charset="utf-8">
<title>Live subtitles / Subtítulos en vivo</title>
<style>
html,body{margin:0;height:100%;background:#000;overflow:hidden;
font-family:'DejaVu Sans',Arial,sans-serif;display:flex;
align-items:flex-end;justify-content:center}
#wrap{width:92%;padding:4vh 0;text-align:center}
#orig{color:#9aa0a6;font-size:3.4vmin;margin-bottom:2.2vh}
#trans{color:#fff;font-size:6.2vmin;font-weight:700;line-height:1.35;
text-shadow:0 0 .6vmin #000, 0 0 1.5vmin #000}
#status{position:absolute;top:1vh;left:50%;transform:translateX(-50%);
color:#fff;font-size:2.5vmin;background:rgba(0,0,0,0.8);padding:.5vmin 1.5vmin;border-radius:.5vmin;
font-weight:bold;text-shadow:0 0 .3vmin #000}
.muted{opacity:0.3!important}
</style></head>
<body><div id="wrap"><div id="orig"></div><div id="trans"></div></div>
<div id="status">[Auto]</div>
<script>
let seq=0;
let isMuted=false;
let targetLang=null;
let stateLabel='Auto';
function updateStatus(){
const statusEl=document.getElementById('status');
let text='[' + stateLabel + ']';
if(isMuted) text='[MUTED]';
statusEl.textContent=text;
}
function applyMute(){
const transEl=document.getElementById('trans');
const origEl=document.getElementById('orig');
if(isMuted){
transEl.classList.add('muted');
origEl.classList.add('muted');
} else {
transEl.classList.remove('muted');
origEl.classList.remove('muted');
}
}
async function sendCommand(cmd){
try{
await fetch('/cmd?'+cmd);
}catch(e){}
}
async function poll(){
try{
const s=await (await fetch('/latest?seq='+seq)).json();
if(s.seq!==seq){
seq=s.seq;
document.getElementById('orig').textContent=s.original||'';
document.getElementById('trans').textContent=s.translation||s.original||'';
}
// Check for state changes
if(s.muted!==undefined && s.muted!==isMuted){
isMuted=s.muted;
applyMute();
updateStatus();
}
if(s.targetLang!==undefined && s.targetLang!==targetLang){
targetLang=s.targetLang;
}
if(s.stateLabel!==undefined && s.stateLabel!==stateLabel){
stateLabel=s.stateLabel;
updateStatus();
}
}catch(e){}
setTimeout(poll,200); // Reduced from 400ms for lower latency
}
document.addEventListener('keydown',e=>{
if(e.key==='f'){
document.documentElement.requestFullscreen();
} else if(e.key===' '){ // Space: cycle through states (single press)
e.preventDefault();
sendCommand('cycle');
}
});
poll();
updateStatus();
</script></body></html>"""
def create_http_handler(state):
"""Create HTTP handler class with access to state."""
from http.server import BaseHTTPRequestHandler
from urllib.parse import urlparse
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
u = urlparse(self.path)
if u.path == "/":
body = PAGE.encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif u.path == "/latest":
body = json.dumps(state.snapshot()).encode("utf-8")
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
elif u.path.startswith("/cmd"):
# Handle commands: /cmd?cycle
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
query = u.query
response = {"status": "ok"}
if query == "cycle":
state.cycle_state()
response["muted"] = state.muted
response["targetLang"] = state.current_target_lang
response["stateLabel"] = state.state_label
elif query == "toggle_mute":
# Legacy support
state.cycle_state()
response["muted"] = state.muted
elif query == "toggle_lang":
# Legacy support
state.cycle_state()
response["targetLang"] = state.current_target_lang
self.wfile.write(json.dumps(response).encode("utf-8"))
else:
self.send_error(404)
def log_message(self, *a):
pass
return Handler
# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def main():
ap = argparse.ArgumentParser(description="Live bilingual subtitles via Groq")
ap.add_argument("--device", type=int, default=None, help="input device index")
ap.add_argument("--list-devices", action="store_true")
ap.add_argument("--target-lang", type=str, default=None,
choices=['en', 'es'],
help="Force output language: 'en' for English, 'es' for Spanish (default: auto-detect)")
ap.add_argument("--port", type=int, default=HTTP_PORT,
help="HTTP server port (default: 8080). Common alternatives: 5000, 8000, 8080, 8888")
args = ap.parse_args()
if args.list_devices:
print(sd.query_devices())
return
from http.server import ThreadingHTTPServer
import signal
state = SubtitleState()
# Set initial state based on CLI argument if provided
if args.target_lang == 'es':
# Start at index 1: Unmuted, force Spanish
state.current_state_idx = 1
elif args.target_lang == 'en':
# Start at index 0: Unmuted, force English
state.current_state_idx = 0
# else: stays at default (MUTED=2)
Handler = create_http_handler(state)
server = None
server_thread = None
def cleanup_server():
"""Properly shutdown and close the HTTP server to free the port."""
if server is not None:
try:
server.shutdown()
server.server_close()
except Exception:
pass
# Try to start HTTP server, handle port conflicts
try:
server = ThreadingHTTPServer(("0.0.0.0", args.port), Handler)
server_thread = threading.Thread(target=server.serve_forever, daemon=True)
server_thread.start()
except OSError as e:
cleanup_server()
if e.errno == 98 or e.errno == 48:
print(f"\n[ERROR] Port {args.port} is already in use!", )
print(f"[ERROR] Try a different port with --port, e.g., --port 5000", )
print(f"[ERROR] Common free ports: 5000, 8080, 8888, 9000", )
try:
result = subprocess.run(['ss', '-tulnp'], capture_output=True, text=True)
for line in result.stdout.split('\n'):
if f':{args.port} ' in line and 'LISTEN' in line:
print(f"[ERROR] Process: {line.strip()}", )
break
except Exception:
pass
sys.exit(1)
else:
raise
lang_info = f" (forced to {args.target_lang.upper()})" if args.target_lang else ""
print(f"[{ts()}] Subtitles page: http://<this-machine>:{args.port}{lang_info}", flush=True)
print(f"[{ts()}] Press Ctrl-C to stop and free the port.", flush=True)
# Show initial state
initial_state = state.STATES[state.current_state_idx]['label']
print(f"[{ts()}] Initial state: [{initial_state}]", flush=True)
print(f"[{ts()}] Controls: SPACE=cycle (EN->ES->MUTED)", flush=True)
seg = Segmenter()
try:
with sd.InputStream(
samplerate=SAMPLE_RATE,
channels=CHANNELS,
dtype="int16",
blocksize=int(SAMPLE_RATE * BLOCK_MS / 1000),
device=args.device,
callback=seg.callback,
):
print(f"[{ts()}] Audio: device={args.device}, rate={SAMPLE_RATE}Hz, {CHANNELS}ch")
print(f"[{ts()}] Config: max_seg={MAX_SEGMENT_S}s, silence_flush={SILENCE_FLUSH_S}s, rms={SILENCE_RMS}, min_send={MIN_SEND_S}s, min_words={MIN_WORDS}")
print(f"[{ts()}] Transcript: {state.transcript_path}")
print("-" * 60)
print(f"[{ts()}] Listening...")
# Track last few transcriptions to detect repeated hallucinations
last_transcriptions = []
max_history = 5
while True:
wav = seg.next_segment()
if wav is None:
continue
# Check if muted - if so, skip transcription entirely for privacy
if state.muted:
continue
original = transcribe(wav)
if not original:
continue
# Check if this is a repeated hallucination
if original in last_transcriptions:
# Same text appeared recently - likely a Whisper hallucination
continue
# Use state's current_target_lang (can be changed via web page OR CLI)
current_lang = state.current_target_lang
translation = translate(original, target_lang=current_lang)
# Only show output when translation succeeds - silent when no valid speech
if translation:
state.publish(original, translation)
lang_display = f"[{state.state_label}]" if state.state_label else "[Auto]"
print(f"[{ts()}] {lang_display} \u001b[33m{original}\u001b[0m -> \u001b[32m{translation}\u001b[0m")
# Remember this transcription
last_transcriptions.append(original)
if len(last_transcriptions) > max_history:
last_transcriptions.pop(0)
# If translation fails/filtered: stay silent (no output)
except KeyboardInterrupt:
print(f"\n\n[{ts()}] Stopping...")
cleanup_server()
print(f"[{ts()}] Port {args.port} has been freed.")
sys.exit(0)
finally:
cleanup_server()
if __name__ == "__main__":
main()