dtelecom-server-sdk 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.
@@ -0,0 +1,273 @@
1
+ """Cloud speech sessions, file jobs, translation, vision and moderation."""
2
+
3
+ from collections.abc import AsyncIterator
4
+ from contextlib import asynccontextmanager
5
+ from typing import BinaryIO, Literal
6
+ from urllib.parse import urljoin, urlsplit, urlunsplit
7
+
8
+ import httpx
9
+
10
+ from .http import (
11
+ CloudHTTP,
12
+ check_response,
13
+ duration_to_minutes,
14
+ id_segment,
15
+ idempotency,
16
+ provided,
17
+ )
18
+ from .models import (
19
+ ExtendedSTTSession,
20
+ ExtendedTTSSession,
21
+ Moderation,
22
+ ModerationStreamTicket,
23
+ SpeechSession,
24
+ TranscriptionJob,
25
+ VisionSnapshot,
26
+ WavJob,
27
+ )
28
+ from .moderation import ModerationStream
29
+
30
+ MediaInput = bytes | BinaryIO
31
+
32
+
33
+ class Service:
34
+ def __init__(self, http: CloudHTTP):
35
+ self.http = http
36
+
37
+
38
+ class STTService(Service):
39
+ async def create_session(
40
+ self,
41
+ duration: str | float,
42
+ *,
43
+ language: str | None = None,
44
+ webrtc_session_id: str | None = None,
45
+ ) -> SpeechSession:
46
+ body = provided(
47
+ duration_minutes=duration_to_minutes(duration),
48
+ language=language,
49
+ webrtc_session_id=webrtc_session_id,
50
+ )
51
+ return SpeechSession.model_validate(
52
+ await self.http.json("POST", "/v1/stt/session", json=body)
53
+ )
54
+
55
+ async def extend(
56
+ self, session_id: str, additional: str | float
57
+ ) -> ExtendedSTTSession:
58
+ body = {
59
+ "session_id": session_id,
60
+ "additional_minutes": duration_to_minutes(additional),
61
+ }
62
+ return ExtendedSTTSession.model_validate(
63
+ await self.http.json("POST", "/v1/stt/session/extend", json=body)
64
+ )
65
+
66
+ extend_session = extend
67
+
68
+
69
+ class TTSService(Service):
70
+ async def create_session(
71
+ self,
72
+ max_characters: int,
73
+ *,
74
+ language: str | None = None,
75
+ voice: str | None = None,
76
+ webrtc_session_id: str | None = None,
77
+ ) -> SpeechSession:
78
+ body = provided(
79
+ max_characters=max_characters,
80
+ language=language,
81
+ voice=voice,
82
+ webrtc_session_id=webrtc_session_id,
83
+ )
84
+ return SpeechSession.model_validate(
85
+ await self.http.json("POST", "/v1/tts/session", json=body)
86
+ )
87
+
88
+ async def extend(
89
+ self, session_id: str, additional_characters: int
90
+ ) -> ExtendedTTSSession:
91
+ body = {
92
+ "session_id": session_id,
93
+ "additional_characters": additional_characters,
94
+ }
95
+ return ExtendedTTSSession.model_validate(
96
+ await self.http.json("POST", "/v1/tts/session/extend", json=body)
97
+ )
98
+
99
+ extend_session = extend
100
+
101
+
102
+ class TranscriptionsService(Service):
103
+ path = "/v1/transcriptions/jobs"
104
+
105
+ async def create(
106
+ self,
107
+ file: MediaInput,
108
+ *,
109
+ idempotency_key: str,
110
+ filename: str = "audio.media",
111
+ language: str | None = None,
112
+ diarize: bool | None = None,
113
+ ) -> TranscriptionJob:
114
+ fields = provided(
115
+ language=language,
116
+ diarize=str(diarize).lower() if diarize is not None else None,
117
+ )
118
+ data = await self.http.json(
119
+ "POST",
120
+ self.path,
121
+ data=fields,
122
+ files={"file": (filename, file)},
123
+ headers=idempotency(idempotency_key, file=True),
124
+ )
125
+ return TranscriptionJob.model_validate(data)
126
+
127
+ async def get(self, job_id: str) -> TranscriptionJob:
128
+ return TranscriptionJob.model_validate(
129
+ await self.http.json("GET", f"{self.path}/{id_segment(job_id)}")
130
+ )
131
+
132
+ async def delete(self, job_id: str) -> TranscriptionJob:
133
+ return TranscriptionJob.model_validate(
134
+ await self.http.json("DELETE", f"{self.path}/{id_segment(job_id)}")
135
+ )
136
+
137
+
138
+ class WavService(Service):
139
+ path = "/v1/tts/jobs"
140
+
141
+ async def create(
142
+ self,
143
+ text: str,
144
+ *,
145
+ idempotency_key: str,
146
+ voice: str | None = None,
147
+ language: str | None = None,
148
+ speed: float | None = None,
149
+ input_format: Literal["text", "ssml"] | None = None,
150
+ dictionary: dict[str, dict[str, str]] | None = None,
151
+ watermark: bool | None = None,
152
+ ) -> WavJob:
153
+ fields = provided(
154
+ text=text,
155
+ voice=voice,
156
+ language=language,
157
+ speed=speed,
158
+ input_format=input_format,
159
+ dictionary=dictionary,
160
+ watermark=watermark,
161
+ )
162
+ data = await self.http.json(
163
+ "POST",
164
+ self.path,
165
+ json=fields,
166
+ headers=idempotency(idempotency_key, file=True),
167
+ )
168
+ return WavJob.model_validate(data)
169
+
170
+ async def get(self, job_id: str) -> WavJob:
171
+ return WavJob.model_validate(
172
+ await self.http.json("GET", f"{self.path}/{id_segment(job_id)}")
173
+ )
174
+
175
+ async def delete(self, job_id: str) -> WavJob:
176
+ return WavJob.model_validate(
177
+ await self.http.json("DELETE", f"{self.path}/{id_segment(job_id)}")
178
+ )
179
+
180
+ @asynccontextmanager
181
+ async def download(self, job_id: str) -> AsyncIterator[httpx.Response]:
182
+ """Use async with and consume response.aiter_bytes() or await response.aread()."""
183
+ url = self.http.base_url + f"{self.path}/{id_segment(job_id)}/audio"
184
+ async with self.http.client.stream(
185
+ "GET", url, headers=self.http.headers(), follow_redirects=False
186
+ ) as response:
187
+ if not response.is_success:
188
+ await response.aread()
189
+ check_response(response)
190
+ yield response
191
+
192
+
193
+ class VisionService(Service):
194
+ async def snapshot(
195
+ self,
196
+ image: MediaInput,
197
+ *,
198
+ idempotency_key: str,
199
+ question: str | None = None,
200
+ source: Literal["camera", "screen"] | None = None,
201
+ webrtc_session_id: str | None = None,
202
+ ) -> VisionSnapshot:
203
+ data = await self.http.json(
204
+ "POST",
205
+ "/v1/vision/snapshot",
206
+ files={"image": ("image.media", image)},
207
+ data=provided(
208
+ question=question, source=source, session_id=webrtc_session_id
209
+ ),
210
+ headers=idempotency(idempotency_key),
211
+ )
212
+ return VisionSnapshot.model_validate(data)
213
+
214
+ async def get(self, request_id: str) -> VisionSnapshot:
215
+ return VisionSnapshot.model_validate(
216
+ await self.http.json("GET", f"/v1/vision/requests/{id_segment(request_id)}")
217
+ )
218
+
219
+
220
+ class ModerationService(Service):
221
+ async def audio(
222
+ self,
223
+ audio: MediaInput,
224
+ *,
225
+ idempotency_key: str,
226
+ language: str | None = None,
227
+ webrtc_session_id: str | None = None,
228
+ ) -> Moderation:
229
+ data = await self.http.json(
230
+ "POST",
231
+ "/v1/moderation/audio",
232
+ files={"audio": ("media.bin", audio)},
233
+ data=provided(session_id=webrtc_session_id, language=language),
234
+ headers=idempotency(idempotency_key),
235
+ )
236
+ return Moderation.model_validate(data)
237
+
238
+ async def video_frame(
239
+ self,
240
+ image: MediaInput,
241
+ *,
242
+ idempotency_key: str,
243
+ webrtc_session_id: str | None = None,
244
+ ) -> Moderation:
245
+ data = await self.http.json(
246
+ "POST",
247
+ "/v1/moderation/video-frame",
248
+ files={"image": ("media.bin", image)},
249
+ data=provided(session_id=webrtc_session_id),
250
+ headers=idempotency(idempotency_key),
251
+ )
252
+ return Moderation.model_validate(data)
253
+
254
+ async def get(self, request_id: str) -> Moderation:
255
+ return Moderation.model_validate(
256
+ await self.http.json(
257
+ "GET", f"/v1/moderation/requests/{id_segment(request_id)}"
258
+ )
259
+ )
260
+
261
+ async def stream_ticket(self) -> ModerationStreamTicket:
262
+ data = await self.http.json("POST", "/v1/moderation/streams")
263
+ path = urlsplit(data.pop("websocket_path"))
264
+ if path.netloc or path.scheme:
265
+ raise ValueError("expected a same-origin moderation WebSocket path")
266
+ url = urlsplit(urljoin(self.http.base_url, path.geturl()))
267
+ data["websocket_url"] = urlunsplit(
268
+ url._replace(scheme="wss" if url.scheme == "https" else "ws")
269
+ )
270
+ return ModerationStreamTicket.model_validate(data)
271
+
272
+ async def stream(self) -> ModerationStream:
273
+ return await ModerationStream.connect(await self.stream_ticket())