- 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 <vibe@mistral.ai>
1181 lines
46 KiB
Python
1181 lines
46 KiB
Python
#!/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 threshold, min segment length) reduces background noise;
|
|
tune it per device with --calibrate.
|
|
|
|
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
|
|
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
|
|
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")
|
|
|
|
# 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 = 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
|
|
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:
|
|
"""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 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 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) / self.sample_rate
|
|
rms = float(np.sqrt(np.mean(block.astype(np.float64) ** 2)))
|
|
if rms > self.silence_rms:
|
|
self._speech_seen = True
|
|
self._silence_run = 0.0
|
|
elif self._speech_seen:
|
|
self._silence_run += len(block) / self.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 >= self.silence_flush_s or self._total_s >= self.max_segment_s
|
|
):
|
|
wav = self._wav_bytes()
|
|
keep = self._segment_len >= self.min_send_s
|
|
self._reset()
|
|
if keep:
|
|
return wav
|
|
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
|
|
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 '<idx>'}")
|
|
|
|
|
|
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
|
|
|
|
|
|
# --------------------------------------------------------------------------
|
|
# 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("--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:
|
|
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
|
|
|
|
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(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 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...")
|
|
# 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() |