dv-pipecat-ai 0.0.82.dev815__py3-none-any.whl → 0.0.82.dev857__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dv-pipecat-ai might be problematic. Click here for more details.

Files changed (106) hide show
  1. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/METADATA +8 -3
  2. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/RECORD +106 -79
  3. pipecat/adapters/base_llm_adapter.py +44 -6
  4. pipecat/adapters/services/anthropic_adapter.py +302 -2
  5. pipecat/adapters/services/aws_nova_sonic_adapter.py +40 -2
  6. pipecat/adapters/services/bedrock_adapter.py +40 -2
  7. pipecat/adapters/services/gemini_adapter.py +276 -6
  8. pipecat/adapters/services/open_ai_adapter.py +88 -7
  9. pipecat/adapters/services/open_ai_realtime_adapter.py +39 -1
  10. pipecat/audio/dtmf/__init__.py +0 -0
  11. pipecat/audio/dtmf/types.py +47 -0
  12. pipecat/audio/dtmf/utils.py +70 -0
  13. pipecat/audio/filters/aic_filter.py +199 -0
  14. pipecat/audio/utils.py +9 -7
  15. pipecat/extensions/ivr/__init__.py +0 -0
  16. pipecat/extensions/ivr/ivr_navigator.py +452 -0
  17. pipecat/frames/frames.py +156 -43
  18. pipecat/pipeline/llm_switcher.py +76 -0
  19. pipecat/pipeline/parallel_pipeline.py +3 -3
  20. pipecat/pipeline/service_switcher.py +144 -0
  21. pipecat/pipeline/task.py +68 -28
  22. pipecat/pipeline/task_observer.py +10 -0
  23. pipecat/processors/aggregators/dtmf_aggregator.py +2 -2
  24. pipecat/processors/aggregators/llm_context.py +277 -0
  25. pipecat/processors/aggregators/llm_response.py +48 -15
  26. pipecat/processors/aggregators/llm_response_universal.py +840 -0
  27. pipecat/processors/aggregators/openai_llm_context.py +3 -3
  28. pipecat/processors/dtmf_aggregator.py +0 -2
  29. pipecat/processors/filters/stt_mute_filter.py +0 -2
  30. pipecat/processors/frame_processor.py +18 -11
  31. pipecat/processors/frameworks/rtvi.py +17 -10
  32. pipecat/processors/metrics/sentry.py +2 -0
  33. pipecat/runner/daily.py +137 -36
  34. pipecat/runner/run.py +1 -1
  35. pipecat/runner/utils.py +7 -7
  36. pipecat/serializers/asterisk.py +20 -4
  37. pipecat/serializers/exotel.py +1 -1
  38. pipecat/serializers/plivo.py +1 -1
  39. pipecat/serializers/telnyx.py +1 -1
  40. pipecat/serializers/twilio.py +1 -1
  41. pipecat/services/__init__.py +2 -2
  42. pipecat/services/anthropic/llm.py +113 -28
  43. pipecat/services/asyncai/tts.py +4 -0
  44. pipecat/services/aws/llm.py +82 -8
  45. pipecat/services/aws/tts.py +0 -10
  46. pipecat/services/aws_nova_sonic/aws.py +5 -0
  47. pipecat/services/cartesia/tts.py +28 -16
  48. pipecat/services/cerebras/llm.py +15 -10
  49. pipecat/services/deepgram/stt.py +8 -0
  50. pipecat/services/deepseek/llm.py +13 -8
  51. pipecat/services/fireworks/llm.py +13 -8
  52. pipecat/services/fish/tts.py +8 -6
  53. pipecat/services/gemini_multimodal_live/gemini.py +5 -0
  54. pipecat/services/gladia/config.py +7 -1
  55. pipecat/services/gladia/stt.py +23 -15
  56. pipecat/services/google/llm.py +159 -59
  57. pipecat/services/google/llm_openai.py +18 -3
  58. pipecat/services/grok/llm.py +2 -1
  59. pipecat/services/llm_service.py +38 -3
  60. pipecat/services/mem0/memory.py +2 -1
  61. pipecat/services/mistral/llm.py +5 -6
  62. pipecat/services/nim/llm.py +2 -1
  63. pipecat/services/openai/base_llm.py +88 -26
  64. pipecat/services/openai/image.py +6 -1
  65. pipecat/services/openai_realtime_beta/openai.py +5 -2
  66. pipecat/services/openpipe/llm.py +6 -8
  67. pipecat/services/perplexity/llm.py +13 -8
  68. pipecat/services/playht/tts.py +9 -6
  69. pipecat/services/rime/tts.py +1 -1
  70. pipecat/services/sambanova/llm.py +18 -13
  71. pipecat/services/sarvam/tts.py +415 -10
  72. pipecat/services/speechmatics/stt.py +2 -2
  73. pipecat/services/tavus/video.py +1 -1
  74. pipecat/services/tts_service.py +15 -5
  75. pipecat/services/vistaar/llm.py +2 -5
  76. pipecat/transports/base_input.py +32 -19
  77. pipecat/transports/base_output.py +39 -5
  78. pipecat/transports/daily/__init__.py +0 -0
  79. pipecat/transports/daily/transport.py +2371 -0
  80. pipecat/transports/daily/utils.py +410 -0
  81. pipecat/transports/livekit/__init__.py +0 -0
  82. pipecat/transports/livekit/transport.py +1042 -0
  83. pipecat/transports/network/fastapi_websocket.py +12 -546
  84. pipecat/transports/network/small_webrtc.py +12 -922
  85. pipecat/transports/network/webrtc_connection.py +9 -595
  86. pipecat/transports/network/websocket_client.py +12 -481
  87. pipecat/transports/network/websocket_server.py +12 -487
  88. pipecat/transports/services/daily.py +9 -2334
  89. pipecat/transports/services/helpers/daily_rest.py +12 -396
  90. pipecat/transports/services/livekit.py +12 -975
  91. pipecat/transports/services/tavus.py +12 -757
  92. pipecat/transports/smallwebrtc/__init__.py +0 -0
  93. pipecat/transports/smallwebrtc/connection.py +612 -0
  94. pipecat/transports/smallwebrtc/transport.py +936 -0
  95. pipecat/transports/tavus/__init__.py +0 -0
  96. pipecat/transports/tavus/transport.py +770 -0
  97. pipecat/transports/websocket/__init__.py +0 -0
  98. pipecat/transports/websocket/client.py +494 -0
  99. pipecat/transports/websocket/fastapi.py +559 -0
  100. pipecat/transports/websocket/server.py +500 -0
  101. pipecat/transports/whatsapp/__init__.py +0 -0
  102. pipecat/transports/whatsapp/api.py +345 -0
  103. pipecat/transports/whatsapp/client.py +364 -0
  104. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/WHEEL +0 -0
  105. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/licenses/LICENSE +0 -0
  106. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/top_level.txt +0 -0
@@ -11,2340 +11,15 @@ audio/video streaming, transcription, recording, dial-in/out functionality, and
11
11
  real-time communication features.
