bessel-audio 0.3.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,8 @@
1
+ **/.venv/
2
+ **/__pycache__/
3
+ **/.pytest_cache/
4
+ **/.ruff_cache/
5
+ **/node_modules/
6
+ **/dist/
7
+ **/*.egg-info/
8
+ **/.coverage
@@ -0,0 +1,93 @@
1
+ Metadata-Version: 2.5
2
+ Name: bessel-audio
3
+ Version: 0.3.0
4
+ Summary: Bessel Transcribe and Decision client with explicit submission and bounded job recovery
5
+ Project-URL: Homepage, https://besselaudio.com
6
+ Project-URL: Documentation, https://besselaudio.com/docs
7
+ Author-email: Charles <charles@asrena.ai>
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: httpx<1,>=0.28
10
+ Description-Content-Type: text/markdown
11
+
12
+ # Bessel Audio Python client
13
+
14
+ Python 3.10+ client for Bessel Transcribe and Decision.
15
+
16
+ Install the release: `python -m pip install bessel-audio==0.3.0`.
17
+ For a source checkout: `python -m pip install ./sdk/bessel/python`.
18
+ Set `BESSEL_API_KEY` to a unified **Bessel** API key. The default origin is
19
+ `https://api.besselaudio.com`; the same key accesses Transcribe and Decision.
20
+ Existing Decision accounts must first be connected in the console.
21
+
22
+ ```python
23
+ from bessel_audio import Bessel
24
+
25
+ with Bessel() as client:
26
+ job = client.transcribe("clip.wav", idempotency_key="your-durable-request-0001")
27
+ print(job["result"]["text"])
28
+ ```
29
+
30
+ The default model is `Sonaflow/bessel-multilingual-v1`, with server-side language
31
+ auto-detection. For the frozen English release, explicitly pass
32
+ `model="Sonaflow/bessel-consensus3-r1", language="en"`.
33
+ MP3/WAV/FLAC, 24 MiB and 5 minutes are the current server limits.
34
+
35
+ For separate upload and recovery:
36
+
37
+ ```python
38
+ with Bessel() as client:
39
+ job = client.create_job("clip.wav", idempotency_key="your-durable-request-0002")
40
+ # Persist job["id"] before waiting. Waiting only makes GET requests.
41
+ completed = client.wait_for_job(job["id"], timeout=300)
42
+ print(completed["result"]["text"])
43
+ ```
44
+
45
+ Use a distinct durable request key for each intended transcription (16–128 ASCII
46
+ letters, digits, `_`, `.` or `-`). Save it before uploading. The SDK does not
47
+ retry uploads or create replacement requests after a network error. For a
48
+ self-service request whose submission response is lost, explicitly resubmit
49
+ the exact same audio/options with the **same** key; the server resolves it to
50
+ the original job. Never generate a new key merely because a request timed out.
51
+
52
+ `BesselError` exposes `code`, `status_code`, `job_id`, `idempotency_key`, and
53
+ `retry_after`. An interrupted GET can be resumed with `get_job(job_id)` or
54
+ `wait_for_job(job_id)`. Failed or expired/deleted results raise explicit errors;
55
+ an empty successful transcript remains a successful result.
56
+
57
+ Read-only helpers: `models()`, `usage()`, `evaluation_contract(model=None)`,
58
+ `get_job(job_id)`. `billing_mode="paid"` explicitly selects prepaid credits;
59
+ otherwise the server's `trial_first` policy is retained. Request timeout defaults
60
+ to 60 seconds and polling to a 300-second deadline, respecting Retry-After.
61
+
62
+ `base_url` accepts an HTTPS origin or origin ending in `/v1`; HTTP is permitted
63
+ only for localhost development. Redirects are not followed with credentials.
64
+ `trust_env=False` disables environment proxy settings when required.
65
+
66
+ These are Bessel job APIs, not a promise of complete OpenAI SDK compatibility.
67
+ Timestamp/subtitle/streaming/Decision APIs are not exposed by this client.
68
+
69
+
70
+ ## Unified Decision access (0.2.0)
71
+
72
+ The same Bessel API key accesses both products. Connect an existing Decision account once in the Bessel console; `legacy_account_link_required` is not a reason to create a second account or reset quota. The wallet is shared; Decision keeps its existing free allowance and does not debit prepaid transcription credits.
73
+
74
+ Decision supports model discovery, account/allowance reads, ranking, comparison submission, polling reads, explicit cancel and explicit retry. Rank requests accept 2–4 candidate objects with `id` and `text`, 0.1–15 seconds and up to 3 MiB. A synchronous rank timeout is ambiguous; the SDK never retries it. Comparisons accept 2–4 distinct model IDs and 0.1–300 seconds/up to 64 MiB, subject to remaining allowance. Keep the same idempotency key and inputs after a lost submission response; honor `poll_after_seconds` and `Retry-After` when polling. Call retry only when the service explicitly marks a comparison retryable.
75
+
76
+ ```python
77
+ with Bessel() as client:
78
+ catalog = client.decision_models()
79
+ allowance = client.decision_account()
80
+ job = client.create_comparison(
81
+ "clip.wav", ["azure/speech-fast", "azure/llm-speech"], "azure/speech-fast",
82
+ idempotency_key="my-comparison-request-0001",
83
+ )
84
+ current = client.get_comparison(job["id"])
85
+ ```
86
+
87
+ ## Signed completion webhooks (0.3.0)
88
+
89
+ Create a receiver with `create_webhook` / `createWebhook`, save its one-time secret, then call `verify_webhook_endpoint` / `verifyWebhookEndpoint`. After validating the signed verification request, echo its `data.challenge` in the `Bessel-Webhook-Challenge` response header. Only future Transcribe jobs are enrolled.
90
+
91
+ Verify the original bytes with `verify_webhook(raw_bytes, headers, secret)` (Python) or `await verifyWebhook(rawBytes, headers, secret)` (TypeScript). The helper rejects tampered signatures and timestamps outside ±5 minutes. It does not deduplicate: persist each event ID atomically with your work and acknowledge valid duplicates. Read jobs separately using the API key. Endpoint secrets are not API keys.
92
+
93
+ Use `webhooks`, `webhook_events` / `webhookEvents`, and `disable_webhook` / `disableWebhook` to manage endpoints. At most eight delivery attempts over 24 hours; failed notifications do not resubmit audio or change billing. See [the full contract](https://scribe.besselaudio.com/docs#webhooks).
@@ -0,0 +1,82 @@
1
+ # Bessel Audio Python client
2
+
3
+ Python 3.10+ client for Bessel Transcribe and Decision.
4
+
5
+ Install the release: `python -m pip install bessel-audio==0.3.0`.
6
+ For a source checkout: `python -m pip install ./sdk/bessel/python`.
7
+ Set `BESSEL_API_KEY` to a unified **Bessel** API key. The default origin is
8
+ `https://api.besselaudio.com`; the same key accesses Transcribe and Decision.
9
+ Existing Decision accounts must first be connected in the console.
10
+
11
+ ```python
12
+ from bessel_audio import Bessel
13
+
14
+ with Bessel() as client:
15
+ job = client.transcribe("clip.wav", idempotency_key="your-durable-request-0001")
16
+ print(job["result"]["text"])
17
+ ```
18
+
19
+ The default model is `Sonaflow/bessel-multilingual-v1`, with server-side language
20
+ auto-detection. For the frozen English release, explicitly pass
21
+ `model="Sonaflow/bessel-consensus3-r1", language="en"`.
22
+ MP3/WAV/FLAC, 24 MiB and 5 minutes are the current server limits.
23
+
24
+ For separate upload and recovery:
25
+
26
+ ```python
27
+ with Bessel() as client:
28
+ job = client.create_job("clip.wav", idempotency_key="your-durable-request-0002")
29
+ # Persist job["id"] before waiting. Waiting only makes GET requests.
30
+ completed = client.wait_for_job(job["id"], timeout=300)
31
+ print(completed["result"]["text"])
32
+ ```
33
+
34
+ Use a distinct durable request key for each intended transcription (16–128 ASCII
35
+ letters, digits, `_`, `.` or `-`). Save it before uploading. The SDK does not
36
+ retry uploads or create replacement requests after a network error. For a
37
+ self-service request whose submission response is lost, explicitly resubmit
38
+ the exact same audio/options with the **same** key; the server resolves it to
39
+ the original job. Never generate a new key merely because a request timed out.
40
+
41
+ `BesselError` exposes `code`, `status_code`, `job_id`, `idempotency_key`, and
42
+ `retry_after`. An interrupted GET can be resumed with `get_job(job_id)` or
43
+ `wait_for_job(job_id)`. Failed or expired/deleted results raise explicit errors;
44
+ an empty successful transcript remains a successful result.
45
+
46
+ Read-only helpers: `models()`, `usage()`, `evaluation_contract(model=None)`,
47
+ `get_job(job_id)`. `billing_mode="paid"` explicitly selects prepaid credits;
48
+ otherwise the server's `trial_first` policy is retained. Request timeout defaults
49
+ to 60 seconds and polling to a 300-second deadline, respecting Retry-After.
50
+
51
+ `base_url` accepts an HTTPS origin or origin ending in `/v1`; HTTP is permitted
52
+ only for localhost development. Redirects are not followed with credentials.
53
+ `trust_env=False` disables environment proxy settings when required.
54
+
55
+ These are Bessel job APIs, not a promise of complete OpenAI SDK compatibility.
56
+ Timestamp/subtitle/streaming/Decision APIs are not exposed by this client.
57
+
58
+
59
+ ## Unified Decision access (0.2.0)
60
+
61
+ The same Bessel API key accesses both products. Connect an existing Decision account once in the Bessel console; `legacy_account_link_required` is not a reason to create a second account or reset quota. The wallet is shared; Decision keeps its existing free allowance and does not debit prepaid transcription credits.
62
+
63
+ Decision supports model discovery, account/allowance reads, ranking, comparison submission, polling reads, explicit cancel and explicit retry. Rank requests accept 2–4 candidate objects with `id` and `text`, 0.1–15 seconds and up to 3 MiB. A synchronous rank timeout is ambiguous; the SDK never retries it. Comparisons accept 2–4 distinct model IDs and 0.1–300 seconds/up to 64 MiB, subject to remaining allowance. Keep the same idempotency key and inputs after a lost submission response; honor `poll_after_seconds` and `Retry-After` when polling. Call retry only when the service explicitly marks a comparison retryable.
64
+
65
+ ```python
66
+ with Bessel() as client:
67
+ catalog = client.decision_models()
68
+ allowance = client.decision_account()
69
+ job = client.create_comparison(
70
+ "clip.wav", ["azure/speech-fast", "azure/llm-speech"], "azure/speech-fast",
71
+ idempotency_key="my-comparison-request-0001",
72
+ )
73
+ current = client.get_comparison(job["id"])
74
+ ```
75
+
76
+ ## Signed completion webhooks (0.3.0)
77
+
78
+ Create a receiver with `create_webhook` / `createWebhook`, save its one-time secret, then call `verify_webhook_endpoint` / `verifyWebhookEndpoint`. After validating the signed verification request, echo its `data.challenge` in the `Bessel-Webhook-Challenge` response header. Only future Transcribe jobs are enrolled.
79
+
80
+ Verify the original bytes with `verify_webhook(raw_bytes, headers, secret)` (Python) or `await verifyWebhook(rawBytes, headers, secret)` (TypeScript). The helper rejects tampered signatures and timestamps outside ±5 minutes. It does not deduplicate: persist each event ID atomically with your work and acknowledge valid duplicates. Read jobs separately using the API key. Endpoint secrets are not API keys.
81
+
82
+ Use `webhooks`, `webhook_events` / `webhookEvents`, and `disable_webhook` / `disableWebhook` to manage endpoints. At most eight delivery attempts over 24 hours; failed notifications do not resubmit audio or change billing. See [the full contract](https://scribe.besselaudio.com/docs#webhooks).
@@ -0,0 +1,23 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "bessel-audio"
7
+ version = "0.3.0"
8
+ description = "Bessel Transcribe and Decision client with explicit submission and bounded job recovery"
9
+ readme = "README.md"
10
+ authors = [{name = "Charles", email = "charles@asrena.ai"}]
11
+ requires-python = ">=3.10"
12
+ dependencies = ["httpx>=0.28,<1"]
13
+
14
+ [project.urls]
15
+ Homepage = "https://besselaudio.com"
16
+ Documentation = "https://besselaudio.com/docs"
17
+
18
+ [tool.hatch.build.targets.wheel]
19
+ packages = ["src/bessel_audio"]
20
+
21
+ [tool.pytest.ini_options]
22
+ testpaths = ["tests"]
23
+ pythonpath = ["src"]
@@ -0,0 +1,7 @@
1
+ """A small client for the existing Bessel Transcribe contract."""
2
+
3
+ from .client import Bessel, BesselError
4
+ from .webhooks import verify_webhook
5
+
6
+ __all__ = ["Bessel", "BesselError", "verify_webhook"]
7
+ __version__ = "0.3.0"
@@ -0,0 +1,282 @@
1
+ from __future__ import annotations
2
+
3
+ import math
4
+ import json
5
+ import os
6
+ import re
7
+ import time
8
+ from pathlib import Path
9
+ from urllib.parse import urlsplit
10
+
11
+ import httpx
12
+
13
+ MULTILINGUAL = "Sonaflow/bessel-multilingual-v1"
14
+ MAX_BYTES = 24 * 1024 * 1024
15
+ ACTIVE = {"processing", "reserved", "submitting", "uncertain", "queued", "running"}
16
+
17
+
18
+ class BesselError(Exception):
19
+ """Error metadata for explicit recovery; credentials and response bodies are omitted."""
20
+
21
+ def __init__(self, code, *, status_code=None, job_id=None, idempotency_key=None, retry_after=None):
22
+ self.code = code
23
+ self.status_code = status_code
24
+ self.job_id = job_id
25
+ self.idempotency_key = idempotency_key
26
+ self.retry_after = retry_after
27
+ super().__init__(f"Bessel: {code}" + (f" (HTTP {status_code})" if status_code else ""))
28
+
29
+
30
+ def positive(value):
31
+ if (
32
+ isinstance(value, bool)
33
+ or not isinstance(value, (int, float))
34
+ or not math.isfinite(value)
35
+ or value <= 0
36
+ ):
37
+ raise ValueError("Timeout must be a positive finite number")
38
+ return value
39
+
40
+
41
+ def delay(value, default=3):
42
+ try:
43
+ number = float(value)
44
+ return number if math.isfinite(number) and number > 0 else default
45
+ except (TypeError, ValueError):
46
+ return default
47
+
48
+
49
+ def job_path(job_id):
50
+ if not isinstance(job_id, str) or not re.fullmatch(r"[A-Za-z0-9_-]{1,128}", job_id):
51
+ raise ValueError("Invalid job ID")
52
+ return "/jobs/" + job_id
53
+
54
+
55
+ class Bessel:
56
+ def __init__(
57
+ self,
58
+ api_key=None,
59
+ *,
60
+ base_url="https://api.besselaudio.com",
61
+ timeout=60,
62
+ trust_env=True,
63
+ transport=None,
64
+ ):
65
+ key = api_key if api_key is not None else os.environ.get("BESSEL_API_KEY", "")
66
+ if not isinstance(key, str) or not re.fullmatch(r"[!-~]+", key):
67
+ raise ValueError("BESSEL_API_KEY or api_key is required")
68
+ url = urlsplit(base_url)
69
+ if (
70
+ url.scheme not in ("http", "https")
71
+ or not url.hostname
72
+ or url.username
73
+ or url.password
74
+ or url.query
75
+ or url.fragment
76
+ or url.path.rstrip("/") not in ("", "/v1")
77
+ or (url.scheme == "http" and url.hostname not in ("127.0.0.1", "localhost", "::1"))
78
+ ):
79
+ raise ValueError("base_url must be an HTTPS API origin, optionally ending in /v1")
80
+ self.timeout = positive(timeout)
81
+ self._origin = f"{url.scheme}://{url.netloc}"
82
+ self._client = httpx.Client(
83
+ base_url=f"{url.scheme}://{url.netloc}/v1",
84
+ headers={"Authorization": "Bearer " + key, "User-Agent": "bessel-audio-python/0.3.0"},
85
+ timeout=timeout,
86
+ trust_env=trust_env,
87
+ follow_redirects=False,
88
+ transport=transport,
89
+ )
90
+
91
+ def close(self):
92
+ self._client.close()
93
+
94
+ def __enter__(self):
95
+ return self
96
+
97
+ def __exit__(self, *_):
98
+ self.close()
99
+
100
+ def _request(self, method, path, *, job_id=None, idempotency_key=None, timeout=None, api_version=1, **kwargs):
101
+ context = {"job_id": job_id, "idempotency_key": idempotency_key}
102
+ try:
103
+ target = self._origin + '/v2' + path if api_version == 2 else path
104
+ response = self._client.request(method, target, timeout=timeout or self.timeout, **kwargs)
105
+ except httpx.TimeoutException:
106
+ raise BesselError("request_timeout", **context) from None
107
+ except httpx.HTTPError:
108
+ raise BesselError("connection_error", **context) from None
109
+ retry_after = delay(response.headers.get("Retry-After"))
110
+ try:
111
+ value = response.json()
112
+ except ValueError:
113
+ value = None
114
+ if not 200 <= response.status_code < 300:
115
+ code = (value.get("error") or value.get("detail")) if isinstance(value, dict) else None
116
+ if not isinstance(code, str) or not re.fullmatch(r"[a-z][a-z0-9_]{0,80}", code):
117
+ code = "http_error"
118
+ raise BesselError(code, status_code=response.status_code, retry_after=retry_after, **context)
119
+ if not isinstance(value, dict):
120
+ raise BesselError("invalid_response", status_code=response.status_code, **context)
121
+ return value, retry_after
122
+
123
+ def models(self):
124
+ return self._request("GET", "/models")[0]
125
+
126
+ def usage(self):
127
+ return self._request("GET", "/usage")[0]
128
+
129
+ def create_webhook(self, url, *, idempotency_key):
130
+ if not isinstance(idempotency_key, str) or not re.fullmatch(r'[A-Za-z0-9_.-]{16,128}', idempotency_key):
131
+ raise ValueError('Webhook idempotency_key must contain 16–128 letters, digits, underscores, dots or hyphens')
132
+ return self._request('POST', '/webhook-endpoints', json={'url': url},
133
+ headers={'Idempotency-Key': idempotency_key}, idempotency_key=idempotency_key)[0]
134
+
135
+ def webhooks(self):
136
+ return self._request('GET', '/webhook-endpoints')[0]
137
+
138
+ def verify_webhook_endpoint(self, endpoint_id):
139
+ return self._webhook(endpoint_id, 'POST', '/verify')
140
+
141
+ def disable_webhook(self, endpoint_id):
142
+ return self._webhook(endpoint_id, 'DELETE')
143
+
144
+ def webhook_events(self, endpoint_id):
145
+ return self._webhook(endpoint_id, 'GET', '/events')
146
+
147
+ def _webhook(self, endpoint_id, method, suffix=''):
148
+ if not isinstance(endpoint_id, str) or not re.fullmatch(r'whe_[a-f0-9]{32}', endpoint_id):
149
+ raise ValueError('Invalid webhook endpoint ID')
150
+ return self._request(method, '/webhook-endpoints/'+endpoint_id+suffix)[0]
151
+
152
+ def decision_models(self):
153
+ return self._request('GET', '/decision/models')[0]
154
+
155
+ def decision_account(self):
156
+ return self._request('GET', '/account', api_version=2)[0]
157
+
158
+ def rank(self, audio, candidates, *, language='auto'):
159
+ if not isinstance(candidates, list) or not 2 <= len(candidates) <= 4:
160
+ raise ValueError('Supply 2–4 candidate objects with id and text')
161
+ path = Path(audio)
162
+ with path.open('rb') as file:
163
+ content = file.read(3 * 1024 * 1024 + 1)
164
+ if not 0 < len(content) <= 3 * 1024 * 1024:
165
+ raise ValueError('Ranking audio must contain 1 byte to 3 MiB')
166
+ return self._request('POST', '/rank', data={'candidates':json.dumps(candidates), 'language':language},
167
+ files={'audio':(path.name, content, 'application/octet-stream')})[0]
168
+
169
+ def create_comparison(self, audio, models, default_model, *, idempotency_key):
170
+ if (not isinstance(models, list) or not 2 <= len(models) <= 4
171
+ or any(not isinstance(m, str) or not re.fullmatch(r'[A-Za-z0-9_./-]{1,96}',m) for m in models)
172
+ or len(set(models)) != len(models) or default_model not in models):
173
+ raise ValueError('Choose 2–4 distinct model IDs and one of them as default_model')
174
+ if not isinstance(idempotency_key, str) or not re.fullmatch(r'[A-Za-z0-9_-]{16,80}', idempotency_key):
175
+ raise ValueError('Comparison idempotency_key must contain 16–80 letters, digits, underscores or hyphens')
176
+ path=Path(audio)
177
+ with path.open('rb') as file:
178
+ content=file.read(64*1024*1024+1)
179
+ if not 0 < len(content) <= 64*1024*1024:
180
+ raise ValueError('Comparison audio must contain 1 byte to 64 MiB')
181
+ return self._request('POST', '/comparisons', api_version=2, idempotency_key=idempotency_key,
182
+ headers={'Idempotency-Key':idempotency_key},data={'models':json.dumps(models),'default_model':default_model},
183
+ files={'audio':(path.name,content,'application/octet-stream')})[0]
184
+
185
+ def get_comparison(self, comparison_id):
186
+ return self._comparison(comparison_id)
187
+
188
+ def cancel_comparison(self, comparison_id):
189
+ return self._comparison(comparison_id, 'cancel')
190
+
191
+ def retry_comparison(self, comparison_id):
192
+ """Explicitly retry only a comparison the service marks retryable."""
193
+ return self._comparison(comparison_id, 'retry')
194
+
195
+ def _comparison(self, comparison_id, action=None):
196
+ if not isinstance(comparison_id, str) or not re.fullmatch(r'[a-f0-9]{40}',comparison_id):
197
+ raise ValueError('Invalid comparison ID')
198
+ path='/comparisons/'+comparison_id+('/'+action if action else '')
199
+ return self._request('POST' if action else 'GET',path,api_version=2,job_id=comparison_id)[0]
200
+
201
+ def evaluation_contract(self, model=None):
202
+ return self._request("GET", "/evaluation-contract", params={} if model is None else {"model": model})[
203
+ 0
204
+ ]
205
+
206
+ def get_job(self, job_id):
207
+ return self._request("GET", job_path(job_id), job_id=job_id)[0]
208
+
209
+ def create_job(
210
+ self, audio, *, idempotency_key, model=MULTILINGUAL, language=None, billing_mode="trial_first"
211
+ ):
212
+ if not isinstance(idempotency_key, str) or not re.fullmatch(
213
+ r"[A-Za-z0-9_.-]{16,128}", idempotency_key
214
+ ):
215
+ raise ValueError(
216
+ "idempotency_key must contain 16–128 letters, digits, underscores, dots or hyphens"
217
+ )
218
+ if (
219
+ not isinstance(model, str)
220
+ or not model
221
+ or (language is not None and (not isinstance(language, str) or not language))
222
+ ):
223
+ raise ValueError("model and any supplied language must be nonempty strings")
224
+ if billing_mode not in ("trial_first", "paid"):
225
+ raise ValueError("billing_mode must be trial_first or paid")
226
+ path = Path(audio)
227
+ with path.open("rb") as file:
228
+ content = file.read(MAX_BYTES + 1)
229
+ if not 0 < len(content) <= MAX_BYTES:
230
+ raise ValueError("Audio must contain 1 byte to 24 MiB")
231
+ data = {"model": model, "billing_mode": billing_mode}
232
+ if language is not None:
233
+ data["language"] = language
234
+ value, _ = self._request(
235
+ "POST",
236
+ "/jobs",
237
+ idempotency_key=idempotency_key,
238
+ headers={"Idempotency-Key": idempotency_key},
239
+ data=data,
240
+ files={"file": (path.name, content, "application/octet-stream")},
241
+ )
242
+ if not isinstance(value.get("id"), str) or not value.get("status"):
243
+ raise BesselError("invalid_response", idempotency_key=idempotency_key)
244
+ return value
245
+
246
+ def wait_for_job(self, job_id, *, timeout=300):
247
+ path = job_path(job_id)
248
+ deadline = time.monotonic() + positive(timeout)
249
+ while True:
250
+ remaining = deadline - time.monotonic()
251
+ if remaining <= 0:
252
+ raise BesselError("poll_timeout", job_id=job_id)
253
+ job, retry_after = self._request("GET", path, job_id=job_id, timeout=min(remaining, self.timeout))
254
+ if job.get("id") != job_id:
255
+ raise BesselError("invalid_response", job_id=job_id)
256
+ if job.get("status") == "complete":
257
+ if job.get("result") is None:
258
+ reason = job.get("result_unavailable_reason")
259
+ raise BesselError(
260
+ "transcript_expired" if reason == "expired" else "transcript_unavailable",
261
+ job_id=job_id,
262
+ )
263
+ if not isinstance(job["result"], dict) or not isinstance(job["result"].get("text"), str):
264
+ raise BesselError("invalid_response", job_id=job_id)
265
+ return job
266
+ if job.get("status") == "failed":
267
+ raise BesselError("transcription_failed", job_id=job_id)
268
+ if job.get("status") not in ACTIVE:
269
+ raise BesselError("invalid_response", job_id=job_id)
270
+ remaining = deadline - time.monotonic()
271
+ if remaining <= 0:
272
+ raise BesselError("poll_timeout", job_id=job_id)
273
+ time.sleep(min(remaining, max(retry_after, delay(job.get("poll_after_seconds")))))
274
+
275
+ def transcribe(self, audio, *, timeout=300, **options):
276
+ positive(timeout)
277
+ job = self.create_job(audio, **options)
278
+ try:
279
+ return self.wait_for_job(job["id"], timeout=timeout)
280
+ except BesselError as exc:
281
+ exc.idempotency_key = options["idempotency_key"]
282
+ raise
@@ -0,0 +1,38 @@
1
+ """Verify raw webhook bytes before JSON parsing. Persist event IDs for deduplication."""
2
+ import hashlib
3
+ import hmac
4
+ import json
5
+ import math
6
+ import re
7
+ import time
8
+
9
+
10
+ def verify_webhook(body, headers, secret, *, now=None):
11
+ """Return authenticated JSON; reject altered, stale or >5-minute future requests.
12
+
13
+ This is signature verification, not exactly-once processing. Receivers must
14
+ atomically persist the event ID with their work and acknowledge duplicates.
15
+ """
16
+ invalid = ValueError('Invalid or expired Bessel webhook')
17
+ if not isinstance(body, bytes) or len(body) > 16384 or not isinstance(secret, str) or not secret:
18
+ raise invalid
19
+ values = {k.lower(): v for k, v in headers.items()}
20
+ ident, timestamp, signed = (values.get(k, '') for k in
21
+ ('bessel-webhook-id', 'bessel-webhook-timestamp', 'bessel-webhook-signature'))
22
+ if not all(isinstance(v, str) for v in (ident, timestamp, signed)):
23
+ raise invalid
24
+ if not re.fullmatch(r'(?:whev_[a-f0-9]{32}|verify_[a-f0-9]{48})', ident) or not re.fullmatch(r'[0-9]{1,12}', timestamp):
25
+ raise invalid
26
+ current = time.time() if now is None else now
27
+ if not math.isfinite(current) or not re.fullmatch(r'v1=[a-f0-9]{64}', signed) or abs(current-int(timestamp)) > 300:
28
+ raise invalid
29
+ expected = 'v1='+hmac.new(secret.encode(), (timestamp+'.'+ident+'.').encode()+body, hashlib.sha256).hexdigest()
30
+ if not hmac.compare_digest(signed, expected):
31
+ raise invalid
32
+ try:
33
+ event = json.loads(body)
34
+ except (ValueError, UnicodeError):
35
+ raise invalid from None
36
+ if not isinstance(event, dict) or event.get('id') != ident:
37
+ raise invalid
38
+ return event
@@ -0,0 +1,189 @@
1
+ import httpx
2
+ import pytest
3
+ from bessel_audio import Bessel, BesselError
4
+ from bessel_audio import client as module
5
+
6
+ KEY = "sdk-local-request-0001"
7
+
8
+
9
+ def test_unified_decision_paths_share_key_and_preserve_explicit_receipt(tmp_path):
10
+ audio=tmp_path/'audio.wav';audio.write_bytes(b'audio bytes');calls=[];cid='a'*40
11
+ def handler(request):
12
+ calls.append(request)
13
+ assert request.headers['Authorization']=='Bearer secret-test-token'
14
+ return httpx.Response(200,json={'id':cid,'status':'complete'})
15
+ with client(handler,base_url='https://api.besselaudio.com/v1/') as c:
16
+ c.decision_models();c.decision_account();c.get_comparison(cid)
17
+ c.create_comparison(audio,['a','b'],'a',idempotency_key=KEY)
18
+ c.cancel_comparison(cid);c.retry_comparison(cid)
19
+ c.rank(audio,[{'id':'a','text':'one'},{'id':'b','text':'two'}])
20
+ assert [r.url.path for r in calls]==['/v1/decision/models','/v2/account','/v2/comparisons/'+cid,
21
+ '/v2/comparisons','/v2/comparisons/'+cid+'/cancel','/v2/comparisons/'+cid+'/retry','/v1/rank']
22
+ assert calls[3].headers['Idempotency-Key']==KEY and b'name="audio"' in calls[3].read()
23
+
24
+
25
+ def test_decision_errors_preserve_legacy_detail_without_retry(tmp_path):
26
+ calls=[]
27
+ def handler(request):
28
+ calls.append(request);return httpx.Response(409,json={'detail':'legacy_account_link_required'})
29
+ with client(handler) as c:
30
+ with pytest.raises(BesselError) as error:c.decision_account()
31
+ assert error.value.code=='legacy_account_link_required' and len(calls)==1
32
+ with pytest.raises(ValueError):c.get_comparison('../account')
33
+ assert len(calls)==1
34
+
35
+
36
+ def client(handler, **options):
37
+ return Bessel("secret-test-token", transport=httpx.MockTransport(handler), **options)
38
+
39
+
40
+ def test_upload_then_poll_preserves_utf8_empty_text_and_one_submission(tmp_path, monkeypatch):
41
+ audio = tmp_path / "中文.wav"
42
+ audio.write_bytes(b"test audio bytes")
43
+ requests = []
44
+ clock = [0.0]
45
+ monkeypatch.setattr(module.time, "monotonic", lambda: clock[0])
46
+ monkeypatch.setattr(module.time, "sleep", lambda n: clock.__setitem__(0, clock[0] + n))
47
+
48
+ def handle(req):
49
+ requests.append(req)
50
+ assert req.headers["authorization"] == "Bearer secret-test-token"
51
+ assert str(req.url).startswith("https://api.besselaudio.com/v1/")
52
+ if req.method == "POST":
53
+ assert req.headers["idempotency-key"] == KEY
54
+ body = req.read()
55
+ assert b"test audio bytes" in body and b'name="billing_mode"\r\n\r\npaid' in body
56
+ assert b'name="language"\r\n\r\nzh' in body
57
+ return httpx.Response(202, json={"id": "job_test", "status": "processing"})
58
+ if len(requests) == 2:
59
+ return httpx.Response(
60
+ 200,
61
+ headers={"Retry-After": "5"},
62
+ json={"id": "job_test", "status": "running", "poll_after_seconds": 2},
63
+ )
64
+ return httpx.Response(200, json={"id": "job_test", "status": "complete", "result": {"text": ""}})
65
+
66
+ with client(handle, base_url="https://api.besselaudio.com/v1/") as c:
67
+ result = c.transcribe(audio, idempotency_key=KEY, language="zh", billing_mode="paid", timeout=10)
68
+ assert result["result"]["text"] == "" and clock[0] == 5
69
+ assert [r.method for r in requests] == ["POST", "GET", "GET"]
70
+
71
+
72
+ @pytest.mark.parametrize("failure", ["timeout", "disconnect", "503", "redirect"])
73
+ def test_uncertain_upload_is_never_retried_and_retains_recovery_key(tmp_path, failure):
74
+ audio = tmp_path / "a.wav"
75
+ audio.write_bytes(b"audio")
76
+ calls = []
77
+
78
+ def handle(req):
79
+ calls.append(req)
80
+ if failure == "timeout":
81
+ raise httpx.ReadTimeout("secret-test-token")
82
+ if failure == "disconnect":
83
+ raise httpx.ReadError("secret-test-token")
84
+ return httpx.Response(
85
+ 503 if failure == "503" else 307,
86
+ headers={"Location": "https://other.example/collect"},
87
+ text="secret-test-token",
88
+ )
89
+
90
+ with client(handle) as c, pytest.raises(BesselError) as exc:
91
+ c.create_job(audio, idempotency_key=KEY)
92
+ assert len(calls) == 1 and exc.value.idempotency_key == KEY
93
+ assert "secret-test-token" not in str(exc.value)
94
+
95
+
96
+ @pytest.mark.parametrize(
97
+ "job,code",
98
+ [
99
+ ({"status": "failed", "error": "provider_failure"}, "transcription_failed"),
100
+ (
101
+ {"status": "complete", "result": None, "result_unavailable_reason": "expired"},
102
+ "transcript_expired",
103
+ ),
104
+ (
105
+ {"status": "complete", "result": None, "result_unavailable_reason": "deleted"},
106
+ "transcript_unavailable",
107
+ ),
108
+ ({"status": "complete", "result": {}}, "invalid_response"),
109
+ ({"status": "unknown"}, "invalid_response"),
110
+ ],
111
+ )
112
+ def test_failed_missing_and_expired_results_are_not_successes(job, code):
113
+ with (
114
+ client(lambda r: httpx.Response(200, json={"id": "job_test", **job})) as c,
115
+ pytest.raises(BesselError) as exc,
116
+ ):
117
+ c.wait_for_job("job_test")
118
+ assert exc.value.code == code and exc.value.job_id == "job_test"
119
+
120
+
121
+ def test_poll_deadline_uses_get_only_and_preserves_job(monkeypatch):
122
+ clock = [0.0]
123
+ calls = []
124
+ monkeypatch.setattr(module.time, "monotonic", lambda: clock[0])
125
+ monkeypatch.setattr(module.time, "sleep", lambda n: clock.__setitem__(0, clock[0] + n))
126
+
127
+ def handle(req):
128
+ calls.append(req)
129
+ return httpx.Response(200, headers={"Retry-After": "20"}, json={"id": "job_test", "status": "queued"})
130
+
131
+ with client(handle) as c, pytest.raises(BesselError) as exc:
132
+ c.wait_for_job("job_test", timeout=2)
133
+ assert exc.value.code == "poll_timeout" and exc.value.job_id == "job_test"
134
+ assert clock[0] == 2 and [r.method for r in calls] == ["GET"]
135
+
136
+
137
+ @pytest.mark.parametrize(
138
+ "value",
139
+ [
140
+ "http://example.com",
141
+ "https://a.example/v1/other",
142
+ "https://key@api.besselaudio.com",
143
+ "https://api.besselaudio.com?key=secret",
144
+ ],
145
+ )
146
+ def test_credentials_cannot_use_insecure_or_ambiguous_base_urls(value):
147
+ with pytest.raises(ValueError):
148
+ client(lambda r: None, base_url=value)
149
+
150
+
151
+ @pytest.mark.parametrize("value", ["../models", "a/b", "..", "x?key=foo"])
152
+ def test_job_paths_cannot_escape_endpoint(value):
153
+ with client(lambda r: pytest.fail("must not send")) as c, pytest.raises(ValueError):
154
+ c.get_job(value)
155
+
156
+
157
+ def test_input_validation_happens_before_any_request(tmp_path):
158
+ path = tmp_path / "empty.wav"
159
+ path.write_bytes(b"")
160
+ with client(lambda r: pytest.fail("must not send")) as c:
161
+ for options in (
162
+ {"idempotency_key": "short"},
163
+ {"idempotency_key": KEY, "billing_mode": "free"},
164
+ {"idempotency_key": KEY},
165
+ ):
166
+ with pytest.raises(ValueError):
167
+ c.create_job(path, **options)
168
+ with pytest.raises(ValueError):
169
+ c.transcribe(path, idempotency_key=KEY, timeout=float("nan"))
170
+
171
+
172
+ def test_http_error_exposes_status_and_retry_after_but_no_untrusted_body():
173
+ with (
174
+ client(
175
+ lambda r: httpx.Response(
176
+ 429,
177
+ headers={"Retry-After": "30"},
178
+ json={"error": "daily_trial_capacity_reached", "detail": "secret-test-token"},
179
+ )
180
+ ) as c,
181
+ pytest.raises(BesselError) as exc,
182
+ ):
183
+ c.models()
184
+ assert (exc.value.code, exc.value.status_code, exc.value.retry_after) == (
185
+ "daily_trial_capacity_reached",
186
+ 429,
187
+ 30,
188
+ )
189
+ assert "secret-test-token" not in str(exc.value)
@@ -0,0 +1,33 @@
1
+ import hashlib
2
+ import hmac
3
+ import json
4
+ import httpx
5
+ import pytest
6
+ from bessel_audio import Bessel, verify_webhook
7
+
8
+ SECRET = 'unit-test-secret'
9
+ ID = 'whev_'+'a'*32
10
+ BODY = json.dumps({'id':ID,'type':'transcription.completed','data':{'job_id':'job_test'}}).encode()
11
+ HEADERS = {'Bessel-Webhook-Id':ID,'Bessel-Webhook-Timestamp':'1800000000',
12
+ 'Bessel-Webhook-Signature':'v1='+hmac.new(SECRET.encode(),('1800000000.'+ID+'.').encode()+BODY,hashlib.sha256).hexdigest()}
13
+
14
+ def test_raw_signature_and_time_boundaries():
15
+ assert verify_webhook(BODY,HEADERS,SECRET,now=1800000000)['id']==ID
16
+ for body,secret,now in [(BODY+b' ',SECRET,1800000000),(BODY,'wrong',1800000000),
17
+ (BODY,SECRET,1800000301),(BODY,SECRET,1799999699),(BODY,SECRET,float('nan'))]:
18
+ with pytest.raises(ValueError): verify_webhook(body,HEADERS,secret,now=now)
19
+ # Same signed delivery is valid twice; deduplication belongs to the receiver's transaction.
20
+ assert verify_webhook(BODY,HEADERS,SECRET,now=1800000000)==verify_webhook(BODY,HEADERS,SECRET,now=1800000000)
21
+
22
+ def test_management_uses_original_key_and_secret_is_never_resubmitted():
23
+ calls=[];ident='whe_'+'b'*32
24
+ def handler(request):
25
+ assert request.headers['Authorization']=='Bearer unit-test-key'
26
+ calls.append(request)
27
+ return httpx.Response(200,json={'id':ident})
28
+ with Bessel('unit-test-key',transport=httpx.MockTransport(handler)) as client:
29
+ client.create_webhook('https://receiver.example.com',idempotency_key='unit-test-receipt-001')
30
+ client.webhooks();client.verify_webhook_endpoint(ident);client.webhook_events(ident);client.disable_webhook(ident)
31
+ with pytest.raises(ValueError): client.disable_webhook('../usage')
32
+ assert [r.method for r in calls]==['POST','GET','POST','GET','DELETE']
33
+ assert calls[0].headers['Idempotency-Key']=='unit-test-receipt-001'