bridge.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. #!/usr/bin/env python3
  2. """
  3. bridge.py — Church Live Transcription Bridge
  4. Streams microphone audio to WhisperLiveKit (ws://localhost:8000/asr),
  5. receives transcription + speaker diarization, buffers sentences, and
  6. publishes rolling 3-line JSON to Mosquitto MQTT for the e-ink display.
  7. Start WhisperLiveKit with:
  8. wlk --model_size large-v3 --language en --diarization
  9. Run this script:
  10. python bridge.py
  11. """
  12. import asyncio
  13. import json
  14. import re
  15. import textwrap
  16. import threading
  17. import time
  18. from collections import Counter
  19. from pathlib import Path
  20. import numpy as np
  21. import paho.mqtt.client as mqtt
  22. import sounddevice as sd
  23. import websockets
  24. # ── Configuration ─────────────────────────────────────────────────────────────
  25. MQTT_HOST = "localhost"
  26. MQTT_PORT = 1883
  27. MQTT_TOPIC_TEXT = "display/text"
  28. MQTT_TOPIC_CLEAR = "display/clear"
  29. WS_URL = "ws://localhost:8000/asr"
  30. SAMPLE_RATE = 16000
  31. CHANNELS = 1
  32. BLOCKSIZE = 4096 # ~256 ms per chunk at 16 kHz
  33. SENTENCE_TIMEOUT = 4.0 # seconds of silence before forcing a flush
  34. MAX_LINE_CHARS = 38 # characters per line (~24pt font at 800 px wide)
  35. DISPLAY_LINES = 3
  36. # Set to a device index (integer) to force a specific microphone.
  37. # Leave as None to use the Windows default input device.
  38. # Run bridge.py once to see available device indices printed at startup.
  39. AUDIO_DEVICE: int | None = 12
  40. SPEAKERS_FILE = Path(__file__).parent / "speakers.json"
  41. DEFAULT_SPEAKERS: dict[str, str] = {
  42. "SPEAKER_00": "Pastor",
  43. "SPEAKER_01": "Reader",
  44. "SPEAKER_02": "Guest",
  45. "SPEAKER_03": "Choir",
  46. }
  47. # ── Speaker persistence ───────────────────────────────────────────────────────
  48. def _load_speakers() -> dict[str, str]:
  49. if SPEAKERS_FILE.exists():
  50. try:
  51. data = json.loads(SPEAKERS_FILE.read_text(encoding="utf-8"))
  52. if isinstance(data, dict):
  53. return data
  54. except (json.JSONDecodeError, OSError):
  55. pass
  56. # First run — seed with defaults and save
  57. _write_speakers(DEFAULT_SPEAKERS)
  58. return dict(DEFAULT_SPEAKERS)
  59. def _write_speakers(names: dict[str, str]) -> None:
  60. try:
  61. SPEAKERS_FILE.write_text(
  62. json.dumps(names, indent=2, ensure_ascii=False),
  63. encoding="utf-8",
  64. )
  65. except OSError as exc:
  66. print(f"[Speakers] Save failed: {exc}")
  67. # ── State ─────────────────────────────────────────────────────────────────────
  68. class BridgeState:
  69. """All mutable state, protected by a single lock."""
  70. def __init__(self):
  71. self._lock = threading.Lock()
  72. self.speaker_names: dict[str, str] = _load_speakers()
  73. self._seen: set[str] = set(self.speaker_names)
  74. self._current_speaker: str | None = None
  75. self._speaker_changed = False
  76. self._text_buffer = ""
  77. self._display: list[str] = [""] * DISPLAY_LINES
  78. self._last_final_time = time.monotonic()
  79. # ── Speaker name management ───────────────────────────────────────────────
  80. def set_speaker_name(self, speaker_id: str, name: str) -> None:
  81. with self._lock:
  82. self.speaker_names[speaker_id] = name.strip()
  83. self._seen.add(speaker_id)
  84. _write_speakers(self.speaker_names)
  85. def delete_speaker(self, speaker_id: str) -> None:
  86. with self._lock:
  87. self.speaker_names.pop(speaker_id, None)
  88. self._seen.discard(speaker_id)
  89. _write_speakers(self.speaker_names)
  90. def seen_speakers_snapshot(self) -> set[str]:
  91. with self._lock:
  92. return set(self._seen)
  93. def _resolve(self, speaker_id: str | None) -> str | None:
  94. if not speaker_id:
  95. return None
  96. return self.speaker_names.get(speaker_id, speaker_id)
  97. # ── Text ingestion ────────────────────────────────────────────────────────
  98. def push_final(self, text: str, speaker_id: str | None, mqtt_client: mqtt.Client) -> None:
  99. """Accept a finalised segment; flush on sentence boundary or speaker change."""
  100. with self._lock:
  101. if speaker_id:
  102. self._seen.add(speaker_id)
  103. resolved = self._resolve(speaker_id)
  104. if resolved != self._current_speaker:
  105. if self._text_buffer:
  106. self._flush(mqtt_client)
  107. self._current_speaker = resolved
  108. self._speaker_changed = True
  109. sep = " " if self._text_buffer else ""
  110. self._text_buffer += sep + text.strip()
  111. self._last_final_time = time.monotonic()
  112. if _is_sentence_end(text):
  113. self._flush(mqtt_client)
  114. def maybe_timeout_flush(self, mqtt_client: mqtt.Client) -> None:
  115. with self._lock:
  116. if self._text_buffer and (time.monotonic() - self._last_final_time) > SENTENCE_TIMEOUT:
  117. self._flush(mqtt_client)
  118. def _flush(self, mqtt_client: mqtt.Client) -> None:
  119. """Word-wrap buffer → rolling display → publish. Must hold lock."""
  120. text = self._text_buffer.strip()
  121. self._text_buffer = ""
  122. if not text:
  123. return
  124. new_lines: list[str] = []
  125. if self._speaker_changed and self._current_speaker:
  126. new_lines.append(f"[{self._current_speaker.upper()}]")
  127. self._speaker_changed = False
  128. new_lines.extend(textwrap.wrap(text, MAX_LINE_CHARS) or [""])
  129. self._display.extend(new_lines)
  130. self._display = self._display[-DISPLAY_LINES:]
  131. while len(self._display) < DISPLAY_LINES:
  132. self._display.insert(0, "")
  133. payload = json.dumps({"lines": list(self._display)})
  134. mqtt_client.publish(MQTT_TOPIC_TEXT, payload)
  135. print(f"[Display] {self._display}")
  136. def clear(self, mqtt_client: mqtt.Client) -> None:
  137. with self._lock:
  138. self._display = [""] * DISPLAY_LINES
  139. self._text_buffer = ""
  140. self._current_speaker = None
  141. self._speaker_changed = False
  142. mqtt_client.publish(MQTT_TOPIC_CLEAR, "")
  143. print("[Display] Cleared")
  144. # ── Helpers ───────────────────────────────────────────────────────────────────
  145. def _is_sentence_end(text: str) -> bool:
  146. return bool(re.search(r'[.!?…]\s*$', text.strip()))
  147. def _extract_speaker(data: dict) -> str | None:
  148. if "speaker" in data:
  149. return data["speaker"] or None
  150. words = data.get("words", [])
  151. if words:
  152. ids = [w.get("speaker") for w in words if w.get("speaker")]
  153. if ids:
  154. return Counter(ids).most_common(1)[0][0]
  155. return None
  156. # ── MQTT ──────────────────────────────────────────────────────────────────────
  157. def build_mqtt_client() -> mqtt.Client:
  158. client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
  159. def on_connect(client, userdata, flags, rc, props):
  160. print("[MQTT] Connected" if rc == 0 else f"[MQTT] Failed: {rc}")
  161. def on_disconnect(client, userdata, flags, rc, props):
  162. print(f"[MQTT] Disconnected ({rc}), will reconnect...")
  163. client.on_connect = on_connect
  164. client.on_disconnect = on_disconnect
  165. client.reconnect_delay_set(min_delay=1, max_delay=30)
  166. client.connect_async(MQTT_HOST, MQTT_PORT)
  167. client.loop_start()
  168. return client
  169. # ── WebSocket + audio pipeline ────────────────────────────────────────────────
  170. async def _sender(ws, queue: asyncio.Queue) -> None:
  171. # Send config handshake first — WhisperLiveKit needs this before audio
  172. config = json.dumps({
  173. "uid": "bridge-client",
  174. "language": "en",
  175. "task": "transcribe",
  176. "model_size": "large-v3",
  177. "use_vad": True,
  178. })
  179. await ws.send(config)
  180. # Drain any stale chunks
  181. while not queue.empty():
  182. queue.get_nowait()
  183. while True:
  184. chunk = await queue.get()
  185. await ws.send(chunk)
  186. async def _receiver(ws, state: BridgeState, mqtt_client: mqtt.Client) -> None:
  187. async for message in ws:
  188. try:
  189. data = json.loads(message)
  190. except (json.JSONDecodeError, TypeError):
  191. continue
  192. text = (data.get("text") or data.get("buffer_transcription") or "").strip()
  193. is_final = data.get("is_final", False) or data.get("end_of_segment", False)
  194. speaker = _extract_speaker(data)
  195. if is_final and text:
  196. print(f"[Whisper] ({speaker or '?'}) {text}")
  197. state.push_final(text, speaker, mqtt_client)
  198. async def _flusher(state: BridgeState, mqtt_client: mqtt.Client) -> None:
  199. while True:
  200. await asyncio.sleep(1.0)
  201. state.maybe_timeout_flush(mqtt_client)
  202. async def _speaker_reloader(state: BridgeState) -> None:
  203. """Reload speakers.json every 5 s so admin UI changes take effect live."""
  204. last_mtime = 0.0
  205. while True:
  206. await asyncio.sleep(5.0)
  207. try:
  208. mtime = SPEAKERS_FILE.stat().st_mtime
  209. if mtime != last_mtime:
  210. fresh = _load_speakers()
  211. with state._lock:
  212. state.speaker_names = fresh
  213. last_mtime = mtime
  214. print("[Bridge] Speaker names reloaded from disk")
  215. except OSError:
  216. pass
  217. def _choose_audio_device() -> int | None:
  218. """
  219. List all input devices and return the index to use.
  220. Prefers AUDIO_DEVICE if set, otherwise the system default,
  221. otherwise the first device with input channels.
  222. """
  223. try:
  224. devices = sd.query_devices()
  225. default_in = sd.default.device[0] # may be -1 if unset
  226. except Exception as exc:
  227. print(f"[Audio] Cannot query devices: {exc}")
  228. return None
  229. print("[Audio] Available input devices:")
  230. input_devices: list[tuple[int, str]] = []
  231. for i, dev in enumerate(devices):
  232. if dev["max_input_channels"] > 0:
  233. marker = " ← default" if i == default_in else ""
  234. print(f" [{i}] {dev['name']}{marker}")
  235. input_devices.append((i, dev["name"]))
  236. if not input_devices:
  237. print("[Audio] ERROR: No input devices found. Connect a microphone and restart.")
  238. return None
  239. # Explicit override from config
  240. if AUDIO_DEVICE is not None:
  241. print(f"[Audio] Using configured device [{AUDIO_DEVICE}]")
  242. return AUDIO_DEVICE
  243. # System default (if valid)
  244. if default_in >= 0:
  245. print(f"[Audio] Using default input device [{default_in}]")
  246. return default_in
  247. # Fall back to first available input
  248. idx, name = input_devices[0]
  249. print(f"[Audio] No system default set — using [{idx}] {name}")
  250. print("[Audio] To choose a different device, set AUDIO_DEVICE in bridge.py")
  251. return idx
  252. # Remove the WebSocket audio sender entirely.
  253. # Use sounddevice → AudioProcessor directly via the Python API.
  254. from whisperlivekit import AudioProcessor, TranscriptionEngine
  255. async def audio_processor_loop(state: BridgeState, mqtt_client: mqtt.Client, engine: TranscriptionEngine) -> None:
  256. audio_queue: asyncio.Queue[bytes] = asyncio.Queue(maxsize=120)
  257. loop = asyncio.get_running_loop()
  258. def audio_callback(indata: np.ndarray, frames: int, time_info, status) -> None:
  259. if status:
  260. print(f"[Audio] {status}")
  261. chunk = indata.astype(np.float32).tobytes()
  262. loop.call_soon_threadsafe(lambda: audio_queue.put_nowait(chunk) if not audio_queue.full() else None)
  263. device = _choose_audio_device()
  264. if device is None:
  265. print("[Audio] No input device — cannot start.")
  266. return
  267. audio_processor = AudioProcessor(transcription_engine=engine)
  268. results_generator = await audio_processor.create_tasks()
  269. async def _receive_results():
  270. async for response in results_generator:
  271. # response is a FrontData dataclass, not a dict
  272. text = (getattr(response, "text", None) or getattr(response, "buffer_transcription", None) or "").strip()
  273. is_final = getattr(response, "is_final", False) or getattr(response, "end_of_segment", False)
  274. speaker = getattr(response, "speaker", None)
  275. if is_final and text:
  276. print(f"[Whisper] ({speaker or '?'}) {text}")
  277. state.push_final(text, speaker, mqtt_client)
  278. async def _send_audio():
  279. with sd.InputStream(
  280. device=device, samplerate=SAMPLE_RATE, channels=CHANNELS,
  281. dtype="float32", blocksize=BLOCKSIZE, callback=audio_callback,
  282. ):
  283. while True:
  284. chunk = await audio_queue.get()
  285. await audio_processor.process_audio(chunk)
  286. flusher = asyncio.create_task(_flusher(state, mqtt_client))
  287. reloader = asyncio.create_task(_speaker_reloader(state))
  288. try:
  289. await asyncio.gather(_send_audio(), _receive_results())
  290. finally:
  291. flusher.cancel()
  292. reloader.cancel()
  293. def run_async_loop(state: BridgeState, mqtt_client: mqtt.Client) -> None:
  294. asyncio.run(audio_ws_loop(state, mqtt_client))
  295. # ── Entry point ───────────────────────────────────────────────────────────────
  296. def main() -> None:
  297. from whisperlivekit import TranscriptionEngine
  298. state = BridgeState()
  299. mqtt_client = build_mqtt_client()
  300. engine = TranscriptionEngine(model_size="large-v3", lan="en", diarization=False)
  301. def _run():
  302. asyncio.run(audio_processor_loop(state, mqtt_client, engine))
  303. ws_thread = threading.Thread(target=_run, daemon=True)
  304. ws_thread.start()
  305. print("[Bridge] Audio pipeline running")
  306. try:
  307. ws_thread.join()
  308. except KeyboardInterrupt:
  309. pass
  310. if __name__ == "__main__":
  311. main()