strata-python 0.2.7__tar.gz → 0.2.9__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.
Files changed (87) hide show
  1. {strata_python-0.2.7 → strata_python-0.2.9}/CHANGELOG.md +10 -0
  2. {strata_python-0.2.7 → strata_python-0.2.9}/PKG-INFO +5 -3
  3. {strata_python-0.2.7 → strata_python-0.2.9}/README.md +4 -2
  4. {strata_python-0.2.7 → strata_python-0.2.9}/pyproject.toml +1 -1
  5. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/clients/models.py +54 -0
  6. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/testing.py +69 -4
  7. strata_python-0.2.9/src/strata_python/wav.py +91 -0
  8. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_clients_models.py +29 -0
  9. strata_python-0.2.9/tests/unit/test_wav.py +92 -0
  10. {strata_python-0.2.7 → strata_python-0.2.9}/.gitignore +0 -0
  11. {strata_python-0.2.7 → strata_python-0.2.9}/LICENSE +0 -0
  12. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/__init__.py +0 -0
  13. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/check.py +0 -0
  14. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/cli.py +0 -0
  15. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/client.py +0 -0
  16. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/clients/__init__.py +0 -0
  17. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/contracts.py +0 -0
  18. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/__init__.py +0 -0
  19. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/__main__.py +0 -0
  20. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/_alembic/env.py +0 -0
  21. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/_alembic/script.py.mako +0 -0
  22. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/cli.py +0 -0
  23. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/config.py +0 -0
  24. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/engine.py +0 -0
  25. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/guard.py +0 -0
  26. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/migrations.py +0 -0
  27. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/models.py +0 -0
  28. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/project.py +0 -0
  29. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/pytest_plugin.py +0 -0
  30. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/scratch.py +0 -0
  31. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/settings.py +0 -0
  32. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/testing.py +0 -0
  33. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/testserver.py +0 -0
  34. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/db/web.py +0 -0
  35. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/files.py +0 -0
  36. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/http.py +0 -0
  37. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/http_server.py +0 -0
  38. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/images.py +0 -0
  39. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/live.py +0 -0
  40. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/media.py +0 -0
  41. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/mediatime.py +0 -0
  42. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/oslib.py +0 -0
  43. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/pages/__init__.py +0 -0
  44. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/pages/model.py +0 -0
  45. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/pages/render.py +0 -0
  46. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/public_check.py +0 -0
  47. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/py.typed +0 -0
  48. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/pytest_plugin.py +0 -0
  49. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/settings.py +0 -0
  50. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/stats.py +0 -0
  51. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/__init__.py +0 -0
  52. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/child.py +0 -0
  53. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/flight.py +0 -0
  54. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/progress.py +0 -0
  55. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/queue.py +0 -0
  56. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/retry.py +0 -0
  57. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/status.py +0 -0
  58. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/tasks/ticker.py +0 -0
  59. {strata_python-0.2.7 → strata_python-0.2.9}/src/strata_python/web.py +0 -0
  60. {strata_python-0.2.7 → strata_python-0.2.9}/tests/conftest.py +0 -0
  61. {strata_python-0.2.7 → strata_python-0.2.9}/tests/integration/test_db_cli.py +0 -0
  62. {strata_python-0.2.7 → strata_python-0.2.9}/tests/integration/test_serve.py +0 -0
  63. {strata_python-0.2.7 → strata_python-0.2.9}/tests/integration/test_strata_check.py +0 -0
  64. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/job_handlers.py +0 -0
  65. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_check.py +0 -0
  66. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_cli.py +0 -0
  67. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_client.py +0 -0
  68. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_contracts.py +0 -0
  69. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_db.py +0 -0
  70. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_files.py +0 -0
  71. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_http.py +0 -0
  72. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_http_server.py +0 -0
  73. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_images.py +0 -0
  74. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_live.py +0 -0
  75. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_media.py +0 -0
  76. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_mediatime.py +0 -0
  77. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_oslib.py +0 -0
  78. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_package.py +0 -0
  79. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_pages.py +0 -0
  80. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_plugin.py +0 -0
  81. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_public_check.py +0 -0
  82. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_queue.py +0 -0
  83. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_settings.py +0 -0
  84. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_stats.py +0 -0
  85. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_tasks.py +0 -0
  86. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_testing.py +0 -0
  87. {strata_python-0.2.7 → strata_python-0.2.9}/tests/unit/test_web.py +0 -0
