ommat 0.5.1__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.
- ommat/__init__.py +114 -0
- ommat/_answer.py +415 -0
- ommat/_axis.py +97 -0
- ommat/_binding.py +269 -0
- ommat/_binding_kit.py +398 -0
- ommat/_canonical.py +410 -0
- ommat/_component.py +271 -0
- ommat/_decide.py +597 -0
- ommat/_design.py +779 -0
- ommat/_documents.py +211 -0
- ommat/_fixture.py +633 -0
- ommat/_form.py +767 -0
- ommat/_interpret.py +2095 -0
- ommat/_ledger.py +2312 -0
- ommat/_load.py +3862 -0
- ommat/_markers.py +140 -0
- ommat/_provenance.py +189 -0
- ommat/_read_view.py +423 -0
- ommat/_refs.py +157 -0
- ommat/_replay.py +227 -0
- ommat/_sorter.py +46 -0
- ommat/_table.py +788 -0
- ommat/_typed.py +176 -0
- ommat/_types.py +1013 -0
- ommat/_values.py +674 -0
- ommat/_views.py +689 -0
- ommat/authoring/__init__.py +16 -0
- ommat/authoring/_reader.py +607 -0
- ommat/bindings/__init__.py +49 -0
- ommat/bindings/conformance.py +534 -0
- ommat/bindings/idia.py +450 -0
- ommat/conversation/__init__.py +115 -0
- ommat/conversation/_exchanges.py +225 -0
- ommat/conversation/pydantic_ai.py +144 -0
- ommat/evaluation/__init__.py +92 -0
- ommat/evaluation/_answers.py +178 -0
- ommat/evaluation/_deciding.py +201 -0
- ommat/evaluation/_diff.py +230 -0
- ommat/evaluation/_edit.py +938 -0
- ommat/evaluation/_gold.py +380 -0
- ommat/evaluation/_grid.py +459 -0
- ommat/evaluation/_reach.py +252 -0
- ommat/evaluation/_refusal.py +77 -0
- ommat/evaluation/_rescore.py +192 -0
- ommat/evaluation/_screen.py +349 -0
- ommat/evaluation/_store.py +220 -0
- ommat/evaluation/_switching.py +1039 -0
- ommat/helpers/__init__.py +68 -0
- ommat/helpers/_call.py +63 -0
- ommat/helpers/_choice.py +293 -0
- ommat/helpers/_combinator.py +237 -0
- ommat/helpers/_combine.py +442 -0
- ommat/helpers/_dead.py +328 -0
- ommat/helpers/_determined.py +25 -0
- ommat/helpers/_many.py +107 -0
- ommat/helpers/_numbers.py +8 -0
- ommat/helpers/_points.py +590 -0
- ommat/lens/__init__.py +96 -0
- ommat/lens/__main__.py +72 -0
- ommat/lens/page.html +2467 -0
- ommat/outline/__init__.py +28 -0
- ommat/outline/__main__.py +112 -0
- ommat/outline/_common.py +282 -0
- ommat/outline/_design.py +472 -0
- ommat/outline/_layout.py +157 -0
- ommat/outline/_path.py +256 -0
- ommat/outline/_reach.py +116 -0
- ommat/outline/_review.py +179 -0
- ommat/outline/_text.py +650 -0
- ommat/outline/_turn.py +478 -0
- ommat/outline/_types.py +201 -0
- ommat/py.typed +0 -0
- ommat/types.py +105 -0
- ommat-0.5.1.dist-info/METADATA +223 -0
- ommat-0.5.1.dist-info/RECORD +77 -0
- ommat-0.5.1.dist-info/WHEEL +4 -0
- ommat-0.5.1.dist-info/licenses/LICENSE +21 -0
ommat/__init__.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"""ommat: a blackboard decision engine.
|
|
2
|
+
|
|
3
|
+
Decide runs interpret, which gathers evidence from a judgement model onto a blackboard and
|
|
4
|
+
fires every rule. It returns the turn's replayable record, which holds each entry, and the
|
|
5
|
+
caller reads the estimates it acts on from it. A source's binding may call any tool, one that writes
|
|
6
|
+
included. Replay reruns a record under any loaded design and reports how the rerun
|
|
7
|
+
differs. The core imports only the standard library.
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from importlib.metadata import version as _version
|
|
11
|
+
|
|
12
|
+
from ommat._answer import Answer, AnswerKind, ExtractionAnswer, ValueType
|
|
13
|
+
from ommat._binding import CallResult, RenderedQuestion, SourceCall
|
|
14
|
+
from ommat._decide import (
|
|
15
|
+
Decision,
|
|
16
|
+
DefectWarning,
|
|
17
|
+
EntryRefusal,
|
|
18
|
+
RunSettings,
|
|
19
|
+
decide,
|
|
20
|
+
decide_sync,
|
|
21
|
+
)
|
|
22
|
+
from ommat._design import (
|
|
23
|
+
Design,
|
|
24
|
+
DesignFailure,
|
|
25
|
+
Group,
|
|
26
|
+
Helper,
|
|
27
|
+
Input,
|
|
28
|
+
InvalidDesign,
|
|
29
|
+
LoadedDesign,
|
|
30
|
+
Param,
|
|
31
|
+
Parameter,
|
|
32
|
+
Question,
|
|
33
|
+
Rule,
|
|
34
|
+
Source,
|
|
35
|
+
SourceRequirement,
|
|
36
|
+
Structured,
|
|
37
|
+
Table,
|
|
38
|
+
Target,
|
|
39
|
+
TargetRole,
|
|
40
|
+
Text,
|
|
41
|
+
When,
|
|
42
|
+
)
|
|
43
|
+
from ommat._fixture import from_record
|
|
44
|
+
from ommat._ledger import InvalidRecord, Record, read_record
|
|
45
|
+
from ommat._load import load
|
|
46
|
+
from ommat._markers import (
|
|
47
|
+
Cause,
|
|
48
|
+
CauseCode,
|
|
49
|
+
Failed,
|
|
50
|
+
Unasked,
|
|
51
|
+
Unavailable,
|
|
52
|
+
Undetermined,
|
|
53
|
+
Unsure,
|
|
54
|
+
)
|
|
55
|
+
from ommat._read_view import ReadView
|
|
56
|
+
from ommat._replay import FindingKind, replay, replay_sync
|
|
57
|
+
from ommat._views import defects, escalation, redact
|
|
58
|
+
|
|
59
|
+
__version__ = _version("ommat")
|
|
60
|
+
|
|
61
|
+
__all__ = [
|
|
62
|
+
"Answer",
|
|
63
|
+
"AnswerKind",
|
|
64
|
+
"CallResult",
|
|
65
|
+
"Cause",
|
|
66
|
+
"CauseCode",
|
|
67
|
+
"Decision",
|
|
68
|
+
"DefectWarning",
|
|
69
|
+
"Design",
|
|
70
|
+
"DesignFailure",
|
|
71
|
+
"EntryRefusal",
|
|
72
|
+
"ExtractionAnswer",
|
|
73
|
+
"Failed",
|
|
74
|
+
"FindingKind",
|
|
75
|
+
"Group",
|
|
76
|
+
"Helper",
|
|
77
|
+
"Input",
|
|
78
|
+
"InvalidDesign",
|
|
79
|
+
"InvalidRecord",
|
|
80
|
+
"LoadedDesign",
|
|
81
|
+
"Param",
|
|
82
|
+
"Parameter",
|
|
83
|
+
"Question",
|
|
84
|
+
"ReadView",
|
|
85
|
+
"Record",
|
|
86
|
+
"RenderedQuestion",
|
|
87
|
+
"Rule",
|
|
88
|
+
"RunSettings",
|
|
89
|
+
"Source",
|
|
90
|
+
"SourceCall",
|
|
91
|
+
"SourceRequirement",
|
|
92
|
+
"Structured",
|
|
93
|
+
"Table",
|
|
94
|
+
"Target",
|
|
95
|
+
"TargetRole",
|
|
96
|
+
"Text",
|
|
97
|
+
"Unasked",
|
|
98
|
+
"Unavailable",
|
|
99
|
+
"Undetermined",
|
|
100
|
+
"Unsure",
|
|
101
|
+
"ValueType",
|
|
102
|
+
"When",
|
|
103
|
+
"__version__",
|
|
104
|
+
"decide",
|
|
105
|
+
"decide_sync",
|
|
106
|
+
"defects",
|
|
107
|
+
"escalation",
|
|
108
|
+
"from_record",
|
|
109
|
+
"load",
|
|
110
|
+
"read_record",
|
|
111
|
+
"redact",
|
|
112
|
+
"replay",
|
|
113
|
+
"replay_sync",
|
|
114
|
+
]
|
ommat/_answer.py
ADDED
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
"""The answer to a ``q:`` ref: of a probability kind, a kind, its labels in order and a
|
|
2
|
+
probability for each; of the extraction kind, a typed value read from a text, with the
|
|
3
|
+
probability that the input holds none, the model's reading whatever it answered, its
|
|
4
|
+
confidence and the span it read."""
|
|
5
|
+
|
|
6
|
+
import enum
|
|
7
|
+
import math
|
|
8
|
+
import re
|
|
9
|
+
from collections.abc import Mapping, Sequence
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
from fractions import Fraction
|
|
12
|
+
from typing import Any, cast
|
|
13
|
+
|
|
14
|
+
from ommat._values import (
|
|
15
|
+
MAX_INTEGER,
|
|
16
|
+
described,
|
|
17
|
+
guarded_repr,
|
|
18
|
+
is_scalar_string,
|
|
19
|
+
string_data,
|
|
20
|
+
type_name,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
_NOUL_LABELS = ("yes", "no")
|
|
24
|
+
# The band an answer's exact sum is flagged outside of, both ends inside it.
|
|
25
|
+
_SUM_LOW = Fraction(95, 100)
|
|
26
|
+
_SUM_HIGH = Fraction(105, 100)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class AnswerKind(enum.StrEnum):
|
|
30
|
+
"""The answer kinds."""
|
|
31
|
+
|
|
32
|
+
noul = "noul"
|
|
33
|
+
choice = "choice"
|
|
34
|
+
score = "score"
|
|
35
|
+
extraction = "extraction"
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
_KINDS: dict[str, AnswerKind] = {k.value: k for k in AnswerKind}
|
|
39
|
+
PROBABILITY_KINDS = frozenset({AnswerKind.noul, AnswerKind.choice, AnswerKind.score})
|
|
40
|
+
"""The kinds whose answer is a probability for each label."""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True, slots=True, init=False)
|
|
44
|
+
class Answer:
|
|
45
|
+
"""A probability for each of the labels its question was asked with.
|
|
46
|
+
|
|
47
|
+
``kind`` is an ``AnswerKind`` member or its string, stored as the member. ``labels`` is
|
|
48
|
+
the question's order (for ``score``, lowest level first), at least one, and
|
|
49
|
+
``probabilities`` is exactly a ``dict`` mapping exactly those labels to values whose type
|
|
50
|
+
is exactly ``int`` or ``float``, a ``bool`` not, finite and in [0, 1]. The constructor
|
|
51
|
+
checks each value alone and raises ``ValueError``; no sum is required, and each value is
|
|
52
|
+
held as a ``float``, ``-0.0`` as ``0.0``, so a reader gets the same type live and in replay.
|
|
53
|
+
|
|
54
|
+
A label, and a key of ``probabilities``, is a ``str`` or an instance of a subclass of
|
|
55
|
+
``str`` whose data are Unicode scalar values; it is read and compared by its string data,
|
|
56
|
+
which no override reaches, and stored as a plain ``str``, as the value domain takes it.
|
|
57
|
+
``probabilities`` is stored as a new plain ``dict`` in label order. An ``Answer`` is not
|
|
58
|
+
hashable, since it holds a ``dict``.
|
|
59
|
+
"""
|
|
60
|
+
|
|
61
|
+
kind: AnswerKind
|
|
62
|
+
labels: tuple[str, ...]
|
|
63
|
+
probabilities: Mapping[str, float]
|
|
64
|
+
|
|
65
|
+
def __init__(
|
|
66
|
+
self,
|
|
67
|
+
kind: AnswerKind | str,
|
|
68
|
+
labels: Sequence[str],
|
|
69
|
+
probabilities: Mapping[str, float],
|
|
70
|
+
) -> None:
|
|
71
|
+
# Refused by type before the lookup, which would hash a caller's object; a string, the
|
|
72
|
+
# members included, is looked up by its string data.
|
|
73
|
+
member = (
|
|
74
|
+
_KINDS.get(string_data(kind))
|
|
75
|
+
if issubclass(type(kind), str) # pyright: ignore[reportUnnecessaryIsInstance]
|
|
76
|
+
else None
|
|
77
|
+
)
|
|
78
|
+
if member is None or member not in PROBABILITY_KINDS:
|
|
79
|
+
raise ValueError(f"answer kind {guarded_repr(kind)} is not noul, choice or score")
|
|
80
|
+
labels_ = _labels(cast(object, labels))
|
|
81
|
+
if member is AnswerKind.noul and labels_ != _NOUL_LABELS:
|
|
82
|
+
raise ValueError(f"a noul answer's labels are ('yes', 'no'), not {labels_!r}")
|
|
83
|
+
object.__setattr__(self, "kind", member)
|
|
84
|
+
object.__setattr__(self, "labels", labels_)
|
|
85
|
+
object.__setattr__(self, "probabilities", _probabilities(probabilities, labels_))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def answer_document(answer: Answer) -> dict[str, object]:
|
|
89
|
+
"""An answer as the record writes it: an object with ``kind``, ``labels`` and
|
|
90
|
+
``probabilities``."""
|
|
91
|
+
return {
|
|
92
|
+
"kind": answer.kind.value,
|
|
93
|
+
"labels": list(answer.labels),
|
|
94
|
+
"probabilities": dict(answer.probabilities),
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _labels(labels: object) -> tuple[str, ...]:
|
|
99
|
+
# By type alone, so no ``__class__`` of the caller's is read.
|
|
100
|
+
if issubclass(type(labels), str) or not issubclass(type(labels), Sequence):
|
|
101
|
+
raise ValueError(f"labels {guarded_repr(labels)} are not a sequence of strings")
|
|
102
|
+
out: list[str] = []
|
|
103
|
+
for label in cast("Sequence[object]", labels):
|
|
104
|
+
if not is_scalar_string(label):
|
|
105
|
+
raise ValueError(
|
|
106
|
+
f"label {guarded_repr(label)} is not a string of Unicode scalar values"
|
|
107
|
+
)
|
|
108
|
+
out.append(string_data(cast(str, label)))
|
|
109
|
+
if not out:
|
|
110
|
+
raise ValueError("an answer has at least one label, as every question does")
|
|
111
|
+
if len(set(out)) != len(out):
|
|
112
|
+
raise ValueError(f"labels {out!r} repeat a label")
|
|
113
|
+
return tuple(out)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def _probabilities(probabilities: object, labels: tuple[str, ...]) -> dict[str, float]:
|
|
117
|
+
if type(probabilities) is not dict:
|
|
118
|
+
raise ValueError(f"probabilities of type {type_name(probabilities)} are not exactly a dict")
|
|
119
|
+
given: dict[str, object] = {}
|
|
120
|
+
for key, p in cast("dict[object, object]", probabilities).items():
|
|
121
|
+
if not is_scalar_string(key):
|
|
122
|
+
raise ValueError(
|
|
123
|
+
f"probability key {guarded_repr(key)} is not a string of Unicode scalar values"
|
|
124
|
+
)
|
|
125
|
+
data = string_data(cast(str, key))
|
|
126
|
+
if data in given:
|
|
127
|
+
raise ValueError(f"two probability keys have the string data {data!r}")
|
|
128
|
+
given[data] = p
|
|
129
|
+
missing = [label for label in labels if label not in given]
|
|
130
|
+
if missing:
|
|
131
|
+
raise ValueError(f"no probability for label(s) {missing!r}")
|
|
132
|
+
known = frozenset(labels)
|
|
133
|
+
extra = [key for key in given if key not in known]
|
|
134
|
+
if extra:
|
|
135
|
+
raise ValueError(f"probability for key(s) {extra!r} not among the labels")
|
|
136
|
+
out: dict[str, float] = {}
|
|
137
|
+
for label in labels:
|
|
138
|
+
p = given[label]
|
|
139
|
+
# Exact types, as the value domain admits: a bool is not a number. An int of any
|
|
140
|
+
# size compares exactly; only a float can be non-finite.
|
|
141
|
+
if not (type(p) is int or type(p) is float):
|
|
142
|
+
raise ValueError(f"probability of type {type_name(p)} for {label!r} is not a number")
|
|
143
|
+
number = cast(float, p)
|
|
144
|
+
if (type(p) is float and not math.isfinite(number)) or not 0 <= number <= 1:
|
|
145
|
+
raise ValueError(f"probability {described(p)} for {label!r} is not in [0, 1]")
|
|
146
|
+
# Held as a float, as replay reads it back: -0.0 is 0 in bytes, so it is held as 0.0.
|
|
147
|
+
out[label] = 0.0 if number == 0 else float(number)
|
|
148
|
+
return out
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def exact_sum(answer: Answer) -> Fraction:
|
|
152
|
+
"""The sum of an answer's probabilities, exact over the decimal each reads back as,
|
|
153
|
+
``Fraction(repr(p))``, as the ``mass`` helper sums."""
|
|
154
|
+
# Exactly as ``helpers._numbers.exact`` sums for ``mass``; kept here so the core imports
|
|
155
|
+
# nothing from the helpers.
|
|
156
|
+
return sum((Fraction(repr(p)) for p in answer.probabilities.values()), Fraction(0))
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def off_sum(answer: Answer) -> float | None:
|
|
160
|
+
"""An answer's exact sum rounded once to a ``float`` when it lies outside [0.95, 1.05],
|
|
161
|
+
each end inside; else ``None``. The band is tested on the exact sum, so a sum just outside
|
|
162
|
+
it may round to 0.95 or 1.05 exactly, as 1 + 0.05 + 1e-17 does. The flag changes nothing
|
|
163
|
+
about the answer.
|
|
164
|
+
"""
|
|
165
|
+
total = exact_sum(answer)
|
|
166
|
+
return None if _SUM_LOW <= total <= _SUM_HIGH else float(total)
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
# ---------------------------------------------------------------------------------------------
|
|
170
|
+
# The extraction kind
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
class ValueType(enum.StrEnum):
|
|
174
|
+
"""The value types of an extraction question."""
|
|
175
|
+
|
|
176
|
+
text = "text"
|
|
177
|
+
number = "number"
|
|
178
|
+
date = "date"
|
|
179
|
+
time = "time"
|
|
180
|
+
datetime = "datetime"
|
|
181
|
+
duration = "duration"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
_VALUE_TYPES: dict[str, ValueType] = {v.value: v for v in ValueType}
|
|
185
|
+
EXTRACTION_MEMBERS = ("value", "guess", "p_null", "confidence", "span")
|
|
186
|
+
"""The members a binding returns for an extraction question, in the order a reader takes them."""
|
|
187
|
+
|
|
188
|
+
# The temporal grammars, ommat's own: ASCII digits only, ``T`` and ``Z`` uppercase only. A
|
|
189
|
+
# date's day is tested against its month apart, leap years counted.
|
|
190
|
+
_DATE = r"([0-9]{4})-([0-9]{2})-([0-9]{2})"
|
|
191
|
+
_CLOCK = r"([0-9]{2}):([0-9]{2}):([0-9]{2})(?:\.[0-9]+)?(?:Z|[+-]([0-9]{2}):([0-9]{2}))?"
|
|
192
|
+
_DATE_RE = re.compile(_DATE)
|
|
193
|
+
_TIME_RE = re.compile(_CLOCK)
|
|
194
|
+
_DATETIME_RE = re.compile(f"{_DATE}T{_CLOCK}")
|
|
195
|
+
_DURATION_RE = re.compile(
|
|
196
|
+
r"P(?:[0-9]+Y)?(?:[0-9]+M)?(?:[0-9]+D)?(?:T(?:[0-9]+H)?(?:[0-9]+M)?(?:[0-9]+S)?)?"
|
|
197
|
+
)
|
|
198
|
+
_MONTH_DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _leap(year: int) -> bool:
|
|
202
|
+
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _date_ok(year: str, month: str, day: str) -> bool:
|
|
206
|
+
m, d = int(month), int(day)
|
|
207
|
+
if not 1 <= m <= 12:
|
|
208
|
+
return False
|
|
209
|
+
last = 29 if m == 2 and _leap(int(year)) else _MONTH_DAYS[m - 1]
|
|
210
|
+
return 1 <= d <= last
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _clock_ok(groups: Sequence[str | None]) -> bool:
|
|
214
|
+
hour, minute, second, off_hour, off_minute = groups
|
|
215
|
+
if not (int(cast(str, hour)) <= 23 and int(cast(str, minute)) <= 59):
|
|
216
|
+
return False
|
|
217
|
+
if int(cast(str, second)) > 59:
|
|
218
|
+
return False
|
|
219
|
+
return off_hour is None or (int(off_hour) <= 23 and int(cast(str, off_minute)) <= 59)
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
def temporal_ok(value_type: ValueType, text: str) -> bool:
|
|
223
|
+
"""Whether ``text`` is a value of the temporal ``value_type`` by ommat's own grammar, the
|
|
224
|
+
same on every Python; ``text`` is a plain ``str``."""
|
|
225
|
+
if value_type is ValueType.date:
|
|
226
|
+
found = _DATE_RE.fullmatch(text)
|
|
227
|
+
return found is not None and _date_ok(*cast("tuple[str, str, str]", found.groups()))
|
|
228
|
+
if value_type is ValueType.time:
|
|
229
|
+
found = _TIME_RE.fullmatch(text)
|
|
230
|
+
return found is not None and _clock_ok(found.groups())
|
|
231
|
+
if value_type is ValueType.datetime:
|
|
232
|
+
found = _DATETIME_RE.fullmatch(text)
|
|
233
|
+
if found is None:
|
|
234
|
+
return False
|
|
235
|
+
groups = found.groups()
|
|
236
|
+
return _date_ok(*cast("tuple[str, str, str]", groups[:3])) and _clock_ok(groups[3:])
|
|
237
|
+
assert value_type is ValueType.duration
|
|
238
|
+
# At least one part in all, and at least one after a T.
|
|
239
|
+
return _DURATION_RE.fullmatch(text) is not None and text != "P" and not text.endswith("T")
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def _item(value_type: ValueType, value: object, member: str) -> object:
|
|
243
|
+
"""One value of ``value_type`` as the answer holds it, a number as a ``float``; anything
|
|
244
|
+
else raises ``ValueError``."""
|
|
245
|
+
if value_type is ValueType.number:
|
|
246
|
+
if type(value) is int:
|
|
247
|
+
if abs(value) > MAX_INTEGER:
|
|
248
|
+
raise ValueError(f"{member} {described(value)} is past 2^53 - 1 in magnitude")
|
|
249
|
+
return float(value)
|
|
250
|
+
if type(value) is float and math.isfinite(value):
|
|
251
|
+
return 0.0 if value == 0 else value # -0.0 is 0 in the bytes
|
|
252
|
+
raise ValueError(f"{member} {guarded_repr(value)} is not a finite number")
|
|
253
|
+
if not is_scalar_string(value):
|
|
254
|
+
raise ValueError(f"{member} {guarded_repr(value)} is not a string of Unicode scalar values")
|
|
255
|
+
text = string_data(cast(str, value))
|
|
256
|
+
if value_type is not ValueType.text and not temporal_ok(value_type, text):
|
|
257
|
+
raise ValueError(f"{member} {text!r} is not a {value_type.value} by ommat's grammar")
|
|
258
|
+
return text
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _typed_member(value_type: ValueType, is_list: bool, value: object, member: str) -> object:
|
|
262
|
+
"""``value`` or ``guess``: ``None``, a value of the type, or when ``is_list`` exactly a
|
|
263
|
+
``list`` of such values with no ``None``, held as a tuple."""
|
|
264
|
+
if value is None:
|
|
265
|
+
return None
|
|
266
|
+
if not is_list:
|
|
267
|
+
return _item(value_type, value, member)
|
|
268
|
+
if type(value) is not list:
|
|
269
|
+
raise ValueError(f"{member} of type {type_name(value)} is not exactly a list")
|
|
270
|
+
out: list[object] = []
|
|
271
|
+
for i, item in enumerate(cast("list[object]", value)):
|
|
272
|
+
if item is None:
|
|
273
|
+
raise ValueError(f"{member}[{i}] is None; a list holds no None item")
|
|
274
|
+
out.append(_item(value_type, item, f"{member}[{i}]"))
|
|
275
|
+
return tuple(out)
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _probability(value: object, member: str) -> float | None:
|
|
279
|
+
if value is None:
|
|
280
|
+
return None
|
|
281
|
+
if not (type(value) is int or type(value) is float):
|
|
282
|
+
raise ValueError(f"{member} of type {type_name(value)} is not a number")
|
|
283
|
+
number = cast(float, value)
|
|
284
|
+
if (type(value) is float and not math.isfinite(number)) or not 0 <= number <= 1:
|
|
285
|
+
raise ValueError(f"{member} {described(value)} is not in [0, 1]")
|
|
286
|
+
# Held as a float, as replay reads it back: -0.0 is 0 in the bytes, so it is held as 0.0.
|
|
287
|
+
return 0.0 if number == 0 else float(number)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _pair(value: object, member: str) -> tuple[int, int]:
|
|
291
|
+
if type(value) is not list or len(cast("list[object]", value)) != 2:
|
|
292
|
+
raise ValueError(f"{member} is not exactly a list of two integers")
|
|
293
|
+
start, end = cast("list[object]", value)
|
|
294
|
+
if type(start) is not int or type(end) is not int:
|
|
295
|
+
raise ValueError(f"{member} holds a bound that is not exactly an int")
|
|
296
|
+
if not 0 <= start <= end <= MAX_INTEGER:
|
|
297
|
+
raise ValueError(
|
|
298
|
+
f"{member} [{described(start)}, {described(end)}] is not 0 <= start <= end"
|
|
299
|
+
)
|
|
300
|
+
return start, end
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def _span(span: object, located: object, is_list: bool) -> Any:
|
|
304
|
+
"""``span``: ``None`` exactly when the member it locates is; for a scalar one pair, for a
|
|
305
|
+
list one pair per item, held as tuples. Its bound against the text is interpret's."""
|
|
306
|
+
if span is None:
|
|
307
|
+
return None
|
|
308
|
+
if located is None:
|
|
309
|
+
raise ValueError("span locates a value or guess, and both are None")
|
|
310
|
+
if not is_list:
|
|
311
|
+
return _pair(span, "span")
|
|
312
|
+
if type(span) is not list:
|
|
313
|
+
raise ValueError(f"span of type {type_name(span)} is not exactly a list")
|
|
314
|
+
pairs = cast("list[object]", span)
|
|
315
|
+
if len(pairs) != len(cast("tuple[object, ...]", located)):
|
|
316
|
+
raise ValueError("span holds a pair count other than the list it locates holds items")
|
|
317
|
+
return tuple(_pair(p, f"span[{i}]") for i, p in enumerate(pairs))
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
@dataclass(frozen=True, slots=True, init=False)
|
|
321
|
+
class ExtractionAnswer:
|
|
322
|
+
"""A typed value a judgement model read from a text, as its question asked.
|
|
323
|
+
|
|
324
|
+
``value_type`` is a ``ValueType`` member or its string and ``is_list`` exactly a ``bool``,
|
|
325
|
+
both copied from the question. ``value`` and ``guess`` are each ``None`` or a value of the
|
|
326
|
+
type, or when ``is_list`` exactly a ``list`` of such values with no ``None`` item, held as a
|
|
327
|
+
tuple; an empty list is a value distinct from ``None``. A ``text`` value is a string; a
|
|
328
|
+
``number`` exactly an ``int`` of magnitude at most 2^53 - 1 or a finite ``float``, never a
|
|
329
|
+
``bool``, held as a ``float``; a ``date``, ``time``, ``datetime`` or ``duration`` a string of
|
|
330
|
+
ommat's own grammar, kept as given. ``p_null`` and ``confidence`` are each ``None`` or
|
|
331
|
+
exactly an ``int`` or ``float``, finite and in [0, 1], held as a ``float``. A ``-0.0`` is held
|
|
332
|
+
as ``0.0``, as the record writes it.
|
|
333
|
+
|
|
334
|
+
``span`` is ``None``, or for a scalar exactly a ``list`` ``[start, end]`` of exact ``int``
|
|
335
|
+
values with 0 <= start <= end, ``end`` exclusive, or for a list one such pair per item. It
|
|
336
|
+
locates ``value``, or ``guess`` when ``value`` is ``None``, and is ``None`` when that member
|
|
337
|
+
is. Pairs are held as tuples. The constructor checks every member but a span's bound
|
|
338
|
+
against its text, which interpret tests at the write, and raises ``ValueError``.
|
|
339
|
+
"""
|
|
340
|
+
|
|
341
|
+
kind: AnswerKind
|
|
342
|
+
value_type: ValueType
|
|
343
|
+
is_list: bool
|
|
344
|
+
value: Any
|
|
345
|
+
guess: Any
|
|
346
|
+
p_null: float | None
|
|
347
|
+
confidence: float | None
|
|
348
|
+
span: Any
|
|
349
|
+
|
|
350
|
+
def __init__(
|
|
351
|
+
self,
|
|
352
|
+
value_type: ValueType | str,
|
|
353
|
+
is_list: bool,
|
|
354
|
+
value: object,
|
|
355
|
+
guess: object,
|
|
356
|
+
p_null: float | None,
|
|
357
|
+
confidence: float | None,
|
|
358
|
+
span: object,
|
|
359
|
+
) -> None:
|
|
360
|
+
member = (
|
|
361
|
+
_VALUE_TYPES.get(string_data(value_type))
|
|
362
|
+
if issubclass(type(value_type), str) # pyright: ignore[reportUnnecessaryIsInstance]
|
|
363
|
+
else None
|
|
364
|
+
)
|
|
365
|
+
if member is None:
|
|
366
|
+
raise ValueError(f"value type {guarded_repr(value_type)} is not one of the six")
|
|
367
|
+
if type(is_list) is not bool:
|
|
368
|
+
raise ValueError(f"is_list of type {type_name(is_list)} is not exactly a bool")
|
|
369
|
+
value_ = _typed_member(member, is_list, value, "value")
|
|
370
|
+
guess_ = _typed_member(member, is_list, guess, "guess")
|
|
371
|
+
located = guess_ if value_ is None else value_
|
|
372
|
+
object.__setattr__(self, "kind", AnswerKind.extraction)
|
|
373
|
+
object.__setattr__(self, "value_type", member)
|
|
374
|
+
object.__setattr__(self, "is_list", is_list)
|
|
375
|
+
object.__setattr__(self, "value", value_)
|
|
376
|
+
object.__setattr__(self, "guess", guess_)
|
|
377
|
+
object.__setattr__(self, "p_null", _probability(p_null, "p_null"))
|
|
378
|
+
object.__setattr__(self, "confidence", _probability(confidence, "confidence"))
|
|
379
|
+
object.__setattr__(self, "span", _span(span, located, is_list))
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def _listed(member: object) -> object:
|
|
383
|
+
if type(member) is tuple:
|
|
384
|
+
return [_listed(m) for m in cast("tuple[object, ...]", member)]
|
|
385
|
+
return member
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def extraction_document(answer: ExtractionAnswer) -> dict[str, object]:
|
|
389
|
+
"""An extraction answer as the record writes it: its eight members, tuples as lists."""
|
|
390
|
+
return {
|
|
391
|
+
"kind": answer.kind.value,
|
|
392
|
+
"value_type": answer.value_type.value,
|
|
393
|
+
"is_list": answer.is_list,
|
|
394
|
+
"value": _listed(answer.value),
|
|
395
|
+
"guess": _listed(answer.guess),
|
|
396
|
+
"p_null": answer.p_null,
|
|
397
|
+
"confidence": answer.confidence,
|
|
398
|
+
"span": _listed(answer.span),
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def binding_form(answer: ExtractionAnswer) -> dict[str, object]:
|
|
403
|
+
"""An extraction answer's five members as a binding returns them: tuples as lists."""
|
|
404
|
+
document = extraction_document(answer)
|
|
405
|
+
return {member: document[member] for member in EXTRACTION_MEMBERS}
|
|
406
|
+
|
|
407
|
+
|
|
408
|
+
def span_bound(answer: ExtractionAnswer) -> int:
|
|
409
|
+
"""The largest ``end`` the answer's span holds, 0 when it has none."""
|
|
410
|
+
span = answer.span
|
|
411
|
+
if span is None:
|
|
412
|
+
return 0
|
|
413
|
+
if not answer.is_list:
|
|
414
|
+
return cast("tuple[int, int]", span)[1]
|
|
415
|
+
return max((end for _, end in cast("tuple[tuple[int, int], ...]", span)), default=0)
|
ommat/_axis.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
# pyright: reportPrivateUsage=false
|
|
2
|
+
"""A numeric axis: the points worth trying along one number, from the boundaries it is compared
|
|
3
|
+
against, shared by the lints' read points and the switching-value job's probes."""
|
|
4
|
+
|
|
5
|
+
import itertools
|
|
6
|
+
import math
|
|
7
|
+
from collections.abc import Iterable, Sequence
|
|
8
|
+
from fractions import Fraction
|
|
9
|
+
|
|
10
|
+
from ommat._types import Type, _numeric
|
|
11
|
+
from ommat._values import MAX_INTEGER
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _exact(x: float) -> Fraction:
|
|
15
|
+
"""The shortest decimal that reads back as ``x``, exactly."""
|
|
16
|
+
return Fraction(repr(x))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def axis(
|
|
20
|
+
bounds: Iterable[Fraction], lo: Fraction | None, hi: Fraction | None, *, integer: bool
|
|
21
|
+
) -> list[Fraction]:
|
|
22
|
+
"""An axis's points, exact and ascending: every boundary, one inside each gap (the
|
|
23
|
+
midpoint, or on an integer axis the least integer above the lower boundary, a gap
|
|
24
|
+
holding none skipped) and one past each end (the type's bound, else the end boundary
|
|
25
|
+
minus or plus 1, on an integer axis the nearest integer beyond it). On an integer axis a
|
|
26
|
+
boundary that is not integral, or of magnitude above 2^53 - 1, is no point, but the
|
|
27
|
+
integers either side of it within those bounds are, and an end past that bound is the
|
|
28
|
+
bound. A boundary outside the interval is not on the axis; an axis so left with no
|
|
29
|
+
boundary has the interval's two bounds, or on an unbounded integer axis the domain's. An
|
|
30
|
+
axis given no boundary has no points. Rounding is the caller's."""
|
|
31
|
+
given = set(bounds)
|
|
32
|
+
on = {
|
|
33
|
+
b
|
|
34
|
+
for b in given
|
|
35
|
+
if (not integer or (b.denominator == 1 and abs(b) <= MAX_INTEGER))
|
|
36
|
+
and (lo is None or lo <= b)
|
|
37
|
+
and (hi is None or b <= hi)
|
|
38
|
+
}
|
|
39
|
+
if integer: # each side of a boundary between two integers
|
|
40
|
+
for b in given:
|
|
41
|
+
if b.denominator != 1 and (lo is None or lo <= b) and (hi is None or b <= hi):
|
|
42
|
+
for n in (math.floor(b), math.ceil(b)):
|
|
43
|
+
side = Fraction(max(-MAX_INTEGER, min(n, MAX_INTEGER)))
|
|
44
|
+
if (lo is None or lo <= side) and (hi is None or side <= hi):
|
|
45
|
+
on.add(side)
|
|
46
|
+
ordered = sorted(on)
|
|
47
|
+
if not ordered:
|
|
48
|
+
if given and integer and lo is None and hi is None:
|
|
49
|
+
return [Fraction(-MAX_INTEGER), Fraction(MAX_INTEGER)]
|
|
50
|
+
return sorted({lo, hi}) if given and lo is not None and hi is not None else []
|
|
51
|
+
points = set(ordered)
|
|
52
|
+
for a, b in itertools.pairwise(ordered):
|
|
53
|
+
if integer:
|
|
54
|
+
n = Fraction(math.floor(a) + 1)
|
|
55
|
+
if n < b:
|
|
56
|
+
points.add(n)
|
|
57
|
+
else:
|
|
58
|
+
points.add((a + b) / 2)
|
|
59
|
+
first, last = ordered[0], ordered[-1]
|
|
60
|
+
if lo is None:
|
|
61
|
+
lo = Fraction(max(math.ceil(first) - 1, -MAX_INTEGER)) if integer else first - 1
|
|
62
|
+
if hi is None:
|
|
63
|
+
hi = Fraction(min(math.floor(last) + 1, MAX_INTEGER)) if integer else last + 1
|
|
64
|
+
points |= {lo, hi}
|
|
65
|
+
return sorted(points)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def numeric_axis(bounds: Sequence[Fraction], t: Type) -> list[int | float]:
|
|
69
|
+
"""A numeric type's axis over ``bounds``, each point rounded once to the type's form: an
|
|
70
|
+
``integer`` or integer interval's an ``int``, a ``number``'s a ``float``, its ends past an
|
|
71
|
+
unbounded ``number``'s boundaries by ``_end``. Given no boundary, the interval's two bounds,
|
|
72
|
+
or on an unbounded type ``-(2^53 - 1)`` and ``2^53 - 1``. Repeats are the caller's."""
|
|
73
|
+
numeric = _numeric(t)
|
|
74
|
+
assert numeric is not None # the caller's type is numeric
|
|
75
|
+
integer, interval = numeric[0] == "integer", numeric[1]
|
|
76
|
+
lo: Fraction | None = None
|
|
77
|
+
hi: Fraction | None = None
|
|
78
|
+
if interval is not None:
|
|
79
|
+
lo, hi = _exact(interval[0]), _exact(interval[1])
|
|
80
|
+
if not bounds:
|
|
81
|
+
ends = (lo, hi) if lo is not None and hi is not None else (-MAX_INTEGER, MAX_INTEGER)
|
|
82
|
+
points: Sequence[Fraction | int] = ends
|
|
83
|
+
else:
|
|
84
|
+
if not integer and lo is None:
|
|
85
|
+
lo, hi = _end(min(bounds), -1), _end(max(bounds), 1)
|
|
86
|
+
points = axis(bounds, lo, hi, integer=integer)
|
|
87
|
+
return [int(x) if integer else float(x) for x in points]
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _end(x: Fraction, step: int) -> Fraction:
|
|
91
|
+
"""A number axis's end past ``x``: ``x`` plus ``step``, or the nearest ``float`` beyond
|
|
92
|
+
``x`` when that rounds onto it; ``x`` itself at the largest ``float``, past which there
|
|
93
|
+
is none."""
|
|
94
|
+
if float(x + step) != float(x):
|
|
95
|
+
return x + step
|
|
96
|
+
beyond = math.nextafter(float(x), step * math.inf)
|
|
97
|
+
return x if math.isinf(beyond) else Fraction(beyond)
|