|
| 1 | +import asyncio |
| 2 | + |
| 3 | +from fishjam.agent import Agent, AgentResponseTrackData |
| 4 | +from transcription.worker import BackgroundWorker |
| 5 | + |
| 6 | +from .transcription import TranscriptionSession |
| 7 | + |
| 8 | + |
| 9 | +class TranscriptionAgent: |
| 10 | + def __init__(self, room_id: str, agent: Agent, worker: BackgroundWorker): |
| 11 | + self._room_id = room_id |
| 12 | + self._agent = agent |
| 13 | + self._sessions: dict[str, TranscriptionSession] = {} |
| 14 | + self._disconnect = asyncio.Event() |
| 15 | + self._worker = worker |
| 16 | + |
| 17 | + @agent.on_track_data |
| 18 | + def _(track_data: AgentResponseTrackData): |
| 19 | + if track_data.peer_id not in self._sessions: |
| 20 | + return |
| 21 | + self._sessions[track_data.peer_id].transcribe(track_data.data) |
| 22 | + |
| 23 | + async def _start(self): |
| 24 | + async with self._agent: |
| 25 | + print(f"Agent connected to room {self._room_id}") |
| 26 | + await self._disconnect.wait() |
| 27 | + self._disconnect.clear() |
| 28 | + print(f"Agent disconnected from room {self._room_id}") |
| 29 | + |
| 30 | + def _stop(self): |
| 31 | + self._disconnect.set() |
| 32 | + |
| 33 | + def _handle_transcription(self, peer_id: str, text: str): |
| 34 | + print(f"Peer {peer_id} in room {self._room_id} said: {text}") |
| 35 | + |
| 36 | + def on_peer_enter(self, peer_id: str): |
| 37 | + if peer_id in self._sessions: |
| 38 | + return |
| 39 | + |
| 40 | + if len(self._sessions) == 0: |
| 41 | + self._worker.run_in_background(self._start()) |
| 42 | + |
| 43 | + session = TranscriptionSession(lambda t: self._handle_transcription(peer_id, t)) |
| 44 | + self._sessions[peer_id] = session |
| 45 | + self._worker.run_in_background(session.start(peer_id)) |
| 46 | + |
| 47 | + def on_peer_leave(self, peer_id: str): |
| 48 | + if peer_id not in self._sessions: |
| 49 | + return |
| 50 | + |
| 51 | + self._sessions[peer_id].end() |
| 52 | + self._sessions.pop(peer_id) |
| 53 | + |
| 54 | + if len(self._sessions) == 0: |
| 55 | + self._stop() |
0 commit comments