strata-python 0.2.4__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/stats.py +196 -0
- strata_python/tasks/__init__.py +2 -1
- strata_python/tasks/status.py +1 -16
- {strata_python-0.2.4.dist-info → strata_python-0.2.5.dist-info}/METADATA +58 -14
- {strata_python-0.2.4.dist-info → strata_python-0.2.5.dist-info}/RECORD +12 -7
- {strata_python-0.2.4.dist-info → strata_python-0.2.5.dist-info}/WHEEL +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.5.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.5.dist-info}/licenses/LICENSE +0 -0
strata_python/media.py
ADDED
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
"""ffprobe and ffmpeg, called one way: a typed probe, a duration, and ffmpeg runs that fail with the tool's own words.
|
|
2
|
+
|
|
3
|
+
strata-360 calls ffprobe in 16 places, listory has three separate wrappers (`process/probe.py`, `store/filegroups.py`,
|
|
4
|
+
`details.py`) and strata-models two (`workers/video.py`, `workers/audio.py`). They differ in the `-v` level, the
|
|
5
|
+
timeout and what a failure is (None, a `ToolError`, a `RuntimeError`, a `ParamError`), and each picks a few fields out
|
|
6
|
+
of the JSON by hand. Here:
|
|
7
|
+
|
|
8
|
+
info = probe(path) # Probe: duration, format, size, bit_rate, tags, streams, chapters, raw
|
|
9
|
+
info.audio.sample_rate; info.video.fps; info.chapters[0].title; info.warnings # ffprobe's own complaints
|
|
10
|
+
duration(path) # seconds, float
|
|
11
|
+
ffmpeg(["-i", src, "-ac", "1", out]) # -nostdin -hide_banner -v error -y; MediaError with stderr's tail
|
|
12
|
+
ffmpeg([...], progress=lambda s: ...) # seconds of output written so far, from -progress
|
|
13
|
+
available() # {"ffmpeg": True, "ffprobe": False}
|
|
14
|
+
|
|
15
|
+
`MediaError` is a `RuntimeError` for a missing tool, a file ffprobe cannot read, a timeout or a failed ffmpeg run. Its
|
|
16
|
+
message ends with the last lines ffmpeg wrote, because that is the only place the reason is.
|
|
17
|
+
|
|
18
|
+
Durations: the container's, else the longest stream's (some MP3s and raw streams have no container duration). A wrong
|
|
19
|
+
VBR header still gives a wrong number; `info.warnings` carries ffprobe's "estimating duration from bitrate" so an app
|
|
20
|
+
that cares (listory) can decode and count instead. The tools are found on the PATH, or `STRATA_FFMPEG`/`STRATA_FFPROBE`
|
|
21
|
+
when set (a build with more codecs). Standard library only; `run` is injectable, but tests should prefer the real
|
|
22
|
+
tools on a tiny generated file."""
|
|
23
|
+
|
|
24
|
+
from __future__ import annotations
|
|
25
|
+
|
|
26
|
+
import contextlib
|
|
27
|
+
import json
|
|
28
|
+
import os
|
|
29
|
+
import shutil
|
|
30
|
+
import subprocess
|
|
31
|
+
import threading
|
|
32
|
+
from collections.abc import Callable, Sequence
|
|
33
|
+
from dataclasses import dataclass, field
|
|
34
|
+
from typing import Any, cast
|
|
35
|
+
|
|
36
|
+
from strata_python import oslib
|
|
37
|
+
|
|
38
|
+
Json = dict[str, Any]
|
|
39
|
+
ENV = {"ffmpeg": "STRATA_FFMPEG", "ffprobe": "STRATA_FFPROBE"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class MediaError(RuntimeError):
|
|
43
|
+
"""ffmpeg or ffprobe is missing, could not read the file, ran out of time or failed."""
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def tool(name: str) -> str:
|
|
47
|
+
"""The path of `ffmpeg` or `ffprobe`: `STRATA_FFMPEG` / `STRATA_FFPROBE` when set, else the PATH."""
|
|
48
|
+
found = os.environ.get(ENV.get(name, "")) or shutil.which(name)
|
|
49
|
+
if not found:
|
|
50
|
+
raise MediaError(f"{name} is not installed (or not on the PATH): install ffmpeg, or set {ENV.get(name, name)}")
|
|
51
|
+
return found
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def available() -> dict[str, bool]:
|
|
55
|
+
"""Which of the tools can be found, for a doctor row."""
|
|
56
|
+
out: dict[str, bool] = {}
|
|
57
|
+
for name in ENV:
|
|
58
|
+
try:
|
|
59
|
+
tool(name)
|
|
60
|
+
out[name] = True
|
|
61
|
+
except MediaError:
|
|
62
|
+
out[name] = False
|
|
63
|
+
return out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _tail(text: str | bytes | None, n: int = 600) -> str:
|
|
67
|
+
if isinstance(text, bytes):
|
|
68
|
+
text = text.decode(errors="replace")
|
|
69
|
+
return (text or "").strip()[-n:]
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _num(v: object, cast_to: Callable[[Any], Any] = float) -> Any:
|
|
73
|
+
try:
|
|
74
|
+
return cast_to(v)
|
|
75
|
+
except (TypeError, ValueError):
|
|
76
|
+
return None
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def _rate(v: object) -> float | None:
|
|
80
|
+
"""ffprobe's "30000/1001" (or "25") as a number; None for "0/0"."""
|
|
81
|
+
num, _, den = str(v or "").partition("/")
|
|
82
|
+
n, d = _num(num), _num(den or 1)
|
|
83
|
+
return n / d if n and d else None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@dataclass
|
|
87
|
+
class Stream:
|
|
88
|
+
index: int
|
|
89
|
+
kind: str # video | audio | subtitle | data | attachment
|
|
90
|
+
codec: str
|
|
91
|
+
duration: float | None
|
|
92
|
+
bit_rate: int | None
|
|
93
|
+
width: int | None = None
|
|
94
|
+
height: int | None = None
|
|
95
|
+
fps: float | None = None # avg_frame_rate, else r_frame_rate
|
|
96
|
+
frames: int | None = None
|
|
97
|
+
pix_fmt: str | None = None
|
|
98
|
+
sample_rate: int | None = None
|
|
99
|
+
channels: int | None = None
|
|
100
|
+
channel_layout: str | None = None
|
|
101
|
+
tags: dict[str, str] = field(default_factory=lambda: {}) # keys lower-cased
|
|
102
|
+
raw: Json = field(default_factory=lambda: {})
|
|
103
|
+
|
|
104
|
+
@classmethod
|
|
105
|
+
def from_json(cls, s: Json) -> Stream:
|
|
106
|
+
return cls(
|
|
107
|
+
index=int(s.get("index", 0)),
|
|
108
|
+
kind=str(s.get("codec_type", "")),
|
|
109
|
+
codec=str(s.get("codec_name", "")),
|
|
110
|
+
duration=_num(s.get("duration")),
|
|
111
|
+
bit_rate=_num(s.get("bit_rate"), int),
|
|
112
|
+
width=_num(s.get("width"), int),
|
|
113
|
+
height=_num(s.get("height"), int),
|
|
114
|
+
fps=_rate(s.get("avg_frame_rate")) or _rate(s.get("r_frame_rate")),
|
|
115
|
+
frames=_num(s.get("nb_frames"), int),
|
|
116
|
+
pix_fmt=s.get("pix_fmt"),
|
|
117
|
+
sample_rate=_num(s.get("sample_rate"), int),
|
|
118
|
+
channels=_num(s.get("channels"), int),
|
|
119
|
+
channel_layout=s.get("channel_layout"),
|
|
120
|
+
tags={str(k).lower(): str(v) for k, v in cast("Json", s.get("tags") or {}).items()},
|
|
121
|
+
raw=s,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class Chapter:
|
|
127
|
+
start: float
|
|
128
|
+
end: float
|
|
129
|
+
title: str
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass
|
|
133
|
+
class Probe:
|
|
134
|
+
path: str
|
|
135
|
+
duration: float | None
|
|
136
|
+
format: str # format_name, e.g. "mov,mp4,m4a,3gp,3g2,mj2"
|
|
137
|
+
size: int | None
|
|
138
|
+
bit_rate: int | None
|
|
139
|
+
tags: dict[str, str] # container tags, keys lower-cased
|
|
140
|
+
streams: list[Stream]
|
|
141
|
+
chapters: list[Chapter]
|
|
142
|
+
warnings: str # what ffprobe wrote on stderr at -v warning
|
|
143
|
+
raw: Json # the whole ffprobe answer
|
|
144
|
+
|
|
145
|
+
def first(self, kind: str) -> Stream | None:
|
|
146
|
+
return next((s for s in self.streams if s.kind == kind), None)
|
|
147
|
+
|
|
148
|
+
@property
|
|
149
|
+
def video(self) -> Stream | None:
|
|
150
|
+
return self.first("video")
|
|
151
|
+
|
|
152
|
+
@property
|
|
153
|
+
def audio(self) -> Stream | None:
|
|
154
|
+
return self.first("audio")
|
|
155
|
+
|
|
156
|
+
@classmethod
|
|
157
|
+
def from_json(cls, path: str, d: Json, warnings: str = "") -> Probe:
|
|
158
|
+
fmt = cast("Json", d.get("format") or {})
|
|
159
|
+
streams = [Stream.from_json(s) for s in cast("list[Json]", d.get("streams") or [])]
|
|
160
|
+
dur = _num(fmt.get("duration")) or max((s.duration or 0.0 for s in streams), default=0.0) or None
|
|
161
|
+
chapters = [
|
|
162
|
+
Chapter(
|
|
163
|
+
float(c.get("start_time", 0)),
|
|
164
|
+
float(c.get("end_time", 0)),
|
|
165
|
+
str(cast("Json", c.get("tags") or {}).get("title", "")),
|
|
166
|
+
)
|
|
167
|
+
for c in cast("list[Json]", d.get("chapters") or [])
|
|
168
|
+
]
|
|
169
|
+
return cls(
|
|
170
|
+
path=path,
|
|
171
|
+
duration=dur,
|
|
172
|
+
format=str(fmt.get("format_name", "")),
|
|
173
|
+
size=_num(fmt.get("size"), int),
|
|
174
|
+
bit_rate=_num(fmt.get("bit_rate"), int),
|
|
175
|
+
tags={str(k).lower(): str(v) for k, v in cast("Json", fmt.get("tags") or {}).items()},
|
|
176
|
+
streams=streams,
|
|
177
|
+
chapters=chapters,
|
|
178
|
+
warnings=warnings.strip(),
|
|
179
|
+
raw=d,
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
Run = Callable[..., "subprocess.CompletedProcess[Any]"]
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def probe(path: str | os.PathLike[str], *, timeout: float = 120, run: Run = subprocess.run) -> Probe:
|
|
187
|
+
"""Everything ffprobe says about a file: format, every stream, chapters and tags. MediaError when it cannot."""
|
|
188
|
+
p = os.fspath(path)
|
|
189
|
+
cmd = [
|
|
190
|
+
tool("ffprobe"),
|
|
191
|
+
"-v",
|
|
192
|
+
"warning",
|
|
193
|
+
"-print_format",
|
|
194
|
+
"json",
|
|
195
|
+
"-show_format",
|
|
196
|
+
"-show_streams",
|
|
197
|
+
"-show_chapters",
|
|
198
|
+
p,
|
|
199
|
+
]
|
|
200
|
+
try:
|
|
201
|
+
r = run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
|
202
|
+
except subprocess.TimeoutExpired:
|
|
203
|
+
raise MediaError(f"ffprobe took longer than {timeout:g} s on {p}") from None
|
|
204
|
+
except OSError as e:
|
|
205
|
+
raise MediaError(f"ffprobe could not start: {e}") from None
|
|
206
|
+
if r.returncode or not (r.stdout or "").strip():
|
|
207
|
+
raise MediaError(f"ffprobe cannot read {p}: {_tail(r.stderr) or f'exit {r.returncode}'}")
|
|
208
|
+
try:
|
|
209
|
+
d = json.loads(r.stdout)
|
|
210
|
+
except ValueError:
|
|
211
|
+
raise MediaError(f"ffprobe gave no JSON for {p}: {_tail(r.stdout, 200)}") from None
|
|
212
|
+
return Probe.from_json(p, d, r.stderr or "")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def duration(path: str | os.PathLike[str], *, timeout: float = 120, run: Run = subprocess.run) -> float:
|
|
216
|
+
"""The file's length in seconds; MediaError when ffprobe cannot tell."""
|
|
217
|
+
d = probe(path, timeout=timeout, run=run).duration
|
|
218
|
+
if d is None:
|
|
219
|
+
raise MediaError(f"ffprobe found no duration in {os.fspath(path)}")
|
|
220
|
+
return d
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def ffmpeg(
|
|
224
|
+
args: Sequence[str | os.PathLike[str]],
|
|
225
|
+
*,
|
|
226
|
+
input: bytes | None = None,
|
|
227
|
+
timeout: float | None = None,
|
|
228
|
+
progress: Callable[[float], None] | None = None,
|
|
229
|
+
level: str = "error",
|
|
230
|
+
cwd: str | None = None,
|
|
231
|
+
) -> bytes:
|
|
232
|
+
"""Run `ffmpeg -nostdin -hide_banner -v <level> -y <args>` and return its stdout (for `-f ... -` output).
|
|
233
|
+
`progress(seconds)` is called as output is written (from `-progress`); then stdout is not returned. MediaError with
|
|
234
|
+
the tail of stderr when it fails or passes `timeout`."""
|
|
235
|
+
exe = tool("ffmpeg")
|
|
236
|
+
base = [exe, "-hide_banner", "-v", level, "-y"]
|
|
237
|
+
if input is None:
|
|
238
|
+
base.insert(1, "-nostdin")
|
|
239
|
+
cmd = [*base, *(os.fspath(a) for a in args)]
|
|
240
|
+
if progress is None:
|
|
241
|
+
proc = subprocess.Popen( # noqa: S603 - our own ffmpeg command
|
|
242
|
+
cmd,
|
|
243
|
+
stdin=subprocess.DEVNULL if input is None else subprocess.PIPE,
|
|
244
|
+
stdout=subprocess.PIPE,
|
|
245
|
+
stderr=subprocess.PIPE,
|
|
246
|
+
cwd=cwd,
|
|
247
|
+
)
|
|
248
|
+
try:
|
|
249
|
+
out, err = proc.communicate(input, timeout=timeout)
|
|
250
|
+
except subprocess.TimeoutExpired:
|
|
251
|
+
_kill(proc)
|
|
252
|
+
raise MediaError(f"ffmpeg took longer than {timeout:g} s") from None
|
|
253
|
+
if proc.returncode:
|
|
254
|
+
raise MediaError(f"ffmpeg failed (exit {proc.returncode}): {_tail(err)}")
|
|
255
|
+
return out
|
|
256
|
+
return _with_progress([*base, "-progress", "pipe:1", "-nostats", *cmd[len(base) :]], progress, timeout, cwd, input)
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def _kill(proc: subprocess.Popen[bytes], reap: bool = True) -> None:
|
|
260
|
+
"""Stop ffmpeg and anything it started. On Windows a package manager's `ffmpeg.exe` is often a shim that starts the
|
|
261
|
+
real one; killing only the shim leaves the real one holding the pipes, and the read waits for ever."""
|
|
262
|
+
oslib.kill_tree(proc.pid, 9)
|
|
263
|
+
with contextlib.suppress(OSError):
|
|
264
|
+
proc.kill()
|
|
265
|
+
if reap: # the progress reader's threads read the pipes themselves
|
|
266
|
+
with contextlib.suppress(subprocess.TimeoutExpired, OSError, ValueError):
|
|
267
|
+
proc.communicate(timeout=10)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def _with_progress(
|
|
271
|
+
cmd: list[str], progress: Callable[[float], None], timeout: float | None, cwd: str | None, data: bytes | None
|
|
272
|
+
) -> bytes:
|
|
273
|
+
"""Read `-progress pipe:1` lines (`out_time_us=...`) and report seconds; stderr is drained on a thread so a chatty
|
|
274
|
+
ffmpeg cannot fill its pipe and stall."""
|
|
275
|
+
proc = subprocess.Popen( # noqa: S603 - our own ffmpeg command
|
|
276
|
+
cmd,
|
|
277
|
+
stdin=subprocess.DEVNULL if data is None else subprocess.PIPE,
|
|
278
|
+
stdout=subprocess.PIPE,
|
|
279
|
+
stderr=subprocess.PIPE,
|
|
280
|
+
cwd=cwd,
|
|
281
|
+
) # bytes, so the input can be written as it is
|
|
282
|
+
out, errs = proc.stdout, proc.stderr
|
|
283
|
+
if out is None or errs is None: # pragma: no cover - both are pipes above
|
|
284
|
+
raise MediaError("ffmpeg's output pipes did not open")
|
|
285
|
+
err: list[str] = []
|
|
286
|
+
drain = threading.Thread(target=lambda: err.append(errs.read().decode(errors="replace")), daemon=True)
|
|
287
|
+
drain.start()
|
|
288
|
+
if data is not None and proc.stdin is not None: # fed on a thread: ffmpeg reads input while it writes progress
|
|
289
|
+
feed_pipe = proc.stdin
|
|
290
|
+
|
|
291
|
+
def feed() -> None:
|
|
292
|
+
with contextlib.suppress(BrokenPipeError, OSError, ValueError):
|
|
293
|
+
feed_pipe.write(data)
|
|
294
|
+
with contextlib.suppress(OSError):
|
|
295
|
+
feed_pipe.close()
|
|
296
|
+
|
|
297
|
+
threading.Thread(target=feed, daemon=True).start()
|
|
298
|
+
fired = threading.Event()
|
|
299
|
+
|
|
300
|
+
def kill() -> None:
|
|
301
|
+
fired.set()
|
|
302
|
+
_kill(proc, reap=False)
|
|
303
|
+
|
|
304
|
+
timer = threading.Timer(timeout, kill) if timeout else None
|
|
305
|
+
if timer:
|
|
306
|
+
timer.start()
|
|
307
|
+
try:
|
|
308
|
+
for raw in out:
|
|
309
|
+
key, _, value = raw.decode(errors="replace").strip().partition("=")
|
|
310
|
+
if key in ("out_time_us", "out_time_ms"): # both are microseconds (out_time_ms is misnamed by ffmpeg)
|
|
311
|
+
us = _num(value, int)
|
|
312
|
+
if us is not None and us >= 0:
|
|
313
|
+
progress(us / 1e6)
|
|
314
|
+
code = proc.wait()
|
|
315
|
+
finally:
|
|
316
|
+
if timer:
|
|
317
|
+
timer.cancel()
|
|
318
|
+
drain.join(5)
|
|
319
|
+
if fired.is_set():
|
|
320
|
+
raise MediaError(f"ffmpeg took longer than {timeout:g} s")
|
|
321
|
+
if code:
|
|
322
|
+
raise MediaError(f"ffmpeg failed (exit {code}): {_tail(''.join(err))}")
|
|
323
|
+
return b""
|
strata_python/stats.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
"""The statistics the apps' rankings and evals share, so "95 % interval" and "strength" mean the same in every app.
|
|
2
|
+
|
|
3
|
+
strata-stills' arena and strata-models' evals each fit Bradley-Terry strengths to pairwise choices (both the MM
|
|
4
|
+
algorithm, 200 iterations; stills also fits the advantage of the picture shown on the left), and models has the
|
|
5
|
+
interval and test functions around it. This is one copy, in pure Python (no numpy), on the `contracts.Judgment` shape:
|
|
6
|
+
a vote is `(a, b, winner)` with `winner` in "a", "b", "tie".
|
|
7
|
+
|
|
8
|
+
fit = bradley_terry(votes, side=True) # Fit: .strengths {name: p} (geometric mean 1), .side (left-side odds)
|
|
9
|
+
fit.ratings() # on the Elo scale, the mean name 1500
|
|
10
|
+
intervals(votes, n=200) # {name: (low, high)} of the rating, a bootstrap over votes
|
|
11
|
+
head_to_head(votes) # {(a, b): [a wins, b wins, ties]}, names sorted
|
|
12
|
+
wilson(k, n) # (share, low, high)
|
|
13
|
+
mcnemar(a_right, b_right) # exact paired test: (only_a, only_b, p)
|
|
14
|
+
holm(pvalues) # Holm-adjusted, in the order given
|
|
15
|
+
votes_from(judgments) # Judgment rows (undone ones left out) as votes
|
|
16
|
+
|
|
17
|
+
A tie counts half a win each way. With `side=True`, P(a wins) = h·p_a / (h·p_a + p_b), `a` being the one shown first
|
|
18
|
+
(left): when the sides are drawn at random, h only takes the person's lean towards one side out of the strengths. A
|
|
19
|
+
name with no usable vote is not in the result. Fits and bootstraps are deterministic (a seed), so a report repeats."""
|
|
20
|
+
|
|
21
|
+
from __future__ import annotations
|
|
22
|
+
|
|
23
|
+
import math
|
|
24
|
+
import random
|
|
25
|
+
from collections.abc import Iterable, Sequence
|
|
26
|
+
from dataclasses import dataclass
|
|
27
|
+
from typing import Literal, Protocol
|
|
28
|
+
|
|
29
|
+
Winner = Literal["a", "b", "tie"]
|
|
30
|
+
Vote = tuple[str, str, str]
|
|
31
|
+
Z95 = 1.959963984540054
|
|
32
|
+
START = 1500.0
|
|
33
|
+
SCORE = {"a": 1.0, "b": 0.0, "tie": 0.5}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _Judgment(Protocol):
|
|
37
|
+
a: str
|
|
38
|
+
b: str
|
|
39
|
+
winner: str
|
|
40
|
+
undone_at: object
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def votes_from(judgments: Iterable[_Judgment]) -> list[Vote]:
|
|
44
|
+
"""`contracts.Judgment` rows (or anything with `a`, `b`, `winner`, `undone_at`) as votes, undone ones left out."""
|
|
45
|
+
return [(j.a, j.b, j.winner) for j in judgments if j.undone_at is None]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass
|
|
49
|
+
class Fit:
|
|
50
|
+
strengths: dict[str, float] # geometric mean 1
|
|
51
|
+
side: float = 1.0 # odds multiplier of the first-shown side; 1.0 = no lean
|
|
52
|
+
|
|
53
|
+
def ratings(self, start: float = START) -> dict[str, float]:
|
|
54
|
+
"""Strengths on the Elo scale: 400·log10(p) + start, so 400 points is 10:1 odds and the mean name is `start`."""
|
|
55
|
+
return {n: start + 400 * math.log10(p) for n, p in self.strengths.items()}
|
|
56
|
+
|
|
57
|
+
def p_beats(self, a: str, b: str) -> float:
|
|
58
|
+
"""The chance `a` is chosen over `b`, with no side lean."""
|
|
59
|
+
pa, pb = self.strengths[a], self.strengths[b]
|
|
60
|
+
return pa / (pa + pb)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _aggregate(votes: Iterable[Vote], exclude: frozenset[str]) -> dict[tuple[str, str], list[float]]:
|
|
64
|
+
"""(first, second) -> [games, score of first]: an iteration then costs the number of pairs, not of votes."""
|
|
65
|
+
agg: dict[tuple[str, str], list[float]] = {}
|
|
66
|
+
for a, b, winner in votes:
|
|
67
|
+
s = SCORE.get(winner)
|
|
68
|
+
if s is None or a == b or a in exclude or b in exclude:
|
|
69
|
+
continue
|
|
70
|
+
g = agg.setdefault((a, b), [0.0, 0.0])
|
|
71
|
+
g[0] += 1
|
|
72
|
+
g[1] += s
|
|
73
|
+
return agg
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
def bradley_terry(
|
|
77
|
+
votes: Iterable[Vote], *, side: bool = False, iters: int = 200, exclude: Iterable[str] = (), prior: float = 0.01
|
|
78
|
+
) -> Fit:
|
|
79
|
+
"""Bradley-Terry strengths by the MM algorithm. `prior` gives every name that much of a win, so a name that
|
|
80
|
+
lost every vote gets a small finite strength rather than zero (stills' arena uses 0.01). `exclude` drops the votes
|
|
81
|
+
about some names (a retired variant)."""
|
|
82
|
+
agg = _aggregate(votes, frozenset(exclude))
|
|
83
|
+
names = sorted({n for pair in agg for n in pair})
|
|
84
|
+
if not names:
|
|
85
|
+
return Fit({})
|
|
86
|
+
p, h = dict.fromkeys(names, 1.0), 1.0
|
|
87
|
+
first_score = sum(g[1] for g in agg.values())
|
|
88
|
+
for _ in range(iters):
|
|
89
|
+
wins, denom = dict.fromkeys(names, prior), dict.fromkeys(names, 1e-9)
|
|
90
|
+
for (a, b), (n, s) in agg.items():
|
|
91
|
+
d = h * p[a] + p[b]
|
|
92
|
+
wins[a] += s
|
|
93
|
+
wins[b] += n - s
|
|
94
|
+
denom[a] += n * h / d
|
|
95
|
+
denom[b] += n / d
|
|
96
|
+
q = {n: wins[n] / denom[n] for n in names}
|
|
97
|
+
g = math.exp(sum(math.log(x) for x in q.values()) / len(q))
|
|
98
|
+
new = {n: x / g for n, x in q.items()}
|
|
99
|
+
old_h = h
|
|
100
|
+
if side:
|
|
101
|
+
h = (first_score + prior) / (
|
|
102
|
+
sum(n * new[a] / (h * new[a] + new[b]) for (a, b), (n, _) in agg.items()) + prior
|
|
103
|
+
)
|
|
104
|
+
done = abs(h - old_h) <= 1e-9 * h and all(abs(new[n] - p[n]) <= 1e-9 * max(1.0, p[n]) for n in names)
|
|
105
|
+
p = new
|
|
106
|
+
if done:
|
|
107
|
+
break
|
|
108
|
+
return Fit(p, h)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def intervals(
|
|
112
|
+
votes: Sequence[Vote],
|
|
113
|
+
*,
|
|
114
|
+
n: int = 200,
|
|
115
|
+
level: float = 0.90,
|
|
116
|
+
side: bool = False,
|
|
117
|
+
exclude: Iterable[str] = (),
|
|
118
|
+
seed: int = 20261123,
|
|
119
|
+
) -> dict[str, tuple[float, float]]:
|
|
120
|
+
"""{name: (low, high)} of each Elo-scale rating over `n` resamples of the votes: how far to trust a gap. The
|
|
121
|
+
default 90 % matches the arena's 5th and 95th percentiles."""
|
|
122
|
+
if not votes:
|
|
123
|
+
return {}
|
|
124
|
+
rng = random.Random(seed) # noqa: S311 - resampling, not secrets; seeded so a report repeats
|
|
125
|
+
skip = frozenset(exclude)
|
|
126
|
+
runs = [
|
|
127
|
+
bradley_terry([votes[rng.randrange(len(votes))] for _ in votes], side=side, iters=60, exclude=skip).ratings()
|
|
128
|
+
for _ in range(n)
|
|
129
|
+
]
|
|
130
|
+
lo_q = (1 - level) / 2
|
|
131
|
+
out: dict[str, tuple[float, float]] = {}
|
|
132
|
+
for name in bradley_terry(votes, side=side, exclude=skip).strengths:
|
|
133
|
+
xs = sorted(r[name] for r in runs if name in r)
|
|
134
|
+
if xs:
|
|
135
|
+
out[name] = (_quantile(xs, lo_q), _quantile(xs, 1 - lo_q))
|
|
136
|
+
return out
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _quantile(sorted_xs: Sequence[float], q: float) -> float:
|
|
140
|
+
"""Linear interpolation between order statistics (numpy's default), so this agrees with the numpy versions."""
|
|
141
|
+
pos = q * (len(sorted_xs) - 1)
|
|
142
|
+
i = math.floor(pos)
|
|
143
|
+
j = min(i + 1, len(sorted_xs) - 1)
|
|
144
|
+
return sorted_xs[i] + (sorted_xs[j] - sorted_xs[i]) * (pos - i)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def head_to_head(votes: Iterable[Vote]) -> dict[tuple[str, str], list[int]]:
|
|
148
|
+
"""{(x, y): [x wins, y wins, ties]} over unordered pairs, the names sorted."""
|
|
149
|
+
out: dict[tuple[str, str], list[int]] = {}
|
|
150
|
+
for a, b, winner in votes:
|
|
151
|
+
if winner not in SCORE or a == b:
|
|
152
|
+
continue
|
|
153
|
+
x, y = sorted((a, b))
|
|
154
|
+
row = out.setdefault((x, y), [0, 0, 0])
|
|
155
|
+
if winner == "tie":
|
|
156
|
+
row[2] += 1
|
|
157
|
+
else:
|
|
158
|
+
row[0 if (winner == "a") == (a == x) else 1] += 1
|
|
159
|
+
return out
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def wilson(k: int, n: int, z: float = Z95) -> tuple[float, float, float]:
|
|
163
|
+
"""(share, low, high) for `k` successes in `n` trials: the Wilson score interval, right near 0 and 1 where the
|
|
164
|
+
normal approximation is not. NaNs for n = 0."""
|
|
165
|
+
if n == 0:
|
|
166
|
+
return (math.nan, math.nan, math.nan)
|
|
167
|
+
p = k / n
|
|
168
|
+
d = 1 + z * z / n
|
|
169
|
+
c = (p + z * z / (2 * n)) / d
|
|
170
|
+
h = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / d
|
|
171
|
+
return p, max(0.0, c - h), min(1.0, c + h)
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def mcnemar(a_right: Iterable[bool], b_right: Iterable[bool]) -> tuple[int, int, float]:
|
|
175
|
+
"""Exact McNemar test for two candidates' right/wrong on the same items: (only a right, only b right, two-sided p
|
|
176
|
+
from the binomial on the discordant pairs)."""
|
|
177
|
+
only_a = only_b = 0
|
|
178
|
+
for x, y in zip(a_right, b_right, strict=True):
|
|
179
|
+
only_a += bool(x and not y)
|
|
180
|
+
only_b += bool(y and not x)
|
|
181
|
+
n = only_a + only_b
|
|
182
|
+
if n == 0:
|
|
183
|
+
return 0, 0, 1.0
|
|
184
|
+
tail = sum(math.comb(n, i) for i in range(min(only_a, only_b) + 1)) / 2**n
|
|
185
|
+
return only_a, only_b, min(1.0, 2 * tail)
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def holm(pvalues: Sequence[float]) -> list[float]:
|
|
189
|
+
"""Holm's step-down adjustment of several comparisons' p values, returned in the order given (NaN stays NaN)."""
|
|
190
|
+
order = sorted((i for i, p in enumerate(pvalues) if not math.isnan(p)), key=lambda i: pvalues[i])
|
|
191
|
+
out = list(pvalues)
|
|
192
|
+
running = 0.0
|
|
193
|
+
for rank, i in enumerate(order):
|
|
194
|
+
running = max(running, min(1.0, (len(order) - rank) * pvalues[i]))
|
|
195
|
+
out[i] = running
|
|
196
|
+
return out
|
strata_python/tasks/__init__.py
CHANGED
|
@@ -10,10 +10,11 @@ queue built on them.
|
|
|
10
10
|
"""
|
|
11
11
|
|
|
12
12
|
from strata_python.contracts import Progress
|
|
13
|
+
from strata_python.files import write_json_atomic
|
|
13
14
|
from strata_python.tasks.flight import Conflict, Flight, SingleFlight
|
|
14
15
|
from strata_python.tasks.progress import ProgressReporter, report_progress, reporting
|
|
15
16
|
from strata_python.tasks.retry import PROGRAMMING_ERRORS, Decision, RetryLater, backoff_s, describe, next_state
|
|
16
|
-
from strata_python.tasks.status import Detached, StatusFile
|
|
17
|
+
from strata_python.tasks.status import Detached, StatusFile
|
|
17
18
|
from strata_python.tasks.ticker import Ticker
|
|
18
19
|
|
|
19
20
|
__all__ = [
|
strata_python/tasks/status.py
CHANGED
|
@@ -26,32 +26,17 @@ import datetime
|
|
|
26
26
|
import json
|
|
27
27
|
import os
|
|
28
28
|
import subprocess
|
|
29
|
-
import tempfile
|
|
30
29
|
from collections.abc import Generator, Mapping, Sequence
|
|
31
30
|
from typing import Any, cast
|
|
32
31
|
|
|
33
32
|
from strata_python import oslib
|
|
33
|
+
from strata_python.files import write_json_atomic
|
|
34
34
|
from strata_python.tasks.flight import Conflict
|
|
35
35
|
|
|
36
36
|
ENV = "STRATA_STATUS_FILE"
|
|
37
37
|
Json = dict[str, Any]
|
|
38
38
|
|
|
39
39
|
|
|
40
|
-
def write_json_atomic(path: str, data: object) -> None:
|
|
41
|
-
"""Write JSON so a reader sees the old file or the new one, never half of either."""
|
|
42
|
-
folder = os.path.dirname(os.path.abspath(path))
|
|
43
|
-
os.makedirs(folder, exist_ok=True)
|
|
44
|
-
fd, tmp = tempfile.mkstemp(dir=folder, prefix=".status.", suffix=".tmp")
|
|
45
|
-
try:
|
|
46
|
-
with os.fdopen(fd, "w", encoding="utf8") as f:
|
|
47
|
-
json.dump(data, f, indent=1, default=str)
|
|
48
|
-
os.replace(tmp, path)
|
|
49
|
-
except BaseException:
|
|
50
|
-
with contextlib.suppress(OSError):
|
|
51
|
-
os.unlink(tmp)
|
|
52
|
-
raise
|
|
53
|
-
|
|
54
|
-
|
|
55
40
|
class StatusFile:
|
|
56
41
|
def __init__(self, path: str) -> None:
|
|
57
42
|
self.path = path
|