bridge.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 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 = None
  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. while not queue.empty():
  172. queue.get_nowait()
  173. while True:
  174. chunk = await queue.get()
  175. await ws.send(chunk)
  176. async def _receiver(ws, state: BridgeState, mqtt_client: mqtt.Client) -> None:
  177. async for message in ws:
  178. try:
  179. data = json.loads(message)
  180. except (json.JSONDecodeError, TypeError):
  181. continue
  182. text = (data.get("text") or data.get("buffer_transcription") or "").strip()
  183. is_final = data.get("is_final", False) or data.get("end_of_segment", False)
  184. speaker = _extract_speaker(data)
  185. if is_final and text:
  186. print(f"[Whisper] ({speaker or '?'}) {text}")
  187. state.push_final(text, speaker, mqtt_client)
  188. async def _flusher(state: BridgeState, mqtt_client: mqtt.Client) -> None:
  189. while True:
  190. await asyncio.sleep(1.0)
  191. state.maybe_timeout_flush(mqtt_client)
  192. async def _speaker_reloader(state: BridgeState) -> None:
  193. """Reload speakers.json every 5 s so admin UI changes take effect live."""
  194. last_mtime = 0.0
  195. while True:
  196. await asyncio.sleep(5.0)
  197. try:
  198. mtime = SPEAKERS_FILE.stat().st_mtime
  199. if mtime != last_mtime:
  200. fresh = _load_speakers()
  201. with state._lock:
  202. state.speaker_names = fresh
  203. last_mtime = mtime
  204. print("[Bridge] Speaker names reloaded from disk")
  205. except OSError:
  206. pass
  207. def _choose_audio_device() -> int | None:
  208. """
  209. List all input devices and return the index to use.
  210. Prefers AUDIO_DEVICE if set, otherwise the system default,
  211. otherwise the first device with input channels.
  212. """
  213. try:
  214. devices = sd.query_devices()
  215. default_in = sd.default.device[0] # may be -1 if unset
  216. except Exception as exc:
  217. print(f"[Audio] Cannot query devices: {exc}")
  218. return None
  219. print("[Audio] Available input devices:")
  220. input_devices: list[tuple[int, str]] = []
  221. for i, dev in enumerate(devices):
  222. if dev["max_input_channels"] > 0:
  223. marker = " ← default" if i == default_in else ""
  224. print(f" [{i}] {dev['name']}{marker}")
  225. input_devices.append((i, dev["name"]))
  226. if not input_devices:
  227. print("[Audio] ERROR: No input devices found. Connect a microphone and restart.")
  228. return None
  229. # Explicit override from config
  230. if AUDIO_DEVICE is not None:
  231. print(f"[Audio] Using configured device [{AUDIO_DEVICE}]")
  232. return AUDIO_DEVICE
  233. # System default (if valid)
  234. if default_in >= 0:
  235. print(f"[Audio] Using default input device [{default_in}]")
  236. return default_in
  237. # Fall back to first available input
  238. idx, name = input_devices[0]
  239. print(f"[Audio] No system default set — using [{idx}] {name}")
  240. print("[Audio] To choose a different device, set AUDIO_DEVICE in bridge.py")
  241. return idx
  242. async def audio_ws_loop(state: BridgeState, mqtt_client: mqtt.Client) -> None:
  243. audio_queue: asyncio.Queue[bytes] = asyncio.Queue(maxsize=120)
  244. loop = asyncio.get_running_loop()
  245. def audio_callback(indata: np.ndarray, frames: int, time_info, status) -> None:
  246. if status:
  247. print(f"[Audio] {status}")
  248. chunk = indata.tobytes()
  249. def _put():
  250. try:
  251. audio_queue.put_nowait(chunk)
  252. except asyncio.QueueFull:
  253. pass
  254. loop.call_soon_threadsafe(_put)
  255. device = _choose_audio_device()
  256. if device is None:
  257. print("[Audio] No input device available — audio pipeline cannot start.")
  258. return
  259. with sd.InputStream(
  260. device=device,
  261. samplerate=SAMPLE_RATE,
  262. channels=CHANNELS,
  263. dtype="int16",
  264. blocksize=BLOCKSIZE,
  265. callback=audio_callback,
  266. ):
  267. flusher = asyncio.create_task(_flusher(state, mqtt_client))
  268. reloader = asyncio.create_task(_speaker_reloader(state))
  269. try:
  270. while True:
  271. try:
  272. print(f"[WS] Connecting to {WS_URL} ...")
  273. async with websockets.connect(WS_URL, max_size=2**23) as ws:
  274. print("[WS] Connected")
  275. send_t = asyncio.create_task(_sender(ws, audio_queue))
  276. recv_t = asyncio.create_task(_receiver(ws, state, mqtt_client))
  277. done, pending = await asyncio.wait(
  278. [send_t, recv_t], return_when=asyncio.FIRST_COMPLETED
  279. )
  280. for t in pending:
  281. t.cancel()
  282. for t in done:
  283. if not t.cancelled() and (exc := t.exception()):
  284. print(f"[WS] Task error: {exc}")
  285. except (websockets.ConnectionClosed, OSError, ConnectionRefusedError) as exc:
  286. print(f"[WS] {exc} — retrying in 3 s...")
  287. await asyncio.sleep(3)
  288. finally:
  289. flusher.cancel()
  290. reloader.cancel()
  291. def run_async_loop(state: BridgeState, mqtt_client: mqtt.Client) -> None:
  292. asyncio.run(audio_ws_loop(state, mqtt_client))
  293. # ── Entry point ───────────────────────────────────────────────────────────────
  294. def main() -> None:
  295. state = BridgeState()
  296. mqtt_client = build_mqtt_client()
  297. ws_thread = threading.Thread(
  298. target=run_async_loop, args=(state, mqtt_client), daemon=True
  299. )
  300. ws_thread.start()
  301. print(f"[Bridge] Speaker names loaded from {SPEAKERS_FILE}")
  302. print("[Bridge] Audio pipeline running — speaker admin at http://localhost:8001")
  303. print("[Bridge] Close this window to quit")
  304. try:
  305. ws_thread.join()
  306. except KeyboardInterrupt:
  307. pass
  308. if __name__ == "__main__":
  309. main()