idia 0.3.0__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.
idia/answers.py ADDED
@@ -0,0 +1,336 @@
1
+ """Answer validation: the rules a mapped answer passes before it enters a wire response.
2
+
3
+ A leaf calls :func:`validate_answers` after mapping the wire's output to each kind's shape,
4
+ with the rounding it declares. Every rule for the kind is run; an answer that passes is
5
+ returned unchanged, and one that fails becomes a :class:`~idia.core.Fault` naming every
6
+ rule it broke. Nothing is renormalized, rounded or corrected.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import datetime
12
+ import math
13
+ from collections.abc import Mapping, Sequence
14
+ from types import MappingProxyType
15
+
16
+ from idia.core import (
17
+ WARNING_CHOSEN_BELOW_MAX,
18
+ WARNING_EXTRA_ANSWER_KEY,
19
+ Answer,
20
+ BoxAnswer,
21
+ ExtractionAnswer,
22
+ Fault,
23
+ LabelAnswer,
24
+ MappedAnswer,
25
+ Notice,
26
+ NoulAnswer,
27
+ Question,
28
+ Refusal,
29
+ Rounding,
30
+ Rule,
31
+ RuleFailure,
32
+ Value,
33
+ )
34
+
35
+
36
+ def validate(question: Question, mapped: MappedAnswer, rounding: Rounding) -> Answer | Fault:
37
+ """Run every rule for the question's kind over one mapped answer.
38
+
39
+ A fault or refusal the leaf built passes through as it is; a fault keyed to another
40
+ question is a leaf bug and raises ``ValueError``. Any other answer comes back
41
+ unchanged when every rule passes, or as a fault recording the key, every failed rule with
42
+ its observed value and bound, and the answer as mapped.
43
+ """
44
+ if isinstance(mapped, Fault):
45
+ if mapped.key != question.key:
46
+ raise ValueError(
47
+ f"fault for key {mapped.key!r} was handed to question {question.key!r}"
48
+ )
49
+ return mapped
50
+ if isinstance(mapped, Refusal):
51
+ return mapped
52
+ failures = _failures(question, mapped, rounding)
53
+ if not failures:
54
+ return mapped
55
+ return Fault(key=question.key, failures=tuple(failures), mapped=mapped)
56
+
57
+
58
+ def validate_answers(
59
+ questions: Sequence[Question],
60
+ mapped: Mapping[str, MappedAnswer],
61
+ rounding: Rounding,
62
+ ) -> tuple[Mapping[str, Answer | Fault], tuple[Notice, ...]]:
63
+ """Validate a map of answers against the questions asked.
64
+
65
+ A question whose key is absent is a fault; a key with no question is dropped with an
66
+ ``extra-answer-key`` warning; every other entry goes through :func:`validate` once. A
67
+ label answer that stands with its chosen label below the highest probability, by at most
68
+ one rounding step, adds a ``chosen-below-max`` warning naming the key. The answers come
69
+ back keyed in question order.
70
+ """
71
+ answers: dict[str, Answer | Fault] = {}
72
+ for question in questions:
73
+ answer = mapped.get(question.key)
74
+ if answer is None:
75
+ failure = RuleFailure(rule=Rule.missing_key, observed=None, bound=None)
76
+ answers[question.key] = Fault(key=question.key, failures=(failure,), mapped=None)
77
+ else:
78
+ answers[question.key] = validate(question, answer, rounding)
79
+ asked = {question.key for question in questions}
80
+ warnings = tuple(
81
+ Notice(
82
+ code=WARNING_EXTRA_ANSWER_KEY,
83
+ message=f"answer key {key!r} matches no question and was dropped",
84
+ field=key,
85
+ )
86
+ for key in mapped
87
+ if key not in asked
88
+ )
89
+ below = tuple(
90
+ warning
91
+ for key, answer in answers.items()
92
+ if (warning := _chosen_below_max(key, answer)) is not None
93
+ )
94
+ return MappingProxyType(answers), below + warnings
95
+
96
+
97
+ def _chosen_below_max(key: str, answer: Answer | Fault) -> Notice | None:
98
+ """The warning for a label answer that stands with its chosen label below the highest
99
+ probability, which the chosen-label rule tolerates by one rounding step."""
100
+ if not isinstance(answer, LabelAnswer) or answer.chosen is None:
101
+ return None
102
+ by_name = dict(answer.probabilities)
103
+ highest = max(by_name.values(), default=0.0)
104
+ chosen = by_name.get(answer.chosen)
105
+ if chosen is None or chosen >= highest:
106
+ return None
107
+ top = next(name for name, probability in answer.probabilities if probability == highest)
108
+ return Notice(
109
+ code=WARNING_CHOSEN_BELOW_MAX,
110
+ message=(
111
+ f"question {key!r}: the chosen label {answer.chosen!r} at {chosen} is below "
112
+ f"{top!r} at {highest}, "
113
+ "within one rounding step; the chosen label stands as given"
114
+ ),
115
+ field=key,
116
+ )
117
+
118
+
119
+ # ----------------------------------------------------------------------------------------
120
+ # The rules
121
+ # ----------------------------------------------------------------------------------------
122
+
123
+
124
+ def _failures(question: Question, mapped: Answer, rounding: Rounding) -> list[RuleFailure]:
125
+ kind = question.kind
126
+ if kind == "noul":
127
+ if not isinstance(mapped, NoulAnswer):
128
+ return [_wrong_shape(mapped)]
129
+ return _noul_failures(mapped)
130
+ if kind in ("choice", "score"):
131
+ if not isinstance(mapped, LabelAnswer):
132
+ return [_wrong_shape(mapped)]
133
+ return _label_failures(question, mapped, rounding)
134
+ if kind == "extraction":
135
+ if not isinstance(mapped, ExtractionAnswer):
136
+ return [_wrong_shape(mapped)]
137
+ return _extraction_failures(question, mapped)
138
+ if not isinstance(mapped, BoxAnswer):
139
+ return [_wrong_shape(mapped)]
140
+ return _box_failures(mapped)
141
+
142
+
143
+ def _wrong_shape(mapped: Answer) -> RuleFailure:
144
+ return RuleFailure(rule=Rule.kind_shape, observed=type(mapped).__name__, bound=None)
145
+
146
+
147
+ def _not_a_number(value: object) -> str | None:
148
+ """What a value that cannot be judged as a number is observed as: its type's name when
149
+ it is not an int or a float, or is a bool; ``int beyond float`` for an int too large
150
+ for a float; ``None`` for a number."""
151
+ if not isinstance(value, int | float) or isinstance(value, bool):
152
+ return type(value).__name__
153
+ try:
154
+ float(value)
155
+ except OverflowError:
156
+ return "int beyond float"
157
+ return None
158
+
159
+
160
+ def _is_number(value: object) -> bool:
161
+ """Whether ``value`` is an int or a float, not a bool, that a float can hold."""
162
+ return _not_a_number(value) is None
163
+
164
+
165
+ def _unit_interval(value: float, rule: Rule) -> list[RuleFailure]:
166
+ """``not_finite`` when the value is not a number (a bool is not one, nor an int too large
167
+ for a float) or not finite, else ``rule`` when it is outside [0, 1]. A value that is not
168
+ a number is observed as its type's name, or as ``int beyond float``."""
169
+ observed = _not_a_number(value)
170
+ if observed is not None:
171
+ return [RuleFailure(rule=Rule.not_finite, observed=observed, bound=None)]
172
+ if not math.isfinite(value):
173
+ return [RuleFailure(rule=Rule.not_finite, observed=value, bound=None)]
174
+ if value < 0.0:
175
+ return [RuleFailure(rule=rule, observed=value, bound=0.0)]
176
+ if value > 1.0:
177
+ return [RuleFailure(rule=rule, observed=value, bound=1.0)]
178
+ return []
179
+
180
+
181
+ def _confidence(confidence: float | None) -> list[RuleFailure]:
182
+ if confidence is None:
183
+ return []
184
+ return _unit_interval(confidence, Rule.confidence_range)
185
+
186
+
187
+ def _noul_failures(answer: NoulAnswer) -> list[RuleFailure]:
188
+ return _unit_interval(answer.probability, Rule.probability_range) + _confidence(
189
+ answer.confidence
190
+ )
191
+
192
+
193
+ def _step(decimals: int | None) -> float:
194
+ """How far below the highest probability a chosen label may lie: one rounding step,
195
+ since a provider may round after it chooses, plus the float slack the sum allows."""
196
+ return 1e-6 + (10.0**-decimals if decimals is not None else 0.0)
197
+
198
+
199
+ def _sum_tolerance(n: int, decimals: int | None) -> float:
200
+ return 1e-6 + (n * 0.5 * 10.0**-decimals if decimals is not None else 0.0)
201
+
202
+
203
+ def _expected_level_bound(n: int, rounding: Rounding) -> float:
204
+ s = rounding.score_decimals
205
+ d = rounding.probability_decimals
206
+ return (
207
+ 1e-6
208
+ + (0.5 * 10.0**-s if s is not None else 0.0)
209
+ + (0.5 * 10.0**-d * n * (n - 1) / 2 if d is not None else 0.0)
210
+ )
211
+
212
+
213
+ def _label_failures(
214
+ question: Question, answer: LabelAnswer, rounding: Rounding
215
+ ) -> list[RuleFailure]:
216
+ failures: list[RuleFailure] = []
217
+ asked = tuple(label.name for label in question.labels)
218
+ names = tuple(name for name, _ in answer.probabilities)
219
+ if names != asked:
220
+ failures.append(
221
+ RuleFailure(rule=Rule.labels_mismatch, observed=",".join(names), bound=None)
222
+ )
223
+ if answer.echo is not None:
224
+ # A level with no description is sent as its name, and the wire echoes that back.
225
+ expected = (
226
+ tuple(
227
+ label.description if label.description is not None else label.name
228
+ for label in question.labels
229
+ )
230
+ if answer.echo_of == "descriptions"
231
+ else asked
232
+ )
233
+ if answer.echo != expected:
234
+ failures.append(
235
+ RuleFailure(rule=Rule.echo_mismatch, observed=",".join(answer.echo), bound=None)
236
+ )
237
+ probabilities = [probability for _, probability in answer.probabilities]
238
+ for probability in probabilities:
239
+ failures.extend(_unit_interval(probability, Rule.probability_range))
240
+ if not all(_is_number(probability) for probability in probabilities):
241
+ # The sum, the chosen label and the expected level are not judged over a value that
242
+ # is not a number.
243
+ failures.extend(_confidence(answer.confidence))
244
+ return failures
245
+ # Each is summed as a float, so ints a float can each hold never overflow together.
246
+ total = sum(float(probability) for probability in probabilities)
247
+ tolerance = _sum_tolerance(len(asked), rounding.probability_decimals)
248
+ deviation = abs(total - 1.0)
249
+ if not deviation <= tolerance:
250
+ failures.append(RuleFailure(rule=Rule.sum_tolerance, observed=deviation, bound=tolerance))
251
+ if answer.chosen is not None:
252
+ highest = max(probabilities, default=0.0)
253
+ by_name = dict(answer.probabilities)
254
+ if answer.chosen not in by_name:
255
+ failures.append(
256
+ RuleFailure(rule=Rule.chosen_not_max, observed=answer.chosen, bound=highest)
257
+ )
258
+ elif highest - by_name[answer.chosen] > _step(rounding.probability_decimals):
259
+ failures.append(
260
+ RuleFailure(
261
+ rule=Rule.chosen_not_max, observed=by_name[answer.chosen], bound=highest
262
+ )
263
+ )
264
+ if question.kind == "score" and answer.expected_level is not None:
265
+ observed = _not_a_number(answer.expected_level)
266
+ if observed is not None:
267
+ failures.append(RuleFailure(rule=Rule.not_finite, observed=observed, bound=None))
268
+ else:
269
+ mean = sum(index * float(p) for index, p in enumerate(probabilities))
270
+ bound = _expected_level_bound(len(asked), rounding)
271
+ deviation = abs(answer.expected_level - mean)
272
+ if not deviation <= bound:
273
+ failures.append(
274
+ RuleFailure(rule=Rule.expected_level, observed=deviation, bound=bound)
275
+ )
276
+ failures.extend(_confidence(answer.confidence))
277
+ return failures
278
+
279
+
280
+ def _has_type(value: object, value_type: str) -> bool:
281
+ if value_type == "text":
282
+ return isinstance(value, str)
283
+ if value_type == "number":
284
+ return isinstance(value, int | float) and not isinstance(value, bool)
285
+ if value_type == "date":
286
+ return isinstance(value, datetime.date) and not isinstance(value, datetime.datetime)
287
+ if value_type == "time":
288
+ return isinstance(value, datetime.time)
289
+ if value_type == "datetime":
290
+ return isinstance(value, datetime.datetime)
291
+ return isinstance(value, datetime.timedelta)
292
+
293
+
294
+ def _value_failure(value: Value | None, question: Question) -> RuleFailure | None:
295
+ """``value_type`` when the value is not of the declared type; ``None`` passes."""
296
+ if value is None:
297
+ return None
298
+ value_type = question.value_type or "text"
299
+ if question.is_list:
300
+ if not isinstance(value, tuple):
301
+ return RuleFailure(rule=Rule.value_type, observed=type(value).__name__, bound=None)
302
+ for item in value:
303
+ if not _has_type(item, value_type):
304
+ return RuleFailure(rule=Rule.value_type, observed=type(item).__name__, bound=None)
305
+ return None
306
+ if isinstance(value, tuple) or not _has_type(value, value_type):
307
+ return RuleFailure(rule=Rule.value_type, observed=type(value).__name__, bound=None)
308
+ return None
309
+
310
+
311
+ def _extraction_failures(question: Question, answer: ExtractionAnswer) -> list[RuleFailure]:
312
+ failures: list[RuleFailure] = []
313
+ for held in (answer.value, answer.guess):
314
+ failure = _value_failure(held, question)
315
+ if failure is not None:
316
+ failures.append(failure)
317
+ if answer.p_null is not None:
318
+ failures.extend(_unit_interval(answer.p_null, Rule.p_null_range))
319
+ failures.extend(_confidence(answer.confidence))
320
+ return failures
321
+
322
+
323
+ def _box_failures(answer: BoxAnswer) -> list[RuleFailure]:
324
+ region = answer.region
325
+ failures: list[RuleFailure] = []
326
+ for edge in (region.top, region.left, region.bottom, region.right):
327
+ failures.extend(_unit_interval(edge, Rule.box_range))
328
+ if not all(_is_number(edge) for edge in (region.top, region.left, region.bottom, region.right)):
329
+ failures.extend(_confidence(answer.confidence))
330
+ return failures
331
+ if region.top > region.bottom:
332
+ failures.append(RuleFailure(rule=Rule.box_order, observed=region.top, bound=region.bottom))
333
+ if region.left > region.right:
334
+ failures.append(RuleFailure(rule=Rule.box_order, observed=region.left, bound=region.right))
335
+ failures.extend(_confidence(answer.confidence))
336
+ return failures
idia/cloudflare.py ADDED
@@ -0,0 +1,70 @@
1
+ """The ``cloudflare`` extra's provider: Clef and Clairic behind one router.
2
+
3
+ :func:`cloudflare` builds the Clef leaf for the label kinds and the Clairic leaf for
4
+ extraction over one HTTP client, wraps each in a :class:`~idia.dispatch.Dispatcher`
5
+ sharing the limiters given, and returns a :class:`~idia.dispatch.Router` keyed
6
+ ``noul``, ``choice`` and ``score`` to Clef and ``extraction`` to Clairic. It lives outside
7
+ ``providers/`` because it builds the call loop; nothing imports it but its caller.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Final
13
+
14
+ import httpx2
15
+
16
+ from idia.dispatch import Dispatcher, Router
17
+ from idia.limits import ConcurrencyLimit, RateLimiter
18
+ from idia.providers.cloudflare import (
19
+ Clairic,
20
+ Clef,
21
+ ClefModel,
22
+ _share_client, # pyright: ignore[reportPrivateUsage]
23
+ )
24
+ from idia.retry import RetryPolicy
25
+
26
+ __all__ = ["cloudflare"]
27
+
28
+ _DEFAULT_RETRY: Final = RetryPolicy()
29
+
30
+
31
+ def cloudflare(
32
+ *,
33
+ account_id: str | None = None,
34
+ api_token: str | None = None,
35
+ clef_model: ClefModel = "clef",
36
+ client: httpx2.AsyncClient | None = None,
37
+ retry: RetryPolicy = _DEFAULT_RETRY,
38
+ concurrency: ConcurrencyLimit | None = None,
39
+ rate: RateLimiter | None = None,
40
+ ) -> Router:
41
+ """The router over Clef and Clairic, sharing one client and the limiters given.
42
+
43
+ ``account_id`` and ``api_token`` default to ``CLOUDFLARE_ACCOUNT_ID`` and
44
+ ``CLOUDFLARE_API_TOKEN``. ``clef_model`` is ``clef``, ``clef-flash``,
45
+ ``@cf/cloudflare/clef`` or ``@cf/cloudflare/clef-flash``, the Clef member reporting
46
+ the short name either way. With no ``client``, the Clef leaf creates one, which
47
+ Clairic shares and the router's ``aclose`` closes; it follows the running event loop,
48
+ Clef making a fresh one on another loop and Clairic sending with whichever Clef holds.
49
+ A ``client`` the caller injects is never closed, and is used on the loop it was first
50
+ used on. ``retry``, ``concurrency`` and ``rate`` go to both dispatchers, the same
51
+ limiter instances to each, so the two models draw on one allowance.
52
+ """
53
+ clef = Clef(model=clef_model, account_id=account_id, api_token=api_token, client=client)
54
+ clairic = Clairic(account_id=account_id, api_token=api_token, client=clef.client)
55
+ _share_client(clairic, clef)
56
+ return _router(clef, clairic, retry=retry, concurrency=concurrency, rate=rate)
57
+
58
+
59
+ def _router(
60
+ clef: Clef,
61
+ clairic: Clairic,
62
+ *,
63
+ retry: RetryPolicy,
64
+ concurrency: ConcurrencyLimit | None,
65
+ rate: RateLimiter | None,
66
+ ) -> Router:
67
+ """The router's shape over two built leaves: one dispatcher each, the limiters shared."""
68
+ label = Dispatcher(clef, retry=retry, concurrency=concurrency, rate=rate)
69
+ extraction = Dispatcher(clairic, retry=retry, concurrency=concurrency, rate=rate)
70
+ return Router({"noul": label, "choice": label, "score": label, "extraction": extraction})
@@ -0,0 +1,52 @@
1
+ """The conformance suite every leaf and every provider passes before it is used.
2
+
3
+ It has two halves. The leaf half, :func:`leaf_checks`, runs against a leaf a
4
+ :class:`LeafHarness` builds; the provider half, :func:`provider_checks`, against a wrapped
5
+ leaf or a composite a :class:`ProviderHarness` builds. A harness is what a provider's
6
+ author supplies: it turns each :class:`Exchange` into its own transport's terms. Each
7
+ :class:`Check` passes, fails with an ``AssertionError``, or raises
8
+ :class:`CheckNotApplicable`; :func:`run_checks` turns them into :class:`Verdict` values
9
+ without a test runner. The suite imports only idia and the standard library.
10
+ """
11
+
12
+ from idia.conformance._base import (
13
+ AnyBody,
14
+ CandidateShape,
15
+ Check,
16
+ CheckNotApplicable,
17
+ Error,
18
+ Exchange,
19
+ Failure,
20
+ LeafHarness,
21
+ Perturbed,
22
+ ProviderHarness,
23
+ RefusalOnWire,
24
+ Stall,
25
+ Success,
26
+ Unreadable,
27
+ Verdict,
28
+ run_checks,
29
+ )
30
+ from idia.conformance._leaf import leaf_checks
31
+ from idia.conformance._provider import provider_checks
32
+
33
+ __all__ = [
34
+ "AnyBody",
35
+ "CandidateShape",
36
+ "Check",
37
+ "CheckNotApplicable",
38
+ "Error",
39
+ "Exchange",
40
+ "Failure",
41
+ "LeafHarness",
42
+ "Perturbed",
43
+ "ProviderHarness",
44
+ "RefusalOnWire",
45
+ "Stall",
46
+ "Success",
47
+ "Unreadable",
48
+ "Verdict",
49
+ "leaf_checks",
50
+ "provider_checks",
51
+ "run_checks",
52
+ ]