strata-python 0.2.8__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.8 → strata_python-0.2.9}/CHANGELOG.md +4 -0
  2. {strata_python-0.2.8 → strata_python-0.2.9}/PKG-INFO +3 -2
  3. {strata_python-0.2.8 → strata_python-0.2.9}/README.md +2 -1
  4. {strata_python-0.2.8 → strata_python-0.2.9}/pyproject.toml +1 -1
  5. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/testing.py +29 -0
  6. strata_python-0.2.9/src/strata_python/wav.py +91 -0
  7. strata_python-0.2.9/tests/unit/test_wav.py +92 -0
  8. {strata_python-0.2.8 → strata_python-0.2.9}/.gitignore +0 -0
  9. {strata_python-0.2.8 → strata_python-0.2.9}/LICENSE +0 -0
  10. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/__init__.py +0 -0
  11. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/check.py +0 -0
  12. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/cli.py +0 -0
  13. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/client.py +0 -0
  14. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/clients/__init__.py +0 -0
  15. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/clients/models.py +0 -0
  16. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/contracts.py +0 -0
  17. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/__init__.py +0 -0
  18. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/__main__.py +0 -0
  19. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/_alembic/env.py +0 -0
  20. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/_alembic/script.py.mako +0 -0
  21. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/cli.py +0 -0
  22. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/config.py +0 -0
  23. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/engine.py +0 -0
  24. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/guard.py +0 -0
  25. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/migrations.py +0 -0
  26. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/models.py +0 -0
  27. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/project.py +0 -0
  28. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/pytest_plugin.py +0 -0
  29. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/scratch.py +0 -0
  30. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/settings.py +0 -0
  31. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/testing.py +0 -0
  32. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/testserver.py +0 -0
  33. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/db/web.py +0 -0
  34. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/files.py +0 -0
  35. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/http.py +0 -0
  36. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/http_server.py +0 -0
  37. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/images.py +0 -0
  38. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/live.py +0 -0
  39. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/media.py +0 -0
  40. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/mediatime.py +0 -0
  41. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/oslib.py +0 -0
  42. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/pages/__init__.py +0 -0
  43. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/pages/model.py +0 -0
  44. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/pages/render.py +0 -0
  45. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/public_check.py +0 -0
  46. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/py.typed +0 -0
  47. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/pytest_plugin.py +0 -0
  48. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/settings.py +0 -0
  49. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/stats.py +0 -0
  50. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/__init__.py +0 -0
  51. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/child.py +0 -0
  52. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/flight.py +0 -0
  53. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/progress.py +0 -0
  54. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/queue.py +0 -0
  55. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/retry.py +0 -0
  56. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/status.py +0 -0
  57. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/tasks/ticker.py +0 -0
  58. {strata_python-0.2.8 → strata_python-0.2.9}/src/strata_python/web.py +0 -0
  59. {strata_python-0.2.8 → strata_python-0.2.9}/tests/conftest.py +0 -0
  60. {strata_python-0.2.8 → strata_python-0.2.9}/tests/integration/test_db_cli.py +0 -0
  61. {strata_python-0.2.8 → strata_python-0.2.9}/tests/integration/test_serve.py +0 -0
  62. {strata_python-0.2.8 → strata_python-0.2.9}/tests/integration/test_strata_check.py +0 -0
  63. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/job_handlers.py +0 -0
  64. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_check.py +0 -0
  65. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_cli.py +0 -0
  66. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_client.py +0 -0
  67. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_clients_models.py +0 -0
  68. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_contracts.py +0 -0
  69. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_db.py +0 -0
  70. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_files.py +0 -0
  71. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_http.py +0 -0
  72. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_http_server.py +0 -0
  73. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_images.py +0 -0
  74. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_live.py +0 -0
  75. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_media.py +0 -0
  76. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_mediatime.py +0 -0
  77. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_oslib.py +0 -0
  78. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_package.py +0 -0
  79. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_pages.py +0 -0
  80. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_plugin.py +0 -0
  81. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_public_check.py +0 -0
  82. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_queue.py +0 -0
  83. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_settings.py +0 -0
  84. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_stats.py +0 -0
  85. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_tasks.py +0 -0
  86. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_testing.py +0 -0
  87. {strata_python-0.2.8 → strata_python-0.2.9}/tests/unit/test_web.py +0 -0
@@ -4,10 +4,14 @@ 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
+
7
9
  ## 0.2.8 (2026-11-23)
8
10
 
9
11
  ### Added
10
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.
11
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.
12
16
 
13
17
  ## 0.2.7 (2026-11-23)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: strata-python
3
- Version: 0.2.8
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
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 |
@@ -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
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 |
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "strata-python"
7
- version = "0.2.8" # 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"
@@ -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,11 +26,14 @@ 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
@@ -468,3 +472,28 @@ class FakeModels:
468
472
  if not 1 <= lease_id <= len(self.leases):
469
473
  raise error(404, f"no lease {lease_id}")
470
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
@@ -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