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,375 @@
1
+ """Image jobs: background removal (``POST /v1/image/remove-background``, model ``zilapi/bgr-1.0``).
2
+
3
+ The API is asynchronous (create a job, then poll or take a webhook, then download). ``remove_background``
4
+ waits for the job by default with a short poll cadence suited to images (they finish in seconds), and
5
+ returns a :class:`BackgroundRemoval` that knows how to save or read its two outputs: ``image``, the cut-out
6
+ (PNG, RGBA, straight alpha, the input's upright size) and ``mask``, the alpha matte (8-bit greyscale PNG).
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ import os
13
+ import tempfile
14
+ from dataclasses import dataclass, field
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+ from typing import TYPE_CHECKING, Any, BinaryIO
18
+
19
+ from .._base import Multipart, parse, validate_poll
20
+ from .._base import idempotency_key as make_key
21
+ from .._uploads import Source
22
+ from ..errors import JobFailedError
23
+ from ..types import File, Job, JobError, JobOutputFile
24
+
25
+ if TYPE_CHECKING:
26
+ from .._client import AsyncZilAPI, ZilAPI
27
+
28
+ BGR_MODEL = "zilapi/bgr-1.0"
29
+ PATH = "/v1/image/remove-background"
30
+ # Images take seconds, so poll every second for the first minute, then every five seconds. The
31
+ # default deadline leaves room for a queue; WaitTimeoutError carries the last job to resume from.
32
+ WAIT_TIMEOUT = 600.0
33
+ POLL_INITIAL = 1.0
34
+ POLL_INITIAL_PERIOD = 60.0
35
+ POLL_INTERVAL = 5.0
36
+ # Local images up to this size go in one multipart request, held in memory so a retry resends the
37
+ # same bytes. Larger ones use the streamed presigned upload (files.create) and are passed by file ID,
38
+ # so memory stays bounded and the multipart body cap (25 MB with a test key) never applies. This
39
+ # picks a transport only: the server still enforces the image limits either way.
40
+ INLINE_MAX_BYTES = 20 * 1024 * 1024
41
+ FILE_KEY_MAX = 246 # files.create reserves nine characters for its ":complete" key.
42
+
43
+
44
+ def _request(
45
+ image: str | os.PathLike[str] | bytes | BinaryIO | None,
46
+ file: str | File | None,
47
+ input_url: str | None,
48
+ filename: str | None,
49
+ content_type: str | None,
50
+ model: str | None,
51
+ webhook_url: str | None,
52
+ end_user: str | None,
53
+ ) -> tuple[dict[str, Any], Multipart | None, bool]:
54
+ """Build the JSON body (``file`` / ``input_url``) or the multipart body (a small local ``image``).
55
+
56
+ Returns ``(json, multipart, upload)``: ``upload`` is True for a large local image, which the caller
57
+ uploads with ``files.create`` and then adds as ``file`` to the JSON fields. The server validates the
58
+ image (type, size, pixels); the SDK only infers the content type from the filename.
59
+ """
60
+ if sum(value is not None for value in (image, file, input_url)) != 1:
61
+ raise ValueError("pass exactly one of image, file or input_url")
62
+ fields: dict[str, str] = {}
63
+ for name, value in (("model", model), ("webhook_url", webhook_url), ("end_user", end_user)):
64
+ if value is not None:
65
+ fields[name] = value
66
+ if image is None:
67
+ body: dict[str, Any] = (
68
+ {"file": file.id if isinstance(file, File) else file}
69
+ if file is not None
70
+ else {"input_url": input_url}
71
+ )
72
+ return {**body, **fields}, None, False
73
+ source = Source(image, filename, content_type)
74
+ if source.size > INLINE_MAX_BYTES:
75
+ return fields, None, True
76
+ # Images are small (tens of MB at most), so the part is read into memory once: a retried request
77
+ # resends identical bytes, which the server's idempotency check (name, size, type, SHA-256) requires.
78
+ data = b"".join(source.chunks())
79
+ return {}, Multipart(fields, {"file": (source.filename, data, source.content_type)}), False
80
+
81
+
82
+ def _file_key(key: str) -> str:
83
+ """The upload's idempotency key, derived from the job's so a retried call reuses the same file."""
84
+ suffix = ":file"
85
+ if len(key) + len(suffix) <= FILE_KEY_MAX:
86
+ return key + suffix
87
+ return hashlib.sha256(key.encode()).hexdigest() + suffix
88
+
89
+
90
+ def _require(job: Job, name: str) -> None:
91
+ # A payment_required job (bill after) goes to the output endpoint, which pays it first or answers 402.
92
+ if job.status not in ("succeeded", "payment_required"):
93
+ raise JobFailedError(job)
94
+ if job.output is not None and job.output.files and job.output.file(name) is None:
95
+ raise ValueError(f"job {job.id} has no {name!r} output")
96
+
97
+
98
+ @dataclass(frozen=True)
99
+ class _Result:
100
+ job: Job
101
+
102
+ @property
103
+ def id(self) -> str:
104
+ """The job ID (``job_…``)."""
105
+ return self.job.id
106
+
107
+ @property
108
+ def status(self) -> str:
109
+ """The job status; ``succeeded`` once both outputs are stored."""
110
+ return self.job.status
111
+
112
+ @property
113
+ def succeeded(self) -> bool:
114
+ """Whether the cut-out and mask are ready to download."""
115
+ return self.job.succeeded
116
+
117
+ @property
118
+ def error(self) -> JobError | None:
119
+ """Why the job failed (for example ``invalid_image`` or ``image_too_large``), else None."""
120
+ return self.job.error
121
+
122
+ @property
123
+ def image(self) -> JobOutputFile | None:
124
+ """The ``image`` output (the cut-out PNG), once the job succeeded."""
125
+ return self.job.output.file("image") if self.job.output is not None else None
126
+
127
+ @property
128
+ def mask(self) -> JobOutputFile | None:
129
+ """The ``mask`` output (the greyscale alpha matte PNG), once the job succeeded."""
130
+ return self.job.output.file("mask") if self.job.output is not None else None
131
+
132
+ @property
133
+ def expires_at(self) -> datetime | None:
134
+ """When the outputs are deleted (7 days after success)."""
135
+ return self.job.output.expires_at if self.job.output is not None else None
136
+
137
+
138
+ @dataclass(frozen=True)
139
+ class BackgroundRemoval(_Result):
140
+ """A background removal job with helpers to wait for it and save or read its outputs."""
141
+
142
+ _client: ZilAPI = field(repr=False, compare=False)
143
+
144
+ def wait(self, *, timeout: float | None = WAIT_TIMEOUT) -> BackgroundRemoval:
145
+ """Poll until the job finishes (every second for a minute, then every five seconds)."""
146
+ if self.job.is_terminal:
147
+ return self
148
+ job = self._client.jobs.wait(
149
+ self.job,
150
+ timeout=timeout,
151
+ initial_interval=POLL_INITIAL,
152
+ initial_period=POLL_INITIAL_PERIOD,
153
+ interval=POLL_INTERVAL,
154
+ )
155
+ return BackgroundRemoval(job, self._client)
156
+
157
+ def refresh(self) -> BackgroundRemoval:
158
+ """Fetch the job's current state once."""
159
+ return BackgroundRemoval(self._client.jobs.retrieve(self.job.id), self._client)
160
+
161
+ def save(self, path: str | os.PathLike[str], *, overwrite: bool = False) -> Path:
162
+ """Save the cut-out PNG (RGBA) to ``path``; a directory uses the server's ``<stem>-cutout.png``."""
163
+ return self._save("image", path, overwrite)
164
+
165
+ def save_mask(self, path: str | os.PathLike[str], *, overwrite: bool = False) -> Path:
166
+ """Save the mask PNG (8-bit greyscale) to ``path``; a directory uses ``<stem>-mask.png``."""
167
+ return self._save("mask", path, overwrite)
168
+
169
+ def read(self) -> bytes:
170
+ """Download the cut-out PNG into memory."""
171
+ return self._read("image")
172
+
173
+ def read_mask(self) -> bytes:
174
+ """Download the mask PNG into memory."""
175
+ return self._read("mask")
176
+
177
+ def _ready(self, name: str) -> Job:
178
+ """The job to download from; a payment_required job is paid first, then re-read for its sizes."""
179
+ _require(self.job, name)
180
+ if self.job.status != "payment_required":
181
+ return self.job
182
+ self._client.jobs.output(self.job.id, name=name) # Pays from credit, or raises 402.
183
+ job = self._client.jobs.retrieve(self.job.id)
184
+ if job.output is None:
185
+ raise JobFailedError(job)
186
+ return job
187
+
188
+ def _save(self, name: str, path: str | os.PathLike[str], overwrite: bool) -> Path:
189
+ return self._client.jobs.download(self._ready(name), path, overwrite=overwrite, name=name)
190
+
191
+ def _read(self, name: str) -> bytes:
192
+ job = self._ready(name)
193
+ # Reuse the size-checked, retried download; the temporary directory is private to this call.
194
+ with tempfile.TemporaryDirectory(prefix="zilapi-") as directory:
195
+ target = Path(directory) / "output.png"
196
+ self._client.jobs.download(job, target, name=name)
197
+ return target.read_bytes()
198
+
199
+
200
+ @dataclass(frozen=True)
201
+ class AsyncBackgroundRemoval(_Result):
202
+ """A background removal job with async helpers to wait for it and save or read its outputs."""
203
+
204
+ _client: AsyncZilAPI = field(repr=False, compare=False)
205
+
206
+ async def wait(self, *, timeout: float | None = WAIT_TIMEOUT) -> AsyncBackgroundRemoval:
207
+ """Poll until the job finishes (every second for a minute, then every five seconds)."""
208
+ if self.job.is_terminal:
209
+ return self
210
+ job = await self._client.jobs.wait(
211
+ self.job,
212
+ timeout=timeout,
213
+ initial_interval=POLL_INITIAL,
214
+ initial_period=POLL_INITIAL_PERIOD,
215
+ interval=POLL_INTERVAL,
216
+ )
217
+ return AsyncBackgroundRemoval(job, self._client)
218
+
219
+ async def refresh(self) -> AsyncBackgroundRemoval:
220
+ """Fetch the job's current state once."""
221
+ return AsyncBackgroundRemoval(await self._client.jobs.retrieve(self.job.id), self._client)
222
+
223
+ async def save(self, path: str | os.PathLike[str], *, overwrite: bool = False) -> Path:
224
+ """Save the cut-out PNG (RGBA) to ``path``; a directory uses the server's ``<stem>-cutout.png``."""
225
+ return await self._save("image", path, overwrite)
226
+
227
+ async def save_mask(self, path: str | os.PathLike[str], *, overwrite: bool = False) -> Path:
228
+ """Save the mask PNG (8-bit greyscale) to ``path``; a directory uses ``<stem>-mask.png``."""
229
+ return await self._save("mask", path, overwrite)
230
+
231
+ async def read(self) -> bytes:
232
+ """Download the cut-out PNG into memory."""
233
+ return await self._read("image")
234
+
235
+ async def read_mask(self) -> bytes:
236
+ """Download the mask PNG into memory."""
237
+ return await self._read("mask")
238
+
239
+ async def _ready(self, name: str) -> Job:
240
+ """The job to download from; a payment_required job is paid first, then re-read for its sizes."""
241
+ _require(self.job, name)
242
+ if self.job.status != "payment_required":
243
+ return self.job
244
+ await self._client.jobs.output(self.job.id, name=name) # Pays from credit, or raises 402.
245
+ job = await self._client.jobs.retrieve(self.job.id)
246
+ if job.output is None:
247
+ raise JobFailedError(job)
248
+ return job
249
+
250
+ async def _save(self, name: str, path: str | os.PathLike[str], overwrite: bool) -> Path:
251
+ return await self._client.jobs.download(await self._ready(name), path, overwrite=overwrite, name=name)
252
+
253
+ async def _read(self, name: str) -> bytes:
254
+ job = await self._ready(name)
255
+ with tempfile.TemporaryDirectory(prefix="zilapi-") as directory:
256
+ target = Path(directory) / "output.png"
257
+ await self._client.jobs.download(job, target, name=name)
258
+ return target.read_bytes()
259
+
260
+
261
+ class Images:
262
+ def __init__(self, client: ZilAPI) -> None:
263
+ self._client = client
264
+
265
+ def remove_background(
266
+ self,
267
+ image: str | os.PathLike[str] | bytes | BinaryIO | None = None,
268
+ *,
269
+ file: str | File | None = None,
270
+ input_url: str | None = None,
271
+ filename: str | None = None,
272
+ content_type: str | None = None,
273
+ model: str | None = BGR_MODEL,
274
+ webhook_url: str | None = None,
275
+ end_user: str | None = None,
276
+ wait: bool = True,
277
+ timeout: float | None = WAIT_TIMEOUT,
278
+ idempotency_key: str | None = None,
279
+ ) -> BackgroundRemoval:
280
+ """Remove an image's background (``zilapi/bgr-1.0``, $0.01 per image).
281
+
282
+ Pass exactly one input: ``image`` (a local path, bytes or a seekable binary stream, sent in one
283
+ multipart request; above 20 MiB it is streamed with ``files.create`` instead), ``file`` (an
284
+ uploaded file's ID) or ``input_url`` (an https URL the API
285
+ fetches). The server checks the image (PNG, JPEG or WebP, its size and pixel limits). With
286
+ ``wait=True`` (the default) the job is polled until it finishes; failed jobs are returned, not
287
+ raised (see ``.succeeded`` and ``.error``), and saving their outputs raises ``JobFailedError``.
288
+ """
289
+ if wait:
290
+ validate_poll(timeout)
291
+ body, multipart, upload = _request(
292
+ image, file, input_url, filename, content_type, model, webhook_url, end_user
293
+ )
294
+ key = make_key(idempotency_key)
295
+ if upload:
296
+ assert image is not None # noqa: S101 - _request returns upload only for a local image.
297
+ uploaded = self._client.files.create(
298
+ image,
299
+ filename=filename,
300
+ content_type=content_type,
301
+ wait=False,
302
+ idempotency_key=_file_key(key),
303
+ )
304
+ body = {"file": uploaded.id, **body}
305
+ job = parse(
306
+ Job.from_dict,
307
+ self._client._request(
308
+ "POST",
309
+ PATH,
310
+ json=body if multipart is None else None,
311
+ multipart=multipart,
312
+ headers={"Idempotency-Key": key},
313
+ ),
314
+ )
315
+ result = BackgroundRemoval(job, self._client)
316
+ return result.wait(timeout=timeout) if wait else result
317
+
318
+
319
+ class AsyncImages:
320
+ def __init__(self, client: AsyncZilAPI) -> None:
321
+ self._client = client
322
+
323
+ async def remove_background(
324
+ self,
325
+ image: str | os.PathLike[str] | bytes | BinaryIO | None = None,
326
+ *,
327
+ file: str | File | None = None,
328
+ input_url: str | None = None,
329
+ filename: str | None = None,
330
+ content_type: str | None = None,
331
+ model: str | None = BGR_MODEL,
332
+ webhook_url: str | None = None,
333
+ end_user: str | None = None,
334
+ wait: bool = True,
335
+ timeout: float | None = WAIT_TIMEOUT,
336
+ idempotency_key: str | None = None,
337
+ ) -> AsyncBackgroundRemoval:
338
+ """Remove an image's background (``zilapi/bgr-1.0``, $0.01 per image).
339
+
340
+ Pass exactly one input: ``image`` (a local path, bytes or a seekable binary stream, sent in one
341
+ multipart request; above 20 MiB it is streamed with ``files.create`` instead), ``file`` (an
342
+ uploaded file's ID) or ``input_url`` (an https URL the API
343
+ fetches). The server checks the image (PNG, JPEG or WebP, its size and pixel limits). With
344
+ ``wait=True`` (the default) the job is polled until it finishes; failed jobs are returned, not
345
+ raised (see ``.succeeded`` and ``.error``), and saving their outputs raises ``JobFailedError``.
346
+ The local file is read synchronously, like other async uploads in this SDK.
347
+ """
348
+ if wait:
349
+ validate_poll(timeout)
350
+ body, multipart, upload = _request(
351
+ image, file, input_url, filename, content_type, model, webhook_url, end_user
352
+ )
353
+ key = make_key(idempotency_key)
354
+ if upload:
355
+ assert image is not None # noqa: S101 - _request returns upload only for a local image.
356
+ uploaded = await self._client.files.create(
357
+ image,
358
+ filename=filename,
359
+ content_type=content_type,
360
+ wait=False,
361
+ idempotency_key=_file_key(key),
362
+ )
363
+ body = {"file": uploaded.id, **body}
364
+ job = parse(
365
+ Job.from_dict,
366
+ await self._client._request(
367
+ "POST",
368
+ PATH,
369
+ json=body if multipart is None else None,
370
+ multipart=multipart,
371
+ headers={"Idempotency-Key": key},
372
+ ),
373
+ )
374
+ result = AsyncBackgroundRemoval(job, self._client)
375
+ return await result.wait(timeout=timeout) if wait else result
@@ -0,0 +1,286 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from collections.abc import AsyncIterator, Iterator, Mapping
5
+ from pathlib import Path
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from .._base import idempotency_key, parse, poll_delay, segment, validate_poll
9
+ from .._downloads import adownload, download
10
+ from ..errors import WaitTimeoutError
11
+ from ..types import CursorPage, Job, OutputLink
12
+
13
+ if TYPE_CHECKING:
14
+ from .._client import AsyncZilAPI, ZilAPI
15
+
16
+
17
+ def _path(job_id: str) -> str:
18
+ return f"/v1/jobs/{segment(job_id)}"
19
+
20
+
21
+ def _page(data: Mapping[str, Any]) -> CursorPage[Job]:
22
+ return CursorPage.from_dict(data, Job.from_dict)
23
+
24
+
25
+ def _params(
26
+ limit: int | None, cursor: str | None, status: str | None, model: str | None
27
+ ) -> dict[str, str | int]:
28
+ params: dict[str, str | int] = {}
29
+ if limit is not None:
30
+ if not 1 <= limit <= 100:
31
+ raise ValueError("limit must be between 1 and 100")
32
+ params["limit"] = limit
33
+ for name, value in (("cursor", cursor), ("status", status), ("model", model)):
34
+ if value is not None:
35
+ params[name] = value
36
+ return params
37
+
38
+
39
+ def _output_params(name: str | None) -> dict[str, str] | None:
40
+ if name is None:
41
+ return None
42
+ if not name:
43
+ raise ValueError("name must be a non-empty output name")
44
+ return {"name": name}
45
+
46
+
47
+ def _link_name(link: OutputLink, name: str | None) -> str | None:
48
+ chosen = link.raw.get("name")
49
+ return chosen if isinstance(chosen, str) and chosen else name
50
+
51
+
52
+ def _expected(job: Job, link: OutputLink, name: str | None) -> int | None:
53
+ return job.output.expected_size(_link_name(link, name)) if job.output is not None else None
54
+
55
+
56
+ class Jobs:
57
+ def __init__(self, client: ZilAPI) -> None:
58
+ self._client = client
59
+
60
+ def retrieve(self, job_id: str) -> Job:
61
+ """Retrieve a job by ID."""
62
+ return parse(Job.from_dict, self._client._request("GET", _path(job_id)))
63
+
64
+ def list_page(
65
+ self,
66
+ *,
67
+ limit: int | None = None,
68
+ cursor: str | None = None,
69
+ status: str | None = None,
70
+ model: str | None = None,
71
+ ) -> CursorPage[Job]:
72
+ """Retrieve one page of jobs, newest first."""
73
+ return parse(
74
+ _page,
75
+ self._client._request("GET", "/v1/jobs", params=_params(limit, cursor, status, model)),
76
+ )
77
+
78
+ def list(
79
+ self, *, limit: int | None = None, status: str | None = None, model: str | None = None
80
+ ) -> Iterator[Job]:
81
+ """Iterate lazily through all matching jobs; limit is the page size."""
82
+ _params(limit, None, status, model) # Validate at the call, not on first iteration.
83
+ return self._iterate(limit, status, model)
84
+
85
+ def _iterate(self, limit: int | None, status: str | None, model: str | None) -> Iterator[Job]:
86
+ cursor = None
87
+ while True:
88
+ page = self.list_page(limit=limit, cursor=cursor, status=status, model=model)
89
+ yield from page.data
90
+ cursor = page.next_cursor
91
+ if cursor is None:
92
+ break
93
+
94
+ def cancel(self, job_id: str) -> Job:
95
+ """Cancel a queued job; already canceled jobs remain canceled."""
96
+ return parse(
97
+ Job.from_dict,
98
+ self._client._request(
99
+ "POST", _path(job_id) + "/cancel", headers={"Idempotency-Key": idempotency_key(None)}
100
+ ),
101
+ )
102
+
103
+ def output(self, job_id: str, *, name: str | None = None) -> OutputLink:
104
+ """Get a signed download URL for one output of a successful job (default: the first)."""
105
+ return parse(
106
+ OutputLink.from_dict,
107
+ self._client._request("GET", _path(job_id) + "/output", params=_output_params(name)),
108
+ )
109
+
110
+ def wait(
111
+ self,
112
+ job_id: str | Job,
113
+ *,
114
+ timeout: float | None = 86400.0,
115
+ initial_interval: float = 15.0,
116
+ initial_period: float = 300.0,
117
+ interval: float = 60.0,
118
+ ) -> Job:
119
+ """Poll immediately, then every 15 seconds for five minutes and every minute thereafter."""
120
+ validate_poll(timeout, initial_interval, interval)
121
+ validate_poll(initial_period)
122
+ identifier = job_id.id if isinstance(job_id, Job) else job_id
123
+ start = self._client._monotonic()
124
+ last = self.retrieve(identifier)
125
+ while not last.is_terminal:
126
+ elapsed = self._client._monotonic() - start
127
+ if timeout is not None and elapsed >= timeout:
128
+ raise WaitTimeoutError(last)
129
+ delay = initial_interval if elapsed < initial_period else interval
130
+ self._client._sleep(poll_delay(elapsed, timeout, delay))
131
+ if timeout is not None and self._client._monotonic() - start >= timeout:
132
+ raise WaitTimeoutError(last)
133
+ last = self.retrieve(identifier)
134
+ return last
135
+
136
+ def download(
137
+ self,
138
+ job_id: str | Job,
139
+ path: str | os.PathLike[str],
140
+ *,
141
+ overwrite: bool = False,
142
+ name: str | None = None,
143
+ ) -> Path:
144
+ """Stream output to an atomic local file, optionally replacing an existing file.
145
+
146
+ The byte count is checked against the job's stored output size (and Content-Length); a short
147
+ or failed body is retried with a fresh signed link when needed, and never left at ``path``.
148
+ """
149
+ job = job_id if isinstance(job_id, Job) and job_id.output is not None else None
150
+ if job is None:
151
+ job = self.retrieve(job_id.id if isinstance(job_id, Job) else job_id)
152
+ link = self.output(job.id, name=name)
153
+ if job.output is None:
154
+ # No output in the first snapshot (payment_required, or the job finished after that read): the
155
+ # link exists now, so read the job again for the stored size of the output the link names.
156
+ job = self.retrieve(job.id)
157
+ return download(
158
+ self._client,
159
+ link,
160
+ path,
161
+ overwrite,
162
+ expected_size=_expected(job, link, name),
163
+ # A refresh runs inside the download's retry loop, so it must not retry on its own.
164
+ refresh=lambda: self._client.with_options(max_retries=0).jobs.output(
165
+ job.id, name=_link_name(link, name)
166
+ ),
167
+ )
168
+
169
+
170
+ class AsyncJobs:
171
+ def __init__(self, client: AsyncZilAPI) -> None:
172
+ self._client = client
173
+
174
+ async def retrieve(self, job_id: str) -> Job:
175
+ """Retrieve a job by ID."""
176
+ return parse(Job.from_dict, await self._client._request("GET", _path(job_id)))
177
+
178
+ async def list_page(
179
+ self,
180
+ *,
181
+ limit: int | None = None,
182
+ cursor: str | None = None,
183
+ status: str | None = None,
184
+ model: str | None = None,
185
+ ) -> CursorPage[Job]:
186
+ """Retrieve one page of jobs, newest first."""
187
+ return parse(
188
+ _page,
189
+ await self._client._request("GET", "/v1/jobs", params=_params(limit, cursor, status, model)),
190
+ )
191
+
192
+ def list(
193
+ self, *, limit: int | None = None, status: str | None = None, model: str | None = None
194
+ ) -> AsyncIterator[Job]:
195
+ """Iterate lazily through all matching jobs; limit is the page size."""
196
+ _params(limit, None, status, model) # Validate at the call, not on first iteration.
197
+ return self._iterate(limit, status, model)
198
+
199
+ async def _iterate(self, limit: int | None, status: str | None, model: str | None) -> AsyncIterator[Job]:
200
+ cursor = None
201
+ while True:
202
+ page = await self.list_page(limit=limit, cursor=cursor, status=status, model=model)
203
+ for job in page.data:
204
+ yield job
205
+ cursor = page.next_cursor
206
+ if cursor is None:
207
+ break
208
+
209
+ async def cancel(self, job_id: str) -> Job:
210
+ """Cancel a queued job; already canceled jobs remain canceled."""
211
+ return parse(
212
+ Job.from_dict,
213
+ await self._client._request(
214
+ "POST", _path(job_id) + "/cancel", headers={"Idempotency-Key": idempotency_key(None)}
215
+ ),
216
+ )
217
+
218
+ async def output(self, job_id: str, *, name: str | None = None) -> OutputLink:
219
+ """Get a signed download URL for one output of a successful job (default: the first)."""
220
+ return parse(
221
+ OutputLink.from_dict,
222
+ await self._client._request("GET", _path(job_id) + "/output", params=_output_params(name)),
223
+ )
224
+
225
+ async def wait(
226
+ self,
227
+ job_id: str | Job,
228
+ *,
229
+ timeout: float | None = 86400.0,
230
+ initial_interval: float = 15.0,
231
+ initial_period: float = 300.0,
232
+ interval: float = 60.0,
233
+ ) -> Job:
234
+ """Poll immediately, then every 15 seconds for five minutes and every minute thereafter."""
235
+ validate_poll(timeout, initial_interval, interval)
236
+ validate_poll(initial_period)
237
+ identifier = job_id.id if isinstance(job_id, Job) else job_id
238
+ start = self._client._monotonic()
239
+ last = await self.retrieve(identifier)
240
+ while not last.is_terminal:
241
+ elapsed = self._client._monotonic() - start
242
+ if timeout is not None and elapsed >= timeout:
243
+ raise WaitTimeoutError(last)
244
+ delay = initial_interval if elapsed < initial_period else interval
245
+ await self._client._sleep(poll_delay(elapsed, timeout, delay))
246
+ if timeout is not None and self._client._monotonic() - start >= timeout:
247
+ raise WaitTimeoutError(last)
248
+ last = await self.retrieve(identifier)
249
+ return last
250
+
251
+ async def download(
252
+ self,
253
+ job_id: str | Job,
254
+ path: str | os.PathLike[str],
255
+ *,
256
+ overwrite: bool = False,
257
+ name: str | None = None,
258
+ ) -> Path:
259
+ """Stream output to an atomic local file, optionally replacing an existing file.
260
+
261
+ The byte count is checked against the job's stored output size (and Content-Length); a short
262
+ or failed body is retried with a fresh signed link when needed, and never left at ``path``.
263
+ """
264
+ job = job_id if isinstance(job_id, Job) and job_id.output is not None else None
265
+ if job is None:
266
+ job = await self.retrieve(job_id.id if isinstance(job_id, Job) else job_id)
267
+ link = await self.output(job.id, name=name)
268
+ if job.output is None:
269
+ # No output in the first snapshot (payment_required, or the job finished after that read): the
270
+ # link exists now, so read the job again for the stored size of the output the link names.
271
+ job = await self.retrieve(job.id)
272
+
273
+ async def refresh() -> OutputLink:
274
+ # A refresh runs inside the download's retry loop, so it must not retry on its own.
275
+ return await self._client.with_options(max_retries=0).jobs.output(
276
+ job.id, name=_link_name(link, name)
277
+ )
278
+
279
+ return await adownload(
280
+ self._client,
281
+ link,
282
+ path,
283
+ overwrite,
284
+ expected_size=_expected(job, link, name),
285
+ refresh=refresh,
286
+ )