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,40 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from .._base import model_path, parse
7
+ from ..types import Model
8
+
9
+ if TYPE_CHECKING:
10
+ from .._client import AsyncZilAPI, ZilAPI
11
+
12
+
13
+ def _models(data: Mapping[str, Any]) -> list[Model]:
14
+ return [Model.from_dict(item) for item in data["data"]]
15
+
16
+
17
+ class Models:
18
+ def __init__(self, client: ZilAPI) -> None:
19
+ self._client = client
20
+
21
+ def list(self) -> list[Model]:
22
+ """List available models."""
23
+ return parse(_models, self._client._request("GET", "/v1/models"))
24
+
25
+ def get(self, model_id: str) -> Model:
26
+ """Retrieve a provider/model identifier."""
27
+ return parse(Model.from_dict, self._client._request("GET", model_path(model_id)))
28
+
29
+
30
+ class AsyncModels:
31
+ def __init__(self, client: AsyncZilAPI) -> None:
32
+ self._client = client
33
+
34
+ async def list(self) -> list[Model]:
35
+ """List available models."""
36
+ return parse(_models, await self._client._request("GET", "/v1/models"))
37
+
38
+ async def get(self, model_id: str) -> Model:
39
+ """Retrieve a provider/model identifier."""
40
+ return parse(Model.from_dict, await self._client._request("GET", model_path(model_id)))
zilapi/types.py ADDED
@@ -0,0 +1,499 @@
1
+ """Immutable response records; unknown fields remain available in ``raw``."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Callable, Mapping
6
+ from dataclasses import dataclass, field
7
+ from datetime import datetime, timezone
8
+ from typing import Any, Generic, Literal, TypeVar
9
+
10
+ JobStatus = Literal[
11
+ "waiting_for_file", "queued", "processing", "succeeded", "failed", "canceled", "payment_required"
12
+ ]
13
+ FileStatus = Literal["fetching", "uploading", "validating", "ready", "rejected", "deleted"]
14
+ """``fetching`` (a URL being imported), ``uploading`` and ``validating`` are pending; ``ready`` is usable."""
15
+ T = TypeVar("T")
16
+
17
+
18
+ def _date(value: str) -> datetime:
19
+ parsed = datetime.fromisoformat(value[:-1] + "+00:00" if value.endswith("Z") else value)
20
+ return parsed.replace(tzinfo=timezone.utc) if parsed.tzinfo is None else parsed
21
+
22
+
23
+ def _optional_date(value: str | None) -> datetime | None:
24
+ return _date(value) if value is not None else None
25
+
26
+
27
+ @dataclass(frozen=True)
28
+ class Me:
29
+ account_id: str
30
+ key_id: str
31
+ mode: str
32
+ scopes: list[str]
33
+ balance: dict[str, Any] | None
34
+ raw: dict[str, Any] = field(repr=False, compare=False)
35
+
36
+ @classmethod
37
+ def from_dict(cls, data: Mapping[str, Any]) -> Me:
38
+ """Parse an account response."""
39
+ return cls(
40
+ data["account_id"],
41
+ data["key_id"],
42
+ data["mode"],
43
+ list(data["scopes"]),
44
+ data.get("balance"),
45
+ dict(data),
46
+ )
47
+
48
+
49
+ @dataclass(frozen=True)
50
+ class ModelPricing:
51
+ unit: str
52
+ unit_price_micros: int
53
+ min_units: int
54
+ pricing_version: int
55
+ display: str
56
+ currency: str
57
+ raw: dict[str, Any] = field(repr=False, compare=False)
58
+
59
+ @classmethod
60
+ def from_dict(cls, data: Mapping[str, Any]) -> ModelPricing:
61
+ """Parse model pricing."""
62
+ return cls(
63
+ data["unit"],
64
+ data["unit_price_micros"],
65
+ data["min_units"],
66
+ data["pricing_version"],
67
+ data["display"],
68
+ data.get("currency", "usd"),
69
+ dict(data),
70
+ )
71
+
72
+
73
+ @dataclass(frozen=True)
74
+ class ModelLimits:
75
+ max_bytes: int | None
76
+ max_seconds: int | None
77
+ raw: dict[str, Any] = field(repr=False, compare=False)
78
+
79
+ @classmethod
80
+ def from_dict(cls, data: Mapping[str, Any]) -> ModelLimits:
81
+ """Parse model limits."""
82
+ return cls(data.get("max_bytes"), data.get("max_seconds"), dict(data))
83
+
84
+
85
+ @dataclass(frozen=True)
86
+ class ModelOutput:
87
+ format: str
88
+ bitrate_kbps: int | None
89
+ raw: dict[str, Any] = field(repr=False, compare=False)
90
+
91
+ @classmethod
92
+ def from_dict(cls, data: Mapping[str, Any]) -> ModelOutput:
93
+ """Parse model output settings."""
94
+ return cls(data["format"], data.get("bitrate_kbps"), dict(data))
95
+
96
+
97
+ @dataclass(frozen=True)
98
+ class Model:
99
+ id: str
100
+ object: str
101
+ task: str
102
+ name: str
103
+ description: str
104
+ status: str
105
+ pricing: ModelPricing
106
+ limits: ModelLimits
107
+ output: ModelOutput
108
+ raw: dict[str, Any] = field(repr=False, compare=False)
109
+
110
+ @classmethod
111
+ def from_dict(cls, data: Mapping[str, Any]) -> Model:
112
+ """Parse a model response."""
113
+ return cls(
114
+ data["id"],
115
+ data.get("object", "model"),
116
+ data["task"],
117
+ data["name"],
118
+ data["description"],
119
+ data["status"],
120
+ ModelPricing.from_dict(data["pricing"]),
121
+ ModelLimits.from_dict(data["limits"]),
122
+ ModelOutput.from_dict(data["output"]),
123
+ dict(data),
124
+ )
125
+
126
+
127
+ @dataclass(frozen=True)
128
+ class Credits:
129
+ balance_micros: int
130
+ reserved_micros: int
131
+ available_micros: int
132
+ currency: str
133
+ display: str
134
+ raw: dict[str, Any] = field(repr=False, compare=False)
135
+
136
+ @classmethod
137
+ def from_dict(cls, data: Mapping[str, Any]) -> Credits:
138
+ """Parse credit balances."""
139
+ return cls(
140
+ data["balance_micros"],
141
+ data["reserved_micros"],
142
+ data["available_micros"],
143
+ data["currency"],
144
+ data["display"],
145
+ dict(data),
146
+ )
147
+
148
+
149
+ @dataclass(frozen=True)
150
+ class FileError:
151
+ code: str
152
+ message: str
153
+ raw: dict[str, Any] = field(repr=False, compare=False)
154
+
155
+ @classmethod
156
+ def from_dict(cls, data: Mapping[str, Any]) -> FileError:
157
+ """Parse a file validation error."""
158
+ return cls(data["code"], data["message"], dict(data))
159
+
160
+
161
+ @dataclass(frozen=True)
162
+ class File:
163
+ id: str
164
+ object: str
165
+ filename: str
166
+ content_type: str
167
+ size_bytes: int | None # None while a URL is being fetched and its size is not yet known.
168
+ status: str
169
+ duration_seconds: float | None
170
+ error: FileError | None
171
+ mode: str
172
+ created_at: datetime
173
+ ready_at: datetime | None
174
+ expires_at: datetime | None
175
+ raw: dict[str, Any] = field(repr=False, compare=False)
176
+
177
+ @classmethod
178
+ def from_dict(cls, data: Mapping[str, Any]) -> File:
179
+ """Parse a file response, including timestamps."""
180
+ return cls(
181
+ data["id"],
182
+ data.get("object", "file"),
183
+ data["filename"],
184
+ data["content_type"],
185
+ data["size_bytes"],
186
+ data["status"],
187
+ data.get("duration_seconds"),
188
+ FileError.from_dict(data["error"]) if data.get("error") else None,
189
+ data["mode"],
190
+ _date(data["created_at"]),
191
+ _optional_date(data.get("ready_at")),
192
+ _optional_date(data.get("expires_at")),
193
+ dict(data),
194
+ )
195
+
196
+ @property
197
+ def is_ready(self) -> bool:
198
+ """Whether validation has completed successfully."""
199
+ return self.status == "ready"
200
+
201
+
202
+ @dataclass(frozen=True)
203
+ class JobInput:
204
+ file: str
205
+ duration_seconds: float | None
206
+ raw: dict[str, Any] = field(repr=False, compare=False)
207
+
208
+ @classmethod
209
+ def from_dict(cls, data: Mapping[str, Any]) -> JobInput:
210
+ """Parse job input details."""
211
+ return cls(data["file"], data.get("duration_seconds"), dict(data))
212
+
213
+
214
+ @dataclass(frozen=True)
215
+ class JobOutputFile:
216
+ name: str
217
+ size_bytes: int | None
218
+ format: str | None
219
+ raw: dict[str, Any] = field(repr=False, compare=False)
220
+
221
+ @classmethod
222
+ def from_dict(cls, data: Mapping[str, Any]) -> JobOutputFile:
223
+ """Parse one named output file (``audio``, ``vocals``, ``instrumental``, ``image``, ``mask``)."""
224
+ return cls(data["name"], data.get("size_bytes"), data.get("format"), dict(data))
225
+
226
+
227
+ @dataclass(frozen=True)
228
+ class JobOutput:
229
+ format: str
230
+ bitrate_kbps: int | None
231
+ size_bytes: int | None
232
+ expires_at: datetime | None
233
+ raw: dict[str, Any] = field(repr=False, compare=False)
234
+ files: list[JobOutputFile] = field(default_factory=list)
235
+ deleted: bool = False
236
+
237
+ @classmethod
238
+ def from_dict(cls, data: Mapping[str, Any]) -> JobOutput:
239
+ """Parse job output details; ``size_bytes`` is null for multi-file outputs (see ``files``)."""
240
+ return cls(
241
+ data["format"],
242
+ data.get("bitrate_kbps"),
243
+ data.get("size_bytes"),
244
+ _optional_date(data.get("expires_at")),
245
+ dict(data),
246
+ [JobOutputFile.from_dict(item) for item in data.get("files") or []],
247
+ bool(data.get("deleted", False)),
248
+ )
249
+
250
+ def file(self, name: str) -> JobOutputFile | None:
251
+ """The output named ``name`` (for example ``image`` or ``mask``), or None when the job has none."""
252
+ return next((f for f in self.files if f.name == name), None)
253
+
254
+ def expected_size(self, name: str | None = None) -> int | None:
255
+ """The stored size in bytes of output ``name`` (default: the first), or None when unknown."""
256
+ if self.files:
257
+ chosen = self.files[0] if name is None else next((f for f in self.files if f.name == name), None)
258
+ size = chosen.size_bytes if chosen is not None else None
259
+ else:
260
+ size = self.size_bytes # Older responses: a single output.
261
+ return size if isinstance(size, int) and not isinstance(size, bool) and size > 0 else None
262
+
263
+
264
+ @dataclass(frozen=True)
265
+ class JobCost:
266
+ estimated_micros: int
267
+ charged_micros: int | None
268
+ display: str
269
+ raw: dict[str, Any] = field(repr=False, compare=False)
270
+
271
+ @classmethod
272
+ def from_dict(cls, data: Mapping[str, Any]) -> JobCost:
273
+ """Parse job cost."""
274
+ return cls(data["estimated_micros"], data.get("charged_micros"), data["display"], dict(data))
275
+
276
+
277
+ @dataclass(frozen=True)
278
+ class JobReceipt:
279
+ billable_seconds: int
280
+ minimum_applied: bool
281
+ unit_price_micros: int | None
282
+ pricing_version: int
283
+ charged_micros: int | None
284
+ ledger_txn_id: str | None
285
+ raw: dict[str, Any] = field(repr=False, compare=False)
286
+ unit: str = "audio_second"
287
+ billable_units: int | None = None
288
+ unit_price_display: str | None = None
289
+ billable_ms: int | None = None
290
+ unit_price_micros_per_minute: int | None = None
291
+
292
+ @classmethod
293
+ def from_dict(cls, data: Mapping[str, Any]) -> JobReceipt:
294
+ """Parse a billing receipt.
295
+
296
+ ``unit`` is ``"audio_second"``, ``"video_second"`` or ``"image"`` (background removal:
297
+ ``billable_units`` is 1, ``billable_seconds`` and ``billable_ms`` 0 and ``unit_price_micros`` the
298
+ price of one image). Audio and video are billed by the millisecond (since 2026-11-12):
299
+ ``billable_ms`` is the billed duration (the measured duration, 1-second minimum) and the charge is
300
+ ceil(billable_ms x unit_price_micros_per_minute / 60000). ``billable_seconds`` is ``billable_ms``
301
+ rounded up to whole seconds, kept for compatibility. ``billable_ms`` is None on receipts from an
302
+ API older than that. For audio, ``unit_price_micros`` is deprecated by the API and null when the
303
+ per-minute price is not a whole number of micros per second.
304
+ """
305
+ return cls(
306
+ data["billable_seconds"],
307
+ data["minimum_applied"],
308
+ data.get("unit_price_micros"),
309
+ data["pricing_version"],
310
+ data.get("charged_micros"),
311
+ data.get("ledger_txn_id"),
312
+ dict(data),
313
+ data.get("unit") or "audio_second",
314
+ data.get("billable_units"),
315
+ data.get("unit_price_display"),
316
+ data.get("billable_ms"),
317
+ data.get("unit_price_micros_per_minute"),
318
+ )
319
+
320
+
321
+ @dataclass(frozen=True)
322
+ class JobPayment:
323
+ amount_due_micros: int
324
+ display: str
325
+ expires_at: datetime | None
326
+ raw: dict[str, Any] = field(repr=False, compare=False)
327
+
328
+ @classmethod
329
+ def from_dict(cls, data: Mapping[str, Any]) -> JobPayment:
330
+ """Parse what a ``payment_required`` job owes; a top-up pays it, or it expires at ``expires_at``."""
331
+ return cls(
332
+ data["amount_due_micros"], data["display"], _optional_date(data.get("expires_at")), dict(data)
333
+ )
334
+
335
+
336
+ @dataclass(frozen=True)
337
+ class JobError:
338
+ code: str
339
+ message: str
340
+ raw: dict[str, Any] = field(repr=False, compare=False)
341
+
342
+ @classmethod
343
+ def from_dict(cls, data: Mapping[str, Any]) -> JobError:
344
+ """Parse a job failure."""
345
+ return cls(data["code"], data["message"], dict(data))
346
+
347
+
348
+ @dataclass(frozen=True)
349
+ class FillerSegment:
350
+ start_s: float
351
+ end_s: float
352
+ duration_s: float
353
+ label: str
354
+ confidence: float | None
355
+ raw: dict[str, Any] = field(repr=False, compare=False)
356
+
357
+ @classmethod
358
+ def from_dict(cls, data: Mapping[str, Any]) -> FillerSegment:
359
+ """Parse one removed segment (seconds on the input's timeline; ``label`` is ``filled_pause``)."""
360
+ return cls(
361
+ data["start_s"],
362
+ data["end_s"],
363
+ data["duration_s"],
364
+ data.get("label", "filled_pause"),
365
+ data.get("confidence"),
366
+ dict(data),
367
+ )
368
+
369
+
370
+ @dataclass(frozen=True)
371
+ class FillerReport:
372
+ count: int
373
+ removed_seconds: float
374
+ input_duration_seconds: float | None
375
+ output_duration_seconds: float | None
376
+ segments: list[FillerSegment] | None
377
+ raw: dict[str, Any] = field(repr=False, compare=False)
378
+
379
+ @classmethod
380
+ def from_dict(cls, data: Mapping[str, Any]) -> FillerReport:
381
+ """Parse a filler removal report (``result.fillers`` or the ``fillers`` JSON output).
382
+
383
+ ``segments`` is None in job lists (the summary only); ``output_duration_seconds`` is None for
384
+ ``timestamps_only`` jobs.
385
+ """
386
+ segments = data.get("segments")
387
+ return cls(
388
+ data["count"],
389
+ data["removed_seconds"],
390
+ data.get("input_duration_seconds"),
391
+ data.get("output_duration_seconds"),
392
+ [FillerSegment.from_dict(item) for item in segments] if segments is not None else None,
393
+ dict(data),
394
+ )
395
+
396
+
397
+ @dataclass(frozen=True)
398
+ class JobResult:
399
+ fillers: FillerReport | None
400
+ raw: dict[str, Any] = field(repr=False, compare=False)
401
+
402
+ @classmethod
403
+ def from_dict(cls, data: Mapping[str, Any]) -> JobResult:
404
+ """Parse the JSON results of a succeeded job (filler removal: ``fillers``)."""
405
+ fillers = data.get("fillers")
406
+ return cls(FillerReport.from_dict(fillers) if fillers else None, dict(data))
407
+
408
+
409
+ @dataclass(frozen=True)
410
+ class Job:
411
+ id: str
412
+ object: str
413
+ task: str
414
+ model: str
415
+ status: str
416
+ progress: float
417
+ input: JobInput
418
+ output: JobOutput | None
419
+ cost: JobCost
420
+ receipt: JobReceipt
421
+ error: JobError | None
422
+ mode: str
423
+ created_at: datetime
424
+ started_at: datetime | None
425
+ finished_at: datetime | None
426
+ raw: dict[str, Any] = field(repr=False, compare=False)
427
+ result: JobResult | None = None
428
+ options: dict[str, Any] = field(default_factory=dict)
429
+ payment: JobPayment | None = None
430
+ end_user: str | None = None
431
+ served_by: str | None = None
432
+
433
+ @classmethod
434
+ def from_dict(cls, data: Mapping[str, Any]) -> Job:
435
+ """Parse a job response and nested billing details."""
436
+ return cls(
437
+ data["id"],
438
+ data.get("object", "job"),
439
+ data["task"],
440
+ data["model"],
441
+ data["status"],
442
+ data["progress"],
443
+ JobInput.from_dict(data["input"]),
444
+ JobOutput.from_dict(data["output"]) if data.get("output") else None,
445
+ JobCost.from_dict(data["cost"]),
446
+ JobReceipt.from_dict(data["receipt"]),
447
+ JobError.from_dict(data["error"]) if data.get("error") else None,
448
+ data["mode"],
449
+ _date(data["created_at"]),
450
+ _optional_date(data.get("started_at")),
451
+ _optional_date(data.get("finished_at")),
452
+ dict(data),
453
+ JobResult.from_dict(data["result"]) if data.get("result") else None,
454
+ dict(data.get("options") or {}),
455
+ JobPayment.from_dict(data["payment"]) if data.get("payment") else None,
456
+ data.get("end_user"),
457
+ data.get("served_by"),
458
+ )
459
+
460
+ @property
461
+ def fillers(self) -> FillerReport | None:
462
+ """The filler removal report of a succeeded filler job (``result.fillers``), else None."""
463
+ return self.result.fillers if self.result is not None else None
464
+
465
+ @property
466
+ def is_terminal(self) -> bool:
467
+ """Whether the job has succeeded, failed, or been canceled."""
468
+ return self.status in ("succeeded", "failed", "canceled")
469
+
470
+ @property
471
+ def succeeded(self) -> bool:
472
+ """Whether output was produced successfully."""
473
+ return self.status == "succeeded"
474
+
475
+
476
+ @dataclass(frozen=True)
477
+ class OutputLink:
478
+ url: str = field(repr=False)
479
+ expires_at: datetime
480
+ filename: str
481
+ raw: dict[str, Any] = field(repr=False, compare=False)
482
+ name: str | None = None
483
+
484
+ @classmethod
485
+ def from_dict(cls, data: Mapping[str, Any]) -> OutputLink:
486
+ """Parse a signed output download link (``name``: which output, e.g. ``image`` or ``mask``)."""
487
+ return cls(data["url"], _date(data["expires_at"]), data["filename"], dict(data), data.get("name"))
488
+
489
+
490
+ @dataclass(frozen=True)
491
+ class CursorPage(Generic[T]):
492
+ data: list[T]
493
+ next_cursor: str | None
494
+ raw: dict[str, Any] = field(repr=False, compare=False)
495
+
496
+ @classmethod
497
+ def from_dict(cls, data: Mapping[str, Any], parser: Callable[[Mapping[str, Any]], T]) -> CursorPage[T]:
498
+ """Parse a page using the supplied item parser."""
499
+ return cls([parser(item) for item in data["data"]], data.get("next_cursor"), dict(data))