bridge.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. #!/usr/bin/env python3
  2. """
  3. bridge.py — Live Transcription Bridge
  4. Uses WhisperLiveKit's AudioProcessor API directly (no WebSocket).
  5. Publishes rolling 3-line JSON to Mosquitto MQTT.
  6. Run this script:
  7. python bridge.py
  8. """
  9. import asyncio
  10. import json
  11. import queue as _stdlib_queue
  12. import re
  13. import textwrap
  14. import threading
  15. import time
  16. from collections import Counter
  17. from pathlib import Path
  18. import numpy as np
  19. import paho.mqtt.client as mqtt
  20. import sounddevice as sd
  21. from fastapi import FastAPI, Request
  22. from whisperlivekit import AudioProcessor, TranscriptionEngine
  23. import uvicorn
  24. # ── Configuration ─────────────────────────────────────────────────────────────
  25. MQTT_HOST = "localhost"
  26. MQTT_PORT = 1883
  27. MQTT_TOPIC_TEXT = "display/text"
  28. MQTT_TOPIC_CLEAR = "display/clear"
  29. SAMPLE_RATE = 16000
  30. CHANNELS = 1
  31. BLOCKSIZE = 4096 # ~256 ms per chunk at 16 kHz
  32. SENTENCE_TIMEOUT = 4.0 # seconds of silence before forcing a flush
  33. MAX_LINE_CHARS = 80 # characters per line
  34. DISPLAY_LINES = 3
  35. # Set to a device index (integer) to force a specific microphone.
  36. # Leave as None to use the Windows default input device.
  37. AUDIO_DEVICE: int | None = 12
  38. SPEAKERS_FILE = Path(__file__).parent / "speakers.json"
  39. DEFAULT_SPEAKERS: dict[str, dict] = {
  40. "SPEAKER_00": {"name": "A.A.A", "role": "Serving Brother", "location": "Sydney","has_embedding": false,"embedding_updated": null,"colour": "#16a34a","notes": ""},
  41. "SPEAKER_01": {"name": "A.A.A", "role": "Contributor", "location": "London","has_embedding": false,"embedding_updated": null,"colour": "#16a34a","notes": ""},
  42. "SPEAKER_02": {"name": "A.A.A", "role": "Contributor", "location": "Hobart","has_embedding": false,"embedding_updated": null,"colour": "#16a34a","notes": ""},
  43. "SPEAKER_03": {"name": "A.A.A", "role": "Contributor", "location": "Perth","has_embedding": false,"embedding_updated": null,"colour": "#16a34a","notes": ""},
  44. }
  45. # ── Audio injection queue ─────────────────────────────────────────────────────
  46. # stdlib queue.Queue is thread-safe across event loops; asyncio.Queue is not.
  47. # admin.py POSTs test audio chunks to /inject (port 8002) which puts them here.
  48. # _send_audio() drains this queue in preference to the live microphone.
  49. _inject_queue: _stdlib_queue.Queue = _stdlib_queue.Queue(maxsize=240)
  50. # ── Audio injection API ───────────────────────────────────────────────────────
  51. _bridge_app = FastAPI()
  52. @_bridge_app.post("/inject")
  53. async def inject_audio(request: Request):
  54. chunk = await request.body()
  55. if chunk:
  56. try:
  57. _inject_queue.put_nowait(chunk)
  58. except _stdlib_queue.Full:
  59. pass
  60. return {"ok": True}
  61. @_bridge_app.post("/inject/clear")
  62. async def inject_clear():
  63. while True:
  64. try:
  65. _inject_queue.get_nowait()
  66. except _stdlib_queue.Empty:
  67. break
  68. return {"ok": True}
  69. # ── Speaker persistence ───────────────────────────────────────────────────────
  70. def _load_speakers() -> dict:
  71. if SPEAKERS_FILE.exists():
  72. try:
  73. data = json.loads(SPEAKERS_FILE.read_text(encoding="utf-8"))
  74. if isinstance(data, dict):
  75. return data
  76. except (json.JSONDecodeError, OSError):
  77. pass
  78. _write_speakers(DEFAULT_SPEAKERS)
  79. return dict(DEFAULT_SPEAKERS)
  80. def _write_speakers(names: dict) -> None:
  81. try:
  82. SPEAKERS_FILE.write_text(
  83. json.dumps(names, indent=2, ensure_ascii=False),
  84. encoding="utf-8",
  85. )
  86. except OSError as exc:
  87. print(f"[Speakers] Save failed: {exc}")
  88. # ── State ─────────────────────────────────────────────────────────────────────
  89. class BridgeState:
  90. """All mutable state, protected by a single lock."""
  91. def __init__(self):
  92. self._lock = threading.Lock()
  93. self.speaker_names: dict = _load_speakers()
  94. self._seen: set[str] = set(self.speaker_names)
  95. self._current_speaker: str | None = None
  96. self._speaker_changed = False
  97. self._text_buffer = ""
  98. self._display: list[str] = [""] * DISPLAY_LINES
  99. self._last_final_time = time.monotonic()
  100. def set_speaker_name(self, speaker_id: str, name: str) -> None:
  101. with self._lock:
  102. entry = self.speaker_names.get(speaker_id, {})
  103. if isinstance(entry, dict):
  104. self.speaker_names[speaker_id] = {**entry, "name": name.strip()}
  105. else:
  106. self.speaker_names[speaker_id] = {"name": name.strip()}
  107. self._seen.add(speaker_id)
  108. _write_speakers(self.speaker_names)
  109. def delete_speaker(self, speaker_id: str) -> None:
  110. with self._lock:
  111. self.speaker_names.pop(speaker_id, None)
  112. self._seen.discard(speaker_id)
  113. _write_speakers(self.speaker_names)
  114. def seen_speakers_snapshot(self) -> set[str]:
  115. with self._lock:
  116. return set(self._seen)
  117. def _resolve(self, speaker_id: str | None) -> str | None:
  118. if not speaker_id:
  119. return None
  120. entry = self.speaker_names.get(speaker_id)
  121. if entry is None:
  122. return speaker_id
  123. if isinstance(entry, dict):
  124. return entry.get("name") or speaker_id
  125. return str(entry)
  126. def push_final(self, text: str, speaker_id: str | None, mqtt_client: mqtt.Client) -> None:
  127. with self._lock:
  128. if speaker_id:
  129. self._seen.add(speaker_id)
  130. resolved = self._resolve(speaker_id)
  131. if resolved != self._current_speaker:
  132. if self._text_buffer:
  133. self._flush(mqtt_client)
  134. self._current_speaker = resolved
  135. self._speaker_changed = True
  136. sep = " " if self._text_buffer else ""
  137. self._text_buffer += sep + text.strip()
  138. self._last_final_time = time.monotonic()
  139. if _is_sentence_end(text):
  140. self._flush(mqtt_client)
  141. def maybe_timeout_flush(self, mqtt_client: mqtt.Client) -> None:
  142. with self._lock:
  143. if self._text_buffer and (time.monotonic() - self._last_final_time) > SENTENCE_TIMEOUT:
  144. self._flush(mqtt_client)
  145. def _flush(self, mqtt_client: mqtt.Client) -> None:
  146. text = self._text_buffer.strip()
  147. self._text_buffer = ""
  148. if not text:
  149. return
  150. new_lines: list[str] = []
  151. if self._speaker_changed and self._current_speaker:
  152. new_lines.append(f"[{self._current_speaker.upper()}]")
  153. self._speaker_changed = False
  154. new_lines.extend(textwrap.wrap(text, MAX_LINE_CHARS) or [""])
  155. for line in new_lines:
  156. self._display.append(line)
  157. self._display = self._display[-DISPLAY_LINES:]
  158. while len(self._display) < DISPLAY_LINES:
  159. self._display.insert(0, "")
  160. payload = json.dumps({"lines": list(self._display)})
  161. mqtt_client.publish(MQTT_TOPIC_TEXT, payload)
  162. print(f"[Display] {self._display}")
  163. def clear(self, mqtt_client: mqtt.Client) -> None:
  164. with self._lock:
  165. self._display = [""] * DISPLAY_LINES
  166. self._text_buffer = ""
  167. self._current_speaker = None
  168. self._speaker_changed = False
  169. mqtt_client.publish(MQTT_TOPIC_CLEAR, "")
  170. print("[Display] Cleared")
  171. # ── Helpers ───────────────────────────────────────────────────────────────────
  172. def _is_sentence_end(text: str) -> bool:
  173. return bool(re.search(r'[.!?…]\s*$', text.strip()))
  174. # ── MQTT ──────────────────────────────────────────────────────────────────────
  175. def build_mqtt_client() -> mqtt.Client:
  176. client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
  177. def on_connect(client, userdata, flags, rc, props):
  178. print("[MQTT] Connected" if rc == 0 else f"[MQTT] Failed: {rc}")
  179. def on_disconnect(client, userdata, flags, rc, props):
  180. print(f"[MQTT] Disconnected ({rc}), will reconnect...")
  181. client.on_connect = on_connect
  182. client.on_disconnect = on_disconnect
  183. client.reconnect_delay_set(min_delay=1, max_delay=30)
  184. client.connect_async(MQTT_HOST, MQTT_PORT)
  185. client.loop_start()
  186. return client
  187. # ── Audio pipeline ────────────────────────────────────────────────────────────
  188. def _choose_audio_device() -> int | None:
  189. try:
  190. devices = sd.query_devices()
  191. default_in = sd.default.device[0]
  192. except Exception as exc:
  193. print(f"[Audio] Cannot query devices: {exc}")
  194. return None
  195. print("[Audio] Available input devices:")
  196. input_devices: list[tuple[int, str]] = []
  197. for i, dev in enumerate(devices):
  198. if dev["max_input_channels"] > 0:
  199. marker = " ← default" if i == default_in else ""
  200. print(f" [{i}] {dev['name']}{marker}")
  201. input_devices.append((i, dev["name"]))
  202. if not input_devices:
  203. print("[Audio] ERROR: No input devices found.")
  204. return None
  205. if AUDIO_DEVICE is not None:
  206. print(f"[Audio] Using configured device [{AUDIO_DEVICE}]")
  207. return AUDIO_DEVICE
  208. if default_in >= 0:
  209. print(f"[Audio] Using default input device [{default_in}]")
  210. return default_in
  211. idx, name = input_devices[0]
  212. print(f"[Audio] No system default — using [{idx}] {name}")
  213. return idx
  214. async def audio_processor_loop(state: BridgeState, mqtt_client: mqtt.Client, engine: TranscriptionEngine) -> None:
  215. audio_queue: asyncio.Queue[bytes] = asyncio.Queue(maxsize=120)
  216. loop = asyncio.get_running_loop()
  217. def audio_callback(indata: np.ndarray, frames: int, time_info, status) -> None:
  218. if status:
  219. print(f"[Audio] {status}")
  220. chunk = indata.tobytes()
  221. loop.call_soon_threadsafe(
  222. lambda: audio_queue.put_nowait(chunk) if not audio_queue.full() else None
  223. )
  224. device = _choose_audio_device()
  225. if device is None:
  226. print("[Audio] No input device — cannot start.")
  227. return
  228. audio_processor = AudioProcessor(transcription_engine=engine)
  229. results_generator = await audio_processor.create_tasks()
  230. async def _receive_results():
  231. # FrontData.lines is validated_segments + a growing current-segment snapshot.
  232. # The last element's text GROWS silently between calls, so index-counting
  233. # misses incremental content. Instead, track the full concatenated
  234. # transcript and push only the delta each time it grows.
  235. prev_full_text = ""
  236. async for response in results_generator:
  237. lines = response.lines or []
  238. current_full_text = " ".join(
  239. (seg.text or "").strip()
  240. for seg in lines
  241. if not seg.is_silence() and (seg.text or "").strip()
  242. )
  243. if current_full_text == prev_full_text:
  244. continue
  245. if prev_full_text and current_full_text.startswith(prev_full_text):
  246. new_text = current_full_text[len(prev_full_text):].strip()
  247. # Drop leading punctuation that belongs to the previous sentence
  248. while new_text and new_text[0] in ".,;:!?":
  249. new_text = new_text[1:].strip()
  250. else:
  251. # First segment or context reset after a long silence
  252. new_text = current_full_text
  253. prev_full_text = current_full_text
  254. if not new_text or len(new_text) < 2:
  255. continue
  256. last_seg = next(
  257. (s for s in reversed(lines) if not s.is_silence() and (s.text or "").strip()),
  258. None,
  259. )
  260. spk = getattr(last_seg, "speaker", None) if last_seg else None
  261. speaker_id = f"SPEAKER_{spk:02d}" if isinstance(spk, int) and spk >= 0 else None
  262. print(f"[Whisper] ({speaker_id or '?'}) {new_text}")
  263. state.push_final(new_text, speaker_id, mqtt_client)
  264. async def _send_audio():
  265. with sd.InputStream(
  266. device=device, samplerate=SAMPLE_RATE, channels=CHANNELS,
  267. dtype="int16", blocksize=BLOCKSIZE, callback=audio_callback,
  268. ):
  269. while True:
  270. # Injected test audio takes priority over live microphone
  271. try:
  272. chunk = _inject_queue.get_nowait()
  273. except _stdlib_queue.Empty:
  274. chunk = await audio_queue.get()
  275. await audio_processor.process_audio(chunk)
  276. flusher = asyncio.create_task(_flusher(state, mqtt_client))
  277. reloader = asyncio.create_task(_speaker_reloader(state))
  278. try:
  279. await asyncio.gather(_send_audio(), _receive_results())
  280. finally:
  281. flusher.cancel()
  282. reloader.cancel()
  283. async def _flusher(state: BridgeState, mqtt_client: mqtt.Client) -> None:
  284. while True:
  285. await asyncio.sleep(1.0)
  286. state.maybe_timeout_flush(mqtt_client)
  287. async def _speaker_reloader(state: BridgeState) -> None:
  288. last_mtime = 0.0
  289. while True:
  290. await asyncio.sleep(5.0)
  291. try:
  292. mtime = SPEAKERS_FILE.stat().st_mtime
  293. if mtime != last_mtime:
  294. fresh = _load_speakers()
  295. with state._lock:
  296. state.speaker_names = fresh
  297. last_mtime = mtime
  298. print("[Bridge] Speaker names reloaded from disk")
  299. except OSError:
  300. pass
  301. # ── Entry point ───────────────────────────────────────────────────────────────
  302. def main() -> None:
  303. state = BridgeState()
  304. mqtt_client = build_mqtt_client()
  305. engine = TranscriptionEngine(
  306. model_size="large-v3",
  307. lan="en",
  308. diarization=False,
  309. pcm_input=True,
  310. backend_policy="localagreement",
  311. confidence_validation=True,
  312. min_chunk_size=3,
  313. vac=False,
  314. )
  315. # Inject API must start before the audio loop so test playback works immediately
  316. def _run_inject_api():
  317. uvicorn.run(_bridge_app, host="127.0.0.1", port=8002, log_level="warning")
  318. inject_thread = threading.Thread(target=_run_inject_api, daemon=True)
  319. inject_thread.start()
  320. print("[Bridge] Test audio inject API at http://127.0.0.1:8002")
  321. def _run():
  322. asyncio.run(audio_processor_loop(state, mqtt_client, engine))
  323. ws_thread = threading.Thread(target=_run, daemon=True)
  324. ws_thread.start()
  325. print(f"[Bridge] Speaker names loaded from {SPEAKERS_FILE}")
  326. print("[Bridge] Audio pipeline running — speaker admin at http://localhost:8001")
  327. print("[Bridge] Close this window to quit")
  328. try:
  329. ws_thread.join()
  330. except KeyboardInterrupt:
  331. pass
  332. if __name__ == "__main__":
  333. main()