strata-python 0.2.1__py3-none-any.whl → 0.2.3__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,783 @@
1
+ """Client for the strata-models service: run a model by role, or hold the GPU for your own kernels. Standard library
2
+ only. It replaces the `strata_models_client` package that apps installed from a path or a git URL; the names and
3
+ behaviour are the same, plus typed result shapes.
4
+
5
+ from strata_python.clients import models as sm
6
+
7
+ sm.faces("/x.jpg", app="bright-horizons") # the service's JSON, as before
8
+ page = sm.OcrPage.from_json(sm.ocr("/p.png", app="strata-scan")) # typed: page.lines[0].words[0].box
9
+ with sm.gpu_lease("strata-stills", vram_gb=4): ...
10
+
11
+ One shortcut per role the service runs (`ROLES`), each with its result shape:
12
+
13
+ faces Faces face_kind FaceKinds ocr OcrPage
14
+ transcribe(-fast) Transcript speak Speech denoise_audio CleanAudio
15
+ audio_quality AudioQuality generate_image GeneratedImage embed Embeddings
16
+ enhance_video EnhancedVideo ask (vision-language, text, judge-text, judge-vision, judge-audio) Answer
17
+
18
+ The service URL is STRATA_MODELS_URL (default http://127.0.0.1:8366). Inputs are file paths: the service runs on the
19
+ same machine. strata-models tests this module against its real API in its own integration suite; this repo tests it
20
+ against a stand-in service over real HTTP.
21
+
22
+ The result shapes read what the service sends and keep all of it in `raw`, so a field the service adds later is
23
+ there before this module learns its name. A field the service leaves out (a face without `pose` when `fields` did not
24
+ ask for it) is None or empty, never an error.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import contextlib
30
+ import json
31
+ import os
32
+ import threading
33
+ import time
34
+ import urllib.error
35
+ import urllib.request
36
+ import warnings
37
+ from collections.abc import Generator, Mapping, Sequence
38
+ from dataclasses import dataclass, field
39
+ from typing import Any, Literal, cast
40
+
41
+ from strata_python import client
42
+
43
+ Json = dict[str, Any]
44
+ Priority = Literal["high", "normal", "low"]
45
+ POLL_S = 30 # one long-poll request waits this long at most
46
+ DEFAULT_URL = "http://127.0.0.1:8366"
47
+
48
+
49
+ class Unavailable(client.Unavailable):
50
+ """The service is not running (or not reachable). A `strata_python.client.Unavailable`, so an app's
51
+ `web.add_error_handlers` answers it as 503 like any other service outage."""
52
+
53
+
54
+ class JobFailed(RuntimeError):
55
+ """The service ran the job and it failed (or refused it); `.job` is the job row when the service sent one."""
56
+
57
+ def __init__(self, msg: str, job: Json | None = None) -> None:
58
+ super().__init__(msg)
59
+ self.job = job
60
+
61
+
62
+ def url() -> str:
63
+ return os.environ.get("STRATA_MODELS_URL", DEFAULT_URL).rstrip("/")
64
+
65
+
66
+ def _call(method: str, path: str, body: object = None, timeout: float = POLL_S + 15) -> Json:
67
+ data = None if body is None else json.dumps(body).encode()
68
+ req = urllib.request.Request( # noqa: S310 - the URL is the service's, from STRATA_MODELS_URL
69
+ url() + path, data=data, method=method, headers={"Content-Type": "application/json"} if data else {}
70
+ )
71
+ try:
72
+ with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310
73
+ return cast("Json", json.load(r))
74
+ except urllib.error.HTTPError as e:
75
+ try:
76
+ d = cast("Json", json.load(e))
77
+ except ValueError:
78
+ d = {}
79
+ if e.code in (400, 404, 422):
80
+ raise JobFailed(str(d.get("detail") or e), d.get("job")) from None
81
+ raise Unavailable(f"strata-models answered {e.code}: {d.get('detail') or e.reason}") from None
82
+ except (urllib.error.URLError, OSError) as e:
83
+ raise Unavailable(f"strata-models is not reachable at {url()}: {e}") from None
84
+
85
+
86
+ def available(timeout: float = 2.0) -> bool:
87
+ """Is the service running?"""
88
+ try:
89
+ return bool(_call("GET", "/api/health", timeout=timeout).get("ok"))
90
+ except (Unavailable, JobFailed):
91
+ return False
92
+
93
+
94
+ def submit(
95
+ role: str,
96
+ params: Mapping[str, Any] | None,
97
+ app: str,
98
+ priority: Priority = "normal",
99
+ model: str | None = None,
100
+ options: Mapping[str, Any] | None = None,
101
+ ) -> Json:
102
+ """Queue a job and return its row at once (poll with `wait`). `options` changes the model's load options (a
103
+ variant loaded apart: evals)."""
104
+ body = {"role": role, "params": dict(params or {}), "app": app, "priority": priority, "model": model}
105
+ return _call("POST", "/api/jobs", {**body, "options": dict(options) if options is not None else None})
106
+
107
+
108
+ def wait_job(job_id: int) -> Json:
109
+ """The job's row once it has finished (done, failed or cancelled), with result, error and timings; never raises
110
+ for a failed job."""
111
+ while True:
112
+ j = _call("GET", f"/api/jobs/{int(job_id)}?wait={POLL_S}")
113
+ if j["status"] not in ("queued", "running"):
114
+ return j
115
+
116
+
117
+ def wait(job_id: int, timeout: float | None = None) -> Json:
118
+ """The job's result once it is done; raises JobFailed if it failed or was cancelled, TimeoutError after
119
+ `timeout` seconds."""
120
+ end = None if timeout is None else time.monotonic() + timeout
121
+ while True:
122
+ step = POLL_S if end is None else max(min(POLL_S, end - time.monotonic()), 0)
123
+ j = _call("GET", f"/api/jobs/{int(job_id)}?wait={step:.1f}")
124
+ if j["status"] == "done":
125
+ return cast("Json", j["result"])
126
+ if j["status"] in ("failed", "cancelled"):
127
+ raise JobFailed(j.get("error") or f"job {job_id} was {j['status']}", j)
128
+ if end is not None and time.monotonic() >= end:
129
+ raise TimeoutError(f"job {job_id} is still {j['status']}")
130
+
131
+
132
+ def run(
133
+ role: str,
134
+ params: Mapping[str, Any] | None,
135
+ app: str,
136
+ priority: Priority = "normal",
137
+ model: str | None = None,
138
+ timeout: float | None = None,
139
+ ) -> Json:
140
+ """Run a model job and return its result (queued behind the GPU's other work; priority `high` goes ahead of
141
+ `normal` (the default), which goes ahead of `low`)."""
142
+ return wait(int(submit(role, params, app, priority, model)["id"]), timeout)
143
+
144
+
145
+ ROLES = (
146
+ "faces",
147
+ "face-kind",
148
+ "transcribe",
149
+ "transcribe-fast",
150
+ "ocr",
151
+ "speak",
152
+ "denoise-audio",
153
+ "audio-quality",
154
+ "image-generate",
155
+ "image-embed",
156
+ "video-enhance",
157
+ "vision-language",
158
+ "text",
159
+ "judge-text",
160
+ "judge-vision",
161
+ "judge-audio",
162
+ )
163
+ """The roles the service runs (each has a shortcut here; `ask` covers the language-model ones). `models.toml` also
164
+ lists sound-events, speaker-embedding, detect-people, upscale, denoise and nsfw, but no runtime serves them yet: apps
165
+ still load those models themselves. `run(role, params, app)` reaches any role, including one added after this list."""
166
+
167
+
168
+ def faces(path: str | None, app: str, priority: Priority = "normal", model: str | None = None, **params: Any) -> Json:
169
+ """Faces in one image (`Faces.from_json`): params max_side, det_thresh, fields. Several images: path=None and
170
+ `paths=[...]`, giving {'images': [...]}, one `Faces` each."""
171
+ if path is not None:
172
+ params["path"] = os.path.abspath(path)
173
+ if "paths" in params:
174
+ params["paths"] = [os.path.abspath(p) for p in params["paths"]]
175
+ return run("faces", params, app, priority=priority, model=model)
176
+
177
+
178
+ def transcribe(
179
+ path: str,
180
+ app: str,
181
+ role: str = "transcribe",
182
+ priority: Priority = "normal",
183
+ model: str | None = None,
184
+ **params: Any,
185
+ ) -> Json:
186
+ """Whisper on an audio or video file (`Transcript.from_json`): params language, task, word_timestamps,
187
+ vad_filter, beam_size, initial_prompt, clip=(start, end)."""
188
+ params["path"] = os.path.abspath(path)
189
+ if "clip" in params:
190
+ params["clip"] = list(params["clip"])
191
+ return run(role, params, app, priority=priority, model=model)
192
+
193
+
194
+ def ocr(path: str, app: str, priority: Priority = "normal", model: str | None = None, **params: Any) -> Json:
195
+ """Printed text from a page picture (role `ocr`, `OcrPage.from_json`): params lang ('eng', 'eng+fra'), psm
196
+ (Tesseract's page segmentation), dpi, clean (steps that clean the page first, such as "flatten,sharpen"; boxes are
197
+ then in the cleaned picture's pixels), pdf (a .pdf path to write as well: the picture with its text searchable)."""
198
+ params["path"] = os.path.abspath(path)
199
+ if params.get("pdf"):
200
+ params["pdf"] = os.path.abspath(params["pdf"])
201
+ return run("ocr", params, app, priority=priority, model=model)
202
+
203
+
204
+ def speak(text: str, app: str, priority: Priority = "normal", model: str | None = None, **params: Any) -> Json:
205
+ """Speech from text (role `speak`, `Speech.from_json`): params voice (a preset name, or a reference recording's
206
+ path for the cloning models), speed, instruct, language, seed. The WAV at `path` is the service's copy: copy it if
207
+ it must last."""
208
+ if params.get("voice") and os.path.exists(str(params["voice"])):
209
+ params["voice"] = os.path.abspath(params["voice"])
210
+ return run("speak", {**params, "text": text}, app, priority=priority, model=model)
211
+
212
+
213
+ def _abs(params: dict[str, Any], *keys: str) -> None:
214
+ """Make the file paths under `keys` absolute (one path or a list): the service resolves them from its own folder."""
215
+ for k in keys:
216
+ v = params.get(k)
217
+ if isinstance(v, str) and v:
218
+ params[k] = os.path.abspath(v)
219
+ elif isinstance(v, list | tuple):
220
+ params[k] = [os.path.abspath(str(x)) for x in cast("Sequence[Any]", v)]
221
+
222
+
223
+ ASK_ROLES = ("vision-language", "text", "judge-text", "judge-vision", "judge-audio")
224
+
225
+
226
+ def ask(
227
+ prompt: str | None,
228
+ app: str,
229
+ role: str = "vision-language",
230
+ priority: Priority = "normal",
231
+ model: str | None = None,
232
+ **params: Any,
233
+ ) -> Json:
234
+ """A language model (`Answer.from_json`), local or cloud, by role: `vision-language` (questions about pictures),
235
+ `text` (text in, text out), and the evals' judges `judge-text`, `judge-vision`, `judge-audio`. params: image /
236
+ images, audio / audios (paths), preset + context (a prompt kept in the service; then `prompt` may be None),
237
+ system or system_preset, schema (a JSON schema the answer must follow; its parsed answer is `json`), max_tokens,
238
+ temperature, seed, think, effort (cloud models)."""
239
+ if prompt is not None:
240
+ params["prompt"] = prompt
241
+ _abs(params, "image", "images", "audio", "audios")
242
+ return run(role, params, app, priority=priority, model=model)
243
+
244
+
245
+ def generate_image(
246
+ prompt: str, app: str, priority: Priority = "normal", model: str | None = None, **params: Any
247
+ ) -> Json:
248
+ """A picture from a prompt (role `image-generate`, `GeneratedImage.from_json`): params negative_prompt, width,
249
+ height (multiples of 16, default 1024), steps, cfg_scale, sampler, seed (random unless given; always returned),
250
+ ref_images (paths to edit from or refer to)."""
251
+ params["prompt"] = prompt
252
+ _abs(params, "ref_images")
253
+ return run("image-generate", params, app, priority=priority, model=model)
254
+
255
+
256
+ def embed(
257
+ app: str,
258
+ paths: Sequence[str] = (),
259
+ texts: Sequence[str] = (),
260
+ priority: Priority = "normal",
261
+ model: str | None = None,
262
+ **params: Any,
263
+ ) -> Json:
264
+ """CLIP vectors, L2-normalised, for pictures and prompts (role `image-embed`, `Embeddings.from_json`): a dot
265
+ product is a cosine similarity. params: array ({path, key?, bgr?}: images in an .npy/.npz), resize ('crop' or
266
+ 'square'), out (an .npz to write instead of answering with the numbers, for thousands of pictures)."""
267
+ if paths:
268
+ params["paths"] = list(paths)
269
+ if texts:
270
+ params["texts"] = list(texts)
271
+ _abs(params, "paths", "out")
272
+ if isinstance(params.get("array"), dict):
273
+ params["array"] = {**params["array"], "path": os.path.abspath(params["array"]["path"])}
274
+ return run("image-embed", params, app, priority=priority, model=model)
275
+
276
+
277
+ def face_kind(
278
+ path: str | None,
279
+ app: str,
280
+ boxes: Sequence[Sequence[float]] = (),
281
+ priority: Priority = "normal",
282
+ model: str | None = None,
283
+ **params: Any,
284
+ ) -> Json:
285
+ """Whether each face is a real person or a statue, picture, toy or animal (role `face-kind`,
286
+ `FaceKinds.from_json`): an image `path` and the `boxes` the faces role gave ([x1, y1, x2, y2]), or path=None and
287
+ array={path, key?, bgr?} of face crops already cut."""
288
+ if path is not None:
289
+ params["path"] = os.path.abspath(path)
290
+ params["boxes"] = [list(b) for b in boxes]
291
+ if isinstance(params.get("array"), dict):
292
+ params["array"] = {**params["array"], "path": os.path.abspath(params["array"]["path"])}
293
+ return run("face-kind", params, app, priority=priority, model=model)
294
+
295
+
296
+ def denoise_audio(path: str, app: str, priority: Priority = "normal", model: str | None = None, **params: Any) -> Json:
297
+ """Noise out of recorded sound, speech kept clear (role `denoise-audio`, `CleanAudio.from_json`): params clip
298
+ (start, end), highpass (Hz), atten_lim_db, finish ("strata360" or "none"), lufs (None keeps the level), and the
299
+ engine's own. The WAV at `path` is the service's copy."""
300
+ params["path"] = os.path.abspath(path)
301
+ if "clip" in params:
302
+ params["clip"] = list(params["clip"])
303
+ return run("denoise-audio", params, app, priority=priority, model=model)
304
+
305
+
306
+ def audio_quality(
307
+ path: str,
308
+ app: str,
309
+ reference: str | None = None,
310
+ metrics: Sequence[str] | None = None,
311
+ priority: Priority = "normal",
312
+ model: str | None = None,
313
+ ) -> Json:
314
+ """How good a speech recording sounds, measured (role `audio-quality`, `AudioQuality.from_json`): DNSMOS and
315
+ SQUIM without a reference, si_sdr, pesq and estoi against a clean `reference`. `metrics` picks among "dnsmos",
316
+ "squim" and "intrusive" (default all that apply)."""
317
+ params: dict[str, Any] = {"path": os.path.abspath(path)}
318
+ if reference is not None:
319
+ params["reference"] = os.path.abspath(reference)
320
+ if metrics is not None:
321
+ params["metrics"] = list(metrics)
322
+ return run("audio-quality", params, app, priority=priority, model=model)
323
+
324
+
325
+ def enhance_video(path: str, app: str, priority: Priority = "normal", model: str | None = None, **params: Any) -> Json:
326
+ """Old video made better: deinterlaced, upscaled and restored into a playable MP4 (role `video-enhance`,
327
+ `EnhancedVideo.from_json`): params deinterlace, field_order, crop [x, y, w, h], prep_size and size [w, h],
328
+ regions [{id, label, box}], stills, crf, seed, cleanup, quality. Long clips take minutes: give `timeout` to
329
+ `run` instead when the app must not wait that long."""
330
+ params["path"] = os.path.abspath(path)
331
+ return run("video-enhance", params, app, priority=priority, model=model)
332
+
333
+
334
+ def role_model(role: str) -> str | None:
335
+ """The model that serves `role` now (from the service's registry), or None for an unknown role. Apps key their
336
+ caches on it, so output made by an earlier model is made again when an eval changes the role's model."""
337
+ roles = cast("list[Json]", _call("GET", "/api/registry").get("roles", []))
338
+ return next((cast("str", r["model"]) for r in roles if r["key"] == role), None)
339
+
340
+
341
+ class Lease:
342
+ """A held lease: `.id`, `.job` (the row when granted). Heartbeats run on a daemon thread until `release()`."""
343
+
344
+ def __init__(self, job: Json, ttl_s: float) -> None:
345
+ self.id: int = int(job["id"])
346
+ self.job = job
347
+ self._stop = threading.Event()
348
+ self._t = threading.Thread(target=self._beat, args=(max(ttl_s / 3, 1.0),), daemon=True)
349
+ self._t.start()
350
+
351
+ def _beat(self, every: float) -> None:
352
+ while not self._stop.wait(every):
353
+ with contextlib.suppress(Exception):
354
+ _call("POST", f"/api/leases/{self.id}/heartbeat", timeout=10)
355
+
356
+ def release(self) -> None:
357
+ self._stop.set()
358
+ with contextlib.suppress(Exception):
359
+ _call("DELETE", f"/api/leases/{self.id}", timeout=10)
360
+
361
+
362
+ def acquire(
363
+ app: str,
364
+ vram_gb: float | None = None,
365
+ ttl_s: float = 120,
366
+ priority: Priority = "normal",
367
+ note: str | None = None,
368
+ timeout: float | None = None,
369
+ ) -> Lease:
370
+ """Ask for the GPU and wait until it is granted; returns a Lease (call `.release()`), TimeoutError after
371
+ `timeout` (the request is withdrawn)."""
372
+ body = {"app": app, "vram_gb": vram_gb, "ttl_s": ttl_s, "priority": priority, "note": note, "pid": os.getpid()}
373
+ j = _call("POST", "/api/leases", body)
374
+ end = None if timeout is None else time.monotonic() + timeout
375
+ last_beat = time.monotonic()
376
+ while j["status"] == "queued":
377
+ if end is not None and time.monotonic() >= end:
378
+ with contextlib.suppress(Exception):
379
+ _call("DELETE", f"/api/leases/{j['id']}", timeout=10)
380
+ raise TimeoutError(f"the GPU was not free within {timeout} s")
381
+ if time.monotonic() - last_beat > ttl_s / 3: # a queued request is kept alive too
382
+ _call("POST", f"/api/leases/{j['id']}/heartbeat", timeout=10)
383
+ last_beat = time.monotonic()
384
+ step = min(POLL_S, ttl_s / 3) if end is None else max(min(POLL_S, ttl_s / 3, end - time.monotonic()), 0)
385
+ j = _call("GET", f"/api/leases/{j['id']}?wait={step:.1f}")
386
+ if j["status"] != "running":
387
+ raise JobFailed(f"lease {j['id']} was {j['status']}", j)
388
+ return Lease(j, ttl_s)
389
+
390
+
391
+ @contextlib.contextmanager
392
+ def gpu_lease(
393
+ app: str,
394
+ vram_gb: float | None = None,
395
+ ttl_s: float = 120,
396
+ priority: Priority = "normal",
397
+ note: str | None = None,
398
+ timeout: float | None = None,
399
+ required: bool = False,
400
+ ) -> Generator[Lease | None]:
401
+ """`with gpu_lease('strata-stills', vram_gb=4):` 4 GB of the GPU are this app's for the block, and other work goes
402
+ on in the rest (give the most this block will use); with vram_gb=None the whole GPU, and nothing else runs.
403
+ Without the service: yields None and runs the block anyway, with a warning (or raises Unavailable when
404
+ `required`)."""
405
+ try:
406
+ lease = acquire(app, vram_gb, ttl_s, priority, note, timeout)
407
+ except Unavailable:
408
+ if required:
409
+ raise
410
+ warnings.warn("strata-models is not running: using the GPU without a lease", RuntimeWarning, stacklevel=3)
411
+ lease = None
412
+ try:
413
+ yield lease
414
+ finally:
415
+ if lease is not None:
416
+ lease.release()
417
+
418
+
419
+ # --- typed results: what each role returns -------------------------------------------------------------------------
420
+
421
+
422
+ def _floats(v: object) -> list[float]:
423
+ return [float(x) for x in cast("Sequence[Any]", v)] if isinstance(v, list) else []
424
+
425
+
426
+ def _box(v: object) -> tuple[int, int, int, int]:
427
+ x, y, w, h = (int(a) for a in cast("Sequence[Any]", v))
428
+ return (x, y, w, h)
429
+
430
+
431
+ def _opt_float(d: Json, key: str) -> float | None:
432
+ v = d.get(key)
433
+ return None if v is None else float(v)
434
+
435
+
436
+ @dataclass(frozen=True)
437
+ class OcrWord:
438
+ text: str
439
+ box: tuple[int, int, int, int] # x, y, w, h in the (cleaned) picture's pixels
440
+ conf: float # 0-100
441
+
442
+ @classmethod
443
+ def from_json(cls, d: Json) -> OcrWord:
444
+ return cls(str(d["text"]), _box(d["box"]), float(d.get("conf", 0)))
445
+
446
+
447
+ @dataclass(frozen=True)
448
+ class OcrLine:
449
+ text: str
450
+ box: tuple[int, int, int, int]
451
+ conf: float
452
+ block: int
453
+ words: list[OcrWord]
454
+
455
+ @classmethod
456
+ def from_json(cls, d: Json) -> OcrLine:
457
+ words = [OcrWord.from_json(w) for w in cast("list[Json]", d.get("words", []))]
458
+ return cls(str(d["text"]), _box(d["box"]), float(d.get("conf", 0)), int(d.get("block", 0)), words)
459
+
460
+
461
+ @dataclass(frozen=True)
462
+ class OcrPage:
463
+ """Role `ocr`: the page's text in reading order, its lines and words with boxes."""
464
+
465
+ width: int
466
+ height: int
467
+ text: str
468
+ lines: list[OcrLine]
469
+ engine: str | None = None
470
+ lang: str | None = None
471
+ seconds: float | None = None
472
+ pdf: str | None = None # the searchable PDF, when `pdf=` asked for one
473
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
474
+
475
+ @classmethod
476
+ def from_json(cls, d: Json) -> OcrPage:
477
+ lines = [OcrLine.from_json(ln) for ln in cast("list[Json]", d.get("lines", []))]
478
+ return cls(
479
+ int(d["width"]), int(d["height"]), str(d.get("text", "")), lines, d.get("engine"), d.get("lang"),
480
+ _opt_float(d, "seconds"), d.get("pdf"), d,
481
+ ) # fmt: skip
482
+
483
+
484
+ @dataclass(frozen=True)
485
+ class Word:
486
+ start: float
487
+ end: float
488
+ word: str
489
+ probability: float | None = None
490
+
491
+
492
+ @dataclass(frozen=True)
493
+ class Segment:
494
+ start: float
495
+ end: float
496
+ text: str
497
+ words: list[Word]
498
+ avg_logprob: float | None = None
499
+ no_speech_prob: float | None = None
500
+
501
+
502
+ @dataclass(frozen=True)
503
+ class Transcript:
504
+ """Roles `transcribe` and `transcribe-fast`: segments in time order, with words when word_timestamps is on."""
505
+
506
+ language: str | None
507
+ duration: float | None
508
+ segments: list[Segment]
509
+ language_probability: float | None = None
510
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
511
+
512
+ @property
513
+ def text(self) -> str:
514
+ return "".join(s.text for s in self.segments).strip()
515
+
516
+ @classmethod
517
+ def from_json(cls, d: Json) -> Transcript:
518
+ segments = [
519
+ Segment(
520
+ float(s["start"]),
521
+ float(s["end"]),
522
+ str(s.get("text", "")),
523
+ [
524
+ Word(float(w["start"]), float(w["end"]), str(w["word"]), _opt_float(w, "probability"))
525
+ for w in cast("list[Json]", s.get("words", []))
526
+ ],
527
+ _opt_float(s, "avg_logprob"),
528
+ _opt_float(s, "no_speech_prob"),
529
+ )
530
+ for s in cast("list[Json]", d.get("segments", []))
531
+ ]
532
+ return cls(d.get("language"), _opt_float(d, "duration"), segments, _opt_float(d, "language_probability"), d)
533
+
534
+
535
+ @dataclass(frozen=True)
536
+ class Face:
537
+ """One face, in the original image's pixels. Each field is there only when `fields` asked for it."""
538
+
539
+ bbox: list[float] # x1, y1, x2, y2
540
+ kps: list[list[float]] # five landmarks, [x, y] each
541
+ det_score: float | None
542
+ embedding: list[float] # normed, 512 for buffalo_l
543
+ pose: list[float] # pitch, yaw, roll
544
+
545
+ @classmethod
546
+ def from_json(cls, d: Json) -> Face:
547
+ kps = [_floats(p) for p in cast("list[Any]", d.get("kps", []))]
548
+ return cls(
549
+ _floats(d.get("bbox")), kps, _opt_float(d, "det_score"), _floats(d.get("embedding")), _floats(d.get("pose"))
550
+ )
551
+
552
+
553
+ @dataclass(frozen=True)
554
+ class Faces:
555
+ """Role `faces` for one image (with `paths=`, the result's `images` are one each)."""
556
+
557
+ width: int
558
+ height: int
559
+ faces: list[Face]
560
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
561
+
562
+ @classmethod
563
+ def from_json(cls, d: Json) -> Faces:
564
+ return cls(
565
+ int(d["width"]), int(d["height"]), [Face.from_json(f) for f in cast("list[Json]", d.get("faces", []))], d
566
+ )
567
+
568
+ @classmethod
569
+ def many(cls, d: Json) -> list[Faces]:
570
+ """The `images` of a several-image result, in the order of `paths`."""
571
+ return [cls.from_json(i) for i in cast("list[Json]", d.get("images", []))]
572
+
573
+
574
+ @dataclass(frozen=True)
575
+ class Speech:
576
+ """Role `speak`: a WAV on this machine (the service's copy) and how it was made."""
577
+
578
+ path: str
579
+ duration_s: float
580
+ sample_rate: int
581
+ engine: str | None = None
582
+ voice: str | None = None
583
+ seconds: float | None = None
584
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
585
+
586
+ @classmethod
587
+ def from_json(cls, d: Json) -> Speech:
588
+ voice = d.get("voice")
589
+ return cls(
590
+ str(d["path"]), float(d["duration_s"]), int(d["sample_rate"]), d.get("engine"),
591
+ None if voice is None else str(voice), _opt_float(d, "seconds"), d,
592
+ ) # fmt: skip
593
+
594
+
595
+ def _opt_str(d: Json, key: str) -> str | None:
596
+ v = d.get(key)
597
+ return None if v is None else str(v)
598
+
599
+
600
+ def _opt_int(d: Json, key: str) -> int | None:
601
+ v = d.get(key)
602
+ return None if v is None else int(v)
603
+
604
+
605
+ def _floats_map(v: object) -> dict[str, float]:
606
+ return {str(k): float(x) for k, x in cast("dict[str, Any]", v).items()} if isinstance(v, dict) else {}
607
+
608
+
609
+ @dataclass(frozen=True)
610
+ class Answer:
611
+ """`ask`'s roles: the model's text, and with a schema its parsed answer in `json` (None when it did not parse)."""
612
+
613
+ text: str
614
+ json: Any = None
615
+ tokens_in: int | None = None
616
+ tokens_out: int | None = None
617
+ seconds: float | None = None
618
+ model: str | None = None
619
+ cost_usd: float | None = None # cloud models
620
+ provider: str | None = None # cloud models
621
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
622
+
623
+ @classmethod
624
+ def from_json(cls, d: Json) -> Answer:
625
+ return cls(
626
+ str(d.get("text", "")), d.get("json"), _opt_int(d, "tokens_in"), _opt_int(d, "tokens_out"),
627
+ _opt_float(d, "seconds"), _opt_str(d, "model"), _opt_float(d, "cost_usd"), _opt_str(d, "provider"), d,
628
+ ) # fmt: skip
629
+
630
+
631
+ @dataclass(frozen=True)
632
+ class GeneratedImage:
633
+ """Role `image-generate`: the picture on this machine (the service's copy) and the seed that makes it again."""
634
+
635
+ path: str
636
+ width: int
637
+ height: int
638
+ seed: int
639
+ steps: int | None = None
640
+ seconds: float | None = None
641
+ model: str | None = None
642
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
643
+
644
+ @classmethod
645
+ def from_json(cls, d: Json) -> GeneratedImage:
646
+ return cls(
647
+ str(d["path"]), int(d["width"]), int(d["height"]), int(d["seed"]), _opt_int(d, "steps"),
648
+ _opt_float(d, "seconds"), _opt_str(d, "model"), d,
649
+ ) # fmt: skip
650
+
651
+
652
+ @dataclass(frozen=True)
653
+ class Embeddings:
654
+ """Role `image-embed`: one vector per picture and per prompt, in the order sent. With `out=`, the vectors are in
655
+ that .npz file and `images` and `texts` are empty (`raw` has their counts)."""
656
+
657
+ images: list[list[float]]
658
+ texts: list[list[float]]
659
+ dim: int
660
+ out: str | None = None
661
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
662
+
663
+ @classmethod
664
+ def from_json(cls, d: Json) -> Embeddings:
665
+ def vectors(v: object) -> list[list[float]]:
666
+ return [_floats(x) for x in cast("list[Any]", v)] if isinstance(v, list) else []
667
+
668
+ return cls(vectors(d.get("images")), vectors(d.get("texts")), int(d["dim"]), _opt_str(d, "out"), d)
669
+
670
+
671
+ @dataclass(frozen=True)
672
+ class FaceKind:
673
+ real: bool
674
+ kind: str # person, statue, picture, toy, animal
675
+ probs: dict[str, float]
676
+
677
+
678
+ @dataclass(frozen=True)
679
+ class FaceKinds:
680
+ """Role `face-kind`: one verdict per box (or crop), in order; `head` says whether a trained head or CLIP's
681
+ zero-shot similarity decided."""
682
+
683
+ faces: list[FaceKind]
684
+ head: str | None = None
685
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
686
+
687
+ @classmethod
688
+ def from_json(cls, d: Json) -> FaceKinds:
689
+ kinds = [
690
+ FaceKind(bool(f["real"]), str(f["kind"]), _floats_map(f.get("probs")))
691
+ for f in cast("list[Json]", d.get("faces", []))
692
+ ]
693
+ return cls(kinds, _opt_str(d, "head"), d)
694
+
695
+
696
+ @dataclass(frozen=True)
697
+ class CleanAudio:
698
+ """Role `denoise-audio`: a 48 kHz mono WAV (the service's copy), its loudness before and after, and how much the
699
+ denoiser took out."""
700
+
701
+ path: str
702
+ duration_s: float
703
+ sample_rate: int
704
+ engine: str | None = None
705
+ model: str | None = None
706
+ lufs_in: float | None = None
707
+ lufs_out: float | None = None
708
+ removed_db: float | None = None
709
+ seconds: float | None = None
710
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
711
+
712
+ @classmethod
713
+ def from_json(cls, d: Json) -> CleanAudio:
714
+ return cls(
715
+ str(d["path"]), float(d["duration_s"]), int(d["sample_rate"]), _opt_str(d, "engine"), _opt_str(d, "model"),
716
+ _opt_float(d, "lufs_in"), _opt_float(d, "lufs_out"), _opt_float(d, "removed_db"), _opt_float(d, "seconds"), d,
717
+ ) # fmt: skip
718
+
719
+
720
+ @dataclass(frozen=True)
721
+ class AudioQuality:
722
+ """Role `audio-quality`: each group only when it was asked for and could be measured, else empty.
723
+ dnsmos: sig, bak, ovrl (1-5); squim: stoi (0-1), pesq (1-4.5), si_sdr (dB); intrusive: si_sdr, pesq, estoi."""
724
+
725
+ dnsmos: dict[str, float]
726
+ squim: dict[str, float]
727
+ intrusive: dict[str, float]
728
+ duration_s: float | None = None
729
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
730
+
731
+ @classmethod
732
+ def from_json(cls, d: Json) -> AudioQuality:
733
+ return cls(
734
+ _floats_map(d.get("dnsmos")), _floats_map(d.get("squim")), _floats_map(d.get("intrusive")),
735
+ _opt_float(d, "duration_s"), d,
736
+ ) # fmt: skip
737
+
738
+
739
+ @dataclass(frozen=True)
740
+ class VideoCrop:
741
+ id: str
742
+ label: str
743
+ box: tuple[int, int, int, int] # in source pixels
744
+ path: str
745
+ stills: list[str]
746
+
747
+
748
+ @dataclass(frozen=True)
749
+ class EnhancedVideo:
750
+ """Role `video-enhance`: the MP4 (the service's copy), enlarged crops of the asked regions, still frames, and the
751
+ quality readings that could be taken (ssim, psnr, flicker, sharpness, noise...)."""
752
+
753
+ path: str
754
+ width: int
755
+ height: int
756
+ fps: float | None
757
+ frames: int | None
758
+ crops: list[VideoCrop]
759
+ stills: list[str]
760
+ quality: dict[str, Any]
761
+ engine: str | None = None
762
+ model: str | None = None
763
+ seconds: float | None = None
764
+ raw: Json = field(default_factory=lambda: {}, repr=False, compare=False)
765
+
766
+ @classmethod
767
+ def from_json(cls, d: Json) -> EnhancedVideo:
768
+ crops = [
769
+ VideoCrop(
770
+ str(c.get("id", "")),
771
+ str(c.get("label", "")),
772
+ _box(c["box"]),
773
+ str(c["path"]),
774
+ [str(p) for p in cast("list[Any]", c.get("stills", []))],
775
+ )
776
+ for c in cast("list[Json]", d.get("crops", []))
777
+ ]
778
+ stills = [str(p) for p in cast("list[Any]", d.get("stills", []))]
779
+ quality = cast("dict[str, Any]", d.get("quality") or {})
780
+ return cls(
781
+ str(d["path"]), int(d["width"]), int(d["height"]), _opt_float(d, "fps"), _opt_int(d, "frames"), crops,
782
+ stills, quality, _opt_str(d, "engine"), _opt_str(d, "model"), _opt_float(d, "seconds"), d,
783
+ ) # fmt: skip