strata-python 0.2.8__py3-none-any.whl → 0.2.9__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
strata_python/testing.py CHANGED
@@ -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()
strata_python/wav.py ADDED
@@ -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
@@ -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 |
@@ -16,7 +16,8 @@ strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
16
16
  strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
17
17
  strata_python/settings.py,sha256=YeQMJwyqFNX7L3bbgbwRN1hdfzBem9uWxqg_WVswT-A,18688
18
18
  strata_python/stats.py,sha256=nc6qXELpMg7eK0xjFo45M1FK7FR3q89be3VCJzExKYc,8354
19
- strata_python/testing.py,sha256=GpqljUX07FuOWZaizC4wHQJvT03NdBpKi31TgZPpi80,22715
19
+ strata_python/testing.py,sha256=1u8g2db2fpPtRfDlLZcwybdtF01fRSINHz9Oe29oeP4,23667
20
+ strata_python/wav.py,sha256=PjT9ZLseKbjXZWOGD4QFnJw1RPMTmvaZPVtZjROTZ2Y,4154
20
21
  strata_python/web.py,sha256=RkT8cR6gZ0MNYnUDMtKjAu9pIkPmdh0coxkoB5cyA9c,15252
21
22
  strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
22
23
  strata_python/clients/models.py,sha256=sHhU1Lfw_0y3lkTQ74Q0OcOV4KjviV6Qq93V_D1mV3Y,32531
@@ -48,8 +49,8 @@ strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,
48
49
  strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
49
50
  strata_python/tasks/status.py,sha256=cZvYghNAGJRlpVIJAtUSb5pW19UbxR6bNQU4etJMYN4,7440
50
51
  strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
51
- strata_python-0.2.8.dist-info/METADATA,sha256=2PGi5Y3ToKWuYgyURHJju0dGXAMOXhjTEIa7w2V2v_Q,38215
52
- strata_python-0.2.8.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
53
- strata_python-0.2.8.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
54
- strata_python-0.2.8.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
55
- strata_python-0.2.8.dist-info/RECORD,,
52
+ strata_python-0.2.9.dist-info/METADATA,sha256=H0ceKx91vmgfADFNqABBgYpNY5OoKtiWnkDpMxuHync,38695
53
+ strata_python-0.2.9.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
54
+ strata_python-0.2.9.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
55
+ strata_python-0.2.9.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
56
+ strata_python-0.2.9.dist-info/RECORD,,