verbex-speech-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,25 @@
1
+ """Verbex Speech API: speech-to-text and text-to-speech.
2
+
3
+ Modules: :mod:`.client` (the entry points), :mod:`.errors` (the shared errors), :mod:`.listen`
4
+ (speech-to-text) and :mod:`.speak` (text-to-speech). Every public name is also importable from here.
5
+ """
6
+ __version__ = "0.1.0"
7
+
8
+ from .client import AsyncVerbexSpeech, VerbexSpeech # noqa: E402
9
+ from .errors import (APIConnectionError, APIError, APITimeoutError, AuthenticationError, # noqa: E402
10
+ BadRequestError, ConfigurationError, FieldError, NotFoundError, PaymentRequiredError,
11
+ PermissionDeniedError, RateLimitError, ServerError, StreamError, ValidationError, VerbexError)
12
+ from .listen import (Job, JobError, ListenEvent, ListenModel, Segment, SubmitReceipt, # noqa: E402
13
+ UploadError, UploadStarted, WaitTimeoutError, WebhookVerificationError, parse_webhook,
14
+ verify_webhook)
15
+ from .speak import SpeakDone, SpeakError, SpeechAudio, Voice # noqa: E402
16
+
17
+ __all__ = [
18
+ "VerbexSpeech", "AsyncVerbexSpeech", "verify_webhook", "parse_webhook",
19
+ "Job", "JobError", "ListenEvent", "ListenModel", "Segment", "SpeakDone", "SpeechAudio", "SubmitReceipt",
20
+ "UploadStarted", "Voice",
21
+ "VerbexError", "ConfigurationError", "APIError", "BadRequestError", "AuthenticationError",
22
+ "PaymentRequiredError", "PermissionDeniedError", "NotFoundError", "RateLimitError", "ServerError",
23
+ "APIConnectionError", "APITimeoutError", "UploadError", "StreamError", "SpeakError", "WaitTimeoutError",
24
+ "WebhookVerificationError", "FieldError", "ValidationError",
25
+ ]
@@ -0,0 +1 @@
1
+ """Private transport: the HTTP request and retry loop, retry rules, WebSocket opening, shared helpers."""
@@ -0,0 +1,240 @@
1
+ """What the clients and products share: configuration, request shapes, audio sources."""
2
+ from __future__ import annotations
3
+
4
+ import io
5
+ import json
6
+ import os
7
+ import re
8
+ import uuid
9
+ from dataclasses import dataclass
10
+ from typing import Any, BinaryIO, Dict, Iterable, List, Mapping, Optional, Tuple, Union
11
+ from urllib.parse import quote, urlencode, urlsplit
12
+
13
+ from .. import __version__
14
+ from ..errors import ConfigurationError, FieldError, ValidationError
15
+
16
+ DIRECT_MAX_BYTES = 1_048_576
17
+ UPLOAD_MAX_BYTES = 104_857_600
18
+ MAX_FRAME_BYTES = 65_536
19
+ SUBMIT_TIMEOUT = 330.0
20
+ SPEAK_TIMEOUT = 360.0
21
+ CONNECT_TIMEOUT = 10.0
22
+ SPEAK_FIELDS = frozenset({"model", "voice", "text", "request_id"})
23
+ IDEMPOTENCY_HEADER = "Idempotency-Key"
24
+ _IDEMPOTENCY_KEY = re.compile(r"[\x21-\x7e]{1,255}")
25
+
26
+ Source = Union[bytes, bytearray, memoryview, str, "os.PathLike[str]", BinaryIO]
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class Config:
31
+ api_key: str
32
+ base_url: str
33
+ timeout: float
34
+ max_retries: int
35
+ user_agent: str
36
+
37
+ def __repr__(self) -> str:
38
+ return f"Config(base_url={self.base_url!r}, timeout={self.timeout!r}, max_retries={self.max_retries!r})"
39
+
40
+
41
+ def resolve_config(api_key: Optional[str], base_url: Optional[str], timeout: float, max_retries: int,
42
+ user_agent: Optional[str]) -> Config:
43
+ key = api_key if api_key is not None else os.environ.get("VERBEX_API_KEY")
44
+ url = base_url if base_url is not None else os.environ.get("VERBEX_BASE_URL")
45
+ if not key:
46
+ raise ConfigurationError("No API key: pass api_key or set VERBEX_API_KEY.")
47
+ if not key.startswith("vbx_"):
48
+ raise ConfigurationError("The API key is not a Verbex key: it must start with vbx_.")
49
+ if not url:
50
+ raise ConfigurationError("No base URL: pass base_url or set VERBEX_BASE_URL.")
51
+ parts = urlsplit(url)
52
+ if parts.scheme not in ("http", "https") or not parts.netloc:
53
+ raise ConfigurationError("The base URL must be an http or https address.")
54
+ if max_retries < 0:
55
+ raise ConfigurationError("max_retries must be 0 or more.")
56
+ agent = f"verbex-speech-python/{__version__}" + (f" {user_agent}" if user_agent else "")
57
+ return Config(key, url.rstrip("/"), float(timeout), int(max_retries), agent)
58
+
59
+
60
+ def api_headers(config: Config, trace_id: str) -> Dict[str, str]:
61
+ return {"Authorization": f"Token {config.api_key}", "User-Agent": config.user_agent, "X-Trace-Id": trace_id}
62
+
63
+
64
+ def new_trace_id() -> str:
65
+ return str(uuid.uuid4())
66
+
67
+
68
+ def tag_params(tags: Optional[Iterable[str]]) -> List[Tuple[str, str]]:
69
+ return [("tag", t) for t in tags or []]
70
+
71
+
72
+ def ws_url(config: Config, path: str, params: List[Tuple[str, str]]) -> str:
73
+ base = config.base_url
74
+ base = "wss" + base[5:] if base.startswith("https") else "ws" + base[4:]
75
+ query = urlencode(params, quote_via=quote)
76
+ return f"{base}{path}" + (f"?{query}" if query else "")
77
+
78
+
79
+ def local_error(message: str, field: Optional[str] = None, code: str = "validation_failed") -> ValidationError:
80
+ return ValidationError(code, message, [FieldError(field, message)] if field else [])
81
+
82
+
83
+ @dataclass
84
+ class Audio:
85
+ """An audio source with a known size, readable once (or re-readable when held in memory)."""
86
+
87
+ size: int
88
+ filename: str
89
+ data: Optional[bytes] = None
90
+ path: Optional[str] = None
91
+ stream: Optional[BinaryIO] = None
92
+
93
+ def read_all(self) -> bytes:
94
+ if self.data is not None:
95
+ return self.data
96
+ if self.path is not None:
97
+ with open(self.path, "rb") as f:
98
+ return f.read()
99
+ assert self.stream is not None
100
+ return self.stream.read()
101
+
102
+ def chunks(self, size: int = 1024 * 1024) -> Iterable[bytes]:
103
+ if self.data is not None:
104
+ for i in range(0, len(self.data), size):
105
+ yield self.data[i:i + size]
106
+ return
107
+ handle = open(self.path, "rb") if self.path is not None else self.stream
108
+ assert handle is not None
109
+ try:
110
+ remaining = self.size
111
+ while remaining > 0:
112
+ chunk = handle.read(min(size, remaining))
113
+ if not chunk:
114
+ break
115
+ remaining -= len(chunk)
116
+ yield chunk
117
+ finally:
118
+ if self.path is not None:
119
+ handle.close()
120
+
121
+
122
+ def open_audio(source: Any, size: Optional[int], filename: Optional[str]) -> Audio:
123
+ if isinstance(source, (bytes, bytearray, memoryview)):
124
+ data = bytes(source)
125
+ audio = Audio(len(data), filename or "audio.wav", data=data)
126
+ elif isinstance(source, (str, os.PathLike)):
127
+ path = os.fspath(source)
128
+ audio = Audio(os.path.getsize(path), filename or os.path.basename(path), path=path)
129
+ elif hasattr(source, "read"):
130
+ known = size
131
+ if known is None:
132
+ try:
133
+ start = source.tell()
134
+ source.seek(0, io.SEEK_END)
135
+ known = source.tell() - start
136
+ source.seek(start)
137
+ except (AttributeError, OSError, ValueError):
138
+ raise local_error("A stream needs its size: pass size=.", "size") from None
139
+ name = getattr(source, "name", None)
140
+ audio = Audio(int(known), filename or (os.path.basename(name) if isinstance(name, str) else "audio.wav"),
141
+ stream=source)
142
+ else:
143
+ raise local_error("The source must be bytes, a path or a readable stream.", "source")
144
+ if audio.size <= 0:
145
+ raise local_error("The audio is empty.", "source")
146
+ if audio.size > UPLOAD_MAX_BYTES:
147
+ raise local_error(f"The audio is {audio.size} bytes; at most {UPLOAD_MAX_BYTES} bytes can be sent.",
148
+ "source", "audio_too_large")
149
+ return audio
150
+
151
+
152
+ def content_type_for(filename: str) -> str:
153
+ lower = filename.lower()
154
+ if lower.endswith(".mp3"):
155
+ return "audio/mpeg"
156
+ if lower.endswith(".wav"):
157
+ return "audio/wav"
158
+ return "application/octet-stream"
159
+
160
+
161
+ def submit_options(model: str, language: str, hotwords: Optional[List[str]], metadata: Optional[Mapping[str, Any]],
162
+ webhook_url: Optional[str]) -> None:
163
+ if not model:
164
+ raise local_error("model is required.", "model")
165
+ if not language:
166
+ raise local_error("language is required.", "language")
167
+ if hotwords is not None and (isinstance(hotwords, str) or not all(isinstance(t, str) for t in hotwords)):
168
+ raise local_error("hotwords must be a list of strings.", "hotwords")
169
+ if metadata is not None and not isinstance(metadata, Mapping):
170
+ raise local_error("metadata must be a JSON object.", "metadata")
171
+
172
+
173
+ def multipart_form(model: str, language: str, hotwords: Optional[List[str]], metadata: Optional[Mapping[str, Any]],
174
+ webhook_url: Optional[str]) -> Dict[str, Any]:
175
+ form: Dict[str, Any] = {"model": model, "language": language}
176
+ if hotwords:
177
+ form["hotwords"] = list(hotwords)
178
+ if metadata is not None:
179
+ form["metadata"] = json.dumps(metadata, ensure_ascii=False)
180
+ if webhook_url:
181
+ form["webhook_url"] = webhook_url
182
+ return form
183
+
184
+
185
+ def json_submit(base: Dict[str, Any], model: str, language: str, hotwords: Optional[List[str]],
186
+ metadata: Optional[Mapping[str, Any]], webhook_url: Optional[str]) -> Dict[str, Any]:
187
+ body = dict(base)
188
+ body.update({"model": model, "language": language})
189
+ if hotwords:
190
+ body["hotwords"] = list(hotwords)
191
+ if metadata is not None:
192
+ body["metadata"] = dict(metadata)
193
+ if webhook_url:
194
+ body["webhook_url"] = webhook_url
195
+ return body
196
+
197
+
198
+ def speak_body(model: str, voice: str, text: str, request_id: Optional[str],
199
+ settings: Optional[Mapping[str, Any]]) -> Dict[str, Any]:
200
+ clash = SPEAK_FIELDS.intersection(settings or {})
201
+ if clash:
202
+ raise local_error(f"settings cannot set {sorted(clash)[0]}.", sorted(clash)[0])
203
+ body: Dict[str, Any] = {"model": model, "voice": voice, "text": text}
204
+ if request_id is not None:
205
+ body["request_id"] = request_id
206
+ body.update(settings or {})
207
+ return body
208
+
209
+
210
+ def idempotency_headers(idempotency_key: Optional[str]) -> Dict[str, str]:
211
+ """The Idempotency-Key header a submit or a speak sends with every attempt: the caller's key, else a
212
+ new UUID for this call, the same for each of its retries."""
213
+ if idempotency_key is None:
214
+ return {IDEMPOTENCY_HEADER: str(uuid.uuid4())}
215
+ if not isinstance(idempotency_key, str) or not _IDEMPOTENCY_KEY.fullmatch(idempotency_key):
216
+ raise local_error("idempotency_key must be 1 to 255 visible ASCII characters, without spaces.",
217
+ "idempotency_key")
218
+ return {IDEMPOTENCY_HEADER: idempotency_key}
219
+
220
+
221
+ def replayed(headers: Mapping[str, str]) -> bool:
222
+ """True when the answer came from an earlier request with the same Idempotency-Key."""
223
+ return headers.get("Idempotent-Replayed", "").strip().lower() == "true"
224
+
225
+
226
+ def speak_params(format: str, tags: Optional[Iterable[str]]) -> List[Tuple[str, str]]:
227
+ if format not in ("pcm", "wav"):
228
+ raise local_error("format must be pcm or wav.", "format")
229
+ return [("format", format)] + tag_params(tags)
230
+
231
+
232
+ def listen_stream_params(model: str, language: str, hotwords: Optional[List[str]],
233
+ tags: Optional[Iterable[str]]) -> List[Tuple[str, str]]:
234
+ submit_options(model, language, hotwords, None, None)
235
+ return [("model", model), ("language", language)] + [("hotwords", t) for t in hotwords or []] + tag_params(tags)
236
+
237
+
238
+ def frames(pcm: bytes) -> List[bytes]:
239
+ data = bytes(pcm)
240
+ return [data[i:i + MAX_FRAME_BYTES] for i in range(0, len(data), MAX_FRAME_BYTES)] or []
@@ -0,0 +1,89 @@
1
+ """One API call over HTTP, retried by the rules of :mod:`.retry` (spec section 8)."""
2
+ from __future__ import annotations
3
+
4
+ from typing import Any, Awaitable, Callable, Dict, List, Optional
5
+
6
+ import httpx
7
+
8
+ from ..errors import APIConnectionError, APIError, APITimeoutError, from_response
9
+ from . import common as c
10
+ from .retry import backoff, should_retry
11
+
12
+
13
+ def _build(http: Any, config: c.Config, trace_id: str, method: str, path: str, params: Optional[List[Any]],
14
+ json: Any, data: Optional[Dict[str, Any]], files: Any, timeout: Optional[float],
15
+ headers: Optional[Dict[str, str]] = None) -> httpx.Request:
16
+ return http.build_request(
17
+ method, config.base_url + path, params=params, json=json, data=data, files=files,
18
+ headers={**c.api_headers(config, trace_id), **(headers or {})},
19
+ timeout=httpx.Timeout(timeout or config.timeout, connect=c.CONNECT_TIMEOUT))
20
+
21
+
22
+ def _retry_wait(config: c.Config, call: str, attempt: int, error: Exception) -> Optional[float]:
23
+ """Seconds to wait before trying again, or None when the error is to be raised."""
24
+ status = error.status if isinstance(error, APIError) else None
25
+ code = error.code if isinstance(error, APIError) else None
26
+ if attempt < config.max_retries and should_retry(
27
+ call, status=status, code=code, error=None if isinstance(error, APIError) else error):
28
+ return backoff(attempt, error.retry_after if isinstance(error, APIError) else None)
29
+ return None
30
+
31
+
32
+ def request(http: httpx.Client, config: c.Config, sleep: Callable[[float], Any], call: str, method: str,
33
+ path: str, *, params: Optional[List[Any]] = None, json: Any = None,
34
+ data: Optional[Dict[str, Any]] = None, files: Any = None, timeout: Optional[float] = None,
35
+ stream: bool = False, headers: Optional[Dict[str, str]] = None) -> httpx.Response:
36
+ """``call`` is ``get``, ``upload_start``, ``speak`` or ``submit``: it decides what is retried.
37
+ ``headers`` go with every attempt, as sent the first time."""
38
+ trace_id = c.new_trace_id()
39
+ attempt = 0
40
+ while True:
41
+ error: Exception
42
+ try:
43
+ response = http.send(_build(http, config, trace_id, method, path, params, json, data, files, timeout,
44
+ headers), stream=stream)
45
+ except httpx.TimeoutException:
46
+ error = APITimeoutError(f"No answer from the API to {method} {path} in time.")
47
+ except httpx.TransportError as exc:
48
+ error = APIConnectionError(f"Could not reach the API for {method} {path}: {type(exc).__name__}.")
49
+ else:
50
+ if response.status_code < 400:
51
+ return response
52
+ body = response.read()
53
+ response.close()
54
+ error = from_response(response.status_code, response.headers, body)
55
+ wait = _retry_wait(config, call, attempt, error)
56
+ if wait is None:
57
+ raise error from None
58
+ sleep(wait)
59
+ attempt += 1
60
+
61
+
62
+ async def request_async(http: httpx.AsyncClient, config: c.Config, sleep: Callable[[float], Awaitable[Any]],
63
+ call: str, method: str, path: str, *, params: Optional[List[Any]] = None, json: Any = None,
64
+ data: Optional[Dict[str, Any]] = None, files: Any = None, timeout: Optional[float] = None,
65
+ stream: bool = False, headers: Optional[Dict[str, str]] = None) -> httpx.Response:
66
+ """The awaited twin of :func:`request`."""
67
+ trace_id = c.new_trace_id()
68
+ attempt = 0
69
+ while True:
70
+ error: Exception
71
+ try:
72
+ response = await http.send(
73
+ _build(http, config, trace_id, method, path, params, json, data, files, timeout, headers),
74
+ stream=stream)
75
+ except httpx.TimeoutException:
76
+ error = APITimeoutError(f"No answer from the API to {method} {path} in time.")
77
+ except httpx.TransportError as exc:
78
+ error = APIConnectionError(f"Could not reach the API for {method} {path}: {type(exc).__name__}.")
79
+ else:
80
+ if response.status_code < 400:
81
+ return response
82
+ body = await response.aread()
83
+ await response.aclose()
84
+ error = from_response(response.status_code, response.headers, body)
85
+ wait = _retry_wait(config, call, attempt, error)
86
+ if wait is None:
87
+ raise error from None
88
+ await sleep(wait)
89
+ attempt += 1
@@ -0,0 +1,36 @@
1
+ """Which failed calls are retried automatically, and how long to wait (spec section 8)."""
2
+ from __future__ import annotations
3
+
4
+ import random
5
+ from typing import Optional
6
+
7
+ from ..errors import APIConnectionError, APITimeoutError
8
+
9
+ RATE_LIMITS = frozenset({"rate_limited", "workspace_rate_limited"})
10
+ # A 5xx that fails the same way every time: the engine refused this text, not a passing fault.
11
+ PERMANENT = frozenset({"synthesis_failed"})
12
+ MAX_RETRY_AFTER = 60
13
+
14
+
15
+ def should_retry(call: str, status: Optional[int] = None, code: Optional[str] = None,
16
+ error: Optional[BaseException] = None) -> bool:
17
+ """``call`` is ``get``, ``upload_start``, ``speak`` or ``submit``.
18
+
19
+ A submit is retried as a read is: it carries its Idempotency-Key, so a retry after a lost answer
20
+ gets the first request's receipt rather than a second job. A speak carries one too. Both are also
21
+ retried while the first request with their key still runs (409 ``request_in_progress``).
22
+ """
23
+ if error is not None:
24
+ return isinstance(error, (APIConnectionError, APITimeoutError))
25
+ if status == 429:
26
+ return code in RATE_LIMITS
27
+ if call in ("submit", "speak") and status == 409:
28
+ return code == "request_in_progress"
29
+ return status in (502, 503, 504) and code not in PERMANENT
30
+
31
+
32
+ def backoff(attempt: int, retry_after: Optional[int] = None) -> Optional[float]:
33
+ """Seconds before retry number ``attempt + 1``; None when the server asks for longer than is waited."""
34
+ if retry_after is not None:
35
+ return float(retry_after) if retry_after <= MAX_RETRY_AFTER else None
36
+ return random.uniform(0, min(8.0, 0.5 * (2 ** attempt)))
@@ -0,0 +1,62 @@
1
+ """Opening a WebSocket with the key header, and reading its frames; a refused handshake is the HTTP error."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import json
6
+ from typing import Any, List, Optional
7
+
8
+ from websockets.asyncio.client import ClientConnection as AsyncClientConnection
9
+ from websockets.asyncio.client import connect as connect_async
10
+ from websockets.exceptions import ConnectionClosed, InvalidStatus, WebSocketException
11
+ from websockets.sync.client import ClientConnection, connect
12
+
13
+ from ..errors import APIConnectionError, APITimeoutError, from_response
14
+ from . import common as c
15
+
16
+
17
+ def open_socket(config: c.Config, path: str, params: List[Any]) -> ClientConnection:
18
+ """Opens the socket with the key header; a refused handshake is the HTTP error it answered."""
19
+ try:
20
+ # Entered as a context manager: websockets 13 returns the connection itself, later versions a
21
+ # factory whose __enter__ opens it; the session closes the connection it is handed.
22
+ return connect(c.ws_url(config, path, params), additional_headers=c.api_headers(config, c.new_trace_id()),
23
+ max_size=1024 * 1024, open_timeout=config.timeout, user_agent_header=None).__enter__()
24
+ except InvalidStatus as refused:
25
+ response = refused.response
26
+ raise from_response(response.status_code, {k.lower(): v for k, v in response.headers.raw_items()},
27
+ response.body or b"") from None
28
+ except TimeoutError:
29
+ raise APITimeoutError(f"The socket {path} did not open in time.") from None
30
+ except (OSError, WebSocketException) as exc:
31
+ raise APIConnectionError(f"Could not open the socket {path}: {type(exc).__name__}.") from None
32
+
33
+
34
+ async def open_socket_async(config: c.Config, path: str, params: List[Any]) -> AsyncClientConnection:
35
+ """The awaited twin of :func:`open_socket`."""
36
+ try:
37
+ return await connect_async(c.ws_url(config, path, params),
38
+ additional_headers=c.api_headers(config, c.new_trace_id()),
39
+ max_size=1024 * 1024, open_timeout=config.timeout, user_agent_header=None)
40
+ except InvalidStatus as refused:
41
+ response = refused.response
42
+ raise from_response(response.status_code, {k.lower(): v for k, v in response.headers.raw_items()},
43
+ response.body or b"") from None
44
+ except (asyncio.TimeoutError, TimeoutError):
45
+ raise APITimeoutError(f"The socket {path} did not open in time.") from None
46
+ except (OSError, WebSocketException) as exc:
47
+ raise APIConnectionError(f"Could not open the socket {path}: {type(exc).__name__}.") from None
48
+
49
+
50
+ def close_code(closed: ConnectionClosed) -> int:
51
+ return closed.rcvd.code if closed.rcvd is not None else 1006
52
+
53
+
54
+ def parse(message: Any) -> Optional[dict]:
55
+ """A text frame's JSON object; None for binary frames and anything that is not a JSON object."""
56
+ if not isinstance(message, str):
57
+ return None
58
+ try:
59
+ frame = json.loads(message)
60
+ except ValueError:
61
+ return None
62
+ return frame if isinstance(frame, dict) else None
@@ -0,0 +1,99 @@
1
+ """The entry points: hold the configuration and the HTTP client, and expose ``.listen`` and ``.speak``."""
2
+ from __future__ import annotations
3
+
4
+ import asyncio
5
+ import time
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ import httpx
9
+
10
+ from ._transport import common as c
11
+ from ._transport import http_client as http
12
+ from .listen import AsyncListen, Listen
13
+ from .speak import AsyncSpeak, Speak
14
+
15
+
16
+ class VerbexSpeech:
17
+ """Client for the Verbex Speech API.
18
+
19
+ >>> client = VerbexSpeech(api_key="vbx_...", base_url="https://speech-api-stage.verbex.ai")
20
+ >>> job = client.listen.transcribe("call.wav", model="verbex_jp_stt_x1", language="ja")
21
+ """
22
+
23
+ def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, *, timeout: float = 30.0,
24
+ max_retries: int = 2, user_agent: Optional[str] = None,
25
+ transport: Optional[httpx.BaseTransport] = None):
26
+ self._config = c.resolve_config(api_key, base_url, timeout, max_retries, user_agent)
27
+ self._http = httpx.Client(transport=transport, follow_redirects=False,
28
+ timeout=httpx.Timeout(self._config.timeout, connect=c.CONNECT_TIMEOUT))
29
+ self._sleep = time.sleep
30
+ self._monotonic = time.monotonic
31
+ self.listen = Listen(self)
32
+ self.speak = Speak(self)
33
+
34
+ @property
35
+ def base_url(self) -> str:
36
+ return self._config.base_url
37
+
38
+ def __repr__(self) -> str:
39
+ return f"VerbexSpeech(base_url={self.base_url!r})"
40
+
41
+ def close(self) -> None:
42
+ self._http.close()
43
+
44
+ def __enter__(self) -> "VerbexSpeech":
45
+ return self
46
+
47
+ def __exit__(self, *exc: Any) -> None:
48
+ self.close()
49
+
50
+ def _request(self, call: str, method: str, path: str, *, params: Optional[List[Any]] = None,
51
+ json: Any = None, data: Optional[Dict[str, Any]] = None, files: Any = None,
52
+ timeout: Optional[float] = None, stream: bool = False,
53
+ headers: Optional[Dict[str, str]] = None) -> httpx.Response:
54
+ # self._sleep is read per call so tests (and callers) can replace it.
55
+ return http.request(self._http, self._config, self._sleep, call, method, path, params=params, json=json,
56
+ data=data, files=files, timeout=timeout, stream=stream, headers=headers)
57
+
58
+
59
+ class AsyncVerbexSpeech:
60
+ """Asynchronous client for the Verbex Speech API.
61
+
62
+ >>> async with AsyncVerbexSpeech(api_key="vbx_...", base_url="https://speech-api-stage.verbex.ai") as client:
63
+ ... job = await client.listen.transcribe("call.wav", model="verbex_jp_stt_x1", language="ja")
64
+ """
65
+
66
+ def __init__(self, api_key: Optional[str] = None, base_url: Optional[str] = None, *, timeout: float = 30.0,
67
+ max_retries: int = 2, user_agent: Optional[str] = None,
68
+ transport: Optional[httpx.AsyncBaseTransport] = None):
69
+ self._config = c.resolve_config(api_key, base_url, timeout, max_retries, user_agent)
70
+ self._http = httpx.AsyncClient(transport=transport, follow_redirects=False,
71
+ timeout=httpx.Timeout(self._config.timeout, connect=c.CONNECT_TIMEOUT))
72
+ self._sleep = asyncio.sleep
73
+ self._monotonic = time.monotonic
74
+ self.listen = AsyncListen(self)
75
+ self.speak = AsyncSpeak(self)
76
+
77
+ @property
78
+ def base_url(self) -> str:
79
+ return self._config.base_url
80
+
81
+ def __repr__(self) -> str:
82
+ return f"AsyncVerbexSpeech(base_url={self.base_url!r})"
83
+
84
+ async def aclose(self) -> None:
85
+ await self._http.aclose()
86
+
87
+ async def __aenter__(self) -> "AsyncVerbexSpeech":
88
+ return self
89
+
90
+ async def __aexit__(self, *exc: Any) -> None:
91
+ await self.aclose()
92
+
93
+ async def _request(self, call: str, method: str, path: str, *, params: Optional[List[Any]] = None,
94
+ json: Any = None, data: Optional[Dict[str, Any]] = None, files: Any = None,
95
+ timeout: Optional[float] = None, stream: bool = False,
96
+ headers: Optional[Dict[str, str]] = None) -> httpx.Response:
97
+ return await http.request_async(self._http, self._config, self._sleep, call, method, path, params=params,
98
+ json=json, data=data, files=files, timeout=timeout, stream=stream,
99
+ headers=headers)