@@ -4,6 +4,16 @@ 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.9 (2026-11-23)
8
+
9
+ ## 0.2.8 (2026-11-23)
10
+
11
+ ### Added
12
+
13
+ - `strata_python.wav`: `read_wav(data_or_path, *, channels=1, widths=(2, 3), min_rate=16_000, min_seconds=0.0, max_seconds=None)` returns a `WavInfo` (`sample_rate`, `sample_width`, `channels`, `frames`, `seconds`) or raises `WavError` (a `ValueError`, answered as a 400) with a sentence, for an app that takes recorded speech (strata-react's `useRecorder` uploads). Replace the app's own `wave` header check.
14
+ - `strata_python.testing.sine_wav(seconds, *, rate, width, channels, hz, amplitude)`: real PCM WAV bytes for an app's upload tests.
15
+ - `clients.models.run_with_provenance(...)` returns `(result, Provenance)`: the job's `model`, the load `options` it ran with, its `settings_hash` and `job_id`; `Provenance.from_job(row)` reads the same from any job row. `clients.models.role_settings(role)` returns `RoleSettings(model, settings_hash)`. Key a result cache on `(model, settings_hash)` so it is made again when strata-models changes a model's options under the same key (strata-models #103; the hash and options are None from a service older than that). `FakeModels.options[role]` sets the stand-in's load options, and its jobs and registry carry the same fields.
16
+
7
17
  ## 0.2.7 (2026-11-23)
8
18
 
9
19
  ### Added
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.7
3
+ Version: 0.2.9
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
@@ -62,12 +62,13 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
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
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 |
65
+ | `strata_python.wav` | `read_wav(data_or_path, max_seconds=...)` checks an uploaded PCM WAV's header with the standard library (mono, 16 or 24-bit, 16 kHz and up by default; `channels`, `widths`, `min_rate`, `min_seconds` change it) and returns a `WavInfo`; anything else is a `WavError` (a `ValueError`, so a 400) with a sentence. strata-react's `useRecorder` writes what it accepts |
65
66
  | `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` |
66
67
  | `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` |
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 |
68
+ | `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 |
68
69
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
69
70
  | 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` |
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)` |
71
+ | `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=...)`, `assert_openapi_current(create_app, path)`, and `sine_wav(seconds, rate=, width=, channels=, amplitude=)` (real WAV bytes for upload tests) |
71
72
  | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
72
73
  | `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
73
74
  | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
@@ -406,6 +407,7 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
406
407
 
407
408
  add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
408
409
 
410
+
409
411
  @app.get("/api/notes")
410
412
  def notes(db: DbSession) -> list[NoteOut]: ...
411
413
  ```
@@ -15,12 +15,13 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
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
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 |
18
+ | `strata_python.wav` | `read_wav(data_or_path, max_seconds=...)` checks an uploaded PCM WAV's header with the standard library (mono, 16 or 24-bit, 16 kHz and up by default; `channels`, `widths`, `min_rate`, `min_seconds` change it) and returns a `WavInfo`; anything else is a `WavError` (a `ValueError`, so a 400) with a sentence. strata-react's `useRecorder` writes what it accepts |
18
19
  | `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` |
19
20
  | `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` |
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 |
21
+ | `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 |
21
22
  | `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
22
23
  | 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` |
