strata-python 0.2.6__tar.gz → 0.2.7__tar.gz
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-0.2.6 → strata_python-0.2.7}/CHANGELOG.md +11 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/PKG-INFO +4 -1
- {strata_python-0.2.6 → strata_python-0.2.7}/README.md +3 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/pyproject.toml +1 -1
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/contracts.py +13 -11
- strata_python-0.2.7/src/strata_python/mediatime.py +232 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/web.py +40 -6
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_contracts.py +36 -0
- strata_python-0.2.7/tests/unit/test_mediatime.py +124 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_web.py +58 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/.gitignore +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/LICENSE +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/__init__.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/check.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/cli.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/client.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/clients/__init__.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/clients/models.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/__init__.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/__main__.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/_alembic/env.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/_alembic/script.py.mako +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/cli.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/config.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/engine.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/guard.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/migrations.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/models.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/project.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/pytest_plugin.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/scratch.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/settings.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/testing.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/testserver.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/db/web.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/files.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/http.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/http_server.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/images.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/live.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/media.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/oslib.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/pages/__init__.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/pages/model.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/pages/render.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/public_check.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/py.typed +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/pytest_plugin.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/settings.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/stats.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/__init__.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/child.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/flight.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/progress.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/queue.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/retry.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/status.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/tasks/ticker.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/src/strata_python/testing.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/conftest.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/integration/test_db_cli.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/integration/test_serve.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/integration/test_strata_check.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/job_handlers.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_check.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_cli.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_client.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_clients_models.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_db.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_files.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_http.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_http_server.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_images.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_live.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_media.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_oslib.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_package.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_pages.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_plugin.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_public_check.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_queue.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_settings.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_stats.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_tasks.py +0 -0
- {strata_python-0.2.6 → strata_python-0.2.7}/tests/unit/test_testing.py +0 -0
|
@@ -4,6 +4,17 @@ What each release adds or changes for an app that depends on strata-python, newe
|
|
|
4
4
|
|
|
5
5
|
## Unreleased
|
|
6
6
|
|
|
7
|
+
## 0.2.7 (2026-11-23)
|
|
8
|
+
|
|
9
|
+
### Added
|
|
10
|
+
|
|
11
|
+
- `strata_python.mediatime`: exact time for media. `rational(...)` (seconds as a `Fraction` from an int, "p/q" or decimal text, a Decimal, or a float by its shortest repr), `Rate` (`parse("30000/1001")`, `frame_at`, `time_of`, `snap`), `Span` (half-open `[start, end)`: `duration`, `in`, `&`, `overlaps` (an empty span overlaps nothing), `shift`, `frames(rate)`), `Piece` and `TimeMap` (an edit's output time to its sources and back: `sequence(ranges)`, `to_source(t)`, `to_output(source, t)`), all with exact JSON (`text`, `to_json`, `from_json`).
|
|
12
|
+
- `web.add_system(..., extra_model=AppNumbers)` (or `extra` annotated `-> AppNumbers`, which may return the model): the route's response is `<App>SystemInfo`, `SystemInfo` plus the app's fields, so they are in `/api/openapi.json` and the generated types (#46). Replace the hand-written `Schema<'SystemInfo'> & {...}` with `Schema<'<App>SystemInfo'>`. Without a model, `extra` works as before.
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
|
|
16
|
+
- The response contracts (`Page`, `Health`, `SystemInfo`, `Folder`, `ServiceStatus`, `ErrorBody`, `Task`, `Progress`) are built on `ApiModel`, so a field with a default is required in the response schema: `Page.next` is `string | null` in the generated types, not `next?` (#45). Drop the app's `page.next ?? null` and similar fill-ins. An app that takes one of them as a request body gets `-Input` and `-Output` schemas for it.
|
|
17
|
+
|
|
7
18
|
## 0.2.6 (2026-11-23)
|
|
8
19
|
|
|
9
20
|
### Added
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.7
|
|
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,6 +61,7 @@ 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
67
|
| `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 |
|
|
@@ -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.
|
|
@@ -14,6 +14,7 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
14
14
|
| `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)`) |
|
|
15
15
|
| `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) |
|
|
16
16
|
| `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()` |
|
|
17
|
+
| `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 |
|
|
17
18
|
| `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` |
|
|
18
19
|
| `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` |
|
|
19
20
|
| `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 |
|
|
@@ -139,6 +140,8 @@ web.add_system(
|
|
|
139
140
|
) # GET /api/system, a SystemInfo
|
|
140
141
|
```
|
|
141
142
|
|
|
143
|
+
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.
|
|
144
|
+
|
|
142
145
|
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`.
|
|
143
146
|
|
|
144
147
|
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.
|
|
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "strata-python"
|
|
7
|
-
version = "0.2.
|
|
7
|
+
version = "0.2.7" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
|
|
8
8
|
description = "Common code for Python web server apps: OS helpers, settings, FastAPI serving, CLI commands, test fixtures and the strata-check gate"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -32,14 +32,16 @@ def utc(epoch: float | None) -> datetime.datetime | None:
|
|
|
32
32
|
|
|
33
33
|
|
|
34
34
|
class ApiModel(BaseModel):
|
|
35
|
-
"""
|
|
36
|
-
the generated TypeScript gets a `?` though the server always sends it; this config makes the
|
|
37
|
-
say what is sent. Use it for responses: a request
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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(
|
|
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))
|
|
@@ -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
|
-
|
|
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
|
|
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
|
-
**(
|
|
269
|
+
**own(),
|
|
236
270
|
)
|
|
237
271
|
|
|
238
272
|
|
|
@@ -59,3 +59,39 @@ def test_api_model_makes_defaulted_fields_required_in_the_response_schema():
|
|
|
59
59
|
assert "required" not in Plain.model_json_schema(mode="serialization")
|
|
60
60
|
assert Exact.model_json_schema(mode="serialization")["required"] == ["n"]
|
|
61
61
|
assert Exact().n == 0 # still optional to construct
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@pytest.mark.parametrize(
|
|
65
|
+
("model", "fields"),
|
|
66
|
+
[
|
|
67
|
+
(c.Page[int], {"items", "next", "total"}),
|
|
68
|
+
(c.Health, {"ok", "version", "commit"}),
|
|
69
|
+
(c.SystemInfo, {"version", "commit", "python", "platform", "started_at", "folders", "services"}),
|
|
70
|
+
(c.Folder, {"name", "path", "exists", "free_bytes", "total_bytes"}),
|
|
71
|
+
(c.ServiceStatus, {"name", "url", "ok", "version", "detail"}),
|
|
72
|
+
(c.ErrorBody, {"detail", "payload"}),
|
|
73
|
+
(c.Progress, {"done", "total", "text", "stage", "at"}),
|
|
74
|
+
],
|
|
75
|
+
)
|
|
76
|
+
def test_shared_responses_list_every_field_they_send_as_required(model, fields):
|
|
77
|
+
"""Issue #45: `Page.next` came out `next?: string | null` in the web app's types though it is always sent."""
|
|
78
|
+
assert set(model.model_json_schema(mode="serialization")["required"]) == fields
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def test_shared_responses_in_the_served_schema(live_app):
|
|
82
|
+
import json
|
|
83
|
+
import urllib.request
|
|
84
|
+
|
|
85
|
+
from fastapi import FastAPI
|
|
86
|
+
|
|
87
|
+
app = FastAPI()
|
|
88
|
+
|
|
89
|
+
@app.get("/page", response_model=c.Page[c.Task])
|
|
90
|
+
def page() -> c.Page[c.Task]:
|
|
91
|
+
return c.Page(items=[])
|
|
92
|
+
|
|
93
|
+
with live_app(app) as base, urllib.request.urlopen(base + "/openapi.json") as r:
|
|
94
|
+
schemas = json.load(r)["components"]["schemas"]
|
|
95
|
+
assert "next" in schemas["Page_Task_"]["required"]
|
|
96
|
+
assert {"error", "progress", "attempts"} <= set(schemas["Task"]["required"])
|
|
97
|
+
assert c.Health(ok=True, version="1", gpu="x").model_dump()["gpu"] == "x" # extra fields still allowed
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
"""strata_python.mediatime: rational time, frame rates, half-open spans and the output-to-source map, with round trips over many random
|
|
2
|
+
edits (a fixed seed, so a failure repeats)."""
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import random
|
|
6
|
+
from decimal import Decimal
|
|
7
|
+
from fractions import Fraction as F
|
|
8
|
+
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from strata_python.mediatime import Piece, Rate, Span, TimeMap, rational, text
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def test_rational_is_exact_and_refuses_what_is_not_a_number():
|
|
15
|
+
assert rational("1001/30000") == F(1001, 30000)
|
|
16
|
+
assert rational("12.04") == F(301, 25)
|
|
17
|
+
assert rational(Decimal("0.1")) == F(1, 10)
|
|
18
|
+
assert rational(0.1) == F(1, 10) # the float's shortest repr, not its binary expansion
|
|
19
|
+
assert rational(3) == 3
|
|
20
|
+
assert rational(F(1, 3)) == F(1, 3)
|
|
21
|
+
for bad in ("soon", "1/0", float("nan"), float("inf"), True, None):
|
|
22
|
+
with pytest.raises(ValueError, match="not a"):
|
|
23
|
+
rational(bad) # pyright: ignore[reportArgumentType]
|
|
24
|
+
assert text(F(1001, 30000)) == "1001/30000"
|
|
25
|
+
assert text(F(3)) == "3"
|
|
26
|
+
assert rational(text(F(7, 3))) == F(7, 3)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def test_frames_of_pal_and_ntsc():
|
|
30
|
+
pal, ntsc = Rate.parse("25/1"), Rate.parse("30000/1001")
|
|
31
|
+
assert pal.frame_s == F(1, 25)
|
|
32
|
+
assert str(ntsc) == "30000/1001"
|
|
33
|
+
assert Rate.parse(29.97).fps == F(2997, 100)
|
|
34
|
+
assert pal.frame_at(F(2)) == 50 # a time on a frame's start is that frame
|
|
35
|
+
assert pal.frame_at(F(2) - F(1, 1000)) == 49
|
|
36
|
+
assert ntsc.time_of(30000) == 1001
|
|
37
|
+
assert ntsc.frame_at(ntsc.time_of(123456)) == 123456
|
|
38
|
+
assert pal.snap(F(1, 50)) == 0 # halfway goes to the earlier frame
|
|
39
|
+
assert pal.snap(F(1, 50) + F(1, 10**6)) == F(1, 25)
|
|
40
|
+
with pytest.raises(ValueError, match="above 0"):
|
|
41
|
+
Rate.parse(0)
|
|
42
|
+
# the float way drifts: adding 0.04 a thousand times is not 40.0, and int() of it lands a frame early; the rational way does not
|
|
43
|
+
t, exact = 0.0, F(0)
|
|
44
|
+
for _ in range(1000):
|
|
45
|
+
t += 0.04
|
|
46
|
+
exact += pal.frame_s
|
|
47
|
+
assert int(t * 25) == 999
|
|
48
|
+
assert pal.frame_at(exact) == 1000
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_spans_are_half_open():
|
|
52
|
+
a, b = Span.of(2, 5), Span.of(5, 7)
|
|
53
|
+
assert a.duration == 3
|
|
54
|
+
assert 2 in a
|
|
55
|
+
assert 5 not in a
|
|
56
|
+
assert F(9, 2) in a
|
|
57
|
+
assert "3" not in a
|
|
58
|
+
assert not a.overlaps(b)
|
|
59
|
+
assert a.overlaps(Span.of(4, 9))
|
|
60
|
+
assert not a.overlaps(Span.of(3, 3)) # an empty span holds no time, even inside another
|
|
61
|
+
assert (a & b) is None
|
|
62
|
+
assert (a & Span.of(4, 9)) == Span.of(4, 5)
|
|
63
|
+
assert a.shift(F(1)) == Span.of(3, 6)
|
|
64
|
+
assert a.to_json() == ["2", "5"]
|
|
65
|
+
assert Span.from_json(a.to_json()) == a
|
|
66
|
+
# frame 0 started before the span: not kept
|
|
67
|
+
assert list(Span.of("1/50", 1).frames(Rate.parse(25))) == list(range(1, 25))
|
|
68
|
+
with pytest.raises(ValueError, match="end before it starts"):
|
|
69
|
+
Span.of(5, 2)
|
|
70
|
+
with pytest.raises(ValueError, match=r"\[start, end\]"):
|
|
71
|
+
Span.from_json(["1"])
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def test_a_cut_list_maps_both_ways():
|
|
75
|
+
m = TimeMap.sequence([("tape1", Span.of(10, 12)), ("tape2", Span.of(0, 1)), ("tape1", Span.of(11, 13))])
|
|
76
|
+
assert m.duration == 5
|
|
77
|
+
assert [p.at for p in m.pieces] == [0, 2, 3]
|
|
78
|
+
assert m.to_source(F(0)) == ("tape1", 10)
|
|
79
|
+
assert m.to_source(F(2)) == ("tape2", 0)
|
|
80
|
+
assert m.to_source(F(5)) is None
|
|
81
|
+
assert m.to_output("tape1", F(23, 2)) == [F(3, 2), F(7, 2)] # 11.5 s of tape1 is used twice
|
|
82
|
+
assert m.to_output("tape2", F(5)) == []
|
|
83
|
+
assert TimeMap().duration == 0
|
|
84
|
+
assert TimeMap().to_source(F(0)) is None
|
|
85
|
+
assert TimeMap.from_json(json.loads(json.dumps(m.to_json()))) == m
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def test_speed_gaps_and_refusals():
|
|
89
|
+
fast = Piece("t", Span.of(0, 4), F(10), F(2))
|
|
90
|
+
m = TimeMap((fast, Piece("t", Span.of(20, 21), F(0))))
|
|
91
|
+
assert fast.out == Span.of(10, 12)
|
|
92
|
+
assert m.pieces[0].at == 0 # sorted by output time
|
|
93
|
+
assert m.to_source(F(11)) == ("t", 2)
|
|
94
|
+
assert m.to_source(F(5)) is None # a gap
|
|
95
|
+
assert m.to_output("t", F(3)) == [F(23, 2)]
|
|
96
|
+
assert fast.to_json()["speed"] == "2"
|
|
97
|
+
assert "speed" not in m.pieces[0].to_json()
|
|
98
|
+
assert TimeMap.from_json(m.to_json()) == m
|
|
99
|
+
with pytest.raises(ValueError, match="overlap"):
|
|
100
|
+
TimeMap((Piece("a", Span.of(0, 2), F(0)), Piece("b", Span.of(0, 2), F(1))))
|
|
101
|
+
with pytest.raises(ValueError, match="speed"):
|
|
102
|
+
Piece("a", Span.of(0, 1), F(0), F(0))
|
|
103
|
+
with pytest.raises(ValueError, match="plays nothing"):
|
|
104
|
+
Piece("a", Span.of(1, 1), F(0))
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def test_round_trips_on_random_edits_are_exact():
|
|
108
|
+
rng = random.Random(20261123) # noqa: S311 (a repeatable sample of edits, not a secret)
|
|
109
|
+
rates = [Rate.parse(r) for r in ("25", "50", "30000/1001", "24000/1001", "60")]
|
|
110
|
+
for _ in range(300):
|
|
111
|
+
rate = rng.choice(rates)
|
|
112
|
+
ranges: list[tuple[str, Span]] = []
|
|
113
|
+
for _ in range(rng.randint(1, 8)):
|
|
114
|
+
a = rate.time_of(rng.randint(0, 100_000))
|
|
115
|
+
ranges.append((rng.choice("xyz"), Span(a, a + rate.time_of(rng.randint(1, 500)))))
|
|
116
|
+
m = TimeMap.sequence(ranges, start=rate.time_of(rng.randint(0, 50)))
|
|
117
|
+
for _ in range(20):
|
|
118
|
+
t = rate.time_of(rng.randint(rate.frame_at(m.pieces[0].at), rate.frame_at(m.duration) - 1))
|
|
119
|
+
src = m.to_source(t)
|
|
120
|
+
assert src is not None
|
|
121
|
+
# output -> source -> output lands on the same output time, exactly; a frame start maps to a frame start
|
|
122
|
+
assert t in m.to_output(*src)
|
|
123
|
+
assert src[1] == rate.time_of(rate.frame_at(src[1]))
|
|
124
|
+
assert m.duration == m.pieces[0].at + sum((s.duration for _, s in ranges), F(0))
|
|
@@ -316,3 +316,61 @@ def test_a_setting_with_choices_is_an_enum_and_numbers_are_numbers(live_app, iso
|
|
|
316
316
|
assert (status, json.loads(text)["workers"], json.loads(text)["memory"]) == (200, 4, 8.5)
|
|
317
317
|
assert typed.get("workers") == "4"
|
|
318
318
|
assert put(base + "/api/settings", {"workers": 40})[0] == 400
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def test_system_extra_fields_are_in_the_schema(live_app):
|
|
322
|
+
"""Issue #46: the app's own /api/system fields are described, so its web type needs nothing written by hand."""
|
|
323
|
+
from strata_python.contracts import ApiModel
|
|
324
|
+
|
|
325
|
+
class AppNumbers(ApiModel):
|
|
326
|
+
greetings: int
|
|
327
|
+
home_bytes: int | None = None
|
|
328
|
+
|
|
329
|
+
def numbers() -> AppNumbers:
|
|
330
|
+
return AppNumbers(greetings=3)
|
|
331
|
+
|
|
332
|
+
inferred = web.base_app("python-app", "1")
|
|
333
|
+
web.add_system(inferred, "1", extra=numbers)
|
|
334
|
+
named = web.base_app("python-app", "1")
|
|
335
|
+
web.add_system(named, "1", extra=lambda: {"greetings": 4}, extra_model=AppNumbers)
|
|
336
|
+
plain = web.base_app("demo", "1")
|
|
337
|
+
web.add_system(plain, "1", extra=lambda: {"queued": 2}) # a mapping and no model: sent, not described
|
|
338
|
+
for app, greetings in ((inferred, 3), (named, 4)):
|
|
339
|
+
with live_app(app) as base:
|
|
340
|
+
with urllib.request.urlopen(base + "/api/openapi.json") as r:
|
|
341
|
+
schemas = json.load(r)["components"]["schemas"]
|
|
342
|
+
info = json.loads(get(base + "/api/system")[1])
|
|
343
|
+
shape = schemas["PythonAppSystemInfo"]
|
|
344
|
+
assert {"greetings", "home_bytes", "version", "folders"} <= set(shape["required"])
|
|
345
|
+
assert shape["properties"]["greetings"]["type"] == "integer"
|
|
346
|
+
assert (info["greetings"], info["home_bytes"]) == (greetings, None)
|
|
347
|
+
with live_app(plain) as base:
|
|
348
|
+
with urllib.request.urlopen(base + "/api/openapi.json") as r:
|
|
349
|
+
schemas = json.load(r)["components"]["schemas"]
|
|
350
|
+
assert "queued" not in schemas["SystemInfo"]["properties"]
|
|
351
|
+
assert json.loads(get(base + "/api/system")[1])["queued"] == 2
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def test_an_unresolvable_return_annotation_means_no_model():
|
|
355
|
+
def broken() -> "NoSuchType": # noqa: F821
|
|
356
|
+
return {}
|
|
357
|
+
|
|
358
|
+
assert web._returned_model(broken) is None
|
|
359
|
+
assert web._returned_model(None) is None
|
|
360
|
+
|
|
361
|
+
|
|
362
|
+
def test_system_extra_model_with_an_alias(live_app):
|
|
363
|
+
from pydantic import Field
|
|
364
|
+
|
|
365
|
+
from strata_python.contracts import ApiModel
|
|
366
|
+
|
|
367
|
+
class Queue(ApiModel):
|
|
368
|
+
queued: int = Field(alias="queueLength")
|
|
369
|
+
|
|
370
|
+
def queue() -> Queue:
|
|
371
|
+
return Queue(queueLength=3)
|
|
372
|
+
|
|
373
|
+
app = web.base_app("demo", "1")
|
|
374
|
+
web.add_system(app, "1", extra=queue)
|
|
375
|
+
with live_app(app) as base:
|
|
376
|
+
assert json.loads(get(base + "/api/system")[1])["queueLength"] == 3
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|