zilapi 0.5.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,117 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any
4
+
5
+ from .._base import idempotency_key as make_key
6
+ from .._base import parse
7
+ from ..types import File, Job
8
+
9
+ if TYPE_CHECKING:
10
+ from .._client import AsyncZilAPI, ZilAPI
11
+
12
+ FILLER_MODEL = "zilapi/filler-1.0"
13
+
14
+
15
+ def _filler_body(
16
+ file: str | File | None, input_url: str | None, model: str | None, timestamps_only: bool
17
+ ) -> dict[str, Any]:
18
+ if (file is None) == (input_url is None):
19
+ raise ValueError("pass exactly one of file or input_url")
20
+ body: dict[str, Any] = (
21
+ {"file": file.id if isinstance(file, File) else file}
22
+ if file is not None
23
+ else {"input_url": input_url}
24
+ )
25
+ if model is not None:
26
+ body["model"] = model
27
+ if timestamps_only:
28
+ body["options"] = {"timestamps_only": True}
29
+ return body
30
+
31
+
32
+ class Audio:
33
+ def __init__(self, client: ZilAPI) -> None:
34
+ self._client = client
35
+
36
+ def denoise(
37
+ self, *, file: str | File, model: str | None = "zilapi/nr-4.1", idempotency_key: str | None = None
38
+ ) -> Job:
39
+ """Submit a ready file for denoising."""
40
+ body = {"file": file.id if isinstance(file, File) else file}
41
+ if model is not None:
42
+ body["model"] = model
43
+ return parse(
44
+ Job.from_dict,
45
+ self._client._request(
46
+ "POST", "/v1/audio/denoise", json=body, headers={"Idempotency-Key": make_key(idempotency_key)}
47
+ ),
48
+ )
49
+
50
+ def remove_fillers(
51
+ self,
52
+ *,
53
+ file: str | File | None = None,
54
+ input_url: str | None = None,
55
+ model: str | None = FILLER_MODEL,
56
+ timestamps_only: bool = False,
57
+ idempotency_key: str | None = None,
58
+ ) -> Job:
59
+ """Submit audio for filler removal (um, uh, er): pass a ready ``file`` or an https ``input_url``.
60
+
61
+ The job's outputs are ``audio`` (the edited MP3) and ``fillers`` (a JSON report, also on
62
+ ``job.result.fillers``). ``timestamps_only=True`` returns only the report. Works best on
63
+ single-speaker speech; with overlapping speakers short words can occasionally be cut.
64
+ """
65
+ return parse(
66
+ Job.from_dict,
67
+ self._client._request(
68
+ "POST",
69
+ "/v1/audio/remove-fillers",
70
+ json=_filler_body(file, input_url, model, timestamps_only),
71
+ headers={"Idempotency-Key": make_key(idempotency_key)},
72
+ ),
73
+ )
74
+
75
+
76
+ class AsyncAudio:
77
+ def __init__(self, client: AsyncZilAPI) -> None:
78
+ self._client = client
79
+
80
+ async def denoise(
81
+ self, *, file: str | File, model: str | None = "zilapi/nr-4.1", idempotency_key: str | None = None
82
+ ) -> Job:
83
+ """Submit a ready file for denoising."""
84
+ body = {"file": file.id if isinstance(file, File) else file}
85
+ if model is not None:
86
+ body["model"] = model
87
+ return parse(
88
+ Job.from_dict,
89
+ await self._client._request(
90
+ "POST", "/v1/audio/denoise", json=body, headers={"Idempotency-Key": make_key(idempotency_key)}
91
+ ),
92
+ )
93
+
94
+ async def remove_fillers(
95
+ self,
96
+ *,
97
+ file: str | File | None = None,
98
+ input_url: str | None = None,
99
+ model: str | None = FILLER_MODEL,
100
+ timestamps_only: bool = False,
101
+ idempotency_key: str | None = None,
102
+ ) -> Job:
103
+ """Submit audio for filler removal (um, uh, er): pass a ready ``file`` or an https ``input_url``.
104
+
105
+ The job's outputs are ``audio`` (the edited MP3) and ``fillers`` (a JSON report, also on
106
+ ``job.result.fillers``). ``timestamps_only=True`` returns only the report. Works best on
107
+ single-speaker speech; with overlapping speakers short words can occasionally be cut.
108
+ """
109
+ return parse(
110
+ Job.from_dict,
111
+ await self._client._request(
112
+ "POST",
113
+ "/v1/audio/remove-fillers",
114
+ json=_filler_body(file, input_url, model, timestamps_only),
115
+ headers={"Idempotency-Key": make_key(idempotency_key)},
116
+ ),
117
+ )
@@ -0,0 +1,27 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ from .._base import parse
6
+ from ..types import Credits
7
+
8
+ if TYPE_CHECKING:
9
+ from .._client import AsyncZilAPI, ZilAPI
10
+
11
+
12
+ class CreditsResource:
13
+ def __init__(self, client: ZilAPI) -> None:
14
+ self._client = client
15
+
16
+ def retrieve(self) -> Credits:
17
+ """Retrieve available, reserved, and total account credit."""
18
+ return parse(Credits.from_dict, self._client._request("GET", "/v1/credits"))
19
+
20
+
21
+ class AsyncCredits:
22
+ def __init__(self, client: AsyncZilAPI) -> None:
23
+ self._client = client
24
+
25
+ async def retrieve(self) -> Credits:
26
+ """Retrieve available, reserved, and total account credit."""
27
+ return parse(Credits.from_dict, await self._client._request("GET", "/v1/credits"))
@@ -0,0 +1,291 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import os
5
+ import threading
6
+ from collections.abc import Mapping
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from contextlib import suppress
9
+ from typing import TYPE_CHECKING, Any, BinaryIO
10
+
11
+ from .._base import idempotency_key as make_key
12
+ from .._base import parse, poll_delay, segment, validate_poll
13
+ from .._uploads import Source, aput, put
14
+ from ..errors import FileRejectedError, UploadError, WaitTimeoutError
15
+ from ..types import File
16
+
17
+ if TYPE_CHECKING:
18
+ from .._client import AsyncZilAPI, ZilAPI
19
+
20
+
21
+ def _path(file_id: str) -> str:
22
+ return f"/v1/files/{segment(file_id)}"
23
+
24
+
25
+ def _ready(file: File) -> bool:
26
+ if file.status in ("rejected", "deleted"):
27
+ raise FileRejectedError(file)
28
+ return file.is_ready
29
+
30
+
31
+ def _upload_plan(created: Mapping[str, Any]) -> tuple[str, dict[str, Any] | None]:
32
+ file_id = created["id"]
33
+ upload = created.get("upload")
34
+ if not isinstance(file_id, str):
35
+ raise TypeError("file id must be a string")
36
+ if upload is not None:
37
+ required = ("url", "headers") if upload["method"] == "PUT" else ("part_size", "parts")
38
+ missing = [name for name in required if name not in upload]
39
+ if missing:
40
+ raise KeyError(missing[0])
41
+ return file_id, upload
42
+
43
+
44
+ def _check_resumable(file_id: str, created: Mapping[str, Any]) -> None:
45
+ status = created.get("status")
46
+ if status == "uploading":
47
+ raise UploadError(
48
+ f"The upload window for file {file_id} has expired; "
49
+ "create the file again with a new idempotency key"
50
+ )
51
+ if status == "deleted":
52
+ raise UploadError(
53
+ f"File {file_id} was deleted (for example after a failed upload) and cannot be resumed; "
54
+ "create the file again with a new idempotency key"
55
+ )
56
+
57
+
58
+ class Files:
59
+ def __init__(self, client: ZilAPI) -> None:
60
+ self._client = client
61
+
62
+ def create(
63
+ self,
64
+ file: str | os.PathLike[str] | bytes | BinaryIO,
65
+ *,
66
+ filename: str | None = None,
67
+ content_type: str | None = None,
68
+ wait: bool = True,
69
+ timeout: float = 600.0,
70
+ upload_concurrency: int = 4,
71
+ idempotency_key: str | None = None,
72
+ ) -> File:
73
+ """Upload audio, video or an image and optionally wait for validation."""
74
+ if upload_concurrency < 1:
75
+ raise ValueError("upload_concurrency must be positive")
76
+ validate_poll(timeout)
77
+ source = Source(file, filename, content_type)
78
+ key = make_key(idempotency_key, max_length=246) # Reserve nine characters for :complete.
79
+ created = self._client._request(
80
+ "POST",
81
+ "/v1/files",
82
+ json={
83
+ "filename": source.filename,
84
+ "size_bytes": source.size,
85
+ "content_type": source.content_type,
86
+ },
87
+ headers={"Idempotency-Key": key},
88
+ )
89
+ file_id, upload = parse(_upload_plan, created)
90
+ if upload is None: # Replayed key: the upload already reached the server, or its window expired.
91
+ _check_resumable(file_id, created)
92
+ current = self.retrieve(file_id)
93
+ return self._wait(file_id, timeout, current) if wait else current
94
+ body: dict[str, Any] = {}
95
+ self._client._storage_client() # Initialize before any worker threads.
96
+ try:
97
+ if upload["method"] == "PUT":
98
+ put(self._client, source, upload["url"], upload["headers"])
99
+ else:
100
+ part_size: int = upload["part_size"]
101
+ failed = threading.Event()
102
+
103
+ def send(part: dict[str, Any]) -> dict[str, Any] | None:
104
+ if failed.is_set(): # Another part failed for good; skip queued parts.
105
+ return None
106
+ number: int = part["part_number"]
107
+ offset = (number - 1) * part_size
108
+ try:
109
+ etag = put(
110
+ self._client,
111
+ source,
112
+ part["url"],
113
+ {},
114
+ offset=offset,
115
+ length=min(part_size, source.size - offset),
116
+ part_number=number,
117
+ )
118
+ except BaseException:
119
+ failed.set()
120
+ raise
121
+ return {"part_number": number, "etag": etag}
122
+
123
+ with ThreadPoolExecutor(max_workers=upload_concurrency) as pool:
124
+ parts = [part for part in pool.map(send, upload["parts"]) if part is not None]
125
+ body["parts"] = sorted(parts, key=lambda part: part["part_number"])
126
+ except UploadError:
127
+ with suppress(Exception):
128
+ self.delete(file_id)
129
+ raise
130
+ completed = parse(
131
+ File.from_dict,
132
+ self._client._request(
133
+ "POST",
134
+ _path(file_id) + "/complete",
135
+ json=body,
136
+ headers={"Idempotency-Key": f"{key}:complete"},
137
+ ),
138
+ )
139
+ return self._wait(file_id, timeout, completed) if wait else completed
140
+
141
+ def retrieve(self, file_id: str) -> File:
142
+ """Retrieve a file's metadata and validation status."""
143
+ return parse(File.from_dict, self._client._request("GET", _path(file_id)))
144
+
145
+ def delete(self, file_id: str) -> None:
146
+ """Delete a file that is not in use."""
147
+ self._client._request("DELETE", _path(file_id))
148
+
149
+ def wait_until_ready(self, file_id: str, *, timeout: float = 600.0) -> File:
150
+ """Poll until the file is ready, rejected, deleted, or the deadline passes."""
151
+ validate_poll(timeout)
152
+ return self._wait(file_id, timeout)
153
+
154
+ def _wait(self, file_id: str, timeout: float, last: File | None = None) -> File:
155
+ start = self._client._monotonic()
156
+ delay = 0.5
157
+ while True:
158
+ if last is not None:
159
+ if _ready(last):
160
+ return last
161
+ elapsed = self._client._monotonic() - start
162
+ if elapsed >= timeout:
163
+ raise WaitTimeoutError(last)
164
+ self._client._sleep(poll_delay(elapsed, timeout, delay))
165
+ delay = min(5, delay * 1.5)
166
+ if self._client._monotonic() - start >= timeout:
167
+ raise WaitTimeoutError(last)
168
+ last = self.retrieve(file_id)
169
+
170
+
171
+ class AsyncFiles:
172
+ def __init__(self, client: AsyncZilAPI) -> None:
173
+ self._client = client
174
+
175
+ async def create(
176
+ self,
177
+ file: str | os.PathLike[str] | bytes | BinaryIO,
178
+ *,
179
+ filename: str | None = None,
180
+ content_type: str | None = None,
181
+ wait: bool = True,
182
+ timeout: float = 600.0,
183
+ upload_concurrency: int = 4,
184
+ idempotency_key: str | None = None,
185
+ ) -> File:
186
+ """Upload audio, video or an image and optionally wait for validation."""
187
+ if upload_concurrency < 1:
188
+ raise ValueError("upload_concurrency must be positive")
189
+ validate_poll(timeout)
190
+ source = Source(file, filename, content_type)
191
+ key = make_key(idempotency_key, max_length=246) # Reserve nine characters for :complete.
192
+ created = await self._client._request(
193
+ "POST",
194
+ "/v1/files",
195
+ json={
196
+ "filename": source.filename,
197
+ "size_bytes": source.size,
198
+ "content_type": source.content_type,
199
+ },
200
+ headers={"Idempotency-Key": key},
201
+ )
202
+ file_id, upload = parse(_upload_plan, created)
203
+ if upload is None: # Replayed key: the upload already reached the server, or its window expired.
204
+ _check_resumable(file_id, created)
205
+ current = await self.retrieve(file_id)
206
+ return await self._wait(file_id, timeout, current) if wait else current
207
+ body: dict[str, Any] = {}
208
+ try:
209
+ if upload["method"] == "PUT":
210
+ await aput(self._client, source, upload["url"], upload["headers"])
211
+ else:
212
+ part_size: int = upload["part_size"]
213
+ semaphore = asyncio.Semaphore(upload_concurrency)
214
+ failed = False
215
+
216
+ async def send(part: dict[str, Any]) -> dict[str, Any] | None:
217
+ nonlocal failed
218
+ async with semaphore:
219
+ if failed: # Another part failed for good; skip queued parts.
220
+ return None
221
+ number: int = part["part_number"]
222
+ offset = (number - 1) * part_size
223
+ try:
224
+ etag = await aput(
225
+ self._client,
226
+ source,
227
+ part["url"],
228
+ {},
229
+ offset=offset,
230
+ length=min(part_size, source.size - offset),
231
+ part_number=number,
232
+ )
233
+ except BaseException:
234
+ failed = True
235
+ raise
236
+ return {"part_number": number, "etag": etag}
237
+
238
+ # Settle every in-flight PUT before deleting a failed upload.
239
+ results = await asyncio.gather(
240
+ *(send(part) for part in upload["parts"]), return_exceptions=True
241
+ )
242
+ parts = []
243
+ for result in results:
244
+ if isinstance(result, BaseException):
245
+ raise result
246
+ if result is not None:
247
+ parts.append(result)
248
+ body["parts"] = sorted(parts, key=lambda part: part["part_number"])
249
+ except UploadError:
250
+ with suppress(Exception):
251
+ await self.delete(file_id)
252
+ raise
253
+ completed = parse(
254
+ File.from_dict,
255
+ await self._client._request(
256
+ "POST",
257
+ _path(file_id) + "/complete",
258
+ json=body,
259
+ headers={"Idempotency-Key": f"{key}:complete"},
260
+ ),
261
+ )
262
+ return await self._wait(file_id, timeout, completed) if wait else completed
263
+
264
+ async def retrieve(self, file_id: str) -> File:
265
+ """Retrieve a file's metadata and validation status."""
266
+ return parse(File.from_dict, await self._client._request("GET", _path(file_id)))
267
+
268
+ async def delete(self, file_id: str) -> None:
269
+ """Delete a file that is not in use."""
270
+ await self._client._request("DELETE", _path(file_id))
271
+
272
+ async def wait_until_ready(self, file_id: str, *, timeout: float = 600.0) -> File:
273
+ """Poll until the file is ready, rejected, deleted, or the deadline passes."""
274
+ validate_poll(timeout)
275
+ return await self._wait(file_id, timeout)
276
+
277
+ async def _wait(self, file_id: str, timeout: float, last: File | None = None) -> File:
278
+ start = self._client._monotonic()
279
+ delay = 0.5
280
+ while True:
281
+ if last is not None:
282
+ if _ready(last):
283
+ return last
284
+ elapsed = self._client._monotonic() - start
285
+ if elapsed >= timeout:
286
+ raise WaitTimeoutError(last)
287
+ await self._client._sleep(poll_delay(elapsed, timeout, delay))
288
+ delay = min(5, delay * 1.5)
289
+ if self._client._monotonic() - start >= timeout:
290
+ raise WaitTimeoutError(last)
291
+ last = await self.retrieve(file_id)