strata-python 0.2.4__py3-none-any.whl → 0.2.6__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/cli.py +45 -2
- strata_python/contracts.py +9 -0
- strata_python/db/__init__.py +7 -1
- strata_python/db/cli.py +23 -9
- strata_python/db/config.py +28 -4
- strata_python/db/engine.py +4 -0
- strata_python/db/project.py +58 -7
- strata_python/db/web.py +103 -0
- 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/public_check.py +122 -19
- strata_python/settings.py +99 -25
- strata_python/stats.py +196 -0
- strata_python/tasks/__init__.py +2 -1
- strata_python/tasks/status.py +1 -16
- strata_python/testing.py +13 -0
- strata_python/web.py +10 -1
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/METADATA +84 -21
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/RECORD +24 -18
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/WHEEL +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/entry_points.txt +0 -0
- {strata_python-0.2.4.dist-info → strata_python-0.2.6.dist-info}/licenses/LICENSE +0 -0
strata_python/settings.py
CHANGED
|
@@ -5,6 +5,7 @@ An app declares its settings once (`Setting`: key, default, optional normaliser)
|
|
|
5
5
|
SETTINGS = Settings("myapp", [Setting("data_dir", default=lambda: "/srv/data", normalise=absolute_path),
|
|
6
6
|
Setting("greeting", default="Hello", normalise=non_empty),
|
|
7
7
|
Setting("workers", default="2", normalise=whole_between(1, 16)),
|
|
8
|
+
Setting("mode", default="mixed", choices=["mixed", "review", "new"]),
|
|
8
9
|
ListSetting("source_roots", item=absolute_path)])
|
|
9
10
|
SETTINGS.get("greeting") # MYAPP_GREETING, else the file, else the default
|
|
10
11
|
SETTINGS.get_int("workers") # typed getters: get_int, get_float, get_bool, get_list
|
|
@@ -14,6 +15,11 @@ Order of precedence: environment variable (`<APP>_<KEY>`, upper-cased, or the na
|
|
|
14
15
|
with `<APP>_HOME`. A stored or environment value that fails its normaliser is ignored (the default applies) rather than crashing the app at start; only `save` raises.
|
|
15
16
|
Values are canonical strings (a normaliser returns the one spelling it accepts), and lists of them: the file is edited by hand as well as by the app.
|
|
16
17
|
|
|
18
|
+
`Settings.model()` describes them for `/api/openapi.json`: a setting with `choices` (or `normalise=one_of(...)`) is a
|
|
19
|
+
`Literal` of them, so the schema has an `enum` and the web app's generated type is the union. `Settings(...,
|
|
20
|
+
numbers=True)` also sends `whole_between` and `number_between` settings as JSON numbers with their range in the schema.
|
|
21
|
+
It is off by default because it changes what `GET /api/settings` sends, so an app turns it on with its web app.
|
|
22
|
+
|
|
17
23
|
Where the values live is a `SettingsStore`: the JSON file by default; `Settings.bind(store)` moves an app onto another one at run time (its database's `settings` table,
|
|
18
24
|
`strata_python.db.settings.TableStore`), copying the file's values in once. The CLI and tests without a database keep the file."""
|
|
19
25
|
|
|
@@ -26,7 +32,7 @@ import tempfile
|
|
|
26
32
|
import threading
|
|
27
33
|
from collections.abc import Callable, Mapping, Sequence
|
|
28
34
|
from dataclasses import dataclass
|
|
29
|
-
from typing import Any, Protocol, cast
|
|
35
|
+
from typing import Any, Literal, Protocol, cast
|
|
30
36
|
|
|
31
37
|
from strata_python.oslib import file_lock
|
|
32
38
|
|
|
@@ -47,34 +53,61 @@ def absolute_path(value: str) -> str:
|
|
|
47
53
|
return os.path.abspath(p)
|
|
48
54
|
|
|
49
55
|
|
|
50
|
-
|
|
51
|
-
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class number_between: # lower case: used as a normaliser function, and was one before it carried its range
|
|
58
|
+
"""Normaliser: a finite number from `lo` to `hi` (GB of memory, a budget in dollars), written the shortest way
|
|
59
|
+
(`"8"`, `"8.5"`). Its range is visible, so `Settings(numbers=True)` puts it in the schema."""
|
|
52
60
|
|
|
53
|
-
|
|
61
|
+
lo: float
|
|
62
|
+
hi: float
|
|
63
|
+
|
|
64
|
+
def __call__(self, value: str) -> str:
|
|
54
65
|
try:
|
|
55
66
|
x = float(value.strip())
|
|
56
67
|
except ValueError:
|
|
57
68
|
raise ValueError("must be a number") from None
|
|
58
|
-
if not math.isfinite(x) or not lo <= x <= hi:
|
|
59
|
-
raise ValueError(f"must be a number from {_num(lo)} to {_num(hi)}")
|
|
69
|
+
if not math.isfinite(x) or not self.lo <= x <= self.hi:
|
|
70
|
+
raise ValueError(f"must be a number from {_num(self.lo)} to {_num(self.hi)}")
|
|
60
71
|
return _num(x)
|
|
61
72
|
|
|
62
|
-
return normalise
|
|
63
73
|
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class whole_between: # lower case: as number_between
|
|
76
|
+
"""Normaliser: a whole number from `lo` to `hi` (job slots, a port). Its range is visible, so
|
|
77
|
+
`Settings(numbers=True)` puts it in the schema."""
|
|
64
78
|
|
|
65
|
-
|
|
66
|
-
|
|
79
|
+
lo: int
|
|
80
|
+
hi: int
|
|
67
81
|
|
|
68
|
-
def
|
|
82
|
+
def __call__(self, value: str) -> str:
|
|
69
83
|
try:
|
|
70
84
|
x = int(value.strip())
|
|
71
85
|
except ValueError:
|
|
72
86
|
raise ValueError("must be a whole number") from None
|
|
73
|
-
if not lo <= x <= hi:
|
|
74
|
-
raise ValueError(f"must be a whole number from {lo} to {hi}")
|
|
87
|
+
if not self.lo <= x <= self.hi:
|
|
88
|
+
raise ValueError(f"must be a whole number from {self.lo} to {self.hi}")
|
|
75
89
|
return str(x)
|
|
76
90
|
|
|
77
|
-
|
|
91
|
+
|
|
92
|
+
@dataclass(frozen=True)
|
|
93
|
+
class one_of: # lower case: as number_between
|
|
94
|
+
"""Normaliser: one of `choices`, matched without regard to case and surrounding space and returned as the choice
|
|
95
|
+
is spelled; anything else is refused with the list. `Setting(choices=...)` is the short form. `Settings.model()`
|
|
96
|
+
sees the choices and types the setting as a `Literal` of them."""
|
|
97
|
+
|
|
98
|
+
choices: tuple[str, ...]
|
|
99
|
+
|
|
100
|
+
def __init__(self, choices: Sequence[str]) -> None:
|
|
101
|
+
if not choices:
|
|
102
|
+
raise ValueError("one_of needs at least one choice")
|
|
103
|
+
object.__setattr__(self, "choices", tuple(choices))
|
|
104
|
+
|
|
105
|
+
def __call__(self, value: str) -> str:
|
|
106
|
+
v = value.strip().casefold()
|
|
107
|
+
for choice in self.choices:
|
|
108
|
+
if choice.casefold() == v:
|
|
109
|
+
return choice
|
|
110
|
+
raise ValueError(f"must be one of {', '.join(self.choices)}")
|
|
78
111
|
|
|
79
112
|
|
|
80
113
|
_DATE = re.compile(r"\d{4}-\d{2}-\d{2}")
|
|
@@ -120,10 +153,18 @@ def _identity(value: str) -> str:
|
|
|
120
153
|
|
|
121
154
|
@dataclass(frozen=True)
|
|
122
155
|
class Setting:
|
|
156
|
+
"""One setting. `normalise` turns a value into its one spelling or raises ValueError; `choices` limits it to a
|
|
157
|
+
fixed set (`one_of`, applied after `normalise`), which `set` shows and the API schema types as an enum."""
|
|
158
|
+
|
|
123
159
|
key: str
|
|
124
160
|
default: str | Callable[[], str]
|
|
125
161
|
normalise: Callable[[str], str] = _identity
|
|
126
162
|
env: str | None = None # environment variable; default `<APP>_<KEY>`
|
|
163
|
+
choices: Sequence[str] | None = None
|
|
164
|
+
|
|
165
|
+
def __post_init__(self) -> None:
|
|
166
|
+
if self.choices is not None:
|
|
167
|
+
object.__setattr__(self, "choices", one_of(self.choices).choices) # a tuple, and refuses an empty list
|
|
127
168
|
|
|
128
169
|
def default_value(self) -> str:
|
|
129
170
|
d = self.default
|
|
@@ -133,7 +174,15 @@ class Setting:
|
|
|
133
174
|
"""A stored, environment or saved value as its canonical string; ValueError when it is not acceptable."""
|
|
134
175
|
if not isinstance(raw, str):
|
|
135
176
|
raise ValueError("must be text") # str(5) would pass a hand-edited number off as a deliberate string
|
|
136
|
-
|
|
177
|
+
v = self.normalise(raw)
|
|
178
|
+
return v if self.choices is None else one_of(self.choices)(v)
|
|
179
|
+
|
|
180
|
+
def allowed(self) -> tuple[str, ...] | None:
|
|
181
|
+
"""The fixed set of values, from `choices` or a `one_of` normaliser, else None."""
|
|
182
|
+
if self.choices is not None:
|
|
183
|
+
return tuple(self.choices)
|
|
184
|
+
n = self.normalise
|
|
185
|
+
return n.choices if isinstance(n, one_of) else None
|
|
137
186
|
|
|
138
187
|
|
|
139
188
|
def _no_list() -> list[str]:
|
|
@@ -231,11 +280,19 @@ class JsonFileStore:
|
|
|
231
280
|
|
|
232
281
|
class Settings:
|
|
233
282
|
def __init__(
|
|
234
|
-
self,
|
|
283
|
+
self,
|
|
284
|
+
app: str,
|
|
285
|
+
settings: Sequence[AnySetting],
|
|
286
|
+
*,
|
|
287
|
+
prefix: str | None = None,
|
|
288
|
+
store: SettingsStore | None = None,
|
|
289
|
+
numbers: bool = False,
|
|
235
290
|
) -> None:
|
|
236
291
|
"""`prefix` names the environment variables (`<PREFIX>_HOME`, `<PREFIX>_<KEY>`); default the upper-cased app name with `-` as `_`.
|
|
237
|
-
Give it when an app's variables already have a short form that deployed services use. `store` is where values live (default: the JSON file).
|
|
292
|
+
Give it when an app's variables already have a short form that deployed services use. `store` is where values live (default: the JSON file).
|
|
293
|
+
`numbers=True` makes `model()` type `whole_between`/`number_between` settings as numbers (see the module notes)."""
|
|
238
294
|
self.app = app
|
|
295
|
+
self.numbers = numbers
|
|
239
296
|
self.prefix = prefix or app.upper().replace("-", "_")
|
|
240
297
|
self._by_key: dict[str, AnySetting] = {s.key: s for s in settings}
|
|
241
298
|
self.file = JsonFileStore(self.path)
|
|
@@ -308,6 +365,11 @@ class Settings:
|
|
|
308
365
|
s = self._by_key[key]
|
|
309
366
|
return s.sep.join(v) if isinstance(s, ListSetting) and isinstance(v, list) else cast("str", v)
|
|
310
367
|
|
|
368
|
+
def allowed(self, key: str) -> tuple[str, ...] | None:
|
|
369
|
+
"""The values setting `key` may take, when it has a fixed set (`choices` or `one_of`), else None."""
|
|
370
|
+
s = self._by_key[key]
|
|
371
|
+
return s.allowed() if isinstance(s, Setting) else None
|
|
372
|
+
|
|
311
373
|
def get_list(self, key: str) -> list[str]:
|
|
312
374
|
s = self._by_key[key]
|
|
313
375
|
if not isinstance(s, ListSetting):
|
|
@@ -327,18 +389,30 @@ class Settings:
|
|
|
327
389
|
return {k: self.value(k) for k in self._by_key}
|
|
328
390
|
|
|
329
391
|
def model(self) -> type[Any]:
|
|
330
|
-
"""The settings as a pydantic model
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
a
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
}
|
|
392
|
+
"""The settings as a pydantic model, named `<App>Settings`: a field per setting, `str` (a `Literal` of its
|
|
393
|
+
choices when it has them; with `numbers=True`, `int` or `float` with its range for `whole_between` and
|
|
394
|
+
`number_between`), or `list[str]` for a `ListSetting`. `web.base_app` declares it as the settings routes'
|
|
395
|
+
response, so `/api/openapi.json` describes each setting and a web app's types can be generated from it. Built
|
|
396
|
+
on each call; pydantic is imported here, so a CLI that only reads settings does not load it."""
|
|
397
|
+
from pydantic import Field, create_model
|
|
398
|
+
|
|
399
|
+
fields: dict[str, Any] = {k: self._field(s, Field) for k, s in self._by_key.items()}
|
|
339
400
|
name = "".join(p.capitalize() for p in re.split(r"[^0-9A-Za-z]+", self.app) if p) + "Settings"
|
|
340
401
|
return create_model(name, **fields)
|
|
341
402
|
|
|
403
|
+
def _field(self, s: AnySetting, field: Callable[..., Any]) -> tuple[Any, Any]:
|
|
404
|
+
if isinstance(s, ListSetting):
|
|
405
|
+
return list[str], ...
|
|
406
|
+
allowed = s.allowed()
|
|
407
|
+
if allowed is not None:
|
|
408
|
+
return Literal[allowed], ... # pyright: ignore[reportInvalidTypeForm] - a Literal built at run time # ty: ignore[invalid-type-form]
|
|
409
|
+
n = s.normalise
|
|
410
|
+
if self.numbers and isinstance(n, whole_between):
|
|
411
|
+
return int, field(..., ge=n.lo, le=n.hi)
|
|
412
|
+
if self.numbers and isinstance(n, number_between):
|
|
413
|
+
return float, field(..., ge=n.lo, le=n.hi)
|
|
414
|
+
return str, ...
|
|
415
|
+
|
|
342
416
|
def folder(self, key: str) -> str:
|
|
343
417
|
"""The setting `key` as a folder that exists (created when asked for)."""
|
|
344
418
|
p = self.get(key)
|
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
|
strata_python/testing.py
CHANGED
|
@@ -15,6 +15,7 @@ Testing policy).
|
|
|
15
15
|
FakeRun `subprocess.run` / `check_output`; `.returns` maps a command-line substring to stdout, `.code` fails
|
|
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
|
+
assert_openapi_current the committed schema file equals what the app answers now (cli.add_openapi writes it)
|
|
18
19
|
FakeModels a stand-in strata-models service (jobs, leases, registry) for `strata_python.clients.models`; served
|
|
19
20
|
by the `fake_models` fixture. MODELS_RESULTS holds one reply per role in the service's shapes.
|
|
20
21
|
"""
|
|
@@ -301,6 +302,18 @@ for _role in ("text", "judge-text", "judge-vision", "judge-audio"):
|
|
|
301
302
|
MODELS_RESULTS[_role] = MODELS_RESULTS["vision-language"]
|
|
302
303
|
|
|
303
304
|
|
|
305
|
+
def assert_openapi_current(create_app: Callable[[], Any], path: str | os.PathLike[str]) -> None:
|
|
306
|
+
"""Fail, with the command to run, when the committed OpenAPI file at `path` is not what `create_app()` answers
|
|
307
|
+
now: the unit test every app with generated web types writes."""
|
|
308
|
+
from strata_python.web import openapi_text # FastAPI only when asked
|
|
309
|
+
|
|
310
|
+
file = Path(path)
|
|
311
|
+
current = file.read_text(encoding="utf-8") if file.is_file() else None
|
|
312
|
+
if current != openapi_text(create_app()):
|
|
313
|
+
state = "missing" if current is None else "out of date"
|
|
314
|
+
raise AssertionError(f"{file} is {state}: run the app's `openapi` command and commit the file")
|
|
315
|
+
|
|
316
|
+
|
|
304
317
|
class FakeModels:
|
|
305
318
|
"""A stand-in strata-models service for an app's tests, over real HTTP: the `fake_models` fixture serves `.app` on
|
|
306
319
|
a loopback port and points `STRATA_MODELS_URL` at it, so the app's own calls through `strata_python.clients.models`
|
strata_python/web.py
CHANGED
|
@@ -13,6 +13,7 @@ assets are relative (Vite `base: './'`)."""
|
|
|
13
13
|
import argparse
|
|
14
14
|
import concurrent.futures
|
|
15
15
|
import datetime
|
|
16
|
+
import json
|
|
16
17
|
import os
|
|
17
18
|
import platform
|
|
18
19
|
import shutil
|
|
@@ -82,7 +83,8 @@ def base_app(
|
|
|
82
83
|
return settings.all()
|
|
83
84
|
|
|
84
85
|
@app.put("/api/settings", response_model=shape)
|
|
85
|
-
|
|
86
|
+
# numbers too: with Settings(numbers=True) the web app sends back the numbers GET gave it; save() takes str(n)
|
|
87
|
+
def put_settings(changes: dict[str, str | int | float | list[str] | None]) -> dict[str, str | list[str]]: # pyright: ignore[reportUnusedFunction]
|
|
86
88
|
try:
|
|
87
89
|
settings.save(changes)
|
|
88
90
|
except (KeyError, ValueError) as e:
|
|
@@ -92,6 +94,13 @@ def base_app(
|
|
|
92
94
|
return app
|
|
93
95
|
|
|
94
96
|
|
|
97
|
+
def openapi_text(app: FastAPI) -> str:
|
|
98
|
+
"""The app's OpenAPI schema as the text an app commits for strata-react's `strata-api-types`: sorted keys, indent 1,
|
|
99
|
+
non-ASCII kept, a final newline, so two runs and a git diff compare like with like. Nothing in it comes from the
|
|
100
|
+
machine or the moment; `base_app`'s version is in `info.version`, so a release changes the file as it should."""
|
|
101
|
+
return json.dumps(app.openapi(), indent=1, sort_keys=True, ensure_ascii=False) + "\n"
|
|
102
|
+
|
|
103
|
+
|
|
95
104
|
def source_commit(path: str) -> str | None:
|
|
96
105
|
"""The git commit of the checkout that holds `path` (pass `__file__`), read from `.git` without running git, or
|
|
97
106
|
None outside a checkout (an installed wheel). A worktree's `.git` file and packed refs are followed."""
|