12
12
  """
13
13
 
14
- import asyncio
15
- import time
16
- from concurrent.futures import CancelledError as FuturesCancelledError
17
- from concurrent.futures import ThreadPoolExecutor
18
- from dataclasses import dataclass
19
- from typing import Any, Awaitable, Callable, Dict, Mapping, Optional
14
+ import warnings
20
15
 
21
- import aiohttp
22
- from loguru import logger
23
- from pydantic import BaseModel
16
+ from pipecat.transports.daily.transport import *
24
17
 
25
- from pipecat.audio.vad.vad_analyzer import VADAnalyzer, VADParams
26
- from pipecat.frames.frames import (
27
- CancelFrame,
28
- EndFrame,
29
- ErrorFrame,
30
- Frame,
31
- InputAudioRawFrame,
32
- InterimTranscriptionFrame,
33
- OutputAudioRawFrame,
34
- OutputDTMFFrame,
35
- OutputDTMFUrgentFrame,
36
- OutputImageRawFrame,
37
- SpriteFrame,
38
- StartFrame,
39
- TranscriptionFrame,
40
- TransportMessageFrame,
41
- TransportMessageUrgentFrame,
42
- UserAudioRawFrame,
43
- UserImageRawFrame,
44
- UserImageRequestFrame,
45
- )
46
- from pipecat.processors.frame_processor import FrameDirection, FrameProcessorSetup
47
- from pipecat.transcriptions.language import Language
48
- from pipecat.transports.base_input import BaseInputTransport
49
- from pipecat.transports.base_output import BaseOutputTransport
50
- from pipecat.transports.base_transport import BaseTransport, TransportParams
51
- from pipecat.utils.asyncio.task_manager import BaseTaskManager
52
-
53
- try:
54
- from daily import (
55
- AudioData,
56
- CallClient,
57
- CustomAudioSource,
58
- CustomAudioTrack,
59
- Daily,
60
- EventHandler,
61
- VideoFrame,
62
- VirtualCameraDevice,
63
- VirtualSpeakerDevice,
64
- )
65
- from daily import (
66
- LogLevel as DailyLogLevel,
18
+ with warnings.catch_warnings():
19
+ warnings.simplefilter("always")
20
+ warnings.warn(
21
+ "Module `pipecat.transports.services.daily` is deprecated, "
22
+ "use `pipecat.transports.daily.transport` instead.",
23
+ DeprecationWarning,
24
+ stacklevel=2,
67
25
  )
68
- except ModuleNotFoundError as e:
69
- logger.error(f"Exception: {e}")
70
- logger.error(
71
- "In order to use the Daily transport, you need to `pip install pipecat-ai[daily]`."
72
- )
73
- raise Exception(f"Missing module: {e}")
74
-
75
- VAD_RESET_PERIOD_MS = 2000
76
-
77
-
78
- @dataclass
79
- class DailyTransportMessageFrame(TransportMessageFrame):
80
- """Frame for transport messages in Daily calls.
81
-
82
- Parameters:
83
- participant_id: Optional ID of the participant this message is for/from.
84
- """
85
-
86
- participant_id: Optional[str] = None
87
-
88
-
89
- @dataclass
90
- class DailyTransportMessageUrgentFrame(TransportMessageUrgentFrame):
91
- """Frame for urgent transport messages in Daily calls.
92
-
93
- Parameters:
94
- participant_id: Optional ID of the participant this message is for/from.
95
- """
96
-
97
- participant_id: Optional[str] = None
98
-
99
-
100
- class WebRTCVADAnalyzer(VADAnalyzer):
101
- """Voice Activity Detection analyzer using WebRTC.
102
-
103
- Implements voice activity detection using Daily's native WebRTC VAD.
104
- """
105
-
106
- def __init__(self, *, sample_rate: Optional[int] = None, params: Optional[VADParams] = None):
107
- """Initialize the WebRTC VAD analyzer.
108
-
109
- Args:
110
- sample_rate: Audio sample rate in Hz.
111
- params: VAD configuration parameters.
112
- """
113
- super().__init__(sample_rate=sample_rate, params=params)
114
-
115
- self._webrtc_vad = Daily.create_native_vad(
116
- reset_period_ms=VAD_RESET_PERIOD_MS, sample_rate=self.sample_rate, channels=1
117
- )
118
- logger.debug("Loaded native WebRTC VAD")
119
-
120
- def num_frames_required(self) -> int:
121
- """Get the number of audio frames required for VAD analysis.
122
-
123
- Returns:
124
- The number of frames needed (equivalent to 10ms of audio).
125
- """
126
- return int(self.sample_rate / 100.0)
127
-
128
- def voice_confidence(self, buffer) -> float:
129
- """Analyze audio buffer and return voice confidence score.
130
-
131
- Args:
132
- buffer: Audio buffer to analyze.
133
-
134
- Returns:
135
- Voice confidence score between 0.0 and 1.0.
136
- """
137
- confidence = 0
138
- if len(buffer) > 0:
139
- confidence = self._webrtc_vad.analyze_frames(buffer)
140
- return confidence
141
-
142
-
143
- class DailyDialinSettings(BaseModel):
144
- """Settings for Daily's dial-in functionality.
145
-
146
- Parameters:
147
- call_id: CallId is represented by UUID and represents the sessionId in the SIP Network.
148
- call_domain: Call Domain is represented by UUID and represents your Daily Domain on the SIP Network.
149
- """
150
-
151
- call_id: str = ""
152
- call_domain: str = ""
153
-
154
-
155
- class DailyTranscriptionSettings(BaseModel):
156
- """Configuration settings for Daily's transcription service.
157
-
158
- Parameters:
159
- language: ISO language code for transcription (e.g. "en").
160
- model: Transcription model to use (e.g. "nova-2-general").
161
- profanity_filter: Whether to filter profanity from transcripts.
162
- redact: Whether to redact sensitive information.
163
- endpointing: Whether to use endpointing to determine speech segments.
164
- punctuate: Whether to add punctuation to transcripts.
165
- includeRawResponse: Whether to include raw response data.
166
- extra: Additional parameters passed to the Deepgram transcription service.
167
- """
168
-
169
- language: str = "en"
170
- model: str = "nova-2-general"
171
- profanity_filter: bool = True
172
- redact: bool = False
173
- endpointing: bool = True
174
- punctuate: bool = True
175
- includeRawResponse: bool = True
176
- extra: Mapping[str, Any] = {"interim_results": True}
177
-
178
-
179
- class DailyParams(TransportParams):
180
- """Configuration parameters for Daily transport.
181
-
182
- Parameters:
183
- api_url: Daily API base URL.
184
- api_key: Daily API authentication key.
185
- audio_in_user_tracks: Receive users' audio in separate tracks
186
- dialin_settings: Optional settings for dial-in functionality.
187
- camera_out_enabled: Whether to enable the main camera output track.
188
- microphone_out_enabled: Whether to enable the main microphone track.
189
- transcription_enabled: Whether to enable speech transcription.
190
- transcription_settings: Configuration for transcription service.
191
- """
192
-
193
- api_url: str = "https://api.daily.co/v1"
194
- api_key: str = ""
195
- audio_in_user_tracks: bool = True
196
- dialin_settings: Optional[DailyDialinSettings] = None
197
- camera_out_enabled: bool = True
198
- microphone_out_enabled: bool = True
199
- transcription_enabled: bool = False
200
- transcription_settings: DailyTranscriptionSettings = DailyTranscriptionSettings()
201
-
202
-
203
- class DailyCallbacks(BaseModel):
204
- """Callback handlers for Daily events.
205
-
206
- Parameters:
207
- on_active_speaker_changed: Called when the active speaker of the call has changed.
208
- on_joined: Called when bot successfully joined a room.
209
- on_left: Called when bot left a room.
210
- on_error: Called when an error occurs.
211
- on_app_message: Called when receiving an app message.
212
- on_call_state_updated: Called when call state changes.
213
- on_client_connected: Called when a client (participant) connects.
214
- on_client_disconnected: Called when a client (participant) disconnects.
215
- on_dialin_connected: Called when dial-in is connected.
216
- on_dialin_ready: Called when dial-in is ready.
217
- on_dialin_stopped: Called when dial-in is stopped.
218
- on_dialin_error: Called when dial-in encounters an error.
219
- on_dialin_warning: Called when dial-in has a warning.
220
- on_dialout_answered: Called when dial-out is answered.
221
- on_dialout_connected: Called when dial-out is connected.
222
- on_dialout_stopped: Called when dial-out is stopped.
223
- on_dialout_error: Called when dial-out encounters an error.
224
- on_dialout_warning: Called when dial-out has a warning.
225
- on_participant_joined: Called when a participant joins.
226
- on_participant_left: Called when a participant leaves.
227
- on_participant_updated: Called when participant info is updated.
228
- on_transcription_message: Called when receiving transcription.
229
- on_transcription_stopped: Called when transcription is stopped.
230
- on_transcription_error: Called when transcription encounters an error.
231
- on_recording_started: Called when recording starts.
232
- on_recording_stopped: Called when recording stops.
233
- on_recording_error: Called when recording encounters an error.
234
- """
235
-
236
- on_active_speaker_changed: Callable[[Mapping[str, Any]], Awaitable[None]]
237
- on_joined: Callable[[Mapping[str, Any]], Awaitable[None]]
238
- on_left: Callable[[], Awaitable[None]]
239
- on_error: Callable[[str], Awaitable[None]]
240
- on_app_message: Callable[[Any, str], Awaitable[None]]
241
- on_call_state_updated: Callable[[str], Awaitable[None]]
242
- on_client_connected: Callable[[Mapping[str, Any]], Awaitable[None]]
243
- on_client_disconnected: Callable[[Mapping[str, Any]], Awaitable[None]]
244
- on_dialin_connected: Callable[[Any], Awaitable[None]]
245
- on_dialin_ready: Callable[[str], Awaitable[None]]
246
- on_dialin_stopped: Callable[[Any], Awaitable[None]]
247
- on_dialin_error: Callable[[Any], Awaitable[None]]
248
- on_dialin_warning: Callable[[Any], Awaitable[None]]
249
- on_dialout_answered: Callable[[Any], Awaitable[None]]
250
- on_dialout_connected: Callable[[Any], Awaitable[None]]
251
- on_dialout_stopped: Callable[[Any], Awaitable[None]]
252
- on_dialout_error: Callable[[Any], Awaitable[None]]
253
- on_dialout_warning: Callable[[Any], Awaitable[None]]
254
- on_participant_joined: Callable[[Mapping[str, Any]], Awaitable[None]]
255
- on_participant_left: Callable[[Mapping[str, Any], str], Awaitable[None]]
256
- on_participant_updated: Callable[[Mapping[str, Any]], Awaitable[None]]
257
- on_transcription_message: Callable[[Mapping[str, Any]], Awaitable[None]]
258
- on_transcription_stopped: Callable[[str, bool], Awaitable[None]]
259
- on_transcription_error: Callable[[str], Awaitable[None]]
260
- on_recording_started: Callable[[Mapping[str, Any]], Awaitable[None]]
261
- on_recording_stopped: Callable[[str], Awaitable[None]]
262
- on_recording_error: Callable[[str, str], Awaitable[None]]
263
-
264
-
265
- def completion_callback(future):
266
- """Create a completion callback for Daily API calls.
267
-
268
- Args:
269
- future: The asyncio Future to set the result on.
270
-
271
- Returns:
272
- A callback function that sets the future result.
273
- """
274
-
275
- def _callback(*args):
276
- def set_result(future, *args):
277
- try:
278
- if len(args) > 1:
279
- future.set_result(args)
280
- else:
281
- future.set_result(*args)
282
- except asyncio.InvalidStateError:
283
- pass
284
-
285
- future.get_loop().call_soon_threadsafe(set_result, future, *args)
286
-
287
- return _callback
288
-
289
-
290
- @dataclass
291
- class DailyAudioTrack:
292
- """Container for Daily audio track components.
293
-
294
- Parameters:
295
- source: The custom audio source for the track.
296
- track: The custom audio track instance.
297
- """
298
-
299
- source: CustomAudioSource
300
- track: CustomAudioTrack
301
-
302
-
303
- class DailyTransportClient(EventHandler):
304
- """Core client for interacting with Daily's API.
305
-
306
- Manages the connection to Daily rooms and handles all low-level API interactions
307
- including room management, media streaming, transcription, and event handling.
308
- """
309
-
310
- _daily_initialized: bool = False
311
-
312
- def __new__(cls, *args, **kwargs):
313
- """Override EventHandler's __new__ method to ensure Daily is initialized only once."""
314
- return super().__new__(cls)
315
-
316
- def __init__(
317
- self,
318
- room_url: str,
319
- token: Optional[str],
320
- bot_name: str,
321
- params: DailyParams,
322
- callbacks: DailyCallbacks,
323
- transport_name: str,
324
- ):
325
- """Initialize the Daily transport client.
326
-
327
- Args:
328
- room_url: URL of the Daily room to connect to.
329
- token: Optional authentication token for the room.
330
- bot_name: Display name for the bot in the call.
331
- params: Configuration parameters for the transport.
332
- callbacks: Event callback handlers.
333
- transport_name: Name identifier for the transport.
334
- """
335
- super().__init__()
336
-
337
- if not DailyTransportClient._daily_initialized:
338
- DailyTransportClient._daily_initialized = True
339
- Daily.init()
340
-
341
- self._room_url: str = room_url
342
- self._token: Optional[str] = token
343
- self._bot_name: str = bot_name
344
- self._params: DailyParams = params
345
- self._callbacks = callbacks
346
- self._transport_name = transport_name
347
-
348
- self._participant_id: str = ""
349
- self._audio_renderers = {}
350
- self._video_renderers = {}
351
- self._transcription_ids = []
352
- self._transcription_status = None
353
-
354
- self._joining = False
355
- self._joined = False
356
- self._joined_event = asyncio.Event()
357
- self._leave_counter = 0
358
-
359
- self._task_manager: Optional[BaseTaskManager] = None
360
-
361
- # We use the executor to cleanup the client. We just do it from one
362
- # place, so only one thread is really needed.
363
- self._executor = ThreadPoolExecutor(max_workers=1)
364
-
365
- self._client: CallClient = CallClient(event_handler=self)
366
-
367
- # We use separate tasks to execute callbacks (events, audio or
368
- # video). In the case of events, if we call a `CallClient` function
369
- # inside the callback and wait for its completion this will result in a
370
- # deadlock (because we haven't exited the event callback). The deadlocks
371
- # occur because `daily-python` is holding the GIL when calling the
372
- # callbacks. So, if our callback handler makes a `CallClient` call and
373
- # waits for it to finish using completions (and a future) we will
374
- # deadlock because completions use event handlers (which are holding the
375
- # GIL).
376
- self._event_task = None
377
- self._audio_task = None
378
- self._video_task = None
379
-
380
- # Input and ouput sample rates. They will be initialize on setup().
381
- self._in_sample_rate = 0
382
- self._out_sample_rate = 0
383
-
384
- self._camera: Optional[VirtualCameraDevice] = None
385
- self._speaker: Optional[VirtualSpeakerDevice] = None
386
- self._microphone_track: Optional[DailyAudioTrack] = None
387
- self._custom_audio_tracks: Dict[str, DailyAudioTrack] = {}
388
-
389
- def _camera_name(self):
390
- """Generate a unique virtual camera name for this client instance."""
391
- return f"camera-{self}"
392
-
393
- def _speaker_name(self):
394
- """Generate a unique virtual speaker name for this client instance."""
395
- return f"speaker-{self}"
396
-
397
- @property
398
- def room_url(self) -> str:
399
- """Get the Daily room URL.
400
-
401
- Returns:
402
- The room URL this client is connected to.
403
- """
404
- return self._room_url
405
-
406
- @property
407
- def participant_id(self) -> str:
408
- """Get the participant ID for this client.
409
-
410
- Returns:
411
- The participant ID assigned by Daily.
412
- """
413
- return self._participant_id
414
-
415
- @property
416
- def in_sample_rate(self) -> int:
417
- """Get the input audio sample rate.
418
-
419
- Returns:
420
- The input sample rate in Hz.
421
- """
422
- return self._in_sample_rate
423
-
424
- @property
425
- def out_sample_rate(self) -> int:
426
- """Get the output audio sample rate.
427
-
428
- Returns:
429
- The output sample rate in Hz.
430
- """
431
- return self._out_sample_rate
432
-
433
- async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
434
- """Send an application message to participants.
435
-
436
- Args:
437
- frame: The message frame to send.
438
- """
439
- if not self._joined:
440
- return
441
-
442
- participant_id = None
443
- if isinstance(frame, (DailyTransportMessageFrame, DailyTransportMessageUrgentFrame)):
444
- participant_id = frame.participant_id
445
-
446
- future = self._get_event_loop().create_future()
447
- self._client.send_app_message(
448
- frame.message, participant_id, completion=completion_callback(future)
449
- )
450
- await future
451
-
452
- async def read_next_audio_frame(self) -> Optional[InputAudioRawFrame]:
453
- """Reads the next 20ms audio frame from the virtual speaker."""
454
- if not self._speaker:
455
- return None
456
-
457
- sample_rate = self._in_sample_rate
458
- num_channels = self._params.audio_in_channels
459
- num_frames = int(sample_rate / 100) * 2 # 20ms of audio
460
-
461
- future = self._get_event_loop().create_future()
462
- self._speaker.read_frames(num_frames, completion=completion_callback(future))
463
- audio = await future
464
-
465
- if len(audio) > 0:
466
- return InputAudioRawFrame(
467
- audio=audio, sample_rate=sample_rate, num_channels=num_channels
468
- )
469
- else:
470
- # If we don't read any audio it could be there's no participant
471
- # connected. daily-python will return immediately if that's the
472
- # case, so let's sleep for a little bit (i.e. busy wait).
473
- await asyncio.sleep(0.01)
474
- return None
475
-
476
- async def register_audio_destination(self, destination: str):
477
- """Register a custom audio destination for multi-track output.
478
-
479
- Args:
480
- destination: The destination identifier to register.
481
- """
482
- self._custom_audio_tracks[destination] = await self.add_custom_audio_track(destination)
483
- self._client.update_publishing({"customAudio": {destination: True}})
484
-
485
- async def write_audio_frame(self, frame: OutputAudioRawFrame):
486
- """Write an audio frame to the appropriate audio track.
487
-
488
- Args:
489
- frame: The audio frame to write.
490
- """
491
- future = self._get_event_loop().create_future()
492
-
493
- destination = frame.transport_destination
494
- audio_source: Optional[CustomAudioSource] = None
495
- if not destination and self._microphone_track:
496
- audio_source = self._microphone_track.source
497
- elif destination and destination in self._custom_audio_tracks:
498
- track = self._custom_audio_tracks[destination]
499
- audio_source = track.source
500
-
501
- if audio_source:
502
- audio_source.write_frames(frame.audio, completion=completion_callback(future))
503
- else:
504
- logger.warning(f"{self} unable to write audio frames to destination [{destination}]")
505
- future.set_result(None)
506
-
507
- await future
508
-
509
- async def write_video_frame(self, frame: OutputImageRawFrame):
510
- """Write a video frame to the camera device.
511
-
512
- Args:
513
- frame: The image frame to write.
514
- """
515
- if not frame.transport_destination and self._camera:
516
- self._camera.write_frame(frame.image)
517
-
518
- async def setup(self, setup: FrameProcessorSetup):
519
- """Setup the client with task manager and event queues.
520
-
521
- Args:
522
- setup: The frame processor setup configuration.
523
- """
524
- if self._task_manager:
525
- return
526
-
527
- self._task_manager = setup.task_manager
528
-
529
- self._event_queue = asyncio.Queue()
530
- self._event_task = self._task_manager.create_task(
531
- self._callback_task_handler(self._event_queue),
532
- f"{self}::event_callback_task",
533
- )
534
-
535
- async def cleanup(self):
536
- """Cleanup client resources and cancel tasks."""
537
- if self._event_task and self._task_manager:
538
- await self._task_manager.cancel_task(self._event_task)
539
- self._event_task = None
540
- if self._audio_task and self._task_manager:
541
- await self._task_manager.cancel_task(self._audio_task)
542
- self._audio_task = None
543
- if self._video_task and self._task_manager:
544
- await self._task_manager.cancel_task(self._video_task)
545
- self._video_task = None
546
- # Make sure we don't block the event loop in case `client.release()`
547
- # takes extra time.
548
- await self._get_event_loop().run_in_executor(self._executor, self._cleanup)
549
-
550
- async def start(self, frame: StartFrame):
551
- """Start the client and initialize audio/video components.
552
-
553
- Args:
554
- frame: The start frame containing initialization parameters.
555
- """
556
- self._in_sample_rate = self._params.audio_in_sample_rate or frame.audio_in_sample_rate
557
- self._out_sample_rate = self._params.audio_out_sample_rate or frame.audio_out_sample_rate
558
-
559
- if self._params.audio_in_enabled:
560
- if self._params.audio_in_user_tracks and not self._audio_task and self._task_manager:
561
- self._audio_queue = asyncio.Queue()
562
- self._audio_task = self._task_manager.create_task(
563
- self._callback_task_handler(self._audio_queue),
564
- f"{self}::audio_callback_task",
565
- )
566
- elif not self._speaker:
567
- self._speaker = Daily.create_speaker_device(
568
- self._speaker_name(),
569
- sample_rate=self._in_sample_rate,
570
- channels=self._params.audio_in_channels,
571
- non_blocking=True,
572
- )
573
- Daily.select_speaker_device(self._speaker_name())
574
-
575
- if self._params.video_in_enabled and not self._video_task and self._task_manager:
576
- self._video_queue = asyncio.Queue()
577
- self._video_task = self._task_manager.create_task(
578
- self._callback_task_handler(self._video_queue),
579
- f"{self}::video_callback_task",
580
- )
581
- if self._params.video_out_enabled and not self._camera:
582
- self._camera = Daily.create_camera_device(
583
- self._camera_name(),
584
- width=self._params.video_out_width,
585
- height=self._params.video_out_height,
586
- color_format=self._params.video_out_color_format,
587
- )
588
-
589
- if self._params.audio_out_enabled and not self._microphone_track:
590
- audio_source = CustomAudioSource(self._out_sample_rate, self._params.audio_out_channels)
591
- audio_track = CustomAudioTrack(audio_source)
592
- self._microphone_track = DailyAudioTrack(source=audio_source, track=audio_track)
593
-
594
- async def join(self):
595
- """Join the Daily room with configured settings."""
596
- # Transport already joined or joining, ignore.
597
- if self._joined or self._joining:
598
- # Increment leave counter if we already joined.
599
- self._leave_counter += 1
600
- return
601
-
602
- logger.info(f"Joining {self._room_url}")
603
- self._joining = True
604
-
605
- # For performance reasons, never subscribe to video streams (unless a
606
- # video renderer is registered).
607
- self._client.update_subscription_profiles(
608
- {"base": {"camera": "unsubscribed", "screenVideo": "unsubscribed"}}
609
- )
610
-
611
- self._client.set_user_name(self._bot_name)
612
-
613
- try:
614
- (data, error) = await self._join()
615
-
616
- if not error:
617
- self._joined = True
618
- self._joining = False
619
- # Increment leave counter if we successfully joined.
620
- self._leave_counter += 1
621
-
622
- logger.info(f"Joined {self._room_url}")
623
-
624
- if self._params.transcription_enabled:
625
- await self.start_transcription(self._params.transcription_settings)
626
-
627
- await self._callbacks.on_joined(data)
628
-
629
- self._joined_event.set()
630
- else:
631
- error_msg = f"Error joining {self._room_url}: {error}"
632
- logger.error(error_msg)
633
- await self._callbacks.on_error(error_msg)
634
- except asyncio.TimeoutError:
635
- error_msg = f"Time out joining {self._room_url}"
636
- logger.error(error_msg)
637
- self._joining = False
638
- await self._callbacks.on_error(error_msg)
639
-
640
- async def _join(self):
641
- """Execute the actual room join operation."""
642
- future = self._get_event_loop().create_future()
643
-
644
- camera_enabled = self._params.video_out_enabled and self._params.camera_out_enabled
645
- microphone_enabled = self._params.audio_out_enabled and self._params.microphone_out_enabled
646
-
647
- self._client.join(
648
- self._room_url,
649
- self._token,
650
- completion=completion_callback(future),
651
- client_settings={
652
- "inputs": {
653
- "camera": {
654
- "isEnabled": camera_enabled,
655
- "settings": {
656
- "deviceId": self._camera_name(),
657
- },
658
- },
659
- "microphone": {
660
- "isEnabled": microphone_enabled,
661
- "settings": {
662
- "customTrack": {
663
- "id": self._microphone_track.track.id
664
- if self._microphone_track
665
- else "no-microphone-track"
666
- }
667
- },
668
- },
669
- },
670
- "publishing": {
671
- "camera": {
672
- "sendSettings": {
673
- "maxQuality": "low",
674
- "encodings": {
675
- "low": {
676
- "maxBitrate": self._params.video_out_bitrate,
677
- "maxFramerate": self._params.video_out_framerate,
678
- }
679
- },
680
- }
681
- },
682
- "microphone": {
683
- "sendSettings": {
684
- "channelConfig": "stereo"
685
- if self._params.audio_out_channels == 2
686
- else "mono",
687
- "bitrate": self._params.audio_out_bitrate,
688
- }
689
- },
690
- },
691
- },
692
- )
693
-
694
- return await asyncio.wait_for(future, timeout=10)
695
-
696
- async def leave(self):
697
- """Leave the Daily room and cleanup resources."""
698
- # Decrement leave counter when leaving.
699
- self._leave_counter -= 1
700
-
701
- # Transport not joined, ignore.
702
- if not self._joined or self._leave_counter > 0:
703
- return
704
-
705
- self._joined = False
706
- self._joined_event.clear()
707
-
708
- logger.info(f"Leaving {self._room_url}")
709
-
710
- if self._params.transcription_enabled:
711
- await self.stop_transcription()
712
-
713
- # Remove any custom tracks, if any.
714
- for track_name, _ in self._custom_audio_tracks.items():
715
- await self.remove_custom_audio_track(track_name)
716
-
717
- try:
718
- error = await self._leave()
719
- if not error:
720
- logger.info(f"Left {self._room_url}")
721
- await self._callbacks.on_left()
722
- else:
723
- error_msg = f"Error leaving {self._room_url}: {error}"
724
- logger.error(error_msg)
725
- await self._callbacks.on_error(error_msg)
726
- except asyncio.TimeoutError:
727
- error_msg = f"Time out leaving {self._room_url}"
728
- logger.error(error_msg)
729
- await self._callbacks.on_error(error_msg)
730
-
731
- async def _leave(self):
732
- """Execute the actual room leave operation."""
733
- future = self._get_event_loop().create_future()
734
- self._client.leave(completion=completion_callback(future))
735
- return await asyncio.wait_for(future, timeout=10)
736
-
737
- def _cleanup(self):
738
- """Cleanup the Daily client instance."""
739
- if self._client:
740
- self._client.release()
741
- self._client = None
742
-
743
- def participants(self):
744
- """Get current participants in the room.
745
-
746
- Returns:
747
- Dictionary of participants keyed by participant ID.
748
- """
749
- return self._client.participants()
750
-
751
- def participant_counts(self):
752
- """Get participant count information.
753
-
754
- Returns:
755
- Dictionary with participant count details.
756
- """
757
- return self._client.participant_counts()
758
-
759
- async def start_dialout(self, settings):
760
- """Start a dial-out call to a phone number.
761
-
762
- Args:
763
- settings: Dial-out configuration settings.
764
- """
765
- logger.debug(f"Starting dialout: settings={settings}")
766
-
767
- future = self._get_event_loop().create_future()
768
- self._client.start_dialout(settings, completion=completion_callback(future))
769
- error = await future
770
- if error:
771
- logger.error(f"Unable to start dialout: {error}")
772
-
773
- async def stop_dialout(self, participant_id):
774
- """Stop a dial-out call for a specific participant.
775
-
776
- Args:
777
- participant_id: ID of the participant to stop dial-out for.
778
- """
779
- logger.debug(f"Stopping dialout: participant_id={participant_id}")
780
-
781
- future = self._get_event_loop().create_future()
782
- self._client.stop_dialout(participant_id, completion=completion_callback(future))
783
- error = await future
784
- if error:
785
- logger.error(f"Unable to stop dialout: {error}")
786
-
787
- async def send_dtmf(self, settings):
788
- """Send DTMF tones during a call.
789
-
790
- Args:
791
- settings: DTMF settings including tones and target session.
792
- """
793
- future = self._get_event_loop().create_future()
794
- self._client.send_dtmf(settings, completion=completion_callback(future))
795
- await future
796
-
797
- async def sip_call_transfer(self, settings):
798
- """Transfer a SIP call to another destination.
799
-
800
- Args:
801
- settings: SIP call transfer settings.
802
- """
803
- future = self._get_event_loop().create_future()
804
- self._client.sip_call_transfer(settings, completion=completion_callback(future))
805
- await future
806
-
807
- async def sip_refer(self, settings):
808
- """Send a SIP REFER request.
809
-
810
- Args:
811
- settings: SIP REFER settings.
812
- """
813
- future = self._get_event_loop().create_future()
814
- self._client.sip_refer(settings, completion=completion_callback(future))
815
- await future
816
-
817
- async def start_recording(self, streaming_settings, stream_id, force_new):
818
- """Start recording the call.
819
-
820
- Args:
821
- streaming_settings: Recording configuration settings.
822
- stream_id: Unique identifier for the recording stream.
823
- force_new: Whether to force a new recording session.
824
- """
825
- logger.debug(
826
- f"Starting recording: stream_id={stream_id} force_new={force_new} settings={streaming_settings}"
827
- )
828
-
829
- future = self._get_event_loop().create_future()
830
- self._client.start_recording(
831
- streaming_settings, stream_id, force_new, completion=completion_callback(future)
832
- )
833
- error = await future
834
- if error:
835
- logger.error(f"Unable to start recording: {error}")
836
-
837
- async def stop_recording(self, stream_id):
838
- """Stop recording the call.
839
-
840
- Args:
841
- stream_id: Unique identifier for the recording stream to stop.
842
- """
843
- logger.debug(f"Stopping recording: stream_id={stream_id}")
844
-
845
- future = self._get_event_loop().create_future()
846
- self._client.stop_recording(stream_id, completion=completion_callback(future))
847
- error = await future
848
- if error:
849
- logger.error(f"Unable to stop recording: {error}")
850
-
851
- async def start_transcription(self, settings):
852
- """Start transcription for the call.
853
-
854
- Args:
855
- settings: Transcription configuration settings.
856
- """
857
- if not self._token:
858
- logger.warning("Transcription can't be started without a room token")
859
- return
860
-
861
- logger.debug(f"Starting transcription: settings={settings}")
862
-
863
- future = self._get_event_loop().create_future()
864
- self._client.start_transcription(
865
- settings=self._params.transcription_settings.model_dump(exclude_none=True),
866
- completion=completion_callback(future),
867
- )
868
- error = await future
869
- if error:
870
- logger.error(f"Unable to start transcription: {error}")
871
-
872
- async def stop_transcription(self):
873
- """Stop transcription for the call."""
874
- if not self._token:
875
- return
876
-
877
- logger.debug(f"Stopping transcription")
878
-
879
- future = self._get_event_loop().create_future()
880
- self._client.stop_transcription(completion=completion_callback(future))
881
- error = await future
882
- if error:
883
- logger.error(f"Unable to stop transcription: {error}")
884
-
885
- async def send_prebuilt_chat_message(self, message: str, user_name: Optional[str] = None):
886
- """Send a chat message to Daily's Prebuilt main room.
887
-
888
- Args:
889
- message: The chat message to send.
890
- user_name: Optional user name that will appear as sender of the message.
891
- """
892
- if not self._joined:
893
- return
894
-
895
- future = self._get_event_loop().create_future()
896
- self._client.send_prebuilt_chat_message(
897
- message, user_name=user_name, completion=completion_callback(future)
898
- )
899
- await future
900
-
901
- async def capture_participant_transcription(self, participant_id: str):
902
- """Enable transcription capture for a specific participant.
903
-
904
- Args:
905
- participant_id: ID of the participant to capture transcription for.
906
- """
907
- if not self._params.transcription_enabled:
908
- return
909
-
910
- self._transcription_ids.append(participant_id)
911
- if self._joined and self._transcription_status:
912
- await self.update_transcription(self._transcription_ids)
913
-
914
- async def capture_participant_audio(
915
- self,
916
- participant_id: str,
917
- callback: Callable,
918
- audio_source: str = "microphone",
919
- sample_rate: int = 16000,
920
- callback_interval_ms: int = 20,
921
- ):
922
- """Capture audio from a specific participant.
923
-
924
- Args:
925
- participant_id: ID of the participant to capture audio from.
926
- callback: Callback function to handle audio data.
927
- audio_source: Audio source to capture (microphone, screenAudio, or custom).
928
- sample_rate: Desired sample rate for audio capture.
929
- callback_interval_ms: Interval between audio callbacks in milliseconds.
930
- """
931
- # Only enable the desired audio source subscription on this participant.
932
- if audio_source in ("microphone", "screenAudio"):
933
- media = {"media": {audio_source: "subscribed"}}
934
- else:
935
- media = {"media": {"customAudio": {audio_source: "subscribed"}}}
936
-
937
- await self.update_subscriptions(participant_settings={participant_id: media})
938
-
939
- self._audio_renderers.setdefault(participant_id, {})[audio_source] = callback
940
-
941
- logger.debug(
942
- f"Starting to capture [{audio_source}] audio from participant {participant_id}"
943
- )
944
-
945
- self._client.set_audio_renderer(
946
- participant_id,
947
- self._audio_data_received,
948
- audio_source=audio_source,
949
- sample_rate=sample_rate,
950
- callback_interval_ms=callback_interval_ms,
951
- )
952
-
953
- async def capture_participant_video(
954
- self,
955
- participant_id: str,
956
- callback: Callable,
957
- framerate: int = 30,
958
- video_source: str = "camera",
959
- color_format: str = "RGB",
960
- ):
961
- """Capture video from a specific participant.
962
-
963
- Args:
964
- participant_id: ID of the participant to capture video from.
965
- callback: Callback function to handle video frames.
966
- framerate: Desired framerate for video capture.
967
- video_source: Video source to capture (camera, screenVideo, or custom).
968
- color_format: Color format for video frames.
969
- """
970
- # Only enable the desired audio source subscription on this participant.
971
- if video_source in ("camera", "screenVideo"):
972
- media = {"media": {video_source: "subscribed"}}
973
- else:
974
- media = {"media": {"customVideo": {video_source: "subscribed"}}}
975
-
976
- await self.update_subscriptions(participant_settings={participant_id: media})
977
-
978
- self._video_renderers.setdefault(participant_id, {})[video_source] = callback
979
-
980
- logger.debug(
981
- f"Starting to capture [{video_source}] video from participant {participant_id}"
982
- )
983
-
984
- self._client.set_video_renderer(
985
- participant_id,
986
- self._video_frame_received,
987
- video_source=video_source,
988
- color_format=color_format,
989
- )
990
-
991
- async def add_custom_audio_track(self, track_name: str) -> DailyAudioTrack:
992
- """Add a custom audio track for multi-stream output.
993
-
994
- Args:
995
- track_name: Name for the custom audio track.
996
-
997
- Returns:
998
- The created DailyAudioTrack instance.
999
- """
1000
- future = self._get_event_loop().create_future()
1001
-
1002
- audio_source = CustomAudioSource(self._out_sample_rate, 1)
1003
-
1004
- audio_track = CustomAudioTrack(audio_source)
1005
-
1006
- self._client.add_custom_audio_track(
1007
- track_name=track_name,
1008
- audio_track=audio_track,
1009
- ignore_audio_level=True,
1010
- completion=completion_callback(future),
1011
- )
1012
-
1013
- await future
1014
-
1015
- track = DailyAudioTrack(source=audio_source, track=audio_track)
1016
-
1017
- return track
1018
-
1019
- async def remove_custom_audio_track(self, track_name: str):
1020
- """Remove a custom audio track.
1021
-
1022
- Args:
1023
- track_name: Name of the custom audio track to remove.
1024
- """
1025
- future = self._get_event_loop().create_future()
1026
- self._client.remove_custom_audio_track(
1027
- track_name=track_name,
1028
- completion=completion_callback(future),
1029
- )
1030
- await future
1031
-
1032
- async def update_transcription(self, participants=None, instance_id=None):
1033
- """Update transcription settings for specific participants.
1034
-
1035
- Args:
1036
- participants: List of participant IDs to enable transcription for.
1037
- instance_id: Optional transcription instance ID.
1038
- """
1039
- future = self._get_event_loop().create_future()
1040
- self._client.update_transcription(
1041
- participants, instance_id, completion=completion_callback(future)
1042
- )
1043
- await future
1044
-
1045
- async def update_subscriptions(self, participant_settings=None, profile_settings=None):
1046
- """Update media subscription settings.
1047
-
1048
- Args:
1049
- participant_settings: Per-participant subscription settings.
1050
- profile_settings: Global subscription profile settings.
1051
- """
1052
- future = self._get_event_loop().create_future()
1053
- self._client.update_subscriptions(
1054
- participant_settings=participant_settings,
1055
- profile_settings=profile_settings,
1056
- completion=completion_callback(future),
1057
- )
1058
- await future
1059
-
1060
- async def update_publishing(self, publishing_settings: Mapping[str, Any]):
1061
- """Update media publishing settings.
1062
-
1063
- Args:
1064
- publishing_settings: Publishing configuration settings.
1065
- """
1066
- future = self._get_event_loop().create_future()
1067
- self._client.update_publishing(
1068
- publishing_settings=publishing_settings,
1069
- completion=completion_callback(future),
1070
- )
1071
- await future
1072
-
1073
- async def update_remote_participants(self, remote_participants: Mapping[str, Any]):
1074
- """Update settings for remote participants.
1075
-
1076
- Args:
1077
- remote_participants: Remote participant configuration settings.
1078
- """
1079
- future = self._get_event_loop().create_future()
1080
- self._client.update_remote_participants(
1081
- remote_participants=remote_participants, completion=completion_callback(future)
1082
- )
1083
- await future
1084
-
1085
- #
1086
- #
1087
- # Daily (EventHandler)
1088
- #
1089
-
1090
- def on_active_speaker_changed(self, participant):
1091
- """Handle active speaker change events.
1092
-
1093
- Args:
1094
- participant: The new active speaker participant info.
1095
- """
1096
- self._call_event_callback(self._callbacks.on_active_speaker_changed, participant)
1097
-
1098
- def on_app_message(self, message: Any, sender: str):
1099
- """Handle application message events.
1100
-
1101
- Args:
1102
- message: The received message data.
1103
- sender: ID of the message sender.
1104
- """
1105
- self._call_event_callback(self._callbacks.on_app_message, message, sender)
1106
-
1107
- def on_call_state_updated(self, state: str):
1108
- """Handle call state update events.
1109
-
1110
- Args:
1111
- state: The new call state.
1112
- """
1113
- self._call_event_callback(self._callbacks.on_call_state_updated, state)
1114
-
1115
- def on_dialin_connected(self, data: Any):
1116
- """Handle dial-in connected events.
1117
-
1118
- Args:
1119
- data: Dial-in connection data.
1120
- """
1121
- self._call_event_callback(self._callbacks.on_dialin_connected, data)
1122
-
1123
- def on_dialin_ready(self, sip_endpoint: str):
1124
- """Handle dial-in ready events.
1125
-
1126
- Args:
1127
- sip_endpoint: The SIP endpoint for dial-in.
1128
- """
1129
- self._call_event_callback(self._callbacks.on_dialin_ready, sip_endpoint)
1130
-
1131
- def on_dialin_stopped(self, data: Any):
1132
- """Handle dial-in stopped events.
1133
-
1134
- Args:
1135
- data: Dial-in stop data.
1136
- """
1137
- self._call_event_callback(self._callbacks.on_dialin_stopped, data)
1138
-
1139
- def on_dialin_error(self, data: Any):
1140
- """Handle dial-in error events.
1141
-
1142
- Args:
1143
- data: Dial-in error data.
1144
- """
1145
- self._call_event_callback(self._callbacks.on_dialin_error, data)
1146
-
1147
- def on_dialin_warning(self, data: Any):
1148
- """Handle dial-in warning events.
1149
-
1150
- Args:
1151
- data: Dial-in warning data.
1152
- """
1153
- self._call_event_callback(self._callbacks.on_dialin_warning, data)
1154
-
1155
- def on_dialout_answered(self, data: Any):
1156
- """Handle dial-out answered events.
1157
-
1158
- Args:
1159
- data: Dial-out answered data.
1160
- """
1161
- self._call_event_callback(self._callbacks.on_dialout_answered, data)
1162
-
1163
- def on_dialout_connected(self, data: Any):
1164
- """Handle dial-out connected events.
1165
-
1166
- Args:
1167
- data: Dial-out connection data.
1168
- """
1169
- self._call_event_callback(self._callbacks.on_dialout_connected, data)
1170
-
1171
- def on_dialout_stopped(self, data: Any):
1172
- """Handle dial-out stopped events.
1173
-
1174
- Args:
1175
- data: Dial-out stop data.
1176
- """
1177
- self._call_event_callback(self._callbacks.on_dialout_stopped, data)
1178
-
1179
- def on_dialout_error(self, data: Any):
1180
- """Handle dial-out error events.
1181
-
1182
- Args:
1183
- data: Dial-out error data.
1184
- """
1185
- self._call_event_callback(self._callbacks.on_dialout_error, data)
1186
-
1187
- def on_dialout_warning(self, data: Any):
1188
- """Handle dial-out warning events.
1189
-
1190
- Args:
1191
- data: Dial-out warning data.
1192
- """
1193
- self._call_event_callback(self._callbacks.on_dialout_warning, data)
1194
-
1195
- def on_participant_joined(self, participant):
1196
- """Handle participant joined events.
1197
-
1198
- Args:
1199
- participant: The participant that joined.
1200
- """
1201
- self._call_event_callback(self._callbacks.on_participant_joined, participant)
1202
-
1203
- def on_participant_left(self, participant, reason):
1204
- """Handle participant left events.
1205
-
1206
- Args:
1207
- participant: The participant that left.
1208
- reason: Reason for leaving.
1209
- """
1210
- self._call_event_callback(self._callbacks.on_participant_left, participant, reason)
1211
-
1212
- def on_participant_updated(self, participant):
1213
- """Handle participant updated events.
1214
-
1215
- Args:
1216
- participant: The updated participant info.
1217
- """
1218
- self._call_event_callback(self._callbacks.on_participant_updated, participant)
1219
-
1220
- def on_transcription_started(self, status):
1221
- """Handle transcription started events.
1222
-
1223
- Args:
1224
- status: Transcription start status.
1225
- """
1226
- logger.debug(f"Transcription started: {status}")
1227
- self._transcription_status = status
1228
- self._call_event_callback(self.update_transcription, self._transcription_ids)
1229
-
1230
- def on_transcription_stopped(self, stopped_by, stopped_by_error):
1231
- """Handle transcription stopped events.
1232
-
1233
- Args:
1234
- stopped_by: Who stopped the transcription.
1235
- stopped_by_error: Whether stopped due to error.
1236
- """
1237
- logger.debug("Transcription stopped")
1238
- self._call_event_callback(
1239
- self._callbacks.on_transcription_stopped, stopped_by, stopped_by_error
1240
- )
1241
-
1242
- def on_transcription_error(self, message):
1243
- """Handle transcription error events.
1244
-
1245
- Args:
1246
- message: Error message.
1247
- """
1248
- logger.error(f"Transcription error: {message}")
1249
- self._call_event_callback(self._callbacks.on_transcription_error, message)
1250
-
1251
- def on_transcription_message(self, message):
1252
- """Handle transcription message events.
1253
-
1254
- Args:
1255
- message: The transcription message data.
1256
- """
1257
- self._call_event_callback(self._callbacks.on_transcription_message, message)
1258
-
1259
- def on_recording_started(self, status):
1260
- """Handle recording started events.
1261
-
1262
- Args:
1263
- status: Recording start status.
1264
- """
1265
- logger.debug(f"Recording started: {status}")
1266
- self._call_event_callback(self._callbacks.on_recording_started, status)
1267
-
1268
- def on_recording_stopped(self, stream_id):
1269
- """Handle recording stopped events.
1270
-
1271
- Args:
1272
- stream_id: ID of the stopped recording stream.
1273
- """
1274
- logger.debug(f"Recording stopped: {stream_id}")
1275
- self._call_event_callback(self._callbacks.on_recording_stopped, stream_id)
1276
-
1277
- def on_recording_error(self, stream_id, message):
1278
- """Handle recording error events.
1279
-
1280
- Args:
1281
- stream_id: ID of the recording stream with error.
1282
- message: Error message.
1283
- """
1284
- logger.error(f"Recording error for {stream_id}: {message}")
1285
- self._call_event_callback(self._callbacks.on_recording_error, stream_id, message)
1286
-
1287
- #
1288
- # Daily (CallClient callbacks)
1289
- #
1290
-
1291
- def _audio_data_received(self, participant_id: str, audio_data: AudioData, audio_source: str):
1292
- """Handle received audio data from participants."""
1293
- callback = self._audio_renderers[participant_id][audio_source]
1294
- self._call_audio_callback(callback, participant_id, audio_data, audio_source)
1295
-
1296
- def _video_frame_received(
1297
- self, participant_id: str, video_frame: VideoFrame, video_source: str
1298
- ):
1299
- """Handle received video frames from participants."""
1300
- callback = self._video_renderers[participant_id][video_source]
1301
- self._call_video_callback(callback, participant_id, video_frame, video_source)
1302
-
1303
- #
1304
- # Queue callbacks handling
1305
- #
1306
-
1307
- def _call_audio_callback(self, callback, *args):
1308
- """Queue an audio callback for async execution."""
1309
- self._call_async_callback(self._audio_queue, callback, *args)
1310
-
1311
- def _call_video_callback(self, callback, *args):
1312
- """Queue a video callback for async execution."""
1313
- self._call_async_callback(self._video_queue, callback, *args)
1314
-
1315
- def _call_event_callback(self, callback, *args):
1316
- """Queue an event callback for async execution."""
1317
- self._call_async_callback(self._event_queue, callback, *args)
1318
-
1319
- def _call_async_callback(self, queue: asyncio.Queue, callback, *args):
1320
- """Queue a callback for async execution on the event loop."""
1321
- try:
1322
- future = asyncio.run_coroutine_threadsafe(
1323
- queue.put((callback, *args)), self._get_event_loop()
1324
- )
1325
- future.result()
1326
- except FuturesCancelledError:
1327
- pass
1328
-
1329
- async def _callback_task_handler(self, queue: asyncio.Queue):
1330
- """Handle queued callbacks from the specified queue."""
1331
- while True:
1332
- # Wait to process any callback until we are joined.
1333
- await self._joined_event.wait()
1334
- (callback, *args) = await queue.get()
1335
- await callback(*args)
1336
- queue.task_done()
1337
-
1338
- def _get_event_loop(self) -> asyncio.AbstractEventLoop:
1339
- """Get the event loop from the task manager."""
1340
- if not self._task_manager:
1341
- raise Exception(f"{self}: missing task manager (pipeline not started?)")
1342
- return self._task_manager.get_event_loop()
1343
-
1344
- def __str__(self):
1345
- """String representation of the DailyTransportClient."""
1346
- return f"{self._transport_name}::DailyTransportClient"
1347
-
1348
-
1349
- class DailyInputTransport(BaseInputTransport):
1350
- """Handles incoming media streams and events from Daily calls.
1351
-
1352
- Processes incoming audio, video, transcriptions and other events from Daily
1353
- room participants, including participant media capture and event forwarding.
1354
- """
1355
-
1356
- def __init__(
1357
- self,
1358
- transport: BaseTransport,
1359
- client: DailyTransportClient,
1360
- params: DailyParams,
1361
- **kwargs,
1362
- ):
1363
- """Initialize the Daily input transport.
1364
-
1365
- Args:
1366
- transport: The parent transport instance.
1367
- client: DailyTransportClient instance.
1368
- params: Configuration parameters.
1369
- **kwargs: Additional arguments passed to parent class.
1370
- """
1371
- super().__init__(params, **kwargs)
1372
-
1373
- self._transport = transport
1374
- self._client = client
1375
- self._params = params
1376
-
1377
- self._video_renderers = {}
1378
-
1379
- # Whether we have seen a StartFrame already.
1380
- self._initialized = False
1381
-
1382
- # Whether we have started audio streaming.
1383
- self._streaming_started = False
1384
-
1385
- # Store the list of participants we should stream. This is necessary in
1386
- # case we don't start streaming right away.
1387
- self._capture_participant_audio = []
1388
-
1389
- # Audio task when using a virtual speaker (i.e. no user tracks).
1390
- self._audio_in_task: Optional[asyncio.Task] = None
1391
-
1392
- self._vad_analyzer: Optional[VADAnalyzer] = params.vad_analyzer
1393
-
1394
- @property
1395
- def vad_analyzer(self) -> Optional[VADAnalyzer]:
1396
- """Get the Voice Activity Detection analyzer.
1397
-
1398
- Returns:
1399
- The VAD analyzer instance if configured.
1400
- """
1401
- return self._vad_analyzer
1402
-
1403
- async def start_audio_in_streaming(self):
1404
- """Start receiving audio from participants."""
1405
- if not self._params.audio_in_enabled:
1406
- return
1407
-
1408
- logger.debug(f"Start receiving audio")
1409
-
1410
- if self._params.audio_in_enabled:
1411
- if self._params.audio_in_user_tracks:
1412
- # Capture invididual participant tracks.
1413
- for participant_id, audio_source, sample_rate in self._capture_participant_audio:
1414
- await self._client.capture_participant_audio(
1415
- participant_id, self._on_participant_audio_data, audio_source, sample_rate
1416
- )
1417
- elif not self._audio_in_task:
1418
- # Create audio task. It reads audio frames from a single room
1419
- # track and pushes them internally for VAD processing.
1420
- self._audio_in_task = self.create_task(self._audio_in_task_handler())
1421
-
1422
- self._streaming_started = True
1423
-
1424
- async def setup(self, setup: FrameProcessorSetup):
1425
- """Setup the input transport with shared client setup.
1426
-
1427
- Args:
1428
- setup: The frame processor setup configuration.
1429
- """
1430
- await super().setup(setup)
1431
- await self._client.setup(setup)
1432
-
1433
- async def cleanup(self):
1434
- """Cleanup input transport and shared resources."""
1435
- await super().cleanup()
1436
- await self._client.cleanup()
1437
- await self._transport.cleanup()
1438
-
1439
- async def start(self, frame: StartFrame):
1440
- """Start the input transport and join the Daily room.
1441
-
1442
- Args:
1443
- frame: The start frame containing initialization parameters.
1444
- """
1445
- # Parent start.
1446
- await super().start(frame)
1447
-
1448
- if self._initialized:
1449
- return
1450
-
1451
- self._initialized = True
1452
-
1453
- # Setup client.
1454
- await self._client.start(frame)
1455
-
1456
- # Join the room.
1457
- await self._client.join()
1458
-
1459
- # Indicate the transport that we are connected.
1460
- await self.set_transport_ready(frame)
1461
-
1462
- if self._params.audio_in_stream_on_start:
1463
- await self.start_audio_in_streaming()
1464
-
1465
- async def stop(self, frame: EndFrame):
1466
- """Stop the input transport and leave the Daily room.
1467
-
1468
- Args:
1469
- frame: The end frame signaling transport shutdown.
1470
- """
1471
- # Parent stop.
1472
- await super().stop(frame)
1473
- # Leave the room.
1474
- await self._client.leave()
1475
- # Stop audio thread.
1476
- if self._audio_in_task:
1477
- await self.cancel_task(self._audio_in_task)
1478
- self._audio_in_task = None
1479
-
1480
- async def cancel(self, frame: CancelFrame):
1481
- """Cancel the input transport and leave the Daily room.
1482
-
1483
- Args:
1484
- frame: The cancel frame signaling immediate cancellation.
1485
- """
1486
- # Parent stop.
1487
- await super().cancel(frame)
1488
- # Leave the room.
1489
- await self._client.leave()
1490
- # Stop audio thread.
1491
- if self._audio_in_task:
1492
- await self.cancel_task(self._audio_in_task)
1493
- self._audio_in_task = None
1494
-
1495
- #
1496
- # FrameProcessor
1497
- #
1498
-
1499
- async def process_frame(self, frame: Frame, direction: FrameDirection):
1500
- """Process incoming frames, including user image requests.
1501
-
1502
- Args:
1503
- frame: The frame to process.
1504
- direction: The direction of frame flow in the pipeline.
1505
- """
1506
- await super().process_frame(frame, direction)
1507
-
1508
- if isinstance(frame, UserImageRequestFrame):
1509
- await self.request_participant_image(frame)
1510
-
1511
- #
1512
- # Frames
1513
- #
1514
-
1515
- async def push_transcription_frame(self, frame: TranscriptionFrame | InterimTranscriptionFrame):
1516
- """Push a transcription frame downstream.
1517
-
1518
- Args:
1519
- frame: The transcription frame to push.
1520
- """
1521
- await self.push_frame(frame)
1522
-
1523
- async def push_app_message(self, message: Any, sender: str):
1524
- """Push an application message as an urgent transport frame.
1525
-
1526
- Args:
1527
- message: The message data to send.
1528
- sender: ID of the message sender.
1529
- """
1530
- frame = DailyTransportMessageUrgentFrame(message=message, participant_id=sender)
1531
- await self.push_frame(frame)
1532
-
1533
- #
1534
- # Audio in
1535
- #
1536
-
1537
- async def capture_participant_audio(
1538
- self,
1539
- participant_id: str,
1540
- audio_source: str = "microphone",
1541
- sample_rate: int = 16000,
1542
- ):
1543
- """Capture audio from a specific participant.
1544
-
1545
- Args:
1546
- participant_id: ID of the participant to capture audio from.
1547
- audio_source: Audio source to capture from.
1548
- sample_rate: Desired sample rate for audio capture.
1549
- """
1550
- if self._streaming_started:
1551
- await self._client.capture_participant_audio(
1552
- participant_id, self._on_participant_audio_data, audio_source, sample_rate
1553
- )
1554
- else:
1555
- self._capture_participant_audio.append((participant_id, audio_source, sample_rate))
1556
-
1557
- async def _on_participant_audio_data(
1558
- self, participant_id: str, audio: AudioData, audio_source: str
1559
- ):
1560
- """Handle received participant audio data."""
1561
- frame = UserAudioRawFrame(
1562
- user_id=participant_id,
1563
- audio=audio.audio_frames,
1564
- sample_rate=audio.sample_rate,
1565
- num_channels=audio.num_channels,
1566
- )
1567
- frame.transport_source = audio_source
1568
- await self.push_audio_frame(frame)
1569
-
1570
- async def _audio_in_task_handler(self):
1571
- while True:
1572
- frame = await self._client.read_next_audio_frame()
1573
- if frame:
1574
- await self.push_audio_frame(frame)
1575
-
1576
- #
1577
- # Camera in
1578
- #
1579
-
1580
- async def capture_participant_video(
1581
- self,
1582
- participant_id: str,
1583
- framerate: int = 30,
1584
- video_source: str = "camera",
1585
- color_format: str = "RGB",
1586
- ):
1587
- """Capture video from a specific participant.
1588
-
1589
- Args:
1590
- participant_id: ID of the participant to capture video from.
1591
- framerate: Desired framerate for video capture.
1592
- video_source: Video source to capture from.
1593
- color_format: Color format for video frames.
1594
- """
1595
- if participant_id not in self._video_renderers:
1596
- self._video_renderers[participant_id] = {}
1597
-
1598
- self._video_renderers[participant_id][video_source] = {
1599
- "framerate": framerate,
1600
- "timestamp": 0,
1601
- "render_next_frame": [],
1602
- }
1603
-
1604
- await self._client.capture_participant_video(
1605
- participant_id, self._on_participant_video_frame, framerate, video_source, color_format
1606
- )
1607
-
1608
- async def request_participant_image(self, frame: UserImageRequestFrame):
1609
- """Request a video frame from a specific participant.
1610
-
1611
- Args:
1612
- frame: The user image request frame.
1613
- """
1614
- if frame.user_id in self._video_renderers:
1615
- video_source = frame.video_source if frame.video_source else "camera"
1616
- self._video_renderers[frame.user_id][video_source]["render_next_frame"].append(frame)
1617
-
1618
- async def _on_participant_video_frame(
1619
- self, participant_id: str, video_frame: VideoFrame, video_source: str
1620
- ):
1621
- """Handle received participant video frames."""
1622
- render_frame = False
1623
-
1624
- curr_time = time.time()
1625
- prev_time = self._video_renderers[participant_id][video_source]["timestamp"]
1626
- framerate = self._video_renderers[participant_id][video_source]["framerate"]
1627
-
1628
- # Some times we render frames because of a request.
1629
- request_frame = None
1630
-
1631
- if framerate > 0:
1632
- next_time = prev_time + 1 / framerate
1633
- render_frame = (next_time - curr_time) < 0.1
1634
-
1635
- if self._video_renderers[participant_id][video_source]["render_next_frame"]:
1636
- request_frame = self._video_renderers[participant_id][video_source][
1637
- "render_next_frame"
1638
- ].pop(0)
1639
- render_frame = True
1640
-
1641
- if render_frame:
1642
- frame = UserImageRawFrame(
1643
- user_id=participant_id,
1644
- request=request_frame,
1645
- image=video_frame.buffer,
1646
- size=(video_frame.width, video_frame.height),
1647
- format=video_frame.color_format,
1648
- )
1649
- frame.transport_source = video_source
1650
- await self.push_video_frame(frame)
1651
- self._video_renderers[participant_id][video_source]["timestamp"] = curr_time
1652
-
1653
-
1654
- class DailyOutputTransport(BaseOutputTransport):
1655
- """Handles outgoing media streams and events to Daily calls.
1656
-
1657
- Manages sending audio, video, DTMF tones, and other data to Daily calls,
1658
- including audio destination registration and message transmission.
1659
- """
1660
-
1661
- def __init__(
1662
- self, transport: BaseTransport, client: DailyTransportClient, params: DailyParams, **kwargs
1663
- ):
1664
- """Initialize the Daily output transport.
1665
-
1666
- Args:
1667
- transport: The parent transport instance.
1668
- client: DailyTransportClient instance.
1669
- params: Configuration parameters.
1670
- **kwargs: Additional arguments passed to parent class.
1671
- """
1672
- super().__init__(params, **kwargs)
1673
-
1674
- self._transport = transport
1675
- self._client = client
1676
-
1677
- # Whether we have seen a StartFrame already.
1678
- self._initialized = False
1679
-
1680
- async def setup(self, setup: FrameProcessorSetup):
1681
- """Setup the output transport with shared client setup.
1682
-
1683
- Args:
1684
- setup: The frame processor setup configuration.
1685
- """
1686
- await super().setup(setup)
1687
- await self._client.setup(setup)
1688
-
1689
- async def cleanup(self):
1690
- """Cleanup output transport and shared resources."""
1691
- await super().cleanup()
1692
- await self._client.cleanup()
1693
- await self._transport.cleanup()
1694
-
1695
- async def start(self, frame: StartFrame):
1696
- """Start the output transport and join the Daily room.
1697
-
1698
- Args:
1699
- frame: The start frame containing initialization parameters.
1700
- """
1701
- # Parent start.
1702
- await super().start(frame)
1703
-
1704
- if self._initialized:
1705
- return
1706
-
1707
- self._initialized = True
1708
-
1709
- # Setup client.
1710
- await self._client.start(frame)
1711
-
1712
- # Join the room.
1713
- await self._client.join()
1714
-
1715
- # Indicate the transport that we are connected.
1716
- await self.set_transport_ready(frame)
1717
-
1718
- async def stop(self, frame: EndFrame):
1719
- """Stop the output transport and leave the Daily room.
1720
-
1721
- Args:
1722
- frame: The end frame signaling transport shutdown.
1723
- """
1724
- # Parent stop.
1725
- await super().stop(frame)
1726
- # Leave the room.
1727
- await self._client.leave()
1728
-
1729
- async def cancel(self, frame: CancelFrame):
1730
- """Cancel the output transport and leave the Daily room.
1731
-
1732
- Args:
1733
- frame: The cancel frame signaling immediate cancellation.
1734
- """
1735
- # Parent stop.
1736
- await super().cancel(frame)
1737
- # Leave the room.
1738
- await self._client.leave()
1739
-
1740
- async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
1741
- """Send a transport message to participants.
1742
-
1743
- Args:
1744
- frame: The transport message frame to send.
1745
- """
1746
- await self._client.send_message(frame)
1747
-
1748
- async def register_video_destination(self, destination: str):
1749
- """Register a video output destination.
1750
-
1751
- Args:
1752
- destination: The destination identifier to register.
1753
- """
1754
- logger.warning(f"{self} registering video destinations is not supported yet")
1755
-
1756
- async def register_audio_destination(self, destination: str):
1757
- """Register an audio output destination.
1758
-
1759
- Args:
1760
- destination: The destination identifier to register.
1761
- """
1762
- await self._client.register_audio_destination(destination)
1763
-
1764
- async def write_dtmf(self, frame: OutputDTMFFrame | OutputDTMFUrgentFrame):
1765
- """Write DTMF tones to the call.
1766
-
1767
- Args:
1768
- frame: The DTMF frame containing tone information.
1769
- """
1770
- await self._client.send_dtmf(
1771
- {
1772
- "sessionId": frame.transport_destination,
1773
- "tones": frame.button.value,
1774
- }
1775
- )
1776
-
1777
- async def write_audio_frame(self, frame: OutputAudioRawFrame):
1778
- """Write an audio frame to the Daily call.
1779
-
1780
- Args:
1781
- frame: The audio frame to write.
1782
- """
1783
- await self._client.write_audio_frame(frame)
1784
-
1785
- async def write_video_frame(self, frame: OutputImageRawFrame):
1786
- """Write a video frame to the Daily call.
1787
-
1788
- Args:
1789
- frame: The video frame to write.
1790
- """
1791
- await self._client.write_video_frame(frame)
1792
-
1793
-
1794
- class DailyTransport(BaseTransport):
1795
- """Transport implementation for Daily audio and video calls.
1796
-
1797
- Provides comprehensive Daily integration including audio/video streaming,
1798
- transcription, recording, dial-in/out functionality, and real-time communication
1799
- features for conversational AI applications.
1800
- """
1801
-
1802
- def __init__(
1803
- self,
1804
- room_url: str,
1805
- token: Optional[str],
1806
- bot_name: str,
1807
- params: Optional[DailyParams] = None,
1808
- input_name: Optional[str] = None,
1809
- output_name: Optional[str] = None,
1810
- ):
1811
- """Initialize the Daily transport.
1812
-
1813
- Args:
1814
- room_url: URL of the Daily room to connect to.
1815
- token: Optional authentication token for the room.
1816
- bot_name: Display name for the bot in the call.
1817
- params: Configuration parameters for the transport.
1818
- input_name: Optional name for the input transport.
1819
- output_name: Optional name for the output transport.
1820
- """
1821
- super().__init__(input_name=input_name, output_name=output_name)
1822
-
1823
- callbacks = DailyCallbacks(
1824
- on_active_speaker_changed=self._on_active_speaker_changed,
1825
- on_joined=self._on_joined,
1826
- on_left=self._on_left,
1827
- on_error=self._on_error,
1828
- on_app_message=self._on_app_message,
1829
- on_call_state_updated=self._on_call_state_updated,
1830
- on_client_connected=self._on_client_connected,
1831
- on_client_disconnected=self._on_client_disconnected,
1832
- on_dialin_connected=self._on_dialin_connected,
1833
- on_dialin_ready=self._on_dialin_ready,
1834
- on_dialin_stopped=self._on_dialin_stopped,
1835
- on_dialin_error=self._on_dialin_error,
1836
- on_dialin_warning=self._on_dialin_warning,
1837
- on_dialout_answered=self._on_dialout_answered,
1838
- on_dialout_connected=self._on_dialout_connected,
1839
- on_dialout_stopped=self._on_dialout_stopped,
1840
- on_dialout_error=self._on_dialout_error,
1841
- on_dialout_warning=self._on_dialout_warning,
1842
- on_participant_joined=self._on_participant_joined,
1843
- on_participant_left=self._on_participant_left,
1844
- on_participant_updated=self._on_participant_updated,
1845
- on_transcription_message=self._on_transcription_message,
1846
- on_transcription_stopped=self._on_transcription_stopped,
1847
- on_transcription_error=self._on_transcription_error,
1848
- on_recording_started=self._on_recording_started,
1849
- on_recording_stopped=self._on_recording_stopped,
1850
- on_recording_error=self._on_recording_error,
1851
- )
1852
- self._params = params or DailyParams()
1853
-
1854
- self._client = DailyTransportClient(
1855
- room_url, token, bot_name, self._params, callbacks, self.name
1856
- )
1857
- self._input: Optional[DailyInputTransport] = None
1858
- self._output: Optional[DailyOutputTransport] = None
1859
-
1860
- self._other_participant_has_joined = False
1861
-
1862
- # Register supported handlers. The user will only be able to register
1863
- # these handlers.
1864
- self._register_event_handler("on_active_speaker_changed")
1865
- self._register_event_handler("on_joined")
1866
- self._register_event_handler("on_left")
1867
- self._register_event_handler("on_error")
1868
- self._register_event_handler("on_app_message")
1869
- self._register_event_handler("on_call_state_updated")
1870
- self._register_event_handler("on_client_connected")
1871
- self._register_event_handler("on_client_disconnected")
1872
- self._register_event_handler("on_dialin_connected")
1873
- self._register_event_handler("on_dialin_ready")
1874
- self._register_event_handler("on_dialin_stopped")
1875
- self._register_event_handler("on_dialin_error")
1876
- self._register_event_handler("on_dialin_warning")
1877
- self._register_event_handler("on_dialout_answered")
1878
- self._register_event_handler("on_dialout_connected")
1879
- self._register_event_handler("on_dialout_stopped")
1880
- self._register_event_handler("on_dialout_error")
1881
- self._register_event_handler("on_dialout_warning")
1882
- self._register_event_handler("on_first_participant_joined")
1883
- self._register_event_handler("on_participant_joined")
1884
- self._register_event_handler("on_participant_left")
1885
- self._register_event_handler("on_participant_updated")
1886
- self._register_event_handler("on_transcription_message")
1887
- self._register_event_handler("on_recording_started")
1888
- self._register_event_handler("on_recording_stopped")
1889
- self._register_event_handler("on_recording_error")
1890
-
1891
- #
1892
- # BaseTransport
1893
- #
1894
-
1895
- def input(self) -> DailyInputTransport:
1896
- """Get the input transport for receiving media and events.
1897
-
1898
- Returns:
1899
- The Daily input transport instance.
1900
- """
1901
- if not self._input:
1902
- self._input = DailyInputTransport(
1903
- self, self._client, self._params, name=self._input_name
1904
- )
1905
- return self._input
1906
-
1907
- def output(self) -> DailyOutputTransport:
1908
- """Get the output transport for sending media and events.
1909
-
1910
- Returns:
1911
- The Daily output transport instance.
1912
- """
1913
- if not self._output:
1914
- self._output = DailyOutputTransport(
1915
- self, self._client, self._params, name=self._output_name
1916
- )
1917
- return self._output
1918
-
1919
- #
1920
- # DailyTransport
1921
- #
1922
-
1923
- @property
1924
- def room_url(self) -> str:
1925
- """Get the Daily room URL.
1926
-
1927
- Returns:
1928
- The room URL this transport is connected to.
1929
- """
1930
- return self._client.room_url
1931
-
1932
- @property
1933
- def participant_id(self) -> str:
1934
- """Get the participant ID for this transport.
1935
-
1936
- Returns:
1937
- The participant ID assigned by Daily.
1938
- """
1939
- return self._client.participant_id
1940
-
1941
- def set_log_level(self, level: DailyLogLevel):
1942
- """Set the logging level for Daily's internal logging system.
1943
-
1944
- Args:
1945
- level: The log level to set. Should be a member of the DailyLogLevel enum,
1946
- such as DailyLogLevel.Info, DailyLogLevel.Debug, etc.
1947
-
1948
- Example:
1949
- transport.set_log_level(DailyLogLevel.Info)
1950
- """
1951
- Daily.set_log_level(level)
1952
-
1953
- async def send_image(self, frame: OutputImageRawFrame | SpriteFrame):
1954
- """Send an image frame to the Daily call.
1955
-
1956
- Args:
1957
- frame: The image frame to send.
1958
- """
1959
- if self._output:
1960
- await self._output.queue_frame(frame, FrameDirection.DOWNSTREAM)
1961
-
1962
- async def send_audio(self, frame: OutputAudioRawFrame):
1963
- """Send an audio frame to the Daily call.
1964
-
1965
- Args:
1966
- frame: The audio frame to send.
1967
- """
1968
- if self._output:
1969
- await self._output.queue_frame(frame, FrameDirection.DOWNSTREAM)
1970
-
1971
- def participants(self):
1972
- """Get current participants in the room.
1973
-
1974
- Returns:
1975
- Dictionary of participants keyed by participant ID.
1976
- """
1977
- return self._client.participants()
1978
-
1979
- def participant_counts(self):
1980
- """Get participant count information.
1981
-
1982
- Returns:
1983
- Dictionary with participant count details.
1984
- """
1985
- return self._client.participant_counts()
1986
-
1987
- async def start_dialout(self, settings=None):
1988
- """Start a dial-out call to a phone number.
1989
-
1990
- Args:
1991
- settings: Dial-out configuration settings.
1992
- """
1993
- await self._client.start_dialout(settings)
1994
-
1995
- async def stop_dialout(self, participant_id):
1996
- """Stop a dial-out call for a specific participant.
1997
-
1998
- Args:
1999
- participant_id: ID of the participant to stop dial-out for.
2000
- """
2001
- await self._client.stop_dialout(participant_id)
2002
-
2003
- async def send_dtmf(self, settings):
2004
- """Send DTMF tones during a call (deprecated).
2005
-
2006
- .. deprecated:: 0.0.69
2007
- Push an `OutputDTMFFrame` or an `OutputDTMFUrgentFrame` instead.
2008
-
2009
- Args:
2010
- settings: DTMF settings including tones and target session.
2011
- """
2012
- import warnings
2013
-
2014
- with warnings.catch_warnings():
2015
- warnings.simplefilter("always")
2016
- warnings.warn(
2017
- "`DailyTransport.send_dtmf()` is deprecated, push an `OutputDTMFFrame` or an `OutputDTMFUrgentFrame` instead.",
2018
- DeprecationWarning,
2019
- )
2020
- await self._client.send_dtmf(settings)
2021
-
2022
- async def sip_call_transfer(self, settings):
2023
- """Transfer a SIP call to another destination.
2024
-
2025
- Args:
2026
- settings: SIP call transfer settings.
2027
- """
2028
- await self._client.sip_call_transfer(settings)
2029
-
2030
- async def sip_refer(self, settings):
2031
- """Send a SIP REFER request.
2032
-
2033
- Args:
2034
- settings: SIP REFER settings.
2035
- """
2036
- await self._client.sip_refer(settings)
2037
-
2038
- async def start_recording(self, streaming_settings=None, stream_id=None, force_new=None):
2039
- """Start recording the call.
2040
-
2041
- Args:
2042
- streaming_settings: Recording configuration settings.
2043
- stream_id: Unique identifier for the recording stream.
2044
- force_new: Whether to force a new recording session.
2045
- """
2046
- await self._client.start_recording(streaming_settings, stream_id, force_new)
2047
-
2048
- async def stop_recording(self, stream_id=None):
2049
- """Stop recording the call.
2050
-
2051
- Args:
2052
- stream_id: Unique identifier for the recording stream to stop.
2053
- """
2054
- await self._client.stop_recording(stream_id)
2055
-
2056
- async def start_transcription(self, settings=None):
2057
- """Start transcription for the call.
2058
-
2059
- Args:
2060
- settings: Transcription configuration settings.
2061
- """
2062
- await self._client.start_transcription(settings)
2063
-
2064
- async def stop_transcription(self):
2065
- """Stop transcription for the call."""
2066
- await self._client.stop_transcription()
2067
-
2068
- async def send_prebuilt_chat_message(self, message: str, user_name: Optional[str] = None):
2069
- """Send a chat message to Daily's Prebuilt main room.
2070
-
2071
- Args:
2072
- message: The chat message to send.
2073
- user_name: Optional user name that will appear as sender of the message.
2074
- """
2075
- await self._client.send_prebuilt_chat_message(message, user_name)
2076
-
2077
- async def capture_participant_transcription(self, participant_id: str):
2078
- """Enable transcription capture for a specific participant.
2079
-
2080
- Args:
2081
- participant_id: ID of the participant to capture transcription for.
2082
- """
2083
- await self._client.capture_participant_transcription(participant_id)
2084
-
2085
- async def capture_participant_audio(
2086
- self,
2087
- participant_id: str,
2088
- audio_source: str = "microphone",
2089
- sample_rate: int = 16000,
2090
- ):
2091
- """Capture audio from a specific participant.
2092
-
2093
- Args:
2094
- participant_id: ID of the participant to capture audio from.
2095
- audio_source: Audio source to capture from.
2096
- sample_rate: Desired sample rate for audio capture.
2097
- """
2098
- if self._input:
2099
- await self._input.capture_participant_audio(participant_id, audio_source, sample_rate)
2100
-
2101
- async def capture_participant_video(
2102
- self,
2103
- participant_id: str,
2104
- framerate: int = 30,
2105
- video_source: str = "camera",
2106
- color_format: str = "RGB",
2107
- ):
2108
- """Capture video from a specific participant.
2109
-
2110
- Args:
2111
- participant_id: ID of the participant to capture video from.
2112
- framerate: Desired framerate for video capture.
2113
- video_source: Video source to capture from.
2114
- color_format: Color format for video frames.
2115
- """
2116
- if self._input:
2117
- await self._input.capture_participant_video(
2118
- participant_id, framerate, video_source, color_format
2119
- )
2120
-
2121
- async def update_publishing(self, publishing_settings: Mapping[str, Any]):
2122
- """Update media publishing settings.
2123
-
2124
- Args:
2125
- publishing_settings: Publishing configuration settings.
2126
- """
2127
- await self._client.update_publishing(publishing_settings=publishing_settings)
2128
-
2129
- async def update_subscriptions(self, participant_settings=None, profile_settings=None):
2130
- """Update media subscription settings.
2131
-
2132
- Args:
2133
- participant_settings: Per-participant subscription settings.
2134
- profile_settings: Global subscription profile settings.
2135
- """
2136
- await self._client.update_subscriptions(
2137
- participant_settings=participant_settings, profile_settings=profile_settings
2138
- )
2139
-
2140
- async def update_remote_participants(self, remote_participants: Mapping[str, Any]):
2141
- """Update settings for remote participants.
2142
-
2143
- Args:
2144
- remote_participants: Remote participant configuration settings.
2145
- """
2146
- await self._client.update_remote_participants(remote_participants=remote_participants)
2147
-
2148
- async def _on_active_speaker_changed(self, participant: Any):
2149
- """Handle active speaker change events."""
2150
- await self._call_event_handler("on_active_speaker_changed", participant)
2151
-
2152
- async def _on_joined(self, data):
2153
- """Handle room joined events."""
2154
- await self._call_event_handler("on_joined", data)
2155
-
2156
- async def _on_left(self):
2157
- """Handle room left events."""
2158
- await self._call_event_handler("on_left")
2159
-
2160
- async def _on_error(self, error):
2161
- """Handle error events and push error frames."""
2162
- await self._call_event_handler("on_error", error)
2163
- # Push error frame to notify the pipeline
2164
- error_frame = ErrorFrame(error)
2165
-
2166
- if self._input:
2167
- await self._input.push_error(error_frame)
2168
- elif self._output:
2169
- await self._output.push_error(error_frame)
2170
- else:
2171
- logger.error("Both input and output are None while trying to push error")
2172
- raise Exception("No valid input or output channel to push error")
2173
-
2174
- async def _on_app_message(self, message: Any, sender: str):
2175
- """Handle application message events."""
2176
- if self._input:
2177
- await self._input.push_app_message(message, sender)
2178
- await self._call_event_handler("on_app_message", message, sender)
2179
-
2180
- async def _on_call_state_updated(self, state: str):
2181
- """Handle call state update events."""
2182
- await self._call_event_handler("on_call_state_updated", state)
2183
-
2184
- async def _on_client_connected(self, participant: Any):
2185
- """Handle client connected events."""
2186
- await self._call_event_handler("on_client_connected", participant)
2187
-
2188
- async def _on_client_disconnected(self, participant: Any):
2189
- """Handle client disconnected events."""
2190
- await self._call_event_handler("on_client_disconnected", participant)
2191
-
2192
- async def _handle_dialin_ready(self, sip_endpoint: str):
2193
- """Handle dial-in ready events by updating SIP configuration."""
2194
- if not self._params.dialin_settings:
2195
- return
2196
-
2197
- async with aiohttp.ClientSession() as session:
2198
- headers = {
2199
- "Authorization": f"Bearer {self._params.api_key}",
2200
- "Content-Type": "application/json",
2201
- }
2202
- data = {
2203
- "callId": self._params.dialin_settings.call_id,
2204
- "callDomain": self._params.dialin_settings.call_domain,
2205
- "sipUri": sip_endpoint,
2206
- }
2207
-
2208
- url = f"{self._params.api_url}/dialin/pinlessCallUpdate"
2209
-
2210
- try:
2211
- async with session.post(
2212
- url, headers=headers, json=data, timeout=aiohttp.ClientTimeout(total=10)
2213
- ) as r:
2214
- if r.status != 200:
2215
- text = await r.text()
2216
- logger.error(
2217
- f"Unable to handle dialin-ready event (status: {r.status}, error: {text})"
2218
- )
2219
- return
2220
-
2221
- logger.debug("Event dialin-ready was handled successfully")
2222
- except asyncio.TimeoutError:
2223
- logger.error(f"Timeout handling dialin-ready event ({url})")
2224
- except Exception as e:
2225
- logger.exception(f"Error handling dialin-ready event ({url}): {e}")
2226
-
2227
- async def _on_dialin_connected(self, data):
2228
- """Handle dial-in connected events."""
2229
- await self._call_event_handler("on_dialin_connected", data)
2230
-
2231
- async def _on_dialin_ready(self, sip_endpoint):
2232
- """Handle dial-in ready events."""
2233
- if self._params.dialin_settings:
2234
- await self._handle_dialin_ready(sip_endpoint)
2235
- await self._call_event_handler("on_dialin_ready", sip_endpoint)
2236
-
2237
- async def _on_dialin_stopped(self, data):
2238
- """Handle dial-in stopped events."""
2239
- await self._call_event_handler("on_dialin_stopped", data)
2240
-
2241
- async def _on_dialin_error(self, data):
2242
- """Handle dial-in error events."""
2243
- await self._call_event_handler("on_dialin_error", data)
2244
-
2245
- async def _on_dialin_warning(self, data):
2246
- """Handle dial-in warning events."""
2247
- await self._call_event_handler("on_dialin_warning", data)
2248
-
2249
- async def _on_dialout_answered(self, data):
2250
- """Handle dial-out answered events."""
2251
- await self._call_event_handler("on_dialout_answered", data)
2252
-
2253
- async def _on_dialout_connected(self, data):
2254
- """Handle dial-out connected events."""
2255
- await self._call_event_handler("on_dialout_connected", data)
2256
-
2257
- async def _on_dialout_stopped(self, data):
2258
- """Handle dial-out stopped events."""
2259
- await self._call_event_handler("on_dialout_stopped", data)
2260
-
2261
- async def _on_dialout_error(self, data):
2262
- """Handle dial-out error events."""
2263
- await self._call_event_handler("on_dialout_error", data)
2264
-
2265
- async def _on_dialout_warning(self, data):
2266
- """Handle dial-out warning events."""
2267
- await self._call_event_handler("on_dialout_warning", data)
2268
-
2269
- async def _on_participant_joined(self, participant):
2270
- """Handle participant joined events."""
2271
- id = participant["id"]
2272
- logger.info(f"Participant joined {id}")
2273
-
2274
- if self._input and self._params.audio_in_enabled and self._params.audio_in_user_tracks:
2275
- await self._input.capture_participant_audio(
2276
- id, "microphone", self._client.in_sample_rate
2277
- )
2278
-
2279
- if not self._other_participant_has_joined:
2280
- self._other_participant_has_joined = True
2281
- await self._call_event_handler("on_first_participant_joined", participant)
2282
-
2283
- await self._call_event_handler("on_participant_joined", participant)
2284
- # Also call on_client_connected for compatibility with other transports
2285
- await self._call_event_handler("on_client_connected", participant)
2286
-
2287
- async def _on_participant_left(self, participant, reason):
2288
- """Handle participant left events."""
2289
- id = participant["id"]
2290
- logger.info(f"Participant left {id}")
2291
- await self._call_event_handler("on_participant_left", participant, reason)
2292
- # Also call on_client_disconnected for compatibility with other transports
2293
- await self._call_event_handler("on_client_disconnected", participant)
2294
-
2295
- async def _on_participant_updated(self, participant):
2296
- """Handle participant updated events."""
2297
- await self._call_event_handler("on_participant_updated", participant)
2298
-
2299
- async def _on_transcription_message(self, message):
2300
- """Handle transcription message events."""
2301
- await self._call_event_handler("on_transcription_message", message)
2302
-
2303
- participant_id = ""
2304
- if "participantId" in message:
2305
- participant_id = message["participantId"]
2306
- if not participant_id:
2307
- return
2308
-
2309
- text = message["text"]
2310
- timestamp = message["timestamp"]
2311
- is_final = message["rawResponse"]["is_final"]
2312
- try:
2313
- language = message["rawResponse"]["channel"]["alternatives"][0]["languages"][0]
2314
- language = Language(language)
2315
- except KeyError:
2316
- language = None
2317
- if is_final:
2318
- frame = TranscriptionFrame(text, participant_id, timestamp, language, result=message)
2319
- logger.debug(f"Transcription (from: {participant_id}): [{text}]")
2320
- else:
2321
- frame = InterimTranscriptionFrame(
2322
- text,
2323
- participant_id,
2324
- timestamp,
2325
- language,
2326
- result=message,
2327
- )
2328
-
2329
- if self._input:
2330
- await self._input.push_transcription_frame(frame)
2331
-
2332
- async def _on_transcription_stopped(self, stopped_by, stopped_by_error):
2333
- """Handle transcription stopped events."""
2334
- await self._call_event_handler("on_transcription_stopped", stopped_by, stopped_by_error)
2335
-
2336
- async def _on_transcription_error(self, message):
2337
- """Handle transcription error events."""
2338
- await self._call_event_handler("on_transcription_error", message)
2339
-
2340
- async def _on_recording_started(self, status):
2341
- """Handle recording started events."""
2342
- await self._call_event_handler("on_recording_started", status)
2343
-
2344
- async def _on_recording_stopped(self, stream_id):
2345
- """Handle recording stopped events."""
2346
- await self._call_event_handler("on_recording_stopped", stream_id)
2347
-
2348
- async def _on_recording_error(self, stream_id, message):
2349
- """Handle recording error events."""
2350
- await self._call_event_handler("on_recording_error", stream_id, message)