strata-python 0.2.6__py3-none-any.whl → 0.2.8__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.
@@ -142,6 +142,42 @@ def run(
142
142
  return wait(int(submit(role, params, app, priority, model)["id"]), timeout)
143
143
 
144
144
 
145
+ @dataclass(frozen=True)
146
+ class Provenance:
147
+ """What a run job's output was made with, from its row: the model key, its load options as the job ran (the
148
+ service's models.toml options merged with the job's own) and `settings_hash`, which changes when the model's
149
+ runtime, file or options do even under the same key. Key a cache on (model, settings_hash). The options and hash
150
+ are None on rows from a service older than the one that records them."""
151
+
152
+ model: str | None
153
+ options: Json | None
154
+ settings_hash: str | None
155
+ job_id: int
156
+
157
+ @classmethod
158
+ def from_job(cls, job: Json) -> Provenance:
159
+ options = job.get("options")
160
+ return cls(
161
+ _opt_str(job, "model"), cast("Json", options) if isinstance(options, dict) else None,
162
+ _opt_str(job, "settings_hash"), int(job["id"]),
163
+ ) # fmt: skip
164
+
165
+
166
+ def run_with_provenance(
167
+ role: str,
168
+ params: Mapping[str, Any] | None,
169
+ app: str,
170
+ priority: Priority = "normal",
171
+ model: str | None = None,
172
+ timeout: float | None = None,
173
+ ) -> tuple[Json, Provenance]:
174
+ """`run`, plus what the result was made with (`Provenance`): for an app that stores each result with its model
175
+ and settings, and keys its cache on them."""
176
+ job_id = int(submit(role, params, app, priority, model)["id"])
177
+ result = wait(job_id, timeout)
178
+ return result, Provenance.from_job(_call("GET", f"/api/jobs/{job_id}"))
179
+
180
+
145
181
  ROLES = (
146
182
  "faces",
147
183
  "face-kind",
@@ -338,6 +374,24 @@ def role_model(role: str) -> str | None:
338
374
  return next((cast("str", r["model"]) for r in roles if r["key"] == role), None)
339
375
 
340
376
 
377
+ @dataclass(frozen=True)
378
+ class RoleSettings:
379
+ """The model that serves a role now and its `settings_hash` (see `Provenance`); the hash is None from a service
380
+ older than the one that reports it."""
381
+
382
+ model: str
383
+ settings_hash: str | None
384
+
385
+
386
+ def role_settings(role: str) -> RoleSettings | None:
387
+ """`role_model` with the settings hash: a cache keyed on both is made again when the role's model changes, and
388
+ also when that model's options change under the same key (a threshold in the service's models.toml). None for an
389
+ unknown role."""
390
+ roles = cast("list[Json]", _call("GET", "/api/registry").get("roles", []))
391
+ r = next((r for r in roles if r["key"] == role), None)
392
+ return None if r is None else RoleSettings(str(r["model"]), _opt_str(r, "settings_hash"))
393
+
394
+
341
395
  class Lease:
342
396
  """A held lease: `.id`, `.job` (the row when granted). Heartbeats run on a daemon thread until `release()`."""
343
397
 
@@ -32,14 +32,16 @@ def utc(epoch: float | None) -> datetime.datetime | None:
32
32
 
33
33
 
34
34
  class ApiModel(BaseModel):
35
- """A base for an app's own response models. pydantic marks a field with a default as optional in the schema, so
36
- the generated TypeScript gets a `?` though the server always sends it; this config makes the response schema
37
- say what is sent. Use it for responses: a request body built on it has an `-Input` and an `-Output` schema."""
35
+ """The base of the response shapes here, and for an app's own. pydantic marks a field with a default as optional in
36
+ the schema, so the generated TypeScript gets a `?` though the server always sends it; this config makes the
37
+ response schema say what is sent (`Page.next` is `string | null`, not `next?`). Use it for responses: a request
38
+ body built on it has an `-Input` and an `-Output` schema. `FileRef` and `Judgment` stay on `BaseModel`, since an
39
+ app may take them as a request body."""
38
40
 
39
41
  model_config = ConfigDict(json_schema_serialization_defaults_required=True)
40
42
 
41
43
 
42
- class Health(BaseModel):
44
+ class Health(ApiModel):
43
45
  """What `GET /api/health` answers. Extra fields are the app's own (strata-models adds `gpu`)."""
44
46
 
45
47
  model_config = ConfigDict(extra="allow")
@@ -48,7 +50,7 @@ class Health(BaseModel):
48
50
  commit: str | None = None # the source commit the server runs, so a probe can tell a stale deploy
49
51
 
50
52
 
51
- class Folder(BaseModel):
53
+ class Folder(ApiModel):
52
54
  """A folder the app uses, and the disk it is on (None when the folder does not exist yet)."""
53
55
 
54
56
  name: str
@@ -58,7 +60,7 @@ class Folder(BaseModel):
58
60
  total_bytes: int | None = None
59
61
 
60
62
 
61
- class ServiceStatus(BaseModel):
63
+ class ServiceStatus(ApiModel):
62
64
  """Another strata service this app calls, as its health endpoint answered just now."""
63
65
 
64
66
  name: str
@@ -68,7 +70,7 @@ class ServiceStatus(BaseModel):
68
70
  detail: str | None = None # why it is not ok: not reachable, or what it answered
69
71
 
70
72
 
71
- class SystemInfo(BaseModel):
73
+ class SystemInfo(ApiModel):
72
74
  """What `GET /api/system` answers: what is running, where its data is, and whether its services answer."""
73
75
 
74
76
  model_config = ConfigDict(extra="allow")
@@ -81,7 +83,7 @@ class SystemInfo(BaseModel):
81
83
  services: list[ServiceStatus] = Field(default_factory=lambda: [])
82
84
 
83
85
 
84
- class ErrorBody(BaseModel):
86
+ class ErrorBody(ApiModel):
85
87
  """The body of every error the app answers. `detail` is what FastAPI already uses, so clients that read it keep
86
88
  working; `payload` carries what the error wants the client to have (the job row of a refused job)."""
87
89
 
@@ -93,7 +95,7 @@ TaskState = Literal["queued", "running", "done", "failed", "cancelled"]
93
95
  FINISHED: frozenset[str] = frozenset({"done", "failed", "cancelled"})
94
96
 
95
97
 
96
- class Progress(BaseModel):
98
+ class Progress(ApiModel):
97
99
  """How far a task has got. `total` None means not known yet; `text` is the line a person reads ("Page 3 of 40")."""
98
100
 
99
101
  done: float = 0
@@ -107,7 +109,7 @@ class Progress(BaseModel):
107
109
  return None if not self.total else min(max(self.done / self.total, 0.0), 1.0)
108
110
 
109
111
 
110
- class Task(BaseModel):
112
+ class Task(ApiModel):
111
113
  """A job or task row as an API answers it."""
112
114
 
113
115
  id: int | str
@@ -126,7 +128,7 @@ class Task(BaseModel):
126
128
  T = TypeVar("T")
127
129
 
128
130
 
129
- class Page(BaseModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
131
+ class Page(ApiModel, Generic[T]): # Generic, not `Page[T]`: Python 3.11 is supported
130
132
  """One page of a list. `next` is an opaque cursor (pass it back as `after`), None on the last page; a cursor, not an
131
133
  offset, so rows added while a person pages through do not repeat or vanish."""
132
134
 
@@ -0,0 +1,232 @@
1
+ """Exact time for media: rational seconds, frame rates, half-open spans and the map from an edit's output time back to its sources.
2
+
3
+ An editor that keeps time as float seconds drifts: 1001/30000 s is not a float, a frame found by `int(t * fps)` lands one early when `t` came
4
+ back from a sum, and a cut moved twice is no longer on a frame. strata-reels (the video editor) and strata-360 both needed the same answer,
5
+ which is the one OpenTimelineIO and every NLE use: time is a rational number of seconds, a rate is a rational number of frames a second,
6
+ and a stretch of time is half-open, [start, end), so two shots that meet share no frame. Here:
7
+
8
+ t = rational("1001/30000") # Fraction; also from an int, a Decimal, a str ("12.04") or a float (by its shortest repr)
9
+ pal = Rate.parse("25/1"); ntsc = Rate.parse("30000/1001") # ffprobe's r_frame_rate / avg_frame_rate text
10
+ ntsc.frame_at(t); ntsc.time_of(120); ntsc.snap(t) # the frame showing at t; when frame 120 starts; the nearest frame start
11
+ s = Span(rational(2), rational(5)); s.duration; s & Span(...) # [2, 5): 3 s; the overlap, or None
12
+ m = TimeMap.sequence([("tape1", Span(...)), ("tape1", Span(...))]) # source ranges played end to end
13
+ m.to_source(rational(4)) -> ("tape1", Fraction(...)); m.to_output("tape1", t) -> [output times]
14
+ text(t) -> "1001/30000"; m.to_json(); TimeMap.from_json(...) # exact in JSON: rationals as strings
15
+
16
+ A float never goes in silently: `rational(0.1)` is 1/10 (the float's shortest repr), not 3602879701896397/36028797018963968, and a value that
17
+ is not a number raises ValueError. Standard library only."""
18
+
19
+ from __future__ import annotations
20
+
21
+ import bisect
22
+ import itertools
23
+ import math
24
+ from collections.abc import Iterable, Sequence
25
+ from dataclasses import dataclass, field
26
+ from decimal import Decimal
27
+ from fractions import Fraction
28
+ from typing import Any
29
+
30
+ Number = int | float | str | Decimal | Fraction
31
+
32
+
33
+ def rational(value: Number) -> Fraction:
34
+ """Exact seconds (or any quantity) from an int, Fraction, Decimal, "p/q" or decimal text, or a float by its shortest repr."""
35
+ if isinstance(value, bool):
36
+ raise ValueError(f"not a number: {value!r}")
37
+ if isinstance(value, float):
38
+ if not math.isfinite(value):
39
+ raise ValueError(f"not a finite number: {value!r}")
40
+ return Fraction(
41
+ repr(value)
42
+ ) # 0.1 -> 1/10: the number the person or file wrote, not the float's binary expansion
43
+ try:
44
+ return Fraction(value)
45
+ except (ValueError, ZeroDivisionError, TypeError) as e:
46
+ raise ValueError(f"not a number: {value!r}") from e
47
+
48
+
49
+ def text(value: Fraction) -> str:
50
+ """A rational as JSON-safe text: "3" or "1001/30000"; `rational` reads it back exactly."""
51
+ return str(value)
52
+
53
+
54
+ @dataclass(frozen=True, order=True)
55
+ class Rate:
56
+ """Frames a second, exact: 25, 50, 30000/1001. Frame n starts at n / rate and shows until frame n + 1 starts."""
57
+
58
+ fps: Fraction
59
+
60
+ def __post_init__(self) -> None:
61
+ if self.fps <= 0:
62
+ raise ValueError(f"a frame rate must be above 0: {self.fps}")
63
+
64
+ @classmethod
65
+ def parse(cls, value: Number) -> Rate:
66
+ """From ffprobe's "30000/1001" (or "25", 25, 29.97 as written)."""
67
+ return cls(rational(value))
68
+
69
+ @property
70
+ def frame_s(self) -> Fraction:
71
+ """How long one frame lasts."""
72
+ return 1 / self.fps
73
+
74
+ def frame_at(self, t: Fraction) -> int:
75
+ """The frame showing at `t` (a time on a frame's start is that frame): floor(t * fps)."""
76
+ return math.floor(t * self.fps)
77
+
78
+ def time_of(self, frame: int) -> Fraction:
79
+ """When `frame` starts."""
80
+ return frame / self.fps
81
+
82
+ def snap(self, t: Fraction) -> Fraction:
83
+ """The frame start nearest `t`; exactly halfway goes to the earlier frame, so snapping never moves a cut past the frame it was in."""
84
+ n = t * self.fps
85
+ lower = math.floor(n)
86
+ return self.time_of(lower if n - lower <= Fraction(1, 2) else lower + 1)
87
+
88
+ def __str__(self) -> str:
89
+ return text(self.fps)
90
+
91
+
92
+ @dataclass(frozen=True, order=True)
93
+ class Span:
94
+ """A stretch of time, half-open: [start, end). Two spans that meet (one's end is the other's start) do not overlap."""
95
+
96
+ start: Fraction
97
+ end: Fraction
98
+
99
+ def __post_init__(self) -> None:
100
+ if self.end < self.start:
101
+ raise ValueError(f"a span cannot end before it starts: [{self.start}, {self.end})")
102
+
103
+ @classmethod
104
+ def of(cls, start: Number, end: Number) -> Span:
105
+ return cls(rational(start), rational(end))
106
+
107
+ @property
108
+ def duration(self) -> Fraction:
109
+ return self.end - self.start
110
+
111
+ def __contains__(self, t: object) -> bool:
112
+ return isinstance(t, (int, Fraction)) and self.start <= t < self.end
113
+
114
+ def overlaps(self, other: Span) -> bool:
115
+ """They share some time; an empty span shares none, even inside another (the same answer as `&`)."""
116
+ return (self & other) is not None
117
+
118
+ def __and__(self, other: Span) -> Span | None:
119
+ """The overlap of two spans, or None when they share no time."""
120
+ start, end = max(self.start, other.start), min(self.end, other.end)
121
+ return Span(start, end) if start < end else None
122
+
123
+ def shift(self, by: Fraction) -> Span:
124
+ return Span(self.start + by, self.end + by)
125
+
126
+ def frames(self, rate: Rate) -> range:
127
+ """The frames whose start lies in the span: the frames a cut [start, end) keeps."""
128
+ first = math.ceil(self.start * rate.fps)
129
+ last = math.ceil(self.end * rate.fps)
130
+ return range(first, last)
131
+
132
+ def to_json(self) -> list[str]:
133
+ return [text(self.start), text(self.end)]
134
+
135
+ @classmethod
136
+ def from_json(cls, value: Sequence[Number]) -> Span:
137
+ if len(value) != 2:
138
+ raise ValueError(f"a span is [start, end]: {value!r}")
139
+ return cls.of(value[0], value[1])
140
+
141
+
142
+ @dataclass(frozen=True)
143
+ class Piece:
144
+ """One stretch of a source placed in the output: `source` from `src.start` to `src.end` plays from output time `at`, at `speed` (2 = twice as
145
+ fast, so it lasts half as long in the output). A freeze frame is not a speed of 0: give it its own piece of one frame and a slow speed."""
146
+
147
+ source: str
148
+ src: Span
149
+ at: Fraction
150
+ speed: Fraction = Fraction(1)
151
+
152
+ def __post_init__(self) -> None:
153
+ if self.speed <= 0:
154
+ raise ValueError(f"speed must be above 0: {self.speed}")
155
+ if self.src.duration == 0:
156
+ raise ValueError(f"a piece of {self.source} plays nothing: {self.src}")
157
+
158
+ @property
159
+ def out(self) -> Span:
160
+ """Where the piece sits in the output."""
161
+ return Span(self.at, self.at + self.src.duration / self.speed)
162
+
163
+ def to_source(self, t: Fraction) -> Fraction:
164
+ return self.src.start + (t - self.at) * self.speed
165
+
166
+ def to_output(self, s: Fraction) -> Fraction:
167
+ return self.at + (s - self.src.start) / self.speed
168
+
169
+ def to_json(self) -> dict[str, Any]:
170
+ d: dict[str, Any] = {"source": self.source, "src": self.src.to_json(), "at": text(self.at)}
171
+ if self.speed != 1:
172
+ d["speed"] = text(self.speed)
173
+ return d
174
+
175
+ @classmethod
176
+ def from_json(cls, d: dict[str, Any]) -> Piece:
177
+ return cls(str(d["source"]), Span.from_json(d["src"]), rational(d["at"]), rational(d.get("speed", 1)))
178
+
179
+
180
+ @dataclass(frozen=True)
181
+ class TimeMap:
182
+ """Output time to source time for one track of an edit: pieces in output order, never overlapping in the output (gaps are allowed: nothing
183
+ plays there). `to_source` answers what is showing; `to_output` answers every place a source moment is used (it may be used twice)."""
184
+
185
+ pieces: tuple[Piece, ...] = ()
186
+ _starts: tuple[Fraction, ...] = field(default=(), init=False, repr=False, compare=False)
187
+
188
+ def __post_init__(self) -> None:
189
+ ordered = tuple(sorted(self.pieces, key=lambda p: p.at))
190
+ for a, b in itertools.pairwise(ordered):
191
+ if a.out.overlaps(b.out):
192
+ raise ValueError(f"pieces overlap in the output: {a.out} and {b.out}")
193
+ object.__setattr__(self, "pieces", ordered)
194
+ object.__setattr__(self, "_starts", tuple(p.at for p in ordered))
195
+
196
+ @classmethod
197
+ def sequence(cls, ranges: Iterable[tuple[str, Span]], start: Fraction = Fraction(0)) -> TimeMap:
198
+ """Source ranges played one after the other with no gap, from output time `start`: a cut list."""
199
+ pieces: list[Piece] = []
200
+ at = start
201
+ for source, src in ranges:
202
+ pieces.append(Piece(source, src, at))
203
+ at += src.duration
204
+ return cls(tuple(pieces))
205
+
206
+ @property
207
+ def duration(self) -> Fraction:
208
+ """The end of the last piece (gaps included)."""
209
+ return self.pieces[-1].out.end if self.pieces else Fraction(0)
210
+
211
+ def piece_at(self, t: Fraction) -> Piece | None:
212
+ i = bisect.bisect_right(self._starts, t) - 1
213
+ if i < 0:
214
+ return None
215
+ p = self.pieces[i]
216
+ return p if t in p.out else None
217
+
218
+ def to_source(self, t: Fraction) -> tuple[str, Fraction] | None:
219
+ """(source, source time) showing at output time `t`, or None in a gap or past the end."""
220
+ p = self.piece_at(t)
221
+ return None if p is None else (p.source, p.to_source(t))
222
+
223
+ def to_output(self, source: str, s: Fraction) -> list[Fraction]:
224
+ """Every output time at which `source` time `s` plays, earliest first (none when the edit leaves it out)."""
225
+ return [p.to_output(s) for p in self.pieces if p.source == source and s in p.src]
226
+
227
+ def to_json(self) -> list[dict[str, Any]]:
228
+ return [p.to_json() for p in self.pieces]
229
+
230
+ @classmethod
231
+ def from_json(cls, value: Iterable[dict[str, Any]]) -> TimeMap:
232
+ return cls(tuple(Piece.from_json(d) for d in value))
strata_python/testing.py CHANGED
@@ -34,7 +34,7 @@ from collections.abc import Callable, Mapping, Sequence
34
34
  from dataclasses import dataclass, field
35
35
  from email.message import Message
36
36
  from pathlib import Path
37
- from typing import Any, ClassVar
37
+ from typing import Any, ClassVar, cast
38
38
 
39
39
  Body = bytes | str | Any # bytes and str are sent as they are; anything else as JSON
40
40
 
@@ -328,13 +328,17 @@ class FakeModels:
328
328
 
329
329
  `running_polls` is how many polls a job answers `running` before it finishes (default 1, as the real service
330
330
  usually is when the first poll arrives). A role with no result is refused with a 422, as the service refuses a role
331
- it does not know. The registry answers each role's model from `.models` (role -> model name)."""
331
+ it does not know. The registry answers each role's model from `.models` (role -> model name). A job records the
332
+ settings it ran with when it starts, as the service does: `options` (`.options[role]`, the role's load options,
333
+ merged with the job's own) and `settings_hash` (a hash of the model and those options, also on the registry's roles),
334
+ so changing `.options` mid-test shows what an app's cache does when the service's settings change."""
332
335
 
333
336
  def __init__(self, results: Mapping[str, Result] | None = None, *, running_polls: int = 1) -> None:
334
337
  from fastapi import FastAPI, HTTPException, Request # here, so importing the fakes does not load FastAPI
335
338
 
336
339
  self.results: dict[str, Result] = dict(MODELS_RESULTS if results is None else results)
337
340
  self.models: dict[str, str] = {}
341
+ self.options: dict[str, Json] = {} # role -> the model's load options (the service's models.toml)
338
342
  self.running_polls = running_polls
339
343
  self.jobs: list[Json] = [] # every job submitted, in order, as the service stored it
340
344
  self.leases: list[Json] = []
@@ -345,6 +349,7 @@ class FakeModels:
345
349
  self.down = False
346
350
  self._failures: list[tuple[str | None, str]] = []
347
351
  self._polls: dict[int, int] = {}
352
+ self._asked: dict[int, Json] = {} # job id -> the load options its submit asked for
348
353
  app = FastAPI()
349
354
  self.app = app
350
355
 
@@ -362,14 +367,25 @@ class FakeModels:
362
367
 
363
368
  @app.get("/api/registry")
364
369
  def registry() -> Json: # pyright: ignore[reportUnusedFunction]
365
- return {"roles": [{"key": r, "model": self.models.get(r, f"fake-{r}")} for r in self.results]}
370
+ return {
371
+ "roles": [{"key": r, "model": self._model(r), "settings_hash": self._hash(r)} for r in self.results]
372
+ }
366
373
 
367
374
  @app.post("/api/jobs")
368
375
  def submit(body: Json) -> Json: # pyright: ignore[reportUnusedFunction]
369
376
  role = str(body.get("role"))
370
377
  if role not in self.results:
371
378
  raise HTTPException(422, f"unknown role {role!r}")
372
- job: Json = {**body, "id": len(self.jobs) + 1, "status": "queued", "result": None, "error": None}
379
+ job: Json = {
380
+ **body,
381
+ "id": len(self.jobs) + 1,
382
+ "status": "queued",
383
+ "result": None,
384
+ "error": None,
385
+ "options": None, # what it runs with, recorded when it starts; the variant asked for is kept apart
386
+ "settings_hash": None,
387
+ }
388
+ self._asked[job["id"]] = cast("Json", body.get("options") or {})
373
389
  self.jobs.append(job)
374
390
  return dict(job)
375
391
 
@@ -378,6 +394,8 @@ class FakeModels:
378
394
  job = self._job(job_id, HTTPException)
379
395
  if job["status"] in ("queued", "running"):
380
396
  n = self._polls[job_id] = self._polls.get(job_id, 0) + 1
397
+ if job["status"] == "queued":
398
+ self._start(job)
381
399
  if n <= self.running_polls:
382
400
  job["status"] = "running"
383
401
  else:
@@ -414,6 +432,24 @@ class FakeModels:
414
432
  self._failures.append((role, error))
415
433
  return self
416
434
 
435
+ def _model(self, role: str, model: object = None) -> str:
436
+ return str(model) if model else self.models.get(role, f"fake-{role}")
437
+
438
+ def _hash(self, role: str, model: object = None, asked: Json | None = None) -> str:
439
+ import hashlib
440
+
441
+ options = {**self.options.get(role, {}), **(asked or {})}
442
+ text = json.dumps([self._model(role, model), options], sort_keys=True, default=str)
443
+ return hashlib.sha256(text.encode()).hexdigest()[:12]
444
+
445
+ def _start(self, job: Json) -> None:
446
+ role, asked = str(job["role"]), self._asked.get(int(job["id"]), {})
447
+ job.update(
448
+ model=self._model(role, job.get("model")),
449
+ options={**self.options.get(role, {}), **asked},
450
+ settings_hash=self._hash(role, job.get("model"), asked),
451
+ )
452
+
417
453
  def _finish(self, job: Json) -> None:
418
454
  for i, (role, error) in enumerate(self._failures):
419
455
  if role is None or role == job["role"]:
strata_python/web.py CHANGED
@@ -16,14 +16,18 @@ import datetime
16
16
  import json
17
17
  import os
18
18
  import platform
19
+ import re
19
20
  import shutil
20
21
  import sys
22
+ import typing
21
23
  from collections.abc import Callable, Mapping, Sequence
24
+ from typing import cast
22
25
 
23
26
  import uvicorn
24
27
  from fastapi import FastAPI, HTTPException, Request
25
28
  from fastapi.responses import FileResponse, HTMLResponse, JSONResponse
26
29
  from fastapi.staticfiles import StaticFiles
30
+ from pydantic import BaseModel
27
31
 
28
32
  from strata_python.client import Rejected, ServiceClient, Unavailable
29
33
  from strata_python.contracts import ErrorBody, Folder, ServiceStatus, SystemInfo
@@ -202,6 +206,22 @@ def _service(name: str, client: ServiceClient) -> ServiceStatus:
202
206
  )
203
207
 
204
208
 
209
+ def _app_name(title: str) -> str:
210
+ """`my-app` -> `MyApp`, the prefix of the app's own schema components (as `Settings.model()` names them)."""
211
+ return "".join(p.capitalize() for p in re.split(r"[^0-9A-Za-z]+", title) if p)
212
+
213
+
214
+ def _returned_model(fn: Callable[[], object] | None) -> type[BaseModel] | None:
215
+ """The pydantic model `fn` is annotated to return, if any."""
216
+ if fn is None:
217
+ return None
218
+ try:
219
+ hint = typing.get_type_hints(fn).get("return")
220
+ except Exception: # an annotation that does not resolve (a lambda has none): no model, as before
221
+ return None
222
+ return hint if isinstance(hint, type) and issubclass(hint, BaseModel) else None
223
+
224
+
205
225
  def add_system(
206
226
  app: FastAPI,
207
227
  version: str,
@@ -209,22 +229,36 @@ def add_system(
209
229
  commit: str | None = None,
210
230
  folders: Mapping[str, str | Callable[[], str]] | None = None,
211
231
  services: Mapping[str, ServiceClient | str] | None = None,
212
- extra: Callable[[], Mapping[str, object]] | None = None,
232
+ extra: Callable[[], Mapping[str, object] | BaseModel] | None = None,
233
+ extra_model: type[BaseModel] | None = None,
213
234
  ) -> None:
214
235
  """`GET /api/system`, a `SystemInfo`: the version and commit, Python and platform, when the server started, each
215
236
  named folder with its disk's free and total space, and each service this app calls with what its health endpoint
216
237
  answers now (probed in parallel, 2 s each). A folder is a path or a function giving one (a setting read on each
217
- request); a service is a `ServiceClient` or a base URL. `extra` adds the app's own fields (a queue length)."""
238
+ request); a service is a `ServiceClient` or a base URL. `extra` adds the app's own fields (a queue length), as a
239
+ mapping or a model. Their model, `extra_model` or the model `extra` is annotated to return, is merged into the
240
+ response model, named `<App>SystemInfo` after the app's title, so the schema and the generated types list them;
241
+ without one they are sent but not described."""
218
242
  started = datetime.datetime.now(datetime.UTC)
219
243
  clients = {k: v if isinstance(v, ServiceClient) else ServiceClient(v) for k, v in (services or {}).items()}
220
-
221
- @app.get("/api/system", response_model=SystemInfo)
244
+ fields = extra_model or _returned_model(extra)
245
+ shape: type[SystemInfo] = SystemInfo
246
+ if fields is not None:
247
+ # one component holding both: the web app's type is Schema<'<App>SystemInfo'>, nothing written by hand
248
+ shape = cast("type[SystemInfo]", type(_app_name(app.title) + "SystemInfo", (SystemInfo, fields), {}))
249
+
250
+ def own() -> dict[str, object]:
251
+ got: Mapping[str, object] | BaseModel = extra() if extra else {}
252
+ # by alias: the merged model validates by the same keys the app's model does (review finding)
253
+ return got.model_dump(by_alias=True) if isinstance(got, BaseModel) else dict(got)
254
+
255
+ @app.get("/api/system", response_model=shape)
222
256
  def get_system() -> SystemInfo: # pyright: ignore[reportUnusedFunction]
223
257
  paths = {k: v if isinstance(v, str) else v() for k, v in (folders or {}).items()}
224
258
  with concurrent.futures.ThreadPoolExecutor(max_workers=max(len(clients), 1)) as pool:
225
259
  probes = [pool.submit(_service, k, c) for k, c in clients.items()]
226
260
  statuses = [p.result() for p in probes]
227
- return SystemInfo(
261
+ return shape(
228
262
  version=version,
229
263
  commit=commit,
230
264
  python=sys.version.split()[0],
@@ -232,7 +266,7 @@ def add_system(
232
266
  started_at=started,
233
267
  folders=[_folder(k, p) for k, p in paths.items()],
234
268
  services=statuses,
235
- **(extra() if extra else {}),
269
+ **own(),
236
270
  )
237
271
 
238
272
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.6
3
+ Version: 0.2.8
4
4
  Summary: Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate
5
5
  Project-URL: Homepage, https://github.com/jburnhams/strata-python
6
6
  Project-URL: Source, https://github.com/jburnhams/strata-python
@@ -61,9 +61,10 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
61
61
  | `strata_python.files` | Atomic writes (`atomic_path` keeps the extension for ffmpeg, `atomic_open`, `write_json_atomic`, `write_text_atomic`, `write_bytes_atomic`), `read_json(path, default)`, `sha256`/`sha256_hex`, `quick_fingerprint` (size and both ends), `stat_key` (a cache key that follows the file), `inside(root, path)` (refuses `..` and links out), and `DiskCache` (values on disk with an age; `json(key, fetch, max_age_s)`) |
62
62
  | `strata_python.http` | `Http(user_agent, min_interval=...)`, the polite client for other people's APIs: a gap per host across threads (and processes with `throttle_file`), Retry-After as seconds or a date, a cool-down for a host that keeps saying 429, retries that never replay a write, a size cap, an optional `DiskCache`, and errors returned as a `Reply` (`raise_for_status()`, `get_json()` for code that wants exceptions) |
63
63
  | `strata_python.media` | `probe(path)` (a typed `Probe`: duration, format, tags, streams, chapters, ffprobe's warnings), `duration`, `ffmpeg(args, progress=...)` raising `MediaError` with ffmpeg's own reason, `available()` |
64
+ | `strata_python.mediatime` | Exact time for media: `rational` seconds (Fraction), `Rate` (`frame_at`, `time_of`, `snap`), half-open `Span`, and `TimeMap` from an edit's output time to its sources and back, with exact JSON |
64
65
  | `strata_python.images` (extra `[images]`) | `thumbnail(src, px, cache_dir=...)` (an upright JPEG, made once, keyed on the file, never enlarged, the app's own reader through `make=`), `open_upright`, `flatten` (alpha and 16-bit greys to 8-bit RGB), `jpeg_bytes` |
65
66
  | `strata_python.stats` | Pairwise rankings and eval statistics in pure Python: `bradley_terry` (ties, an optional side advantage, Elo-scale `ratings()`), `intervals` (bootstrap), `head_to_head`, `votes_from(judgments)`, `wilson`, `mcnemar`, `holm` |
66
- | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
67
+ | `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `run_with_provenance` and `role_settings` (the model and settings a result was made with, for cache keys), `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
67
68
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
68
69
  | pytest plugin | Loaded automatically: hermetic home and data folders (`strata_env` adds the app's own variables), a no-network guard, `http_server` and `live_app`, the `fake_urlopen`, `fake_popen`, `fake_run` and `no_sleep` fixtures, `fake_models` (a stand-in strata-models), and the `integration` marker on everything under `tests/integration` |
69
70
  | `strata_python.testing` | The fakes behind those fixtures (`FakeResponse`, `http_error`, `FakeUrlopen`, `FakePopen`, `FakeRun`, `Sleeper`) `FakeModels`, the CLI runners `run_cli(main, *args)` and `run_module("myapp", *args, src=...)`, and `assert_openapi_current(create_app, path)` |
@@ -186,6 +187,8 @@ web.add_system(
186
187
  ) # GET /api/system, a SystemInfo
187
188
  ```
188
189
 
190
+ The app's own `/api/system` fields go in `extra=`, a function returning a mapping or a model. Give their model (`extra_model=AppNumbers`, or annotate the function `-> AppNumbers`) and the route's response is `<App>SystemInfo`, `SystemInfo` plus those fields, so the web app's type is `Schema<'MyappSystemInfo'>` with nothing added by hand.
191
+
189
192
  Delete the app's `guard()` (or each route's `try/except` raising `HTTPException`), passing its own exceptions as `add_error_handlers(app, {BookLocked: 423})`, and its `/api/system` route. Give `base_app` the same `commit=` so `/api/health` says which source the server runs. Declare a route's answer with a shape from `strata_python.contracts` (`response_model=Page[Task]`) where the app already returns that shape, so the web app's types can come from `/api/openapi.json`.
190
193
 
191
194
  Delete the app's own `/api/health` and `/api/settings` routes, its `/assets` mount, SPA fallback, `with_base` and `static_file` copies and its `uvicorn.run` wrapper. `web.serve(app, argv, default_port=...)` replaces the last of these. For health fields of the app's own, pass `health=lambda: {"gpu": gpu_name()}`: they follow `ok` and `version`, and may set `ok` to false. It runs on every request, so keep it cheap.
@@ -403,6 +406,7 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
403
406
 
404
407
  add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
405
408
 
409
+
406
410
  @app.get("/api/notes")
407
411
  def notes(db: DbSession) -> list[NoteOut]: ...
408
412
  ```
@@ -2,23 +2,24 @@ strata_python/__init__.py,sha256=eF-f5-pwPokTJjoq063Hr78JTnjPkVm-3hQBN9tXqDs,172
2
2
  strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
3
3
  strata_python/cli.py,sha256=guO3aDiSe8Ri4-0aHDLCwUKMiu6rLpnSo7leWzf0Ehw,8170
4
4
  strata_python/client.py,sha256=S-cfDQqbO0dJ951TAiFyW2CbkFQkN1OWnUBCYaTO3Lg,7911
5
- strata_python/contracts.py,sha256=DNyCi8pKXrfaRIadJ3DuAH8YUbXh4fVVY5T21sAJf98,6379
5
+ strata_python/contracts.py,sha256=5-PdY404s2X2pS3UU8_glV-1n_53cJCsrp0IHVKr-NU,6536
6
6
  strata_python/files.py,sha256=jJMFnzsigY29f6EcpjEtbBnc-66FCOuw875epYMOSjg,11423
7
7
  strata_python/http.py,sha256=dltLx14TqQGuLhFeFoYyNZiOVAXx7ZEeXPQwPjaT2hc,16152
8
8
  strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
9
9
  strata_python/images.py,sha256=nNQ7fQxkpmnTf5iotYlR7VejxCfthXgIpMEGTsLvNVE,4872
10
10
  strata_python/live.py,sha256=kNY6h6gMxBo9l78UoGUIWjcADeZi4eZuAEp0jqDowEE,1215
11
11
  strata_python/media.py,sha256=66Pk1_CTHyApKlWD8LuzS08O3EOx-7dNaj9AkEbNxmw,12647
12
+ strata_python/mediatime.py,sha256=6xf2vh_iZnZ22E0ja4u4XrbCldOqCgJMqZNY3OZQ2nY,9855
12
13
  strata_python/oslib.py,sha256=vfZDUCNZnTjjjB704eoyNXlPFCz2yVR3puFljE0Z1gE,12137
13
14
  strata_python/public_check.py,sha256=2N1X15D578QFgN32TUazFDj6SOHtAJhjOgoZNOQu_vU,13398
14
15
  strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
15
16
  strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
16
17
  strata_python/settings.py,sha256=YeQMJwyqFNX7L3bbgbwRN1hdfzBem9uWxqg_WVswT-A,18688
17
18
  strata_python/stats.py,sha256=nc6qXELpMg7eK0xjFo45M1FK7FR3q89be3VCJzExKYc,8354
18
- strata_python/testing.py,sha256=WvakeIAJtdeOrIDq32WWXfWkfBkMQ2cUU279L0Ebhs0,20888
19
- strata_python/web.py,sha256=-AWb9Ad2e870zbr4OT1oZS1IpOZ0nd-jdpu4ICOHejE,13528
19
+ strata_python/testing.py,sha256=GpqljUX07FuOWZaizC4wHQJvT03NdBpKi31TgZPpi80,22715
20
+ strata_python/web.py,sha256=RkT8cR6gZ0MNYnUDMtKjAu9pIkPmdh0coxkoB5cyA9c,15252
20
21
  strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
21
- strata_python/clients/models.py,sha256=vxnvINQ_xQRbU848BTnGyjlTcr1-bhv6GAkrCN5ZDuU,30314
22
+ strata_python/clients/models.py,sha256=sHhU1Lfw_0y3lkTQ74Q0OcOV4KjviV6Qq93V_D1mV3Y,32531
22
23
  strata_python/db/__init__.py,sha256=Vx28OmktWBhEM9gj1VxoxNuJDvdtpYoJ3-prrzoBR40,4009
23
24
  strata_python/db/__main__.py,sha256=nHCtenRtjL_Ouig4FHh60dax2oILeVdoIIKrxXEc6Ss,106
24
25
  strata_python/db/cli.py,sha256=kCNHDlFIzECtvExUGBaJ0BK4ZqesGHS7Jjnhh-gWIpI,10896
@@ -47,8 +48,8 @@ strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,
47
48
  strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
48
49
  strata_python/tasks/status.py,sha256=cZvYghNAGJRlpVIJAtUSb5pW19UbxR6bNQU4etJMYN4,7440
49
50
  strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
50
- strata_python-0.2.6.dist-info/METADATA,sha256=dDY27gm38DSVlkMD1G1_GIVYjyYut3TsTEfbb_YAwIM,37541
51
- strata_python-0.2.6.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
52
- strata_python-0.2.6.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
53
- strata_python-0.2.6.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
54
- strata_python-0.2.6.dist-info/RECORD,,
51
+ strata_python-0.2.8.dist-info/METADATA,sha256=2PGi5Y3ToKWuYgyURHJju0dGXAMOXhjTEIa7w2V2v_Q,38215
52
+ strata_python-0.2.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
53
+ strata_python-0.2.8.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
54
+ strata_python-0.2.8.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
55
+ strata_python-0.2.8.dist-info/RECORD,,