teler 0.1.0__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.
teler/__init__.py ADDED
File without changes
teler/exceptions.py ADDED
@@ -0,0 +1,23 @@
1
+ class TelerException(Exception):
2
+ message = "An exception occurred."
3
+ code = 500
4
+
5
+ def __init__(self, msg: str = message):
6
+ super().__init__(msg)
7
+
8
+
9
+ class BadParameters(TelerException):
10
+ message = "Bad Parameter"
11
+ code = 400
12
+
13
+ def __init__(self, param: str = "", msg: str = message):
14
+ self.param = param
15
+ super().__init__(msg)
16
+
17
+
18
+ class NotImplemented(TelerException):
19
+ message = "Not implemented"
20
+ code = 501
21
+
22
+ def __init__(self, msg: str = message):
23
+ super().__init__(msg)
teler/streams.py ADDED
@@ -0,0 +1,122 @@
1
+ import asyncio
2
+ import contextlib
3
+ import logging
4
+ from enum import Enum
5
+ from typing import Awaitable, Callable, Tuple
6
+
7
+ import websockets
8
+
9
+ from teler import exceptions
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ class StreamType(Enum):
15
+ UNIDIRECTIONAL = 0
16
+ BIDIRECTIONAL = 1
17
+
18
+
19
+ class StreamOp(Enum):
20
+ RELAY = 0
21
+ PASS = 1
22
+ STOP = 2
23
+
24
+
25
+ StreamHandler = Callable[[str], Awaitable[Tuple[str, StreamOp]]]
26
+
27
+
28
+ class StreamConnector:
29
+ """
30
+ Media Stream Connector Interface.
31
+
32
+ Bridges the call stream to a remote websocket via pluggable handlers.
33
+ """
34
+
35
+ @staticmethod
36
+ async def _default_stream_handler(message: str) -> Tuple[str, StreamOp]:
37
+ return (message, StreamOp.RELAY)
38
+
39
+ def __init__(
40
+ self,
41
+ stream_type: StreamType = StreamType.BIDIRECTIONAL,
42
+ remote_url: str = "",
43
+ call_stream_handler: StreamHandler = _default_stream_handler,
44
+ remote_stream_handler: StreamHandler = _default_stream_handler,
45
+ ):
46
+ if stream_type == StreamType.UNIDIRECTIONAL:
47
+ raise exceptions.NotImplemented(
48
+ msg="Unidirectional streams are not supported yet."
49
+ )
50
+ if not remote_url:
51
+ raise exceptions.BadParameters(
52
+ param="remote_url", msg="remote_url is a required parameter."
53
+ )
54
+ self.stream_type = stream_type
55
+ self.remote_url = remote_url
56
+ self.call_stream_handler = call_stream_handler
57
+ self.remote_stream_handler = remote_stream_handler
58
+
59
+ async def bridge_stream(self, call_ws) -> None:
60
+ async with websockets.connect(self.remote_url) as remote_ws:
61
+
62
+ logger.info(f"StreamConnector: connected to {self.remote_url}")
63
+
64
+ async def call_stream() -> None:
65
+ async for message in call_ws.iter_text():
66
+ logger.debug(
67
+ f"StreamConnector: received message on call stream: {message}"
68
+ )
69
+ res = await self.call_stream_handler(message)
70
+ if not isinstance(res, tuple):
71
+ raise exceptions.BadParameters(
72
+ param="Stream handler response",
73
+ msg="Stream handler response must be a tuple of (str, StreamOp)",
74
+ )
75
+ data, stream_op = res
76
+ if stream_op == StreamOp.RELAY:
77
+ await remote_ws.send(data)
78
+ elif stream_op == StreamOp.STOP:
79
+ logger.info(
80
+ f"StreamConnector: Received STOP, closing call stream..."
81
+ )
82
+ await call_ws.close(
83
+ code=1000, reason="Stream stopped by client"
84
+ )
85
+ break
86
+
87
+ async def remote_stream() -> None:
88
+ async for message in remote_ws:
89
+ logger.debug(
90
+ f"StreamConnector: received message on remote stream: {message}"
91
+ )
92
+ res = await self.remote_stream_handler(message)
93
+ if not isinstance(res, tuple):
94
+ raise exceptions.BadParameters(
95
+ param="Stream handler response",
96
+ msg="Stream handler response must be a tuple of (str, StreamOp)",
97
+ )
98
+ data, stream_op = res
99
+ if stream_op == StreamOp.RELAY:
100
+ await call_ws.send_text(data)
101
+ elif stream_op == StreamOp.STOP:
102
+ logger.info(
103
+ f"StreamConnector: Received STOP, closing call stream..."
104
+ )
105
+ await call_ws.close(
106
+ code=1000, reason="Stream stopped by client"
107
+ )
108
+ break
109
+
110
+ done, pending = await asyncio.wait(
111
+ [
112
+ asyncio.create_task(call_stream()),
113
+ asyncio.create_task(remote_stream()),
114
+ ],
115
+ return_when=asyncio.FIRST_COMPLETED,
116
+ )
117
+ for t in pending:
118
+ t.cancel()
119
+ with contextlib.suppress(asyncio.CancelledError):
120
+ await t
121
+
122
+ logger.info("StreamConnector: closing remote stream")
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.4
2
+ Name: teler
3
+ Version: 0.1.0
4
+ Summary: A helper library for FreJun Teler
5
+ Author-email: FreJun <hello@frejun.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025, FreJun, Inc. <https://frejun.com/contact-us/>
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Description-Content-Type: text/markdown
28
+ License-File: LICENSE
29
+ Requires-Dist: websockets>=10.0
30
+ Dynamic: license-file
31
+
32
+ # Teler
33
+
34
+ This library offers a lightweight and developer-friendly abstraction over the FreJun Teler API.
35
+
36
+ ## Media Streaming
37
+
38
+ With the launch of the first minor version, the library introduces an intuitive interface for integrating real-time call audio streams from Teler into your application, unlocking advanced capabilities such as Conversational AI, Real-time transcription, and Actionable insights.
39
+
40
+ ### `StreamConnector`
41
+
42
+ This class lets you bridge the call audio stream to an endpoint of your choice. It handles the message relaying between the 2 streams via pluggable handlers, making it highly customizable.
43
+ It also handles graceful shutdown of the media streams in case of any unexpected errors.
44
+
45
+ It takes the following 4 parameters:
46
+
47
+ 1. **stream_type** - Only `StreamType.BIDIRECTIONAL` is supported for now.
48
+ 2. **remote_url** - The remote websocket URL where the call audio stream needs to be bridged.
49
+ 3. **call_stream_handler** - A `StreamHandler` coroutine that handles the call audio stream.
50
+ 4. **remote_stream_handler** - A `StreamHandler` coroutine that handles the remote audio stream.
51
+
52
+ ### `StreamHandler`
53
+
54
+ A `StreamHandler` coroutine receives the incoming messages on the websocket, processes them and returns a tuple of `(str, StreamOp)`. `StreamOp` is an operation flag that decides the subsequent action the `StreamConnector` will take.
55
+
56
+ `StreamOp` can be one of:
57
+
58
+ 1. **StreamOp.RELAY** - Relays the message to the other stream. The message needs to be supplied as a string as the first item in the returned tuple.
59
+ 2. **StreamOp.PASS** - Does not relay any message to the other stream. Any message in the returned tuple will be ignored.
60
+ 3. **StreamOp.STOP** - Stops both streams, ends the call and exits gracefully. Any message in the returned tuple will be ignored.
61
+
62
+ ### Sample Usage - FastAPI Echo Server
63
+
64
+ The following setup bridges the call audio stream to a dummy endpoint that echoes back all incoming messages. As a result, the caller will hear their own voice played back in real time, effectively creating an audio loopback.
65
+
66
+
67
+ ```python
68
+ import json
69
+ import logging
70
+
71
+ from fastapi import APIRouter, WebSocket, WebSocketDisconnect
72
+ from teler.streams import StreamConnector, StreamOp, StreamType
73
+
74
+
75
+ router = APIRouter()
76
+
77
+ logger = logging.getLogger(__name__)
78
+
79
+ TEST_WEBSOCKET_URL = "wss://{SERVER_DOMAIN}/test-remote-ws"
80
+
81
+
82
+ async def call_stream_handler(message: str):
83
+     msg = json.loads(message)
84
+     if msg["type"] == "audio":
85
+         payload = json.dumps(
86
+             {
87
+                 "type": "audio",
88
+                 "audio_b64": msg["data"]["audio_b64"],
89
+                 "chunk_id": msg["message_id"],
90
+             }
91
+         )
92
+         return (payload, StreamOp.RELAY)
93
+     return ({}, StreamOp.PASS)
94
+
95
+ async def remote_stream_handler(message: str):
96
+     msg = json.loads(message)
97
+     if msg["type"] == "audio":
98
+         payload = json.dumps(
99
+             {
100
+ "type": "audio",
101
+                 "audio_b64": msg["audio_b64"],
102
+                 "chunk_id": msg["chunk_id"],
103
+             }
104
+         )
105
+         return (payload, StreamOp.RELAY)
106
+     return ({}, StreamOp.PASS)
107
+    
108
+
109
+ connector = StreamConnector(
110
+     stream_type=StreamType.BIDIRECTIONAL,
111
+     remote_url=TEST_WEBSOCKET_URL,
112
+     call_stream_handler=call_stream_handler,
113
+     remote_stream_handler=remote_stream_handler,
114
+ )
115
+
116
+
117
+ @router.websocket("/media-stream")
118
+ async def handle_media_stream(websocket: WebSocket):
119
+     await websocket.accept()
120
+     logger.info("WebSocket connected.")
121
+     await connector.bridge_stream(websocket)
122
+
123
+
124
+ @router.websocket("/test-remote-ws")
125
+ async def test_remote_ws(websocket: WebSocket):
126
+     await websocket.accept()
127
+     logger.info("WebSocket connected.")
128
+     try:
129
+         async for data in websocket.iter_text():
130
+             await websocket.send_text(data)
131
+     except WebSocketDisconnect:
132
+         print("Client disconnected")
133
+ ```
@@ -0,0 +1,8 @@
1
+ teler/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
2
+ teler/exceptions.py,sha256=orz4vc3Y7TySZ4OGqgPIDYN-ZxwqeUDHUY0cdeukDVQ,550
3
+ teler/streams.py,sha256=rgJ1PPZKVa5nxLbxAKxXolB3VsMiSyo0kAjpXZPJ9OY,4550
4
+ teler-0.1.0.dist-info/licenses/LICENSE,sha256=7bsXT8rz2-iSmczpoWvXN8eARBgQo4oLDXr_l50XOIc,1122
5
+ teler-0.1.0.dist-info/METADATA,sha256=Qv8qGGpjnL22MksJArPL-9_83G4bVW-P49Z7ZQBu2ck,5641
6
+ teler-0.1.0.dist-info/WHEEL,sha256=zaaOINJESkSfm_4HQVc5ssNzHCPXhJm0kEUakpsEHaU,91
7
+ teler-0.1.0.dist-info/top_level.txt,sha256=XfMnYFGBhZwg5C7XMMLt5qxqmne_l2lDUG23LJhRoKQ,6
8
+ teler-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.8.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025, FreJun, Inc. <https://frejun.com/contact-us/>
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 @@
1
+ teler