strata-python 0.2.3__py3-none-any.whl → 0.2.5__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/files.py +247 -0
- strata_python/http.py +326 -0
- strata_python/images.py +107 -0
- strata_python/media.py +323 -0
- strata_python/oslib.py +9 -3
- strata_python/pages/render.py +10 -2
- strata_python/stats.py +196 -0
- strata_python/tasks/__init__.py +2 -1
- strata_python/tasks/status.py +1 -16
- {strata_python-0.2.3.dist-info → strata_python-0.2.5.dist-info}/METADATA +58 -14
- {strata_python-0.2.3.dist-info → strata_python-0.2.5.dist-info}/RECORD +14 -9
- {strata_python-0.2.3.dist-info → strata_python-0.2.5.dist-info}/WHEEL +0 -0
- {strata_python-0.2.3.dist-info → strata_python-0.2.5.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.3.dist-info → strata_python-0.2.5.dist-info}/licenses/LICENSE +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.5
|
|
2
2
|
Name: strata-python
|
|
3
|
-
Version: 0.2.
|
|
3
|
+
Version: 0.2.5
|
|
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
|
|
@@ -37,6 +37,8 @@ Requires-Dist: pytest-timeout<3,>=2; extra == 'dev'
|
|
|
37
37
|
Requires-Dist: pytest-xdist<4,>=3; extra == 'dev'
|
|
38
38
|
Requires-Dist: ruff<0.18,>=0.17; extra == 'dev'
|
|
39
39
|
Requires-Dist: ty<0.1,>=0.0.99; extra == 'dev'
|
|
40
|
+
Provides-Extra: images
|
|
41
|
+
Requires-Dist: pillow<14,>=13; extra == 'images'
|
|
40
42
|
Provides-Extra: pdf
|
|
41
43
|
Requires-Dist: pillow<14,>=13; extra == 'pdf'
|
|
42
44
|
Requires-Dist: pypdfium2<6,>=4.30; extra == 'pdf'
|
|
@@ -56,6 +58,11 @@ Common code for the strata Python web server apps (FastAPI + CLI), the Python co
|
|
|
56
58
|
| `strata_python.contracts` | The shapes the apps' APIs share, as pydantic models for `response_model`: `Health`, `SystemInfo`, `ErrorBody`, `Task` (with `TaskState`), `Progress`, `Page[T]`, `FileRef`, `Judgment` |
|
|
57
59
|
| `strata_python.client` | `ServiceClient`, the standard-library base for calling a strata service: JSON calls, `Rejected` (4xx, with the reason and payload) and `Unavailable` (down or 5xx), retried reads, a long-poll `wait`, `available()`, and `env_url` |
|
|
58
60
|
| `strata_python.tasks` | Work outside a request: `next_state`/`backoff_s`/`RetryLater` (when to retry), `report_progress` and `ProgressReporter` (throttled), `SingleFlight` (one run per key, `Conflict` on a second), `StatusFile` and `Detached` (a process that outlives the server), `Ticker` (a loop that survives its errors), and with the `[db]` extra `tasks.queue` (`Queue`, `Worker`, `jobs_table`: durable jobs with retry, dedupe, resources, cancel and crash recovery) |
|
|
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
|
+
| `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
|
+
| `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.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
|
+
| `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` |
|
|
59
66
|
| `strata_python.clients.models` | The strata-models client, standard library only: `run`, `submit`, `wait`, `role_model`, `gpu_lease`, a shortcut for every role the service runs (`faces`, `face_kind`, `transcribe`, `ocr`, `speak`, `denoise_audio`, `audio_quality`, `generate_image`, `embed`, `enhance_video`, and `ask` for the language models) and a typed result for each |
|
|
60
67
|
| `strata_python.http_server` / `live` | A real scripted HTTP server and a real uvicorn server on loopback, for tests that make actual requests |
|
|
61
68
|
| 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` |
|
|
@@ -145,8 +152,8 @@ To keep the values in the app's database instead of the file, add the table to t
|
|
|
145
152
|
```python
|
|
146
153
|
from strata_python.db.settings import TableStore, settings_table
|
|
147
154
|
|
|
148
|
-
SETTINGS_TABLE = settings_table(Base.metadata)
|
|
149
|
-
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE))
|
|
155
|
+
SETTINGS_TABLE = settings_table(Base.metadata) # in models.py, so the migrations create it
|
|
156
|
+
SETTINGS.bind(TableStore(engine, SETTINGS_TABLE)) # any object with load() and update(changes) is a store
|
|
150
157
|
```
|
|
151
158
|
|
|
152
159
|
### 4. The server
|
|
@@ -165,11 +172,15 @@ def create_app():
|
|
|
165
172
|
Two more that replace code most servers carry:
|
|
166
173
|
|
|
167
174
|
```python
|
|
168
|
-
web.add_error_handlers(app)
|
|
169
|
-
|
|
170
|
-
web.add_system(
|
|
171
|
-
|
|
172
|
-
|
|
175
|
+
web.add_error_handlers(app) # ValueError 400, PermissionError 403, KeyError and FileNotFoundError 404,
|
|
176
|
+
# tasks.Conflict 409, client.Rejected 502, client.Unavailable 503: {detail, payload}
|
|
177
|
+
web.add_system(
|
|
178
|
+
app,
|
|
179
|
+
__version__,
|
|
180
|
+
commit=web.source_commit(__file__),
|
|
181
|
+
folders={"data": lambda: SETTINGS.get("data_dir")},
|
|
182
|
+
services={"strata-models": "http://127.0.0.1:8366"},
|
|
183
|
+
) # GET /api/system, a SystemInfo
|
|
173
184
|
```
|
|
174
185
|
|
|
175
186
|
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`.
|
|
@@ -219,9 +230,9 @@ A check returns `(status, text)` with status `ok`, `missing`, `slow` (works, but
|
|
|
219
230
|
Drop the `strata-models-client` path or git dependency and change the import. The functions, their arguments and the exceptions are the same:
|
|
220
231
|
|
|
221
232
|
```python
|
|
222
|
-
from strata_python.clients import models as sm
|
|
233
|
+
from strata_python.clients import models as sm # was: import strata_models_client as sm
|
|
223
234
|
|
|
224
|
-
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan"))
|
|
235
|
+
page = sm.OcrPage.from_json(sm.ocr("/path/page.png", app="strata-scan")) # typed: page.lines[0].words[0].box
|
|
225
236
|
talk = sm.Transcript.from_json(sm.transcribe("/path/talk.wav", app="strata-360"))
|
|
226
237
|
with sm.gpu_lease("strata-stills", vram_gb=4):
|
|
227
238
|
run_my_own_cuda_code()
|
|
@@ -246,15 +257,48 @@ Replace the app's job dicts and loops with `strata_python.tasks`:
|
|
|
246
257
|
```python
|
|
247
258
|
from strata_python.tasks.queue import Job, Queue, Worker
|
|
248
259
|
|
|
249
|
-
QUEUE = Queue(engine, JOBS, on_fail=cascade)
|
|
260
|
+
QUEUE = Queue(engine, JOBS, on_fail=cascade) # on_fail(conn, job, error), in the failing transaction
|
|
250
261
|
QUEUE.enqueue("ocr", {"page": 3}, domain="book:12", dedupe=True, resources=["gpu"], timeout_s=600)
|
|
251
|
-
WORKER = Worker(
|
|
252
|
-
QUEUE
|
|
253
|
-
|
|
262
|
+
WORKER = Worker(
|
|
263
|
+
QUEUE, {"ocr": ocr_page}, concurrency=2
|
|
264
|
+
).start() # a job process per thread, reused; recovers dead workers' jobs
|
|
265
|
+
QUEUE.page(state="running", after=cursor) # Page[Task] for GET /api/jobs
|
|
266
|
+
QUEUE.cancel(job_id)
|
|
267
|
+
QUEUE.retry(job_id)
|
|
268
|
+
QUEUE.prune(older_than_s=30 * 86400)
|
|
254
269
|
```
|
|
255
270
|
|
|
256
271
|
A handler is a module-level `fn(job) -> result` that reads `job.options` and reports progress. By default jobs run in job processes (`python -m strata_python.tasks.child`, one per worker thread, kept between jobs and importing the handlers by name), so a cancel, a timeout or `WORKER.stop()` kills the job and every tool it started, and jobs die with the server; a quick job costs about half a millisecond more than on a thread (3.5 ms against 2.9 ms a job on SQLite), since only a kill starts a new process. `max_jobs=N` replaces a process after N jobs, for code that leaks. The worker checks at start-up that every handler can be imported. `Worker(lower_priority=True)` runs the jobs at idle CPU and disk priority. `Worker(isolate=False)` runs handlers on the server's threads instead, where they return early when `job.stopping`. In tests, `QUEUE.step(handlers)` claims and runs one job in the test's own thread.
|
|
257
272
|
|
|
273
|
+
### 6c. Files, web APIs, media, pictures and rankings
|
|
274
|
+
|
|
275
|
+
Each of these replaces code that two to six apps wrote for themselves; move to it when you next touch that code.
|
|
276
|
+
|
|
277
|
+
- **Writes.** Every `tmp = path + ".tmp"; ...; os.replace(tmp, path)` becomes `write_json_atomic(path, data)` (or `write_text_atomic`, `write_bytes_atomic`, `with atomic_open(path, "wb") as f:`). A tool that writes the file itself writes to `with atomic_path(out) as tmp:`; the temp name keeps the extension, so `ffmpeg ... tmp` still picks the format. Reads that tolerate a missing or broken file are `read_json(path, default)`. Delete the app's `_save`, `write_status` and `.part` helpers.
|
|
278
|
+
- **Hashes and keys.** `sha256(path)` (bytes, for a `LargeBinary` column) and `sha256_hex(path)` replace listory's two copies, filecat's and stills' scripts'. `quick_fingerprint(path)` is 360's `clips.fingerprint` idea on SHA-256 (an app that stored the old 12-character SHA-1 keeps its own until it re-keys). A cache that must follow a file's changes keys on `stat_key(path, px, version)`.
|
|
279
|
+
- **Paths from a request.** `files.inside(root, name)` before opening a file a request names; it raises `ValueError` (400 with `add_error_handlers`) for `..`, an absolute path elsewhere, or a link out of the root.
|
|
280
|
+
- **Other people's APIs.** One `Http` per service, at module level so its gap is shared:
|
|
281
|
+
|
|
282
|
+
```python
|
|
283
|
+
from strata_python.files import DiskCache
|
|
284
|
+
from strata_python.http import Http
|
|
285
|
+
|
|
286
|
+
NOMINATIM = Http(
|
|
287
|
+
"myapp/1.0 (reverse geocoding of my own tracks)",
|
|
288
|
+
min_interval=1.1,
|
|
289
|
+
throttle_file=cache_dir / ".nominatim",
|
|
290
|
+
cache=DiskCache(cache_dir),
|
|
291
|
+
)
|
|
292
|
+
reply = NOMINATIM.get(URL, params={"lat": lat, "lon": lon, "format": "json"}, cache_s=30 * 86400)
|
|
293
|
+
if reply.ok:
|
|
294
|
+
place = reply.json() # reply.status == 0 when unreachable; reply.limited when rate limited
|
|
295
|
+
```
|
|
296
|
+
|
|
297
|
+
The User-Agent names the app and what it is for, never a person. Delete the app's `_throttle`, `_retry_after`, `_cool_until`, `_open`/`_get` wrappers and its response cache; listory's `providers.base.Http` keeps its own `emit` through `observe=`. A provider result worth keeping (not an HTTP body) is `DiskCache(...).json(key, fetch, max_age_s)`.
|
|
298
|
+
- **ffprobe and ffmpeg.** `media.probe(path)` replaces every hand-written `ffprobe -show_entries` call; read `info.duration`, `info.audio.sample_rate`, `info.video.fps`, `info.chapters`, `info.tags`, and `info.raw` for anything else. `media.ffmpeg(args)` adds `-nostdin -hide_banner -v error -y` and raises `MediaError` with ffmpeg's last lines; `progress=` reports seconds written. Map `MediaError` in `add_error_handlers` if the app answers it over HTTP. A doctor row is `cli.program("ffmpeg")`.
|
|
299
|
+
- **Thumbnails** (`strata-python[images]`): `images.thumbnail(src, px, cache_dir=settings.thumbs_dir())` returns the cached JPEG's path for a `FileResponse`. An app with its own reader (stills' raw previews, 360's video frames) passes `make=lambda path, px: ...` returning a Pillow image. Bump `version=` when the way a thumbnail is made changes.
|
|
300
|
+
- **Rankings and evals.** `stats.bradley_terry(votes, side=True)` with votes as `(a, b, "a" | "b" | "tie")` (or `stats.votes_from(judgments)`), `.ratings()` for the Elo scale, `stats.intervals(votes)` for how far to trust a gap; `wilson`, `mcnemar` and `holm` for eval write-ups. The numpy bootstraps over items in strata-models' evals stay there until a second app needs them.
|
|
301
|
+
|
|
258
302
|
### 7. Tests
|
|
259
303
|
|
|
260
304
|
The pytest plugin loads itself once strata-python is installed. Configure it in `pyproject.toml`:
|
|
@@ -3,13 +3,18 @@ strata_python/check.py,sha256=lFjXuPjVIWn6dBu2yMKIW-76RloUREijuMHCRsBW4Z8,2932
|
|
|
3
3
|
strata_python/cli.py,sha256=KKcFNjLsNXygeSUvzbaznZ8sTTW1ADkgsovJcyd3Sjc,5991
|
|
4
4
|
strata_python/client.py,sha256=S-cfDQqbO0dJ951TAiFyW2CbkFQkN1OWnUBCYaTO3Lg,7911
|
|
5
5
|
strata_python/contracts.py,sha256=g72b9GQt_ZeiShYXhMJzy4hppDz6t124Ik7lEnnM_HA,5813
|
|
6
|
+
strata_python/files.py,sha256=jJMFnzsigY29f6EcpjEtbBnc-66FCOuw875epYMOSjg,11423
|
|
7
|
+
strata_python/http.py,sha256=dltLx14TqQGuLhFeFoYyNZiOVAXx7ZEeXPQwPjaT2hc,16152
|
|
6
8
|
strata_python/http_server.py,sha256=64uYWy4zFxughOgtvkssGXMJDZ7jhRj1bxUIfnzte8w,4475
|
|
9
|
+
strata_python/images.py,sha256=nNQ7fQxkpmnTf5iotYlR7VejxCfthXgIpMEGTsLvNVE,4872
|
|
7
10
|
strata_python/live.py,sha256=kNY6h6gMxBo9l78UoGUIWjcADeZi4eZuAEp0jqDowEE,1215
|
|
8
|
-
strata_python/
|
|
11
|
+
strata_python/media.py,sha256=66Pk1_CTHyApKlWD8LuzS08O3EOx-7dNaj9AkEbNxmw,12647
|
|
12
|
+
strata_python/oslib.py,sha256=vfZDUCNZnTjjjB704eoyNXlPFCz2yVR3puFljE0Z1gE,12137
|
|
9
13
|
strata_python/public_check.py,sha256=A0JusSWnwXtaA3sKsRoa4ocM5MNx38Nc49-dymd__3Q,8398
|
|
10
14
|
strata_python/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
11
15
|
strata_python/pytest_plugin.py,sha256=BaD-XokrX1PMMj0Cqxj9IJTb6EXBp7ozQZ6SSCDumMg,7223
|
|
12
16
|
strata_python/settings.py,sha256=zozaBZetHToxy0XSj4jmRcvgeC8jxW6v3qt8IMrjDwQ,14896
|
|
17
|
+
strata_python/stats.py,sha256=nc6qXELpMg7eK0xjFo45M1FK7FR3q89be3VCJzExKYc,8354
|
|
13
18
|
strata_python/testing.py,sha256=SXIUtWgbqjHPdXhjbtzC6Voo7QhL0nexnY9mSp8euUs,20107
|
|
14
19
|
strata_python/web.py,sha256=Ur7Tt_wLC-qJtPse1U1gDAvyTcIFSpEVg4MFhlzW3c8,12897
|
|
15
20
|
strata_python/clients/__init__.py,sha256=xivuysmYG7rbCGProVNvdSs-h4xVFQsuqUY6EwzuJbk,182
|
|
@@ -32,17 +37,17 @@ strata_python/db/_alembic/env.py,sha256=gXzRn02h59PB_1RaABkaT6GuyuzPQCZh3Z5ml2Jl
|
|
|
32
37
|
strata_python/db/_alembic/script.py.mako,sha256=04kgeBtNMa4cCnG8CfQcKt6P6rnloIfj8wy0u_DBydM,704
|
|
33
38
|
strata_python/pages/__init__.py,sha256=6QsTqJbFiuLCxywt8C0D6nyXRXjpzI1Xoo5u6rK9toQ,665
|
|
34
39
|
strata_python/pages/model.py,sha256=8Skz3eishAZiNHIHzScI0g60wGpH6jZ3vNc0LpMZ4q4,9821
|
|
35
|
-
strata_python/pages/render.py,sha256=
|
|
36
|
-
strata_python/tasks/__init__.py,sha256=
|
|
40
|
+
strata_python/pages/render.py,sha256=Q3_xliHCkDoGKXNLT3KksaYtfNnm0T2-p-7FhOu6loQ,12421
|
|
41
|
+
strata_python/tasks/__init__.py,sha256=jX-aXJFaivpjt6-WfHd_Xg4YVzLQeRYvAvyjKUTGwbw,1561
|
|
37
42
|
strata_python/tasks/child.py,sha256=1ZpQwlFx0bbNXD5UKmPrlcEogCf-MrPGSOSK8TpqllA,11133
|
|
38
43
|
strata_python/tasks/flight.py,sha256=FjWl7M1Y1qV5Mcr3Qwu6H464sobzpYEjQAKcz_GjPH4,5704
|
|
39
44
|
strata_python/tasks/progress.py,sha256=AqfrrDA-ZBkha98ex0kQIzwk45TiTe_pX1FhYyi2u2I,3636
|
|
40
45
|
strata_python/tasks/queue.py,sha256=b4in3XnplTlapL_ECTs_WYJcittYj3iKz7q_fQ8_HDY,32188
|
|
41
46
|
strata_python/tasks/retry.py,sha256=NztmOf3Q-rl5y3CZlfP1qcDqPT0jOiIDjMfD-MUkr5s,3995
|
|
42
|
-
strata_python/tasks/status.py,sha256=
|
|
47
|
+
strata_python/tasks/status.py,sha256=cZvYghNAGJRlpVIJAtUSb5pW19UbxR6bNQU4etJMYN4,7440
|
|
43
48
|
strata_python/tasks/ticker.py,sha256=V6JLWgAGV5sIGeX1vp4t35omuRvvB6AYWv_lzJAq69Y,2860
|
|
44
|
-
strata_python-0.2.
|
|
45
|
-
strata_python-0.2.
|
|
46
|
-
strata_python-0.2.
|
|
47
|
-
strata_python-0.2.
|
|
48
|
-
strata_python-0.2.
|
|
49
|
+
strata_python-0.2.5.dist-info/METADATA,sha256=N-29ritqMIp6zx_5olDJjkDlWf64HGLQ5hu29NMluJI,34119
|
|
50
|
+
strata_python-0.2.5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
51
|
+
strata_python-0.2.5.dist-info/entry_points.txt,sha256=6RVv-uDumVQ-KY2YdvKwd5R3l6P9WQD4kPtPOKKEM-I,256
|
|
52
|
+
strata_python-0.2.5.dist-info/licenses/LICENSE,sha256=9yVMCPoK7unONyTAiDYjMTt3MZPGJ639nWOwxyNsZGg,1066
|
|
53
|
+
strata_python-0.2.5.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|