From e2b303b5eddbab9df10b01543247a0a242171507 Mon Sep 17 00:00:00 2001 From: "robertwinkler@posteo.net" Date: Tue, 3 Nov 2026 14:54:37 -0600 Subject: [PATCH] Add device-aware audio input, calibration/test modes, and guided start.sh - Open input devices at a supported native sample rate and resample to 16 kHz in software (fixes 'Invalid sample rate' with webcams/USB mics) - Lower default SILENCE_RMS to 800, add --agc, make all segmentation thresholds CLI-configurable, load/save them via calibration.json - Add --calibrate (measures room noise vs. speech, recommends threshold) and --test (end-to-end mic + Groq ASR + translation gate, exit 0 on pass) - Add --list-devices-json for machine-readable device listing - Add start.sh: venv setup, interactive device picker, optional calibration, test gate before live mode, kiosk-mode browser launch - Add requirements.txt; document installation and running in README Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .gitignore | 1 + README.md | 103 +++- live-en-es-conference-subtitles-with-groq.py | 515 +++++++++++++++++-- requirements.txt | 4 + start.sh | 124 +++++ 5 files changed, 703 insertions(+), 44 deletions(-) create mode 100644 requirements.txt create mode 100755 start.sh diff --git a/.gitignore b/.gitignore index aaf99a5..f3651f3 100644 --- a/.gitignore +++ b/.gitignore @@ -37,3 +37,4 @@ env/ # Transcript files transcript-*.tsv +calibration.json diff --git a/README.md b/README.md index fded303..d1863a5 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,10 @@ Real-time bilingual subtitles for conference talks, translating between English - **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 +- **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 @@ -31,23 +34,63 @@ Real-time bilingual subtitles for conference talks, translating between English cd live-en-es-conference-subtitles-with-groq ``` -2. Install dependencies: +2. Install dependencies into a virtualenv (this is what `start.sh` does automatically on first run): ```bash - pip install sounddevice numpy requests python-dotenv + 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: +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 ``` -## Usage +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` -### Quick Start ```bash -python3 live-en-es-conference-subtitles-with-groq.py +./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 @@ -73,6 +116,52 @@ python3 live-en-es-conference-subtitles-with-groq.py ``` 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): diff --git a/live-en-es-conference-subtitles-with-groq.py b/live-en-es-conference-subtitles-with-groq.py index 5318c5e..6b4890e 100644 --- a/live-en-es-conference-subtitles-with-groq.py +++ b/live-en-es-conference-subtitles-with-groq.py @@ -23,7 +23,8 @@ Keyboard controls (on the web page): 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. + Audio filtering (RMS threshold, min segment length) reduces background noise; + tune it per device with --calibrate. Usage ----- @@ -35,6 +36,19 @@ Usage 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 + python3 live-en-es-conference-subtitles-with-groq.py --calibrate 20 # measure noise/speech levels, save calibration.json + python3 live-en-es-conference-subtitles-with-groq.py --device 4 --test 10 # verify mic + Groq pipeline (exit 0 = pass) + python3 live-en-es-conference-subtitles-with-groq.py --device 4 --agc # webcam + level normalization for quiet mics + python3 live-en-es-conference-subtitles-with-groq.py --list-devices-json # machine-readable device list (used by start.sh) + ./start.sh # guided startup: venv, device picker, calibrate, test, kiosk browser + +Audio input: the device's native sample rate is used automatically (webcams often +only support 44100/48000 Hz) and resampled to 16 kHz in software, so external +devices no longer cause "invalid sample rate" errors. Run --calibrate once per +machine/device: it measures ambient noise vs. your speech and saves tuned +thresholds to calibration.json, which is loaded automatically on startup +(--no-config to ignore, CLI flags override the file). --agc normalizes the level +of each segment before sending it to Groq, which helps quiet built-in mics. 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 @@ -79,13 +93,15 @@ 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 +# Defaults below; all of them can be overridden by calibration.json and CLI flags +SAMPLE_RATE = 16000 # Whisper native rate (input is resampled to this) 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 +SILENCE_RMS = 800 # RMS threshold (int16). 1500 was too high for quiet laptop mics; + # run --calibrate to pick the right value for your hardware/room +MIN_SEND_S = 2.0 # 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 @@ -102,31 +118,40 @@ 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): + """Collects 16 kHz mono int16 blocks and flushes them on speech pauses.""" + + def __init__(self, sample_rate=SAMPLE_RATE, silence_rms=SILENCE_RMS, + silence_flush_s=SILENCE_FLUSH_S, max_segment_s=MAX_SEGMENT_S, + min_send_s=MIN_SEND_S, agc=False): + self.sample_rate = sample_rate + self.silence_rms = silence_rms + self.silence_flush_s = silence_flush_s + self.max_segment_s = max_segment_s + self.min_send_s = min_send_s + self.agc = agc self.blocks = queue.Queue() self._reset() def _reset(self): - self._audio = [] # list of np.ndarray blocks + self._audio = [] # list of 1-D np.ndarray blocks (int16, self.sample_rate) 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 feed(self, block): + """Queue one 1-D int16 mono block already at self.sample_rate.""" + self.blocks.put(block) def _append(self, block): self._audio.append(block) - self._total_s += len(block) / SAMPLE_RATE + self._total_s += len(block) / self.sample_rate rms = float(np.sqrt(np.mean(block.astype(np.float64) ** 2))) - if rms > SILENCE_RMS: + if rms > self.silence_rms: self._speech_seen = True self._silence_run = 0.0 elif self._speech_seen: - self._silence_run += len(block) / SAMPLE_RATE + self._silence_run += len(block) / self.sample_rate def next_segment(self): """Blocking. Returns WAV bytes for one utterance segment, or None.""" @@ -134,27 +159,336 @@ class Segmenter: 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 + self._silence_run >= self.silence_flush_s or self._total_s >= self.max_segment_s ): wav = self._wav_bytes() - keep = self._segment_len >= MIN_SEND_S + keep = self._segment_len >= self.min_send_s self._reset() if keep: return wav - elif not self._speech_seen and self._total_s >= MAX_SEGMENT_S: + elif not self._speech_seen and self._total_s >= self.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() + return encode_wav(np.concatenate(self._audio), self.sample_rate, agc=self.agc) + + +# -------------------------------------------------------------------------- +# Device sample-rate handling and resampling +# -------------------------------------------------------------------------- +def resample_audio(block, src_rate, dst_rate): + """Linear-interpolation resampling of a 1-D float array.""" + if src_rate == dst_rate or len(block) == 0: + return block.astype(np.float64) if src_rate == dst_rate else block + n_src = len(block) + n_dst = max(1, int(round(n_src * dst_rate / src_rate))) + return np.interp(np.linspace(0.0, n_src - 1, n_dst), np.arange(n_src), + block.astype(np.float64)) + + +def resolve_input_rate(device, requested_rate): + """Return a sample rate the input device supports, preferring requested_rate. + + Many USB webcams/mics only support 44100 or 48000 Hz and raise + 'Invalid sample rate' when opened at 16000 Hz — this is the fix. + """ + try: + sd.check_input_settings(device=device, samplerate=requested_rate, + channels=CHANNELS, dtype="int16") + return int(requested_rate) + except Exception: + pass + try: + return int(sd.query_devices(device)["default_samplerate"]) + except Exception: + return 48000 + + +def probe_supported_rates(device, candidates=(8000, 11025, 16000, 22050, 32000, + 44100, 48000, 96000)): + ok = [] + for r in candidates: + try: + sd.check_input_settings(device=device, samplerate=r, + channels=CHANNELS, dtype="int16") + ok.append(r) + except Exception: + pass + return ok + + +def make_audio_callback(seg, src_rate, dst_rate): + """PortAudio callback: mono int16 at src_rate -> resampled to seg.sample_rate.""" + def cb(indata, frames, time_info, status): + if status: + print(f"[audio] {status}", ) + mono = indata.mean(axis=1) if indata.ndim > 1 else indata[:, 0] + if src_rate != dst_rate: + mono = resample_audio(mono.astype(np.float64), src_rate, dst_rate) + seg.feed(mono.astype(np.int16)) + return cb + + +def encode_wav(audio, sample_rate, agc=False): + """Encode a 1-D int16 mono array as 16-bit WAV bytes.""" + audio = np.asarray(audio).astype(np.float64) + if agc and audio.size: + # Normalize quiet sources (e.g. built-in laptop mics) before sending + peak = float(np.max(np.abs(audio))) + if peak > 0: + audio = audio * (0.6 * 32767.0 / peak) + buf = io.BytesIO() + with wave.open(buf, "wb") as w: + w.setnchannels(1) + w.setsampwidth(2) + w.setframerate(int(sample_rate)) + w.writeframes(audio.astype(np.int16).tobytes()) + return buf.getvalue() + + +def open_input_stream(device, requested_rate, block_ms, callback_factory): + """Open an input stream at a rate the device supports. + + callback_factory(native_rate) must return the PortAudio callback. + Returns (stream, native_rate). Falls back to the device default rate if the + probed rate is rejected at open time (some drivers lie in check_input_settings). + """ + native = resolve_input_rate(device, requested_rate) + + def build(rate): + return sd.InputStream( + samplerate=rate, channels=CHANNELS, dtype="int16", + blocksize=int(rate * block_ms / 1000), device=device, + callback=callback_factory(rate), + ) + + try: + return build(native), native + except Exception as e: + fallback = int(sd.query_devices(device)["default_samplerate"]) + if fallback == native: + raise + print(f"[audio] {native} Hz rejected by device ({e}); " + f"retrying at device default {fallback} Hz") + return build(fallback), fallback + + +# -------------------------------------------------------------------------- +# Calibration: measure noise vs. speech levels, save tuned parameters +# -------------------------------------------------------------------------- +TUNING_KEYS = ("sample_rate", "silence_rms", "silence_flush_s", + "max_segment_s", "min_send_s", "block_ms", "agc") + + +def _pct(values, p): + if not values: + return 0.0 + s = sorted(values) + k = (len(s) - 1) * (p / 100.0) + f = int(k) + c = min(f + 1, len(s) - 1) + return s[f] + (s[c] - s[f]) * (k - f) + + +def load_tuning_config(path): + """Read calibration.json if present. Returns dict with tuning keys + metadata.""" + cfg = {} + if path and os.path.exists(path): + try: + with open(path, encoding="utf-8") as f: + data = json.load(f) + for k in TUNING_KEYS: + if k in data: + cfg[k] = data[k] + cfg["_device"] = data.get("device") + cfg["_device_name"] = data.get("device_name") + cfg["_native_rate"] = data.get("native_rate") + cfg["_measured"] = data.get("measured") + except Exception as e: + print(f"[config] could not read {path}: {e}") + return cfg + + +def run_calibration(device, seconds, config_path): + """Listen for `seconds` seconds: first 60% stay SILENT, last 40% SPEAK. + + Measures per-block RMS in both phases, derives a silence threshold between + the noise floor and speech level, probes supported sample rates, and saves + everything to config_path (default calibration.json). + """ + info = sd.query_devices(device) + name = info.get("name", "?") + supported = probe_supported_rates(device) + native = resolve_input_rate(device, SAMPLE_RATE) + print("=" * 60) + print(f"[calibrate] device={device} ({name})") + print(f"[calibrate] device default rate: {int(info['default_samplerate'])} Hz; " + f"supported: {supported}") + print(f"[calibrate] capturing at {native} Hz, resampling to {SAMPLE_RATE} Hz") + print(f"[calibrate] duration {seconds:.0f}s -> stay SILENT for the first " + f"{seconds * 0.6:.0f}s, then SPEAK a few sentences for the last {seconds * 0.4:.0f}s") + print("=" * 60, flush=True) + + silence_frac = 0.6 + rms_silence, rms_speech = [], [] + start = time.time() + + def factory(rate): + def cb(indata, frames, time_info, status): + mono = indata.mean(axis=1) if indata.ndim > 1 else indata[:, 0] + if rate != SAMPLE_RATE: + mono = resample_audio(mono.astype(np.float64), rate, SAMPLE_RATE) + mono = mono.astype(np.int16).astype(np.float64) + rms = float(np.sqrt(np.mean(mono ** 2))) if mono.size else 0.0 + elapsed = time.time() - start + (rms_silence if elapsed < seconds * silence_frac else rms_speech).append(rms) + return cb + + stream, native = open_input_stream(device, SAMPLE_RATE, BLOCK_MS, factory) + with stream: + last_shown = -1 + while True: + elapsed = time.time() - start + remaining = seconds - elapsed + if remaining <= 0: + break + phase = "SILENCE (measure room noise)" if elapsed < seconds * silence_frac \ + else "SPEAK (a few sentences)" + shown = int(remaining) + if shown != last_shown: + last_shown = shown + print(f"[calibrate] {shown:3d}s left - {phase}", flush=True) + time.sleep(0.05) + + noise_p50 = _pct(rms_silence, 50) + noise_p95 = _pct(rms_silence, 95) + noise_max = max(rms_silence) if rms_silence else 0.0 + speech_p10 = _pct(rms_speech, 10) if rms_speech else 0.0 + speech_p50 = _pct(rms_speech, 50) if rms_speech else 0.0 + + # Threshold: well above the noise floor, safely below the quietest speech + rec = max(noise_p95 * 2.0, 100.0) + if speech_p10 > 0: + rec = min(rec, speech_p10 * 0.8) + rec = int(min(max(rec, 50.0), 8000.0)) + + measured = { + "noise_rms_p50": round(noise_p50, 1), + "noise_rms_p95": round(noise_p95, 1), + "noise_rms_max": round(noise_max, 1), + "speech_rms_p10": round(speech_p10, 1), + "speech_rms_p50": round(speech_p50, 1), + } + cal = { + "device": device, + "device_name": name, + "native_rate": native, + "supported_rates": supported, + "measured": measured, + "silence_rms": rec, + "silence_flush_s": SILENCE_FLUSH_S, + "max_segment_s": MAX_SEGMENT_S, + "min_send_s": MIN_SEND_S, + "block_ms": BLOCK_MS, + "agc": bool(speech_p50 > 0 and speech_p50 < 3000), # quiet mic -> normalize + } + with open(config_path, "w", encoding="utf-8") as f: + json.dump(cal, f, indent=2, ensure_ascii=False) + + print("-" * 60) + print(f"[calibrate] silence phase: p50={measured['noise_rms_p50']} " + f"p95={measured['noise_rms_p95']} max={measured['noise_rms_max']}") + print(f"[calibrate] speech phase: p10={measured['speech_rms_p10']} " + f"p50={measured['speech_rms_p50']}") + print(f"[calibrate] recommended SILENCE_RMS = {rec} (int16), " + f"agc={'on' if cal['agc'] else 'off'}") + print(f"[calibrate] saved to {config_path} - loaded automatically on next start") + print(f"[calibrate] start with: python3 {os.path.basename(__file__)} " + f"--device {device if device is not None else ''}") + + +def run_test(device, seconds, tuning): + """End-to-end test: open the device, capture `seconds` of audio while the user + speaks, verify speech is detected above the threshold, then verify Groq ASR + and translation both return text. Returns True on pass.""" + rate = tuning["sample_rate"] + blocks, rms_list = [], [] + + def factory(native): + def cb(indata, frames, time_info, status): + if status: + print(f"[audio] {status}", ) + mono = indata.mean(axis=1) if indata.ndim > 1 else indata[:, 0] + if native != rate: + mono = resample_audio(mono.astype(np.float64), native, rate) + mono = mono.astype(np.int16) + blocks.append(mono) + rms_list.append(float(np.sqrt(np.mean(mono.astype(np.float64) ** 2)))) + return cb + + print("=" * 60) + print(f"[test] opening device {device} ...") + try: + stream, native = open_input_stream(device, rate, tuning["block_ms"], factory) + except Exception as e: + print(f"[test] FAIL: could not open audio device: {e}") + return False + print(f"[test] device opened at {native} Hz" + + (f" (resampled to {rate} Hz)" if native != rate else "")) + + print(f"[test] capturing {seconds:.0f}s - SPEAK a few sentences now!") + start = time.time() + with stream: + last_shown = -1 + while True: + remaining = seconds - (time.time() - start) + if remaining <= 0: + break + shown = int(remaining) + if shown != last_shown: + last_shown = shown + print(f"[test] {shown:3d}s left - keep speaking", flush=True) + time.sleep(0.05) + + if not blocks: + print("[test] FAIL: no audio captured from device") + return False + audio = np.concatenate(blocks) + noise_p50 = _pct([r for r in rms_list if r <= tuning["silence_rms"]], 50) \ + if any(r <= tuning["silence_rms"] for r in rms_list) else 0.0 + speech_s = sum(1 for r in rms_list if r > tuning["silence_rms"]) * tuning["block_ms"] / 1000.0 + print(f"[test] captured {len(audio) / rate:.1f}s; max RMS={max(rms_list):.0f}, " + f"noise p50={noise_p50:.0f}, speech above threshold: {speech_s:.1f}s " + f"(need >= {tuning['min_send_s']}s at rms>{tuning['silence_rms']:.0f})") + if speech_s < tuning["min_send_s"]: + print("[test] FAIL: speech not detected above the silence threshold. " + "Speak louder/closer to the mic, or run --calibrate / lower --silence-rms.") + return False + print("[test] speech detection OK") + + wav = encode_wav(audio, rate, agc=tuning["agc"]) + print("[test] sending capture to Groq Whisper ...") + try: + original = transcribe(wav) + except Exception as e: + print(f"[test] FAIL: Groq ASR request error: {e}. Check GROQ_API_KEY in .env " + "and network access.") + return False + if not original: + print("[test] FAIL: Groq ASR returned no text. Check GROQ_API_KEY in .env, " + "network access, and that you actually spoke.") + return False + print(f"[test] transcription OK: {original!r}") + + translation = translate(original, target_lang=None) + if not translation: + print(f"[test] FAIL: translation returned empty for {original!r}") + return False + print(f"[test] translation OK: {translation!r}") + print("[test] PASS: audio -> transcription -> translation all working") + return True # -------------------------------------------------------------------------- @@ -606,17 +940,115 @@ 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, + ap.add_argument("--list-devices-json", action="store_true", + help="print input devices (index, name, supported rates) as JSON and exit") + ap.add_argument("--test", type=float, nargs="?", const=10.0, default=None, + metavar="SECONDS", + help="test mode: capture SECONDS of audio while you speak, verify speech " + "detection + Groq transcription + translation; exit 0 only on pass") + 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") + ap.add_argument("--samplerate", type=int, default=None, + help="requested input sample rate in Hz (default: 16000; if the device does " + "not support it, its native rate is used and audio is resampled)") + ap.add_argument("--silence-rms", type=float, default=None, + help="RMS threshold (int16) above which audio counts as speech (default: 800; " + "use --calibrate to tune for your mic and room)") + ap.add_argument("--silence-flush", type=float, default=None, + help="seconds of trailing silence that cut a segment (default: 0.5)") + ap.add_argument("--max-segment", type=float, default=None, + help="maximum segment length in seconds (default: 3.5)") + ap.add_argument("--min-send", type=float, default=None, + help="minimum segment length in seconds sent to the API (default: 2.0)") + ap.add_argument("--block-ms", type=int, default=None, + help="audio callback block size in ms (default: 20)") + ap.add_argument("--agc", action="store_true", + help="normalize each segment's level before sending to Groq (helps quiet built-in mics)") + ap.add_argument("--config", type=str, default="calibration.json", + help="JSON file with calibrated parameters, auto-loaded if present (default: calibration.json)") + ap.add_argument("--no-config", action="store_true", + help="ignore the calibration config file") + ap.add_argument("--calibrate", type=float, nargs="?", const=20.0, default=None, + metavar="SECONDS", + help="calibration mode: measure room noise vs. speech for SECONDS (default: 20), " + "then save tuned parameters to the config file and exit") args = ap.parse_args() if args.list_devices: - print(sd.query_devices()) + devices = sd.query_devices() + if isinstance(devices, dict): + devices = [devices] + print(devices if isinstance(devices, list) else sd.query_devices()) + print("\nSupported sample rates per input device:") + for i, d in enumerate(devices): + if d.get("max_input_channels", 0) > 0: + print(f" [{i}] {d['name']}: {probe_supported_rates(i)}") return + if args.list_devices_json: + devices = sd.query_devices() + if isinstance(devices, dict): + devices = [devices] + out = [ + { + "index": i, + "name": d["name"], + "default_samplerate": int(d["default_samplerate"]), + "supported_rates": probe_supported_rates(i), + } + for i, d in enumerate(devices) if d.get("max_input_channels", 0) > 0 + ] + print(json.dumps(out, indent=2, ensure_ascii=False)) + return + + # --- Resolve tuning parameters: defaults < calibration file < CLI flags --- + tuning = { + "sample_rate": SAMPLE_RATE, + "silence_rms": SILENCE_RMS, + "silence_flush_s": SILENCE_FLUSH_S, + "max_segment_s": MAX_SEGMENT_S, + "min_send_s": MIN_SEND_S, + "block_ms": BLOCK_MS, + "agc": False, + } + file_cfg = {} if args.no_config else load_tuning_config(args.config) + if file_cfg: + print(f"[{ts()}] Loaded calibrated parameters from {args.config}") + if file_cfg.get("_measured"): + m = file_cfg["_measured"] + print(f"[{ts()}] measured noise p95={m.get('noise_rms_p95')}, " + f"speech p10={m.get('speech_rms_p10')} (RMS int16)") + tuning.update({k: v for k, v in file_cfg.items() if k in tuning}) + for arg_name, key in (("samplerate", "sample_rate"), ("silence_rms", "silence_rms"), + ("silence_flush", "silence_flush_s"), ("max_segment", "max_segment_s"), + ("min_send", "min_send_s"), ("block_ms", "block_ms")): + v = getattr(args, arg_name) + if v is not None: + tuning[key] = v + if args.agc: + tuning["agc"] = True + + device = args.device + if device is None and file_cfg.get("_device") is not None: + try: + sd.query_devices(file_cfg["_device"]) + device = file_cfg["_device"] + print(f"[{ts()}] Using calibrated device #{device} " + f"({file_cfg.get('_device_name')}); override with --device") + except Exception: + pass + + if args.calibrate is not None: + run_calibration(device, args.calibrate, args.config) + return + + if args.test is not None: + ok = run_test(device, args.test, tuning) + sys.exit(0 if ok else 1) + from http.server import ThreadingHTTPServer import signal @@ -676,18 +1108,27 @@ def main(): print(f"[{ts()}] Initial state: [{initial_state}]", flush=True) print(f"[{ts()}] Controls: SPACE=cycle (EN->ES->MUTED)", flush=True) - seg = Segmenter() + seg = Segmenter(sample_rate=tuning["sample_rate"], silence_rms=tuning["silence_rms"], + silence_flush_s=tuning["silence_flush_s"], max_segment_s=tuning["max_segment_s"], + min_send_s=tuning["min_send_s"], agc=tuning["agc"]) + + # Open the device at a rate it actually supports; resample to 16 kHz if needed. + # This is what makes webcams/USB interfaces (44.1/48 kHz only) work. + stream, native_rate = open_input_stream( + device, tuning["sample_rate"], tuning["block_ms"], + lambda r: make_audio_callback(seg, r, tuning["sample_rate"]), + ) + if native_rate != tuning["sample_rate"]: + print(f"[{ts()}] Device does not support {tuning['sample_rate']} Hz; " + f"capturing at native {native_rate} Hz and resampling to {tuning['sample_rate']} Hz") + 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}") + with stream: + print(f"[{ts()}] Audio: device={device}, capturing at {native_rate}Hz -> " + f"{tuning['sample_rate']}Hz, {CHANNELS}ch, agc={'on' if tuning['agc'] else 'off'}") + print(f"[{ts()}] Config: max_seg={tuning['max_segment_s']}s, " + f"silence_flush={tuning['silence_flush_s']}s, rms={tuning['silence_rms']}, " + f"min_send={tuning['min_send_s']}s, min_words={MIN_WORDS}") print(f"[{ts()}] Transcript: {state.transcript_path}") print("-" * 60) print(f"[{ts()}] Listening...") diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..c3481cb --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +sounddevice +numpy +requests +python-dotenv diff --git a/start.sh b/start.sh new file mode 100755 index 0000000..d047212 --- /dev/null +++ b/start.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# start.sh — guided startup for live EN-ES conference subtitles. +# +# Flow: set up the virtualenv -> detect audio input devices and ask which one +# to use -> offer calibration -> run an end-to-end test (mic + Groq) and only +# proceed if it passes -> start live transcription/translation -> open the +# subtitle page in a kiosk-mode browser. +# +# Usage: ./start.sh [extra args for the python program, e.g. --target-lang es] +# Env: PORT=8080 to change the web port (default 8080). +set -euo pipefail +cd "$(dirname "$0")" + +PROG="live-en-es-conference-subtitles-with-groq.py" +PORT="${PORT:-8080}" +URL="http://127.0.0.1:${PORT}" + +# --- 1. Virtualenv ----------------------------------------------------------- +if [ ! -x .venv/bin/python ]; then + echo "[start] creating virtualenv in .venv ..." + python3 -m venv .venv + .venv/bin/pip install --quiet --upgrade pip + .venv/bin/pip install --quiet -r requirements.txt +fi +PY=.venv/bin/python + +if [ ! -f .env ]; then + echo "[start] WARNING: no .env file found. Create one with: GROQ_API_KEY=\"gsk_...\"" +fi + +# --- 2. Detect audio input devices and ask which to use ---------------------- +echo "[start] detecting audio input devices ..." +mapfile -t DEVICES < <("$PY" "$PROG" --list-devices-json | "$PY" -c ' +import json, sys +for d in json.load(sys.stdin): + rates = ",".join(str(r) for r in d["supported_rates"]) or "unknown" + print("%s|%s|%s|%s" % (d["index"], d["name"], d["default_samplerate"], rates)) +') +if [ "${#DEVICES[@]}" -eq 0 ]; then + echo "[start] ERROR: no audio input devices found. Plug in a microphone/webcam." + exit 1 +fi +echo "[start] available input devices:" +for d in "${DEVICES[@]}"; do + IFS='|' read -r i n def rates <<<"$d" + echo " [$i] $n (default ${def} Hz, supports: ${rates} Hz)" +done +DEV="" +while [ -z "$DEV" ]; do + read -rp "[start] select device index: " choice + for d in "${DEVICES[@]}"; do + if [ "${d%%|*}" = "$choice" ]; then DEV="$choice"; break; fi + done + [ -n "$DEV" ] || echo "[start] invalid choice, try again." +done +echo "[start] using device [$DEV]" + +# --- 3. Offer calibration ---------------------------------------------------- +read -rp "[start] run calibration now (recommended after changing device/room)? [Y/n] " ans +if [[ ! "$ans" =~ ^[Nn] ]]; then + read -rp "[start] calibration length in seconds [20]: " secs + secs="${secs:-20}" + "$PY" "$PROG" --device "$DEV" --calibrate "$secs" +fi + +# --- 4. Test gate: live mode only starts if the test passes ------------------ +while true; do + read -rp "[start] run the audio+API test before going live? [Y/n] " ans + if [[ "$ans" =~ ^[Nn] ]]; then + echo "[start] aborting: live transcription requires a passing test." + exit 1 + fi + read -rp "[start] test length in seconds [10]: " tsecs + tsecs="${tsecs:-10}" + if "$PY" "$PROG" --device "$DEV" --test "$tsecs"; then + echo "[start] test passed." + break + fi + echo "[start] test FAILED." + read -rp "[start] retry the test? [Y/n] " retry + if [[ "$retry" =~ ^[Nn] ]]; then + echo "[start] aborting: live transcription requires a passing test." + exit 1 + fi +done + +# --- 5. Start live transcription/translation --------------------------------- +echo "[start] starting live subtitles on ${URL} ..." +"$PY" "$PROG" --device "$DEV" --port "$PORT" "$@" & +APP_PID=$! +BROWSER_PID="" +cleanup() { + [ -n "$BROWSER_PID" ] && kill "$BROWSER_PID" 2>/dev/null || true + kill "$APP_PID" 2>/dev/null || true +} +trap cleanup EXIT INT TERM + +# wait until the web server answers +for _ in $(seq 1 50); do + curl -sf "${URL}/latest" >/dev/null 2>&1 && break + sleep 0.2 +done + +# --- 6. Open the subtitle page in a kiosk-mode browser ----------------------- +if [ -z "${DISPLAY:-}" ]; then + echo "[start] no DISPLAY set - open ${URL} manually on the subtitle screen." +else + BROWSER="" + for b in google-chrome google-chrome-stable chromium chromium-browser firefox; do + if command -v "$b" >/dev/null 2>&1; then BROWSER="$b"; break; fi + done + if [ -z "$BROWSER" ]; then + echo "[start] no supported browser found - open ${URL} manually." + elif [ "$BROWSER" = "firefox" ]; then + echo "[start] opening ${URL} in Firefox kiosk mode ..." + firefox --kiosk "$URL" & BROWSER_PID=$! + else + echo "[start] opening ${URL} in ${BROWSER} kiosk mode ..." + "$BROWSER" --kiosk --no-first-run --disable-infobars --autoplay-policy=no-user-gesture-required "$URL" & BROWSER_PID=$! + fi +fi + +echo "[start] running. Press Ctrl-C to stop (browser and server are closed automatically)." +wait "$APP_PID"