bridge.py 15 KB

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