Spaces:
Sleeping
Sleeping
Download app/monitor.py from userIdc2024/call-bot: direct link, hf CLI and curl.
- Browser
- Download file 1.54 kB
-
https://huggingface.co/spaces/userIdc2024/call-bot/resolve/main/app/monitor.py
- Command line
-
hf download hf://spaces/userIdc2024/call-bot/app/monitor.py
-
curl -L -o monitor.py https://huggingface.co/spaces/userIdc2024/call-bot/resolve/main/app/monitor.py
1.54 kB
| """Fan-out of live events and audio to dashboard listeners.""" | |
| from __future__ import annotations | |
| import asyncio | |
| import json | |
| from collections import defaultdict | |
| CALLER, BOT = 0, 1 | |
| class Hub: | |
| def __init__(self): | |
| self._call_subs: dict[str, set[asyncio.Queue]] = defaultdict(set) | |
| self._global_subs: set[asyncio.Queue] = set() | |
| self.live_sessions: dict = {} # call_id -> CallSession | |
| # ---- subscriptions ---- | |
| def subscribe(self, call_id: str | None) -> asyncio.Queue: | |
| q: asyncio.Queue = asyncio.Queue(maxsize=400) | |
| (self._call_subs[call_id] if call_id else self._global_subs).add(q) | |
| return q | |
| def unsubscribe(self, call_id: str | None, q: asyncio.Queue): | |
| (self._call_subs.get(call_id, set()) if call_id else self._global_subs).discard(q) | |
| def _put(q: asyncio.Queue, item): | |
| try: | |
| q.put_nowait(item) | |
| except asyncio.QueueFull: | |
| pass # slow listener: drop rather than slow down the call | |
| # ---- publishing ---- | |
| def event(self, call_id: str, ev: dict): | |
| msg = json.dumps(ev) | |
| for q in list(self._call_subs.get(call_id, ())): | |
| self._put(q, msg) | |
| for q in list(self._global_subs): | |
| self._put(q, msg) | |
| def audio(self, call_id: str, who: int, pcm: bytes): | |
| subs = self._call_subs.get(call_id) | |
| if not subs: | |
| return | |
| frame = bytes([who]) + pcm | |
| for q in list(subs): | |
| self._put(q, frame) | |
| hub = Hub() | |