plivo-stream-sdk 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Plivo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,346 @@
1
+ Metadata-Version: 2.4
2
+ Name: plivo-stream-sdk
3
+ Version: 0.1.0
4
+ Summary: Official Python SDK for the Plivo Streaming API with asyncio, WebSockets and FastAPI support
5
+ Author-email: Plivo <sdks@plivo.com>
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/plivo/plivo-stream-sdk-python
8
+ Project-URL: Issues, https://github.com/plivo/plivo-stream-sdk-python/issues
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Programming Language :: Python :: 3.9
12
+ Classifier: Programming Language :: Python :: 3.10
13
+ Classifier: Programming Language :: Python :: 3.11
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Requires-Python: >=3.9
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: fastapi>=0.104.0
21
+ Requires-Dist: websockets>=12.0
22
+ Requires-Dist: pydantic>=2.0.0
23
+ Provides-Extra: dev
24
+ Requires-Dist: uvicorn[standard]>=0.24.0; extra == "dev"
25
+ Requires-Dist: deepgram-sdk>=5.3.0; extra == "dev"
26
+ Requires-Dist: plivo>=4.59.3; extra == "dev"
27
+ Requires-Dist: elevenlabs>=2.22.0; extra == "dev"
28
+ Requires-Dist: openai>=2.6.1; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # Python SDK for the Plivo Streaming API
32
+
33
+ ## Features
34
+ - **FastAPI Integration**: Native support for FastAPI WebSocket connections
35
+ - **WebSockets Library**: Support for the standard websockets library
36
+ - **Event-Driven**: Register callbacks/hooks for different events
37
+ - **Easy Media Handling**: Simple methods to send and receive media
38
+ - **Type-Safe**: Full type hints and Pydantic models for better IDE support
39
+ - **Modular Design**: Built to support multiple frameworks
40
+
41
+ ## Installation
42
+ ```bash
43
+ pip install plivo-stream-sdk
44
+ ```
45
+
46
+ For development (includes uvicorn for running examples):
47
+
48
+ ```bash
49
+ pip install -e[dev]
50
+ ```
51
+
52
+ ## Quick Start
53
+
54
+ ### FastAPI Example
55
+
56
+ ```python
57
+ from fastapi import FastAPI, WebSocket
58
+ from plivo_stream import PlivoFastAPIStreamingHandler, MediaEvent
59
+
60
+ app = FastAPI()
61
+
62
+ @app.websocket("/stream")
63
+ async def websocket_endpoint(websocket: WebSocket):
64
+ handler = PlivoFastAPIStreamingHandler(websocket)
65
+
66
+ @handler.on_connected
67
+ async def on_connect():
68
+ print("Client connected!")
69
+
70
+ @handler.on_media
71
+ async def on_media(event: MediaEvent):
72
+ audio_bytes = event.get_raw_media() # raw decoded bytes
73
+ print(f"Received {len(audio_bytes)} bytes at chunk {event.media.chunk}")
74
+
75
+ @handler.on_disconnected
76
+ async def on_disconnect():
77
+ print("Client disconnected!")
78
+
79
+ await handler.start()
80
+ ```
81
+
82
+ ### WebSockets Library Example
83
+
84
+ ```python
85
+ import asyncio
86
+ import websockets
87
+ from plivo_stream import PlivoWebsocketStreamingHandler
88
+ from plivo_stream import MediaEvent
89
+
90
+ async def create_handler(websocket):
91
+ handler = PlivoWebsocketStreamingHandler()
92
+
93
+ @handler.on_connected
94
+ async def on_connect():
95
+ print("Client connected!")
96
+
97
+ @handler.on_media
98
+ async def on_media(event: MediaEvent):
99
+ audio_bytes = event.get_raw_media()
100
+ print(f"Received {len(audio_bytes)} bytes")
101
+
102
+ @handler.on_disconnected
103
+ async def on_disconnect():
104
+ print("Client disconnected!")
105
+
106
+ await handler.handle(websocket)
107
+
108
+ async def main():
109
+ async with websockets.serve(create_handler, "0.0.0.0", 8000):
110
+ await asyncio.Future() # run forever
111
+
112
+ if __name__ == "__main__":
113
+ asyncio.run(main())
114
+ ```
115
+
116
+ ## Architecture
117
+
118
+ ![Plivo Streaming Architecture](doc/img/streaming_architecture.png)
119
+
120
+ The SDK acts as a bridge between Plivo's server and your application, handling bidirectional audio streaming.
121
+
122
+ ## Examples
123
+
124
+ * [Minimal Websocket example](examples/websockets_example.py)
125
+ * [Minimal FastAPI example](examples/fastapi_example.py)
126
+ * [Demo using FastAPI, Deepgram STT, ElevenLabs TTS, OpenAI LLM](examples/demo/README.md)
127
+
128
+ ## API Reference
129
+
130
+ ### PlivoFastAPIStreamingHandler
131
+
132
+ Main class for handling FastAPI WebSocket connections.
133
+
134
+ #### Initialization
135
+
136
+ ```python
137
+ handler = PlivoFastAPIStreamingHandler(websocket)
138
+ ```
139
+
140
+ #### Event Hooks
141
+
142
+ Register callbacks using decorators:
143
+
144
+ **`@handler.on_connected`**
145
+ Called when WebSocket connection is established.
146
+
147
+ ```python
148
+ @handler.on_connected
149
+ async def on_connect():
150
+ print("Connected!")
151
+ ```
152
+
153
+ **`@handler.on_disconnected`**
154
+ Called when WebSocket connection is closed.
155
+
156
+ ```python
157
+ @handler.on_disconnected
158
+ async def on_disconnect():
159
+ print("Disconnected!")
160
+ ```
161
+
162
+ **`@handler.on_media`**
163
+ Called when media (audio) data is received.
164
+
165
+ ```python
166
+ @handler.on_media
167
+ async def on_media(event: MediaEvent):
168
+ # Access Pydantic fields
169
+ print(event.media.track, event.media.timestamp, event.media.chunk)
170
+ # Get raw decoded audio bytes
171
+ audio_bytes = event.get_raw_media()
172
+ ```
173
+
174
+ **`@handler.on_start`**
175
+ Called when the stream starts; includes stream and call identifiers.
176
+
177
+ ```python
178
+ @handler.on_start
179
+ async def on_start(event: StartEvent):
180
+ print(f"Stream started: streamId={event.start.stream_id}, callId={event.start.call_id}")
181
+ ```
182
+
183
+ **`@handler.on_dtmf`**
184
+ Called when a DTMF tone is detected.
185
+
186
+ ```python
187
+ @handler.on_dtmf
188
+ async def on_dtmf(event: DtmfEvent):
189
+ print(f"DTMF received: {event.dtmf.digit}")
190
+ ```
191
+
192
+ **`@handler.on_played_stream`**
193
+ Called when buffered audio before a checkpoint has finished playing.
194
+
195
+ ```python
196
+ @handler.on_played_stream
197
+ async def on_played_stream(event: PlayedStreamEvent):
198
+ print(f"Checkpoint played: {event.name} on stream {event.stream_id}")
199
+ ```
200
+
201
+ **`@handler.on_cleared_audio`**
202
+ Called when the audio buffer is cleared.
203
+
204
+ ```python
205
+ @handler.on_cleared_audio
206
+ async def on_cleared_audio(event: ClearedAudioEvent):
207
+ print(f"Cleared audio on stream {event.stream_id}")
208
+ ```
209
+
210
+ **`@handler.on_event(event_type)`**
211
+ Called for specific Plivo event types.
212
+
213
+ ```python
214
+ @handler.on_event("start")
215
+ async def on_start(event: StreamEvent):
216
+ print(f"Stream started: {event.data}")
217
+ ```
218
+
219
+ **`@handler.on_error`**
220
+ Called when an error occurs.
221
+
222
+ ```python
223
+ @handler.on_error
224
+ async def on_error(error):
225
+ print(f"Error: {error}")
226
+ ```
227
+
228
+ #### Sending Methods
229
+
230
+ **`send_media(media_data)`**
231
+ Send media data through the WebSocket.
232
+
233
+ ```python
234
+ # raw PCM/mulaw bytes (SDK will base64-encode for you)
235
+ await handler.send_media(audio_bytes)
236
+
237
+ # optionally specify content type and sample rate
238
+ await handler.send_media(audio_bytes, content_type="audio/x-l16", sample_rate=16000)
239
+ ```
240
+
241
+ **`send_checkpoint(checkpoint_name)`**
242
+ Send a checkpoint event to track message processing.
243
+
244
+ ```python
245
+ await handler.send_checkpoint("processing_complete")
246
+ ```
247
+
248
+ **`send_clear_audio()`**
249
+ Clear the audio buffer on the stream.
250
+
251
+ ```python
252
+ await handler.send_clear_audio()
253
+ ```
254
+
255
+ **`send_json(data)`**
256
+ Send arbitrary JSON data.
257
+
258
+ ```python
259
+ await handler.send_json({"event": "custom", "data": "value"})
260
+ ```
261
+
262
+ **`send_text(message)`**
263
+ Send text message.
264
+
265
+ ```python
266
+ await handler.send_text("Hello")
267
+ ```
268
+
269
+ #### Lifecycle Methods
270
+
271
+ **`start()`**
272
+ Start the WebSocket listener loop. This should be awaited in your endpoint.
273
+
274
+ ```python
275
+ await handler.start()
276
+ ```
277
+
278
+ **`stop()`**
279
+ Stop the WebSocket listener and close the connection.
280
+
281
+ ```python
282
+ await handler.stop()
283
+ ```
284
+
285
+ ### PlivoWebsocketStreamingHandler
286
+
287
+ Main class for handling plain WebSocket connections using the websockets library.
288
+
289
+ #### Initialization
290
+
291
+ ```python
292
+ handler = PlivoWebsocketStreamingHandler()
293
+ ```
294
+
295
+ #### Event Hooks
296
+
297
+ Same decorator-based event hooks as PlivoFastAPIStreamingHandler:
298
+ - `@handler.on_connected`
299
+ - `@handler.on_disconnected`
300
+ - `@handler.on_media`
301
+ - `@handler.on_start`
302
+ - `@handler.on_dtmf`
303
+ - `@handler.on_played_stream`
304
+ - `@handler.on_cleared_audio`
305
+ - `@handler.on_event(event_type)`
306
+ - `@handler.on_error`
307
+
308
+ #### Sending Methods
309
+
310
+ Same methods as PlivoFastAPIStreamingHandler:
311
+ - `send_media(media_data)`
312
+ - `send_checkpoint(checkpoint_name)`
313
+ - `send_clear_audio()`
314
+ - `send_json(data)`
315
+ - `send_text(message)`
316
+
317
+ #### Lifecycle Methods
318
+
319
+ **`handle(websocket)`**
320
+ Handle a WebSocket connection. This should be called from your websockets.serve handler.
321
+
322
+ ```python
323
+ async def connection_handler(websocket):
324
+ await handler.handle(websocket)
325
+ ```
326
+
327
+ **`stop()`**
328
+ Stop the WebSocket listener and close the connection.
329
+
330
+ ```python
331
+ await handler.stop()
332
+ ```
333
+
334
+ ## Event Types
335
+
336
+ The SDK recognizes these Plivo Streaming API events:
337
+
338
+ - `connected` - WebSocket connection established
339
+ - `disconnected` - WebSocket connection closed
340
+ - `media` - Audio data received
341
+ - `start` - Stream started
342
+ - `error` - Error occurred
343
+ - `playedStream` - Audio events buffered before the Checkpoint were successfully played out to the end user
344
+ - `clearedAudio` - Cleared all buffered media events
345
+ - `dtmf` - Sent when someone presses a touch-tone number key in the inbound stream
346
+
@@ -0,0 +1,316 @@
1
+ # Python SDK for the Plivo Streaming API
2
+
3
+ ## Features
4
+ - **FastAPI Integration**: Native support for FastAPI WebSocket connections
5
+ - **WebSockets Library**: Support for the standard websockets library
6
+ - **Event-Driven**: Register callbacks/hooks for different events
7
+ - **Easy Media Handling**: Simple methods to send and receive media
8
+ - **Type-Safe**: Full type hints and Pydantic models for better IDE support
9
+ - **Modular Design**: Built to support multiple frameworks
10
+
11
+ ## Installation
12
+ ```bash
13
+ pip install plivo-stream-sdk
14
+ ```
15
+
16
+ For development (includes uvicorn for running examples):
17
+
18
+ ```bash
19
+ pip install -e[dev]
20
+ ```
21
+
22
+ ## Quick Start
23
+
24
+ ### FastAPI Example
25
+
26
+ ```python
27
+ from fastapi import FastAPI, WebSocket
28
+ from plivo_stream import PlivoFastAPIStreamingHandler, MediaEvent
29
+
30
+ app = FastAPI()
31
+
32
+ @app.websocket("/stream")
33
+ async def websocket_endpoint(websocket: WebSocket):
34
+ handler = PlivoFastAPIStreamingHandler(websocket)
35
+
36
+ @handler.on_connected
37
+ async def on_connect():
38
+ print("Client connected!")
39
+
40
+ @handler.on_media
41
+ async def on_media(event: MediaEvent):
42
+ audio_bytes = event.get_raw_media() # raw decoded bytes
43
+ print(f"Received {len(audio_bytes)} bytes at chunk {event.media.chunk}")
44
+
45
+ @handler.on_disconnected
46
+ async def on_disconnect():
47
+ print("Client disconnected!")
48
+
49
+ await handler.start()
50
+ ```
51
+
52
+ ### WebSockets Library Example
53
+
54
+ ```python
55
+ import asyncio
56
+ import websockets
57
+ from plivo_stream import PlivoWebsocketStreamingHandler
58
+ from plivo_stream import MediaEvent
59
+
60
+ async def create_handler(websocket):
61
+ handler = PlivoWebsocketStreamingHandler()
62
+
63
+ @handler.on_connected
64
+ async def on_connect():
65
+ print("Client connected!")
66
+
67
+ @handler.on_media
68
+ async def on_media(event: MediaEvent):
69
+ audio_bytes = event.get_raw_media()
70
+ print(f"Received {len(audio_bytes)} bytes")
71
+
72
+ @handler.on_disconnected
73
+ async def on_disconnect():
74
+ print("Client disconnected!")
75
+
76
+ await handler.handle(websocket)
77
+
78
+ async def main():
79
+ async with websockets.serve(create_handler, "0.0.0.0", 8000):
80
+ await asyncio.Future() # run forever
81
+
82
+ if __name__ == "__main__":
83
+ asyncio.run(main())
84
+ ```
85
+
86
+ ## Architecture
87
+
88
+ ![Plivo Streaming Architecture](doc/img/streaming_architecture.png)
89
+
90
+ The SDK acts as a bridge between Plivo's server and your application, handling bidirectional audio streaming.
91
+
92
+ ## Examples
93
+
94
+ * [Minimal Websocket example](examples/websockets_example.py)
95
+ * [Minimal FastAPI example](examples/fastapi_example.py)
96
+ * [Demo using FastAPI, Deepgram STT, ElevenLabs TTS, OpenAI LLM](examples/demo/README.md)
97
+
98
+ ## API Reference
99
+
100
+ ### PlivoFastAPIStreamingHandler
101
+
102
+ Main class for handling FastAPI WebSocket connections.
103
+
104
+ #### Initialization
105
+
106
+ ```python
107
+ handler = PlivoFastAPIStreamingHandler(websocket)
108
+ ```
109
+
110
+ #### Event Hooks
111
+
112
+ Register callbacks using decorators:
113
+
114
+ **`@handler.on_connected`**
115
+ Called when WebSocket connection is established.
116
+
117
+ ```python
118
+ @handler.on_connected
119
+ async def on_connect():
120
+ print("Connected!")
121
+ ```
122
+
123
+ **`@handler.on_disconnected`**
124
+ Called when WebSocket connection is closed.
125
+
126
+ ```python
127
+ @handler.on_disconnected
128
+ async def on_disconnect():
129
+ print("Disconnected!")
130
+ ```
131
+
132
+ **`@handler.on_media`**
133
+ Called when media (audio) data is received.
134
+
135
+ ```python
136
+ @handler.on_media
137
+ async def on_media(event: MediaEvent):
138
+ # Access Pydantic fields
139
+ print(event.media.track, event.media.timestamp, event.media.chunk)
140
+ # Get raw decoded audio bytes
141
+ audio_bytes = event.get_raw_media()
142
+ ```
143
+
144
+ **`@handler.on_start`**
145
+ Called when the stream starts; includes stream and call identifiers.
146
+
147
+ ```python
148
+ @handler.on_start
149
+ async def on_start(event: StartEvent):
150
+ print(f"Stream started: streamId={event.start.stream_id}, callId={event.start.call_id}")
151
+ ```
152
+
153
+ **`@handler.on_dtmf`**
154
+ Called when a DTMF tone is detected.
155
+
156
+ ```python
157
+ @handler.on_dtmf
158
+ async def on_dtmf(event: DtmfEvent):
159
+ print(f"DTMF received: {event.dtmf.digit}")
160
+ ```
161
+
162
+ **`@handler.on_played_stream`**
163
+ Called when buffered audio before a checkpoint has finished playing.
164
+
165
+ ```python
166
+ @handler.on_played_stream
167
+ async def on_played_stream(event: PlayedStreamEvent):
168
+ print(f"Checkpoint played: {event.name} on stream {event.stream_id}")
169
+ ```
170
+
171
+ **`@handler.on_cleared_audio`**
172
+ Called when the audio buffer is cleared.
173
+
174
+ ```python
175
+ @handler.on_cleared_audio
176
+ async def on_cleared_audio(event: ClearedAudioEvent):
177
+ print(f"Cleared audio on stream {event.stream_id}")
178
+ ```
179
+
180
+ **`@handler.on_event(event_type)`**
181
+ Called for specific Plivo event types.
182
+
183
+ ```python
184
+ @handler.on_event("start")
185
+ async def on_start(event: StreamEvent):
186
+ print(f"Stream started: {event.data}")
187
+ ```
188
+
189
+ **`@handler.on_error`**
190
+ Called when an error occurs.
191
+
192
+ ```python
193
+ @handler.on_error
194
+ async def on_error(error):
195
+ print(f"Error: {error}")
196
+ ```
197
+
198
+ #### Sending Methods
199
+
200
+ **`send_media(media_data)`**
201
+ Send media data through the WebSocket.
202
+
203
+ ```python
204
+ # raw PCM/mulaw bytes (SDK will base64-encode for you)
205
+ await handler.send_media(audio_bytes)
206
+
207
+ # optionally specify content type and sample rate
208
+ await handler.send_media(audio_bytes, content_type="audio/x-l16", sample_rate=16000)
209
+ ```
210
+
211
+ **`send_checkpoint(checkpoint_name)`**
212
+ Send a checkpoint event to track message processing.
213
+
214
+ ```python
215
+ await handler.send_checkpoint("processing_complete")
216
+ ```
217
+
218
+ **`send_clear_audio()`**
219
+ Clear the audio buffer on the stream.
220
+
221
+ ```python
222
+ await handler.send_clear_audio()
223
+ ```
224
+
225
+ **`send_json(data)`**
226
+ Send arbitrary JSON data.
227
+
228
+ ```python
229
+ await handler.send_json({"event": "custom", "data": "value"})
230
+ ```
231
+
232
+ **`send_text(message)`**
233
+ Send text message.
234
+
235
+ ```python
236
+ await handler.send_text("Hello")
237
+ ```
238
+
239
+ #### Lifecycle Methods
240
+
241
+ **`start()`**
242
+ Start the WebSocket listener loop. This should be awaited in your endpoint.
243
+
244
+ ```python
245
+ await handler.start()
246
+ ```
247
+
248
+ **`stop()`**
249
+ Stop the WebSocket listener and close the connection.
250
+
251
+ ```python
252
+ await handler.stop()
253
+ ```
254
+
255
+ ### PlivoWebsocketStreamingHandler
256
+
257
+ Main class for handling plain WebSocket connections using the websockets library.
258
+
259
+ #### Initialization
260
+
261
+ ```python
262
+ handler = PlivoWebsocketStreamingHandler()
263
+ ```
264
+
265
+ #### Event Hooks
266
+
267
+ Same decorator-based event hooks as PlivoFastAPIStreamingHandler:
268
+ - `@handler.on_connected`
269
+ - `@handler.on_disconnected`
270
+ - `@handler.on_media`
271
+ - `@handler.on_start`
272
+ - `@handler.on_dtmf`
273
+ - `@handler.on_played_stream`
274
+ - `@handler.on_cleared_audio`
275
+ - `@handler.on_event(event_type)`
276
+ - `@handler.on_error`
277
+
278
+ #### Sending Methods
279
+
280
+ Same methods as PlivoFastAPIStreamingHandler:
281
+ - `send_media(media_data)`
282
+ - `send_checkpoint(checkpoint_name)`
283
+ - `send_clear_audio()`
284
+ - `send_json(data)`
285
+ - `send_text(message)`
286
+
287
+ #### Lifecycle Methods
288
+
289
+ **`handle(websocket)`**
290
+ Handle a WebSocket connection. This should be called from your websockets.serve handler.
291
+
292
+ ```python
293
+ async def connection_handler(websocket):
294
+ await handler.handle(websocket)
295
+ ```
296
+
297
+ **`stop()`**
298
+ Stop the WebSocket listener and close the connection.
299
+
300
+ ```python
301
+ await handler.stop()
302
+ ```
303
+
304
+ ## Event Types
305
+
306
+ The SDK recognizes these Plivo Streaming API events:
307
+
308
+ - `connected` - WebSocket connection established
309
+ - `disconnected` - WebSocket connection closed
310
+ - `media` - Audio data received
311
+ - `start` - Stream started
312
+ - `error` - Error occurred
313
+ - `playedStream` - Audio events buffered before the Checkpoint were successfully played out to the end user
314
+ - `clearedAudio` - Cleared all buffered media events
315
+ - `dtmf` - Sent when someone presses a touch-tone number key in the inbound stream
316
+