23
- | `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)` |
24
+ | `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=...)`, `assert_openapi_current(create_app, path)`, and `sine_wav(seconds, rate=, width=, channels=, amplitude=)` (real WAV bytes for upload tests) |
24
25
  | `strata_python.db` (extra `[db]`) | The shared database: `connect("myapp")` (the app's schema of one shared Postgres, or a SQLite path), a declarative base with the shared `NAMING_CONVENTION` for typed models, Alembic migrations with no per-app `env.py`, the live-database guard, the `strata-db` command, the `db_*` fixtures (SQLite by default, a throwaway Postgres with `--pg`), and `strata_python.db.web` (`add_database`, `DbSession`) for a server's records |
25
26
  | `strata_python.pages` (extra `[pdf]`) | A scanned page described as blocks, lines, styled spans and figures in scan pixels, drawn as a PDF with real embedded fonts (`render`), and read back as pixels at the scan's dpi (`rasterise`) and as text (`read_text`): for rebuilding scanned books, and for scoring a rebuild with the renderer that prints it |
26
27
  | `strata-check` | The one gate: lockfile, ruff, `ruff format`, pyright strict, ty, unit tests with coverage |
@@ -359,6 +360,7 @@ migrations = "migrations" # the app's Alembic revisions, unchanged
359
360
 
360
361
  add_database(app, Project.load(__file__), default=lambda: local_url(SETTINGS))
361
362
 
363
+
362
364
  @app.get("/api/notes")
363
365
  def notes(db: DbSession) -> list[NoteOut]: ...
364
366
  ```
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "strata-python"
7
- version = "0.2.7" # the single source of truth: `strata_python.__version__` reads it back with importlib.metadata
7
+ version = "0.2.9" # 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"
@@ -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
 
@@ -16,6 +16,7 @@ Testing policy).
16
16
  Sleeper `time.sleep` that returns at once and records `.delays`
17
17
  run_cli an argparse `main(argv)` in this process -> CliResult; run_module the same as a real `python -m`
18
18
  assert_openapi_current the committed schema file equals what the app answers now (cli.add_openapi writes it)
19
+ sine_wav a short PCM WAV of a tone (or silence), for an app's upload and `wav.read_wav` tests
19
20
  FakeModels a stand-in strata-models service (jobs, leases, registry) for `strata_python.clients.models`; served
20
21
  by the `fake_models` fixture. MODELS_RESULTS holds one reply per role in the service's shapes.
21
22
  """
@@ -25,16 +26,19 @@ from __future__ import annotations
25
26
  import contextlib
26
27
  import io
27
28
  import json
29
+ import math
28
30
  import os
31
+ import struct
29
32
  import subprocess
30
33
  import sys
31
34
  import urllib.error
32
35
  import urllib.request
36
+ import wave
33
37
  from collections.abc import Callable, Mapping, Sequence
34
38
  from dataclasses import dataclass, field
35
39
  from email.message import Message
36
40
  from pathlib import Path
37
- from typing import Any, ClassVar
41
+ from typing import Any, ClassVar, cast
38
42
 
39
43
  Body = bytes | str | Any # bytes and str are sent as they are; anything else as JSON
40
44
 
@@ -328,13 +332,17 @@ class FakeModels:
328
332
 
329
333
  `running_polls` is how many polls a job answers `running` before it finishes (default 1, as the real service
330
334
  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)."""
335
+ it does not know. The registry answers each role's model from `.models` (role -> model name). A job records the
336
+ settings it ran with when it starts, as the service does: `options` (`.options[role]`, the role's load options,
337
+ merged with the job's own) and `settings_hash` (a hash of the model and those options, also on the registry's roles),
338
+ so changing `.options` mid-test shows what an app's cache does when the service's settings change."""
332
339
 
333
340
  def __init__(self, results: Mapping[str, Result] | None = None, *, running_polls: int = 1) -> None:
334
341
  from fastapi import FastAPI, HTTPException, Request # here, so importing the fakes does not load FastAPI
335
342
 
336
343
  self.results: dict[str, Result] = dict(MODELS_RESULTS if results is None else results)
337
344
  self.models: dict[str, str] = {}
345
+ self.options: dict[str, Json] = {} # role -> the model's load options (the service's models.toml)
338
346
  self.running_polls = running_polls
339
347
  self.jobs: list[Json] = [] # every job submitted, in order, as the service stored it
340
348
  self.leases: list[Json] = []
@@ -345,6 +353,7 @@ class FakeModels:
345
353
  self.down = False
346
354
  self._failures: list[tuple[str | None, str]] = []
347
355
  self._polls: dict[int, int] = {}
356
+ self._asked: dict[int, Json] = {} # job id -> the load options its submit asked for
348
357
  app = FastAPI()
349
358
  self.app = app
350
359
 
@@ -362,14 +371,25 @@ class FakeModels:
362
371
 
363
372
  @app.get("/api/registry")
364
373
  def registry() -> Json: # pyright: ignore[reportUnusedFunction]
365
- return {"roles": [{"key": r, "model": self.models.get(r, f"fake-{r}")} for r in self.results]}
374
+ return {
375
+ "roles": [{"key": r, "model": self._model(r), "settings_hash": self._hash(r)} for r in self.results]
376
+ }
366
377
 
367
378
  @app.post("/api/jobs")
368
379
  def submit(body: Json) -> Json: # pyright: ignore[reportUnusedFunction]
369
380
  role = str(body.get("role"))
370
381
  if role not in self.results:
371
382
  raise HTTPException(422, f"unknown role {role!r}")
372
- job: Json = {**body, "id": len(self.jobs) + 1, "status": "queued", "result": None, "error": None}
383
+ job: Json = {
384
+ **body,
385
+ "id": len(self.jobs) + 1,
386
+ "status": "queued",
387
+ "result": None,
388
+ "error": None,
389
+ "options": None, # what it runs with, recorded when it starts; the variant asked for is kept apart
390
+ "settings_hash": None,
391
+ }
392
+ self._asked[job["id"]] = cast("Json", body.get("options") or {})
373
393
  self.jobs.append(job)
374
394
  return dict(job)
375
395
 
@@ -378,6 +398,8 @@ class FakeModels:
378
398
  job = self._job(job_id, HTTPException)
379
399
  if job["status"] in ("queued", "running"):
380
400
  n = self._polls[job_id] = self._polls.get(job_id, 0) + 1
401
+ if job["status"] == "queued":
402
+ self._start(job)
381
403
  if n <= self.running_polls:
382
404
  job["status"] = "running"
383
405
  else:
@@ -414,6 +436,24 @@ class FakeModels:
414
436
  self._failures.append((role, error))
415
437
  return self
416
438
 
439
+ def _model(self, role: str, model: object = None) -> str:
440
+ return str(model) if model else self.models.get(role, f"fake-{role}")
441
+
442
+ def _hash(self, role: str, model: object = None, asked: Json | None = None) -> str:
443
+ import hashlib
444
+
445
+ options = {**self.options.get(role, {}), **(asked or {})}
446
+ text = json.dumps([self._model(role, model), options], sort_keys=True, default=str)
447
+ return hashlib.sha256(text.encode()).hexdigest()[:12]
448
+
449
+ def _start(self, job: Json) -> None:
450
+ role, asked = str(job["role"]), self._asked.get(int(job["id"]), {})
451
+ job.update(
452
+ model=self._model(role, job.get("model")),
453
+ options={**self.options.get(role, {}), **asked},
454
+ settings_hash=self._hash(role, job.get("model"), asked),
455
+ )
456
+
417
457
  def _finish(self, job: Json) -> None:
418
458
  for i, (role, error) in enumerate(self._failures):
419
459
  if role is None or role == job["role"]:
@@ -432,3 +472,28 @@ class FakeModels:
432
472
  if not 1 <= lease_id <= len(self.leases):
433
473
  raise error(404, f"no lease {lease_id}")
434
474
  return self.leases[lease_id - 1]
475
+
476
+
477
+ def sine_wav(
478
+ seconds: float = 1.0,
479
+ *,
480
+ rate: int = 16_000,
481
+ width: int = 2,
482
+ channels: int = 1,
483
+ hz: float = 220.0,
484
+ amplitude: float = 0.3,
485
+ ) -> bytes:
486
+ """A PCM WAV of a tone at `amplitude` (0 to 1; 0 is silence): real bytes an app's upload tests send."""
487
+ full = (1 << (8 * width - 1)) - 1
488
+ frames = bytearray()
489
+ for i in range(round(seconds * rate)):
490
+ v = round(full * amplitude * math.sin(2 * math.pi * hz * i / rate))
491
+ sample = struct.pack("<i", v)[:width] if width > 1 else struct.pack("<B", v + 128)
492
+ frames += sample * channels
493
+ out = io.BytesIO()
494
+ with wave.open(out, "wb") as w:
495
+ w.setnchannels(channels)
496
+ w.setsampwidth(width)
497
+ w.setframerate(rate)
498
+ w.writeframes(bytes(frames))
499
+ return out.getvalue()
@@ -0,0 +1,91 @@
1
+ """A WAV upload checked before it is kept: the header read with the standard library, refused with a sentence.
2
+
3
+ An app that records in the browser (strata-react's `useRecorder` writes 16-bit PCM mono WAV) or takes WAV files in
4
+ gets raw bytes it must not trust: a truncated upload, a stereo file, 8-bit audio, a click of Record then Stop. Here:
5
+
6
+ info = read_wav(data, max_seconds=60) # WavInfo: sample_rate, sample_width, channels, frames, seconds
7
+ read_wav(path, channels=None, min_rate=8_000) # any channel count, telephone rate and up
8
+
9
+ `WavError` is a `ValueError`, so `web.add_error_handlers` answers it as a 400 with the sentence. Only the header and
10
+ the last frame are read (a path is opened, not loaded): `wave` takes the frame count from the data chunk's declared
11
+ size, so a truncated upload still claims its full length until the last frame is looked for. Nothing is decoded, so it
12
+ costs the same for an hour as for a second. 32-bit float WAV is refused by `wave` itself (it reads PCM only), which is why the widths default to the
13
+ two a voice is recorded in."""
14
+
15
+ from __future__ import annotations
16
+
17
+ import io
18
+ import os
19
+ import wave
20
+ from collections.abc import Collection
21
+ from dataclasses import dataclass
22
+ from pathlib import Path
23
+ from typing import BinaryIO
24
+
25
+ #: Below 16 kHz the higher formants and fricatives a voice model needs are gone.
26
+ SPEECH_RATE = 16_000
27
+
28
+
29
+ class WavError(ValueError):
30
+ """A WAV that cannot be kept; the message says why in words a person can act on."""
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class WavInfo:
35
+ sample_rate: int
36
+ #: Bytes per sample: 2 is 16-bit, 3 is 24-bit.
37
+ sample_width: int
38
+ channels: int
39
+ frames: int
40
+
41
+ @property
42
+ def seconds(self) -> float:
43
+ return self.frames / self.sample_rate
44
+
45
+
46
+ def read_wav(
47
+ source: bytes | str | os.PathLike[str],
48
+ *,
49
+ channels: int | None = 1,
50
+ widths: Collection[int] = (2, 3),
51
+ min_rate: int = SPEECH_RATE,
52
+ min_seconds: float = 0.0,
53
+ max_seconds: float | None = None,
54
+ ) -> WavInfo:
55
+ """The header of a PCM WAV (bytes or a path), or `WavError` when it is not one the app keeps.
56
+
57
+ `channels=None` takes any count; `widths` are bytes per sample; `min_seconds`/`max_seconds` bound the length."""
58
+ with io.BytesIO(source) if isinstance(source, bytes) else Path(source).open("rb") as f:
59
+ found = _header(f)
60
+ if channels is not None and found.channels != channels:
61
+ want = "a mono" if channels == 1 else f"a {channels}-channel"
62
+ raise WavError(f"Send {want} recording; this one has {found.channels} channels.")
63
+ if found.sample_width not in widths:
64
+ allowed = " or ".join(f"{w * 8}-bit" for w in sorted(widths))
65
+ raise WavError(f"Send {allowed} samples; this recording has {found.sample_width * 8}-bit.")
66
+ if found.sample_rate < min_rate:
67
+ raise WavError(f"Record at {min_rate} Hz or more; this recording is {found.sample_rate} Hz.")
68
+ if found.seconds < min_seconds:
69
+ raise WavError(f"The recording is {found.seconds:.1f} seconds long; the shortest kept is {min_seconds:g}.")
70
+ if max_seconds is not None and found.seconds > max_seconds:
71
+ raise WavError(f"The recording is {found.seconds:.0f} seconds long; the longest kept is {max_seconds:g}.")
72
+ return found
73
+
74
+
75
+ def _header(f: BinaryIO) -> WavInfo:
76
+ if not f.read(1):
77
+ raise WavError("The recording is empty: nothing was recorded.")
78
+ f.seek(0)
79
+ try:
80
+ with wave.open(f, "rb") as w:
81
+ found = WavInfo(w.getframerate(), w.getsampwidth(), w.getnchannels(), w.getnframes())
82
+ if found.frames:
83
+ w.setpos(found.frames - 1)
84
+ complete = len(w.readframes(1)) == found.sample_width * found.channels
85
+ else:
86
+ complete = True
87
+ except (wave.Error, EOFError, RuntimeError) as e: # RuntimeError: a chunk that claims more bytes than follow
88
+ raise WavError(f"The recording is not a WAV file that can be read ({str(e) or 'it ends early'}).") from None
89
+ if not complete:
90
+ raise WavError("The recording ends early: its header promises more sound than the file holds.")
91
+ return found
@@ -186,3 +186,32 @@ def test_the_other_typed_results():
186
186
  assert (v.fps, v.frames, v.crops[0].box, v.crops[0].stills, v.quality["skipped"]) == (
187
187
  50.0, 400, (100, 50, 80, 80), ["/out/v-face-3.png"], "no numpy",
188
188
  ) # fmt: skip
189
+
190
+
191
+ def test_a_result_with_what_made_it_and_the_settings_a_cache_keys_on(service):
192
+ service.models["shot-boundaries"] = "scene-score"
193
+ service.results["shot-boundaries"] = {"cuts": []}
194
+ service.options["shot-boundaries"] = {"threshold": 0.3}
195
+ now = sm.role_settings("shot-boundaries")
196
+ assert now is not None
197
+ assert (now.model, len(now.settings_hash or "")) == ("scene-score", 12)
198
+ result, p = sm.run_with_provenance("shot-boundaries", {"path": "/v.mp4"}, app="strata-reels")
199
+ assert result == {"cuts": []}
200
+ assert p == sm.Provenance("scene-score", {"threshold": 0.3}, now.settings_hash, p.job_id)
201
+ assert service.jobs[p.job_id - 1]["settings_hash"] == now.settings_hash
202
+ service.options["shot-boundaries"] = {"threshold": 0.4} # the service's models.toml changed, the key did not
203
+ later = sm.role_settings("shot-boundaries")
204
+ assert later is not None
205
+ assert later.model == now.model
206
+ assert later.settings_hash != now.settings_hash
207
+ _, q = sm.run_with_provenance("shot-boundaries", {"path": "/v.mp4"}, app="strata-reels")
208
+ assert (q.options, q.settings_hash) == ({"threshold": 0.4}, later.settings_hash)
209
+ job = sm.submit("shot-boundaries", {}, app="evals", options={"width": 320})
210
+ assert (job["options"], job["settings_hash"]) == (None, None) # recorded when it starts
211
+ assert sm.Provenance.from_job(sm.wait_job(job["id"])).options == {"threshold": 0.4, "width": 320}
212
+ assert sm.role_settings("nope") is None
213
+
214
+
215
+ def test_provenance_from_a_row_of_an_older_service():
216
+ p = sm.Provenance.from_job({"id": 7, "model": "buffalo_l", "status": "done"})
217
+ assert p == sm.Provenance("buffalo_l", None, None, 7)
@@ -0,0 +1,92 @@
1
+ import io
2
+ import re
3
+ import wave
4
+ from pathlib import Path
5
+
6
+ import pytest
7
+
8
+ from strata_python.testing import sine_wav
9
+ from strata_python.wav import SPEECH_RATE, WavError, WavInfo, read_wav
10
+
11
+
12
+ def test_reads_a_mono_16_bit_wav() -> None:
13
+ info = read_wav(sine_wav(1.5, rate=48_000))
14
+ assert info == WavInfo(sample_rate=48_000, sample_width=2, channels=1, frames=72_000)
15
+ assert info.seconds == 1.5
16
+
17
+
18
+ def test_reads_a_path_and_24_bit(tmp_path: Path) -> None:
19
+ path = tmp_path / "take.wav"
20
+ path.write_bytes(sine_wav(0.5, width=3))
21
+ assert read_wav(path).sample_width == 3
22
+ assert read_wav(str(path)).frames == SPEECH_RATE // 2
23
+
24
+
25
+ def test_the_tone_is_at_its_amplitude() -> None:
26
+ with wave.open(io.BytesIO(sine_wav(0.1, amplitude=0.5, width=2)), "rb") as w:
27
+ raw = w.readframes(w.getnframes())
28
+ peak = max(abs(int.from_bytes(raw[i : i + 2], "little", signed=True)) for i in range(0, len(raw), 2))
29
+ assert peak == pytest.approx(0.5 * 32767, rel=0.01)
30
+ with wave.open(io.BytesIO(sine_wav(0.1, width=1, amplitude=0)), "rb") as w:
31
+ assert set(w.readframes(w.getnframes())) == {128} # 8-bit is unsigned: silence is the middle
32
+
33
+
34
+ @pytest.mark.parametrize(
35
+ ("data", "words"),
36
+ [
37
+ (b"", "empty"),
38
+ (b"not a wav at all", "not a WAV file that can be read (file does not start with RIFF id)"),
39
+ (sine_wav(1.0)[:30], "not a WAV file that can be read (it ends early)"),
40
+ ],
41
+ )
42
+ def test_refuses_what_is_not_a_wav(data: bytes, words: str) -> None:
43
+ with pytest.raises(WavError, match=re.escape(words)):
44
+ read_wav(data)
45
+
46
+
47
+ def test_a_chunk_that_claims_more_than_follows_is_refused() -> None:
48
+ data = bytearray(sine_wav(0.5))
49
+ data[16:20] = (10_000).to_bytes(4, "little") # the fmt chunk now claims 10 kB
50
+ with pytest.raises(WavError, match="not a WAV file that can be read"):
51
+ read_wav(bytes(data))
52
+
53
+
54
+ def test_refuses_the_wrong_shape_with_a_sentence() -> None:
55
+ with pytest.raises(WavError, match="Send a mono recording; this one has 2 channels"):
56
+ read_wav(sine_wav(1.0, channels=2))
57
+ with pytest.raises(WavError, match="Send a 2-channel recording; this one has 1 channels"):
58
+ read_wav(sine_wav(1.0), channels=2)
59
+ assert read_wav(sine_wav(1.0, channels=2), channels=None).channels == 2
60
+ with pytest.raises(WavError, match="Send 16-bit or 24-bit samples; this recording has 8-bit"):
61
+ read_wav(sine_wav(1.0, width=1))
62
+ with pytest.raises(WavError, match="Record at 16000 Hz or more; this recording is 8000 Hz"):
63
+ read_wav(sine_wav(1.0, rate=8_000))
64
+ assert read_wav(sine_wav(1.0, rate=8_000), min_rate=8_000).sample_rate == 8_000
65
+
66
+
67
+ def test_bounds_the_length() -> None:
68
+ with pytest.raises(WavError, match=r"0\.1 seconds long; the shortest kept is 0\.3"):
69
+ read_wav(sine_wav(0.1), min_seconds=0.3)
70
+ with pytest.raises(WavError, match="3 seconds long; the longest kept is 2"):
71
+ read_wav(sine_wav(3.0), max_seconds=2)
72
+ assert read_wav(sine_wav(2.0), min_seconds=0.3, max_seconds=2).seconds == 2.0
73
+
74
+
75
+ def test_a_recording_cut_short_after_its_header_is_refused(tmp_path: Path) -> None:
76
+ whole = sine_wav(1.0)
77
+ with pytest.raises(WavError, match="ends early: its header promises more sound"):
78
+ read_wav(whole[:44], min_seconds=0.5)
79
+ with pytest.raises(WavError, match="ends early"):
80
+ read_wav(whole[:-1]) # half of the last frame
81
+ path = tmp_path / "cut.wav"
82
+ path.write_bytes(whole[:1000])
83
+ with pytest.raises(WavError, match="ends early"):
84
+ read_wav(path)
85
+
86
+
87
+ def test_an_empty_file_and_a_wav_with_no_frames(tmp_path: Path) -> None:
88
+ path = tmp_path / "empty.wav"
89
+ path.write_bytes(b"")
90
+ with pytest.raises(WavError, match="empty"):
91
+ read_wav(path)
92
+ assert read_wav(sine_wav(0.0)).frames == 0
File without changes
File without changes