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.
- dtelecom_server/__init__.py +43 -0
- dtelecom_server/_typing/livekit_egress_pb2.pyi +473 -0
- dtelecom_server/_typing/livekit_ingress_pb2.pyi +213 -0
- dtelecom_server/_typing/livekit_models_pb2.pyi +524 -0
- dtelecom_server/_typing/livekit_room_pb2.pyi +154 -0
- dtelecom_server/_typing/livekit_webhook_pb2.pyi +28 -0
- dtelecom_server/client.py +159 -0
- dtelecom_server/http.py +112 -0
- dtelecom_server/models.py +250 -0
- dtelecom_server/moderation.py +84 -0
- dtelecom_server/protocol/LICENSE +202 -0
- dtelecom_server/protocol/NOTICE +1 -0
- dtelecom_server/protocol/__init__.py +25 -0
- dtelecom_server/protocol/wire.pb +0 -0
- dtelecom_server/py.typed +0 -0
- dtelecom_server/room.py +298 -0
- dtelecom_server/services.py +273 -0
- dtelecom_server/speech.py +642 -0
- dtelecom_server/webhooks.py +148 -0
- dtelecom_server/wire.py +32 -0
- dtelecom_server_sdk-0.1.0.dist-info/METADATA +78 -0
- dtelecom_server_sdk-0.1.0.dist-info/RECORD +25 -0
- dtelecom_server_sdk-0.1.0.dist-info/WHEEL +4 -0
- dtelecom_server_sdk-0.1.0.dist-info/licenses/LICENSE +201 -0
- dtelecom_server_sdk-0.1.0.dist-info/licenses/NOTICE +9 -0
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
from . import livekit_models_pb2 as _livekit_models_pb2
|
|
2
|
+
from . import livekit_egress_pb2 as _livekit_egress_pb2
|
|
3
|
+
from . import livekit_ingress_pb2 as _livekit_ingress_pb2
|
|
4
|
+
from google.protobuf import descriptor as _descriptor
|
|
5
|
+
from google.protobuf import message as _message
|
|
6
|
+
from typing import ClassVar as _ClassVar, Mapping as _Mapping, Optional as _Optional, Union as _Union
|
|
7
|
+
|
|
8
|
+
DESCRIPTOR: _descriptor.FileDescriptor
|
|
9
|
+
|
|
10
|
+
class WebhookEvent(_message.Message):
|
|
11
|
+
__slots__ = ("event", "room", "participant", "egress_info", "ingress_info", "track", "id", "created_at")
|
|
12
|
+
EVENT_FIELD_NUMBER: _ClassVar[int]
|
|
13
|
+
ROOM_FIELD_NUMBER: _ClassVar[int]
|
|
14
|
+
PARTICIPANT_FIELD_NUMBER: _ClassVar[int]
|
|
15
|
+
EGRESS_INFO_FIELD_NUMBER: _ClassVar[int]
|
|
16
|
+
INGRESS_INFO_FIELD_NUMBER: _ClassVar[int]
|
|
17
|
+
TRACK_FIELD_NUMBER: _ClassVar[int]
|
|
18
|
+
ID_FIELD_NUMBER: _ClassVar[int]
|
|
19
|
+
CREATED_AT_FIELD_NUMBER: _ClassVar[int]
|
|
20
|
+
event: str
|
|
21
|
+
room: _livekit_models_pb2.Room
|
|
22
|
+
participant: _livekit_models_pb2.ParticipantInfo
|
|
23
|
+
egress_info: _livekit_egress_pb2.EgressInfo
|
|
24
|
+
ingress_info: _livekit_ingress_pb2.IngressInfo
|
|
25
|
+
track: _livekit_models_pb2.TrackInfo
|
|
26
|
+
id: str
|
|
27
|
+
created_at: int
|
|
28
|
+
def __init__(self, event: _Optional[str] = ..., room: _Optional[_Union[_livekit_models_pb2.Room, _Mapping]] = ..., participant: _Optional[_Union[_livekit_models_pb2.ParticipantInfo, _Mapping]] = ..., egress_info: _Optional[_Union[_livekit_egress_pb2.EgressInfo, _Mapping]] = ..., ingress_info: _Optional[_Union[_livekit_ingress_pb2.IngressInfo, _Mapping]] = ..., track: _Optional[_Union[_livekit_models_pb2.TrackInfo, _Mapping]] = ..., id: _Optional[str] = ..., created_at: _Optional[int] = ...) -> None: ...
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Async client for dTelecom Cloud."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from datetime import datetime
|
|
5
|
+
from typing import Self
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from .http import CloudHTTP, duration_to_minutes, id_segment, idempotency, provided
|
|
10
|
+
from .models import (
|
|
11
|
+
AdminToken,
|
|
12
|
+
ExtendedToken,
|
|
13
|
+
ParticipantToken,
|
|
14
|
+
SessionCharge,
|
|
15
|
+
SessionCharges,
|
|
16
|
+
TokenGrants,
|
|
17
|
+
Translation,
|
|
18
|
+
)
|
|
19
|
+
from .services import (
|
|
20
|
+
ModerationService,
|
|
21
|
+
STTService,
|
|
22
|
+
TranscriptionsService,
|
|
23
|
+
TTSService,
|
|
24
|
+
VisionService,
|
|
25
|
+
WavService,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class CloudClient:
|
|
30
|
+
def __init__(
|
|
31
|
+
self,
|
|
32
|
+
api_key: str | None = None,
|
|
33
|
+
api_secret: str | None = None,
|
|
34
|
+
base_url: str | None = None,
|
|
35
|
+
*,
|
|
36
|
+
http_client: httpx.AsyncClient | None = None,
|
|
37
|
+
):
|
|
38
|
+
key = api_key or os.getenv("DTELECOM_API_KEY")
|
|
39
|
+
secret = api_secret or os.getenv("DTELECOM_API_SECRET")
|
|
40
|
+
origin = base_url or os.getenv("DTELECOM_CLOUD_URL")
|
|
41
|
+
if not key or not secret or not origin:
|
|
42
|
+
raise ValueError(
|
|
43
|
+
"set DTELECOM_API_KEY, DTELECOM_API_SECRET and DTELECOM_CLOUD_URL"
|
|
44
|
+
)
|
|
45
|
+
self._owned = http_client is None
|
|
46
|
+
self.http = CloudHTTP(
|
|
47
|
+
http_client if http_client is not None else httpx.AsyncClient(timeout=30),
|
|
48
|
+
origin,
|
|
49
|
+
key,
|
|
50
|
+
secret,
|
|
51
|
+
)
|
|
52
|
+
self.stt = STTService(self.http)
|
|
53
|
+
self.tts = TTSService(self.http)
|
|
54
|
+
self.wav = WavService(self.http)
|
|
55
|
+
self.transcriptions = TranscriptionsService(self.http)
|
|
56
|
+
self.vision = VisionService(self.http)
|
|
57
|
+
self.moderation = ModerationService(self.http)
|
|
58
|
+
|
|
59
|
+
async def __aenter__(self) -> Self:
|
|
60
|
+
return self
|
|
61
|
+
|
|
62
|
+
async def __aexit__(self, *args) -> None:
|
|
63
|
+
await self.aclose()
|
|
64
|
+
|
|
65
|
+
async def aclose(self) -> None:
|
|
66
|
+
if self._owned:
|
|
67
|
+
await self.http.client.aclose()
|
|
68
|
+
|
|
69
|
+
async def create_token(
|
|
70
|
+
self,
|
|
71
|
+
room: str,
|
|
72
|
+
identity: str,
|
|
73
|
+
*,
|
|
74
|
+
name: str | None = None,
|
|
75
|
+
metadata: str | None = None,
|
|
76
|
+
ttl: str | float = "6h",
|
|
77
|
+
client_ip: str | None = None,
|
|
78
|
+
webhook_urls: list[str] | None = None,
|
|
79
|
+
grants: TokenGrants | None = None,
|
|
80
|
+
) -> ParticipantToken:
|
|
81
|
+
body = provided(
|
|
82
|
+
room_name=room,
|
|
83
|
+
identity=identity,
|
|
84
|
+
name=name,
|
|
85
|
+
metadata=metadata,
|
|
86
|
+
duration_minutes=duration_to_minutes(ttl),
|
|
87
|
+
client_ip=client_ip,
|
|
88
|
+
webhook_urls=webhook_urls,
|
|
89
|
+
grants=grants,
|
|
90
|
+
)
|
|
91
|
+
return ParticipantToken.model_validate(
|
|
92
|
+
await self.http.json("POST", "/v1/webrtc/token", json=body)
|
|
93
|
+
)
|
|
94
|
+
|
|
95
|
+
async def extend_token(
|
|
96
|
+
self, session_id: str, additional: str | float
|
|
97
|
+
) -> ExtendedToken:
|
|
98
|
+
body = {
|
|
99
|
+
"session_id": session_id,
|
|
100
|
+
"additional_minutes": duration_to_minutes(additional),
|
|
101
|
+
}
|
|
102
|
+
return ExtendedToken.model_validate(
|
|
103
|
+
await self.http.json("POST", "/v1/webrtc/token/extend", json=body)
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
async def admin_token(self, room: str) -> AdminToken:
|
|
107
|
+
data = await self.http.json(
|
|
108
|
+
"POST", "/v1/webrtc/admin-token", json={"room_name": room}
|
|
109
|
+
)
|
|
110
|
+
return AdminToken.model_validate(
|
|
111
|
+
{**data, "api_urls": data.get("api_urls") or []}
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
async def get_session(self, session_id: str) -> SessionCharge:
|
|
115
|
+
return SessionCharge.model_validate(
|
|
116
|
+
await self.http.json("GET", f"/v1/sessions/{id_segment(session_id)}")
|
|
117
|
+
)
|
|
118
|
+
|
|
119
|
+
async def list_sessions(
|
|
120
|
+
self, room: str, *, since: datetime | None = None, limit: int | None = None
|
|
121
|
+
) -> SessionCharges:
|
|
122
|
+
if since is not None and since.utcoffset() is None:
|
|
123
|
+
raise ValueError("since must include a timezone")
|
|
124
|
+
params = provided(
|
|
125
|
+
room=room, since=since.isoformat() if since else None, limit=limit
|
|
126
|
+
)
|
|
127
|
+
data = await self.http.json("GET", "/v1/sessions", params=params)
|
|
128
|
+
return SessionCharges.model_validate(
|
|
129
|
+
{**data, "sessions": data.get("sessions") or []}
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
def room_service(self) -> "RoomServiceClient":
|
|
133
|
+
from .room import RoomServiceClient
|
|
134
|
+
|
|
135
|
+
return RoomServiceClient(self)
|
|
136
|
+
|
|
137
|
+
async def translate(
|
|
138
|
+
self, q: str, target: str, *, idempotency_key: str, source: str | None = None
|
|
139
|
+
) -> Translation:
|
|
140
|
+
data = await self.http.json(
|
|
141
|
+
"POST",
|
|
142
|
+
"/v1/translation",
|
|
143
|
+
json=provided(q=q, target=target, source=source),
|
|
144
|
+
headers=idempotency(idempotency_key),
|
|
145
|
+
)
|
|
146
|
+
return Translation.model_validate(data)
|
|
147
|
+
|
|
148
|
+
async def get_translation(self, request_id: str) -> Translation:
|
|
149
|
+
return Translation.model_validate(
|
|
150
|
+
await self.http.json(
|
|
151
|
+
"GET", f"/v1/translation/requests/{id_segment(request_id)}"
|
|
152
|
+
)
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
from typing import TYPE_CHECKING
|
|
157
|
+
|
|
158
|
+
if TYPE_CHECKING:
|
|
159
|
+
from .room import RoomServiceClient
|
dtelecom_server/http.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""Transport for authenticated Cloud requests."""
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import re
|
|
5
|
+
from typing import Any
|
|
6
|
+
from urllib.parse import quote
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def duration_to_minutes(value: str | float) -> int:
|
|
12
|
+
if isinstance(value, str):
|
|
13
|
+
match = re.fullmatch(
|
|
14
|
+
r"\s*(\d+(?:\.\d+)?)\s*(s|secs?|seconds?|m|mins?|minutes?|h|hrs?|hours?|d|days?)?\s*",
|
|
15
|
+
value,
|
|
16
|
+
re.IGNORECASE,
|
|
17
|
+
)
|
|
18
|
+
if match is None:
|
|
19
|
+
raise ValueError("invalid duration")
|
|
20
|
+
unit = (match[2] or "s").lower()[0]
|
|
21
|
+
seconds = float(match[1]) * {"s": 1, "m": 60, "h": 3600, "d": 86400}[unit]
|
|
22
|
+
elif isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
23
|
+
seconds = value
|
|
24
|
+
else:
|
|
25
|
+
raise TypeError("duration must be seconds or a duration string")
|
|
26
|
+
if not math.isfinite(seconds) or not 0 < seconds <= 86400:
|
|
27
|
+
raise ValueError("duration must be positive and at most 24 hours")
|
|
28
|
+
return math.ceil(seconds / 60)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def id_segment(value: str) -> str:
|
|
32
|
+
if not value or value in (".", ".."):
|
|
33
|
+
raise ValueError("expected a resource ID")
|
|
34
|
+
return quote(value, safe="")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def idempotency(key: str, *, file: bool = False) -> dict[str, str]:
|
|
38
|
+
if re.fullmatch(r"[!-~]{1,128}" if file else r"[A-Za-z0-9_-]{1,128}", key) is None:
|
|
39
|
+
raise ValueError("invalid idempotency key")
|
|
40
|
+
return {"Idempotency-Key": key}
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def provided(**fields: Any) -> dict[str, Any]:
|
|
44
|
+
return {name: value for name, value in fields.items() if value is not None}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class CloudApiError(Exception):
|
|
48
|
+
def __init__(
|
|
49
|
+
self,
|
|
50
|
+
status: int,
|
|
51
|
+
code: str,
|
|
52
|
+
*,
|
|
53
|
+
retry_after: float | None = None,
|
|
54
|
+
request_id: str | None = None,
|
|
55
|
+
detail: dict | None = None,
|
|
56
|
+
):
|
|
57
|
+
super().__init__(f"dTelecom Cloud returned {status} {code}")
|
|
58
|
+
self.status = status
|
|
59
|
+
self.code = code
|
|
60
|
+
self.retry_after = retry_after
|
|
61
|
+
self.id = request_id
|
|
62
|
+
self.detail = detail
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def check_response(response: httpx.Response) -> None:
|
|
66
|
+
if response.is_success:
|
|
67
|
+
return
|
|
68
|
+
try:
|
|
69
|
+
data = response.json()
|
|
70
|
+
except ValueError:
|
|
71
|
+
data = {}
|
|
72
|
+
if not isinstance(data, dict):
|
|
73
|
+
data = {}
|
|
74
|
+
try:
|
|
75
|
+
retry = float(response.headers.get("retry-after", "0"))
|
|
76
|
+
except ValueError:
|
|
77
|
+
retry = 0
|
|
78
|
+
raise CloudApiError(
|
|
79
|
+
response.status_code,
|
|
80
|
+
data.get("error") or f"http_{response.status_code}",
|
|
81
|
+
request_id=data.get("id"),
|
|
82
|
+
detail=data.get("detail"),
|
|
83
|
+
retry_after=retry if math.isfinite(retry) and retry > 0 else None,
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
class CloudHTTP:
|
|
88
|
+
def __init__(
|
|
89
|
+
self, client: httpx.AsyncClient, base_url: str, api_key: str, api_secret: str
|
|
90
|
+
):
|
|
91
|
+
self.client = client
|
|
92
|
+
self.base_url = base_url.rstrip("/")
|
|
93
|
+
self._auth = f"Bearer {api_key}:{api_secret}"
|
|
94
|
+
|
|
95
|
+
def headers(self, extra: dict | None = None) -> dict:
|
|
96
|
+
return {"Authorization": self._auth, **(extra or {})}
|
|
97
|
+
|
|
98
|
+
async def request(
|
|
99
|
+
self, method: str, path: str, *, headers: dict | None = None, **kwargs
|
|
100
|
+
) -> httpx.Response:
|
|
101
|
+
response = await self.client.request(
|
|
102
|
+
method,
|
|
103
|
+
self.base_url + path,
|
|
104
|
+
headers=self.headers(headers),
|
|
105
|
+
follow_redirects=False,
|
|
106
|
+
**kwargs,
|
|
107
|
+
)
|
|
108
|
+
check_response(response)
|
|
109
|
+
return response
|
|
110
|
+
|
|
111
|
+
async def json(self, method: str, path: str, **kwargs) -> dict:
|
|
112
|
+
return (await self.request(method, path, **kwargs)).json()
|
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
"""Typed results from the dTelecom Cloud API. Monetary amounts retain wire precision."""
|
|
2
|
+
|
|
3
|
+
from datetime import datetime
|
|
4
|
+
from typing import Generic, Literal, TypedDict, TypeVar
|
|
5
|
+
|
|
6
|
+
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, model_validator
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Result(BaseModel):
|
|
10
|
+
model_config = ConfigDict(extra="allow", hide_input_in_errors=True)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class TokenGrants(TypedDict, total=False):
|
|
14
|
+
can_publish: bool
|
|
15
|
+
can_subscribe: bool
|
|
16
|
+
can_publish_data: bool
|
|
17
|
+
room_admin: bool
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ExtendedToken(Result):
|
|
21
|
+
token: str = Field(repr=False)
|
|
22
|
+
ws_url: str
|
|
23
|
+
fallback_urls: list[str]
|
|
24
|
+
expires_at: datetime = Field(
|
|
25
|
+
validation_alias=AliasChoices("expires_at", "new_expires_at")
|
|
26
|
+
)
|
|
27
|
+
region: str = ""
|
|
28
|
+
|
|
29
|
+
@model_validator(mode="before")
|
|
30
|
+
@classmethod
|
|
31
|
+
def legacy_urls(cls, data: dict) -> dict:
|
|
32
|
+
if data.get("fallback_urls") is None:
|
|
33
|
+
return {**data, "fallback_urls": [data["ws_url"]]}
|
|
34
|
+
return data
|
|
35
|
+
|
|
36
|
+
def client_fields(self) -> dict:
|
|
37
|
+
return {
|
|
38
|
+
"token": self.token,
|
|
39
|
+
"wsUrl": self.ws_url,
|
|
40
|
+
"fallbackUrls": self.fallback_urls,
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class ParticipantToken(ExtendedToken):
|
|
45
|
+
session_id: str
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
class AdminToken(Result):
|
|
49
|
+
token: str = Field(repr=False)
|
|
50
|
+
api_urls: list[str]
|
|
51
|
+
expires_at: datetime
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class SessionCharge(Result):
|
|
55
|
+
session_id: str
|
|
56
|
+
service: str
|
|
57
|
+
status: str
|
|
58
|
+
room_name: str | None = None
|
|
59
|
+
identity: str | None = None
|
|
60
|
+
webrtc_session_id: str | None = None
|
|
61
|
+
region: str | None = None
|
|
62
|
+
created_at: datetime
|
|
63
|
+
started_at: datetime | None = None
|
|
64
|
+
ended_at: datetime | None = None
|
|
65
|
+
characters: int | None = None
|
|
66
|
+
charged_microcredits: str
|
|
67
|
+
charged_usd: str
|
|
68
|
+
final: bool
|
|
69
|
+
covered_by_addon: bool
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SessionCharges(Result):
|
|
73
|
+
sessions: list[SessionCharge]
|
|
74
|
+
total_microcredits: str
|
|
75
|
+
total_usd: str
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
class ExtendedSTTSession(Result):
|
|
79
|
+
token: str = Field(repr=False)
|
|
80
|
+
expires_at: datetime = Field(
|
|
81
|
+
validation_alias=AliasChoices("expires_at", "new_expires_at")
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
@property
|
|
85
|
+
def session_key(self) -> str:
|
|
86
|
+
return self.token
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class ExtendedTTSSession(ExtendedSTTSession):
|
|
90
|
+
max_characters: int
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
class SpeechSession(ExtendedSTTSession):
|
|
94
|
+
session_id: str
|
|
95
|
+
server_url: str
|
|
96
|
+
stream_url: str
|
|
97
|
+
|
|
98
|
+
@model_validator(mode="before")
|
|
99
|
+
@classmethod
|
|
100
|
+
def legacy_url(cls, data: dict) -> dict:
|
|
101
|
+
if not data.get("stream_url"):
|
|
102
|
+
return {**data, "stream_url": data["server_url"].rstrip("/") + "/v1/stream"}
|
|
103
|
+
return data
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
class TranscriptionSegment(Result):
|
|
107
|
+
start: float
|
|
108
|
+
end: float
|
|
109
|
+
speaker: str | None = None
|
|
110
|
+
text: str
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class MediaInfo(Result):
|
|
114
|
+
sample_count: int
|
|
115
|
+
sample_rate: int
|
|
116
|
+
channels: int
|
|
117
|
+
duration_seconds: float
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class SpeakerSegment(Result):
|
|
121
|
+
start: float
|
|
122
|
+
end: float
|
|
123
|
+
speaker: str
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
class TranscriptionResult(Result):
|
|
127
|
+
text: str
|
|
128
|
+
language: str
|
|
129
|
+
segments: list[TranscriptionSegment]
|
|
130
|
+
media: MediaInfo
|
|
131
|
+
speaker_segments: list[SpeakerSegment] | None = None
|
|
132
|
+
speaker_labels: str | None = None
|
|
133
|
+
timing_type: str
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
class WavResult(Result):
|
|
137
|
+
characters: int
|
|
138
|
+
sample_rate: int
|
|
139
|
+
channels: int
|
|
140
|
+
encoding: str
|
|
141
|
+
samples: int
|
|
142
|
+
bytes: int
|
|
143
|
+
sha256: str
|
|
144
|
+
watermark: bool
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
class Job(Result):
|
|
148
|
+
id: str
|
|
149
|
+
status: str
|
|
150
|
+
error: str | None = None
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
class TranscriptionJob(Job):
|
|
154
|
+
duration_seconds: float | None = None
|
|
155
|
+
result: TranscriptionResult | None = None
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
class WavJob(Job):
|
|
159
|
+
characters: int | None = None
|
|
160
|
+
result: WavResult | None = None
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
class DetectedLanguage(Result):
|
|
164
|
+
language: str
|
|
165
|
+
confidence: float
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class TranslationUsage(Result):
|
|
169
|
+
characters: int
|
|
170
|
+
output_tokens: int | None = None
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class TranslationResult(Result):
|
|
174
|
+
translated_text: str
|
|
175
|
+
source: str
|
|
176
|
+
target: str
|
|
177
|
+
detected_language: DetectedLanguage | None = None
|
|
178
|
+
usage: TranslationUsage
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
class VisionResult(Result):
|
|
182
|
+
request_id: str
|
|
183
|
+
answer: str
|
|
184
|
+
model: str
|
|
185
|
+
generated_tokens: int
|
|
186
|
+
prompt_tokens: int
|
|
187
|
+
finish_reason: str
|
|
188
|
+
output_token_limit_reached: bool
|
|
189
|
+
usage: dict[str, int]
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
class ModerationEvidence(Result):
|
|
193
|
+
model: str
|
|
194
|
+
yes_probability: float
|
|
195
|
+
calibrated: bool
|
|
196
|
+
score_type: str
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
class ImageScreening(Result):
|
|
200
|
+
model: str
|
|
201
|
+
native_scores: dict[str, float]
|
|
202
|
+
calibrated: bool
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
class ModerationResult(Result):
|
|
206
|
+
policy: str
|
|
207
|
+
policy_version: str
|
|
208
|
+
evaluated_categories: list[str]
|
|
209
|
+
decision: Literal["pass", "flag"]
|
|
210
|
+
evidence: ModerationEvidence
|
|
211
|
+
image_screening: ImageScreening | None = None
|
|
212
|
+
transcript: str | None = None
|
|
213
|
+
language: str | None = None
|
|
214
|
+
usage: dict[str, int]
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
T = TypeVar("T")
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class InferenceRequest(Result, Generic[T]):
|
|
221
|
+
id: str
|
|
222
|
+
kind: str
|
|
223
|
+
status: Literal["running", "completed", "failed"]
|
|
224
|
+
charged_microcredits: str
|
|
225
|
+
result: T | None = None
|
|
226
|
+
error: str | None = None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
class Translation(InferenceRequest[TranslationResult]):
|
|
230
|
+
kind: Literal["translation"]
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
class VisionSnapshot(InferenceRequest[VisionResult]):
|
|
234
|
+
kind: Literal["vision"]
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
class Moderation(InferenceRequest[ModerationResult]):
|
|
238
|
+
kind: Literal["moderation-audio", "moderation-video"]
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
class ModerationStreamTicket(Result):
|
|
242
|
+
token: str = Field(repr=False)
|
|
243
|
+
websocket_url: str
|
|
244
|
+
expires_at: datetime
|
|
245
|
+
protocol: str
|
|
246
|
+
max_inflight: int
|
|
247
|
+
audio_format: str
|
|
248
|
+
sample_rate: int
|
|
249
|
+
channels: int
|
|
250
|
+
max_audio_seconds: int
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""Ticket-authenticated moderation WebSocket."""
|
|
2
|
+
|
|
3
|
+
import asyncio
|
|
4
|
+
import json
|
|
5
|
+
from typing import Self
|
|
6
|
+
|
|
7
|
+
from websockets.asyncio.client import ClientConnection, connect
|
|
8
|
+
|
|
9
|
+
from .http import CloudApiError, idempotency
|
|
10
|
+
from .models import Moderation, ModerationStreamTicket
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class ModerationStream:
|
|
14
|
+
def __init__(self, socket: ClientConnection):
|
|
15
|
+
self._socket = socket
|
|
16
|
+
self._busy = False
|
|
17
|
+
|
|
18
|
+
@classmethod
|
|
19
|
+
async def connect(cls, ticket: ModerationStreamTicket) -> Self:
|
|
20
|
+
socket = await connect(ticket.websocket_url, open_timeout=10)
|
|
21
|
+
try:
|
|
22
|
+
async with asyncio.timeout(10):
|
|
23
|
+
await socket.send(json.dumps({"type": "auth", "token": ticket.token}))
|
|
24
|
+
response = json.loads(await socket.recv())
|
|
25
|
+
if (
|
|
26
|
+
response.get("type") != "ready"
|
|
27
|
+
or response.get("protocol") != "dtelecom.moderation.v1"
|
|
28
|
+
):
|
|
29
|
+
raise RuntimeError("moderation service refused the handshake")
|
|
30
|
+
except BaseException:
|
|
31
|
+
await socket.close()
|
|
32
|
+
raise
|
|
33
|
+
return cls(socket)
|
|
34
|
+
|
|
35
|
+
async def __aenter__(self) -> Self:
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
async def __aexit__(self, *args) -> None:
|
|
39
|
+
await self.aclose()
|
|
40
|
+
|
|
41
|
+
async def aclose(self) -> None:
|
|
42
|
+
await self._socket.close()
|
|
43
|
+
|
|
44
|
+
async def send_audio(
|
|
45
|
+
self, idempotency_key: str, pcm: bytes, language: str = "en"
|
|
46
|
+
) -> Moderation:
|
|
47
|
+
if not pcm or len(pcm) > 960_000 or len(pcm) % 2:
|
|
48
|
+
raise ValueError("expected at most 30 seconds of PCM16 mono at 16 kHz")
|
|
49
|
+
return await self._send(idempotency_key, pcm, kind="audio", language=language)
|
|
50
|
+
|
|
51
|
+
async def send_video_frame(self, idempotency_key: str, image: bytes) -> Moderation:
|
|
52
|
+
if not image or len(image) > 6 * 1024 * 1024:
|
|
53
|
+
raise ValueError("expected a nonempty image up to 6 MiB")
|
|
54
|
+
return await self._send(idempotency_key, image, kind="video")
|
|
55
|
+
|
|
56
|
+
async def _send(self, key: str, data: bytes, **fields: str) -> Moderation:
|
|
57
|
+
idempotency(key)
|
|
58
|
+
if self._busy:
|
|
59
|
+
raise RuntimeError("await the previous moderation result first")
|
|
60
|
+
self._busy = True
|
|
61
|
+
try:
|
|
62
|
+
async with asyncio.timeout(35):
|
|
63
|
+
await self._socket.send(json.dumps({"id": key, **fields}))
|
|
64
|
+
await self._socket.send(data)
|
|
65
|
+
response = json.loads(await self._socket.recv())
|
|
66
|
+
if response.get("id") != key or response.get("type") not in (
|
|
67
|
+
"result",
|
|
68
|
+
"error",
|
|
69
|
+
):
|
|
70
|
+
raise RuntimeError("unexpected moderation response")
|
|
71
|
+
if response["type"] == "error":
|
|
72
|
+
raise CloudApiError(
|
|
73
|
+
response.get("http_status", 503),
|
|
74
|
+
response.get("error", "moderation_failed"),
|
|
75
|
+
request_id=key,
|
|
76
|
+
)
|
|
77
|
+
return Moderation.model_validate(response["request"])
|
|
78
|
+
except CloudApiError:
|
|
79
|
+
raise
|
|
80
|
+
except BaseException:
|
|
81
|
+
await self.aclose()
|
|
82
|
+
raise
|
|
83
|
+
finally:
|
|
84
|
+
self._busy = False
|