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