llmvalidate 1.0.1__tar.gz → 1.2.0__tar.gz
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.
- {llmvalidate-1.0.1/src/llmvalidate.egg-info → llmvalidate-1.2.0}/PKG-INFO +1 -1
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/pyproject.toml +1 -1
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate/__init__.py +44 -2
- llmvalidate-1.2.0/src/llmvalidate/cells.py +282 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate/sortable_date.py +99 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate/utils.py +7 -6
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate/validation.py +16 -12
- {llmvalidate-1.0.1 → llmvalidate-1.2.0/src/llmvalidate.egg-info}/PKG-INFO +1 -1
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate.egg-info/SOURCES.txt +1 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/LICENSE +0 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/readme.md +0 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/setup.cfg +0 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate/structured.py +0 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate.egg-info/dependency_links.txt +0 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate.egg-info/requires.txt +0 -0
- {llmvalidate-1.0.1 → llmvalidate-1.2.0}/src/llmvalidate.egg-info/top_level.txt +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# Managed by python-semantic-release — do not edit by hand; the release workflow rewrites
|
|
2
2
|
# this line. Set to 0.7.0 once by hand to clear the drift from ONC-12379, during which the
|
|
3
3
|
# release never reached this file and it stayed at 0.0.0 across every published version.
|
|
4
|
-
__version__ = "1.0
|
|
4
|
+
__version__ = "1.2.0"
|
|
5
5
|
|
|
6
6
|
# `structured` is pydantic-only and cheap, so it is imported eagerly: consumers that
|
|
7
7
|
# only need the extraction contract (StructuredResult / StructuredField) get it without
|
|
@@ -10,7 +10,31 @@ from .structured import StructuredResult, StructuredGroup, StructuredField
|
|
|
10
10
|
|
|
11
11
|
# `sortable_date` is std-lib only (`re`, `datetime`), so it is likewise eager: normalising a
|
|
12
12
|
# date string must not cost the caller a pandas import. Keep it dependency-free.
|
|
13
|
-
from .sortable_date import
|
|
13
|
+
from .sortable_date import (
|
|
14
|
+
DATE_MASKS,
|
|
15
|
+
is_canonical_date,
|
|
16
|
+
is_date_mask,
|
|
17
|
+
to_canonical_date,
|
|
18
|
+
to_sortable_date,
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
# `cells` states the value-level conventions of a scored table — the no-finding sentinel,
|
|
22
|
+
# list cells, and the `-value`/`-code` facet columns. Std-lib only for the same reason:
|
|
23
|
+
# reading or writing a cell must not pull in the scoring stack.
|
|
24
|
+
from .cells import (
|
|
25
|
+
CODE_SUFFIX,
|
|
26
|
+
FACET_SUFFIXES,
|
|
27
|
+
NO_FINDING,
|
|
28
|
+
VALUE_SUFFIX,
|
|
29
|
+
canonical_date_cell,
|
|
30
|
+
facet_columns,
|
|
31
|
+
format_list_cell,
|
|
32
|
+
is_canonical_date_cell,
|
|
33
|
+
is_no_finding,
|
|
34
|
+
is_unlabelled,
|
|
35
|
+
parse_list_cell,
|
|
36
|
+
split_facet,
|
|
37
|
+
)
|
|
14
38
|
|
|
15
39
|
__all__ = [
|
|
16
40
|
"validate",
|
|
@@ -18,7 +42,25 @@ __all__ = [
|
|
|
18
42
|
"StructuredResult",
|
|
19
43
|
"StructuredGroup",
|
|
20
44
|
"StructuredField",
|
|
45
|
+
# dates
|
|
21
46
|
"to_sortable_date",
|
|
47
|
+
"to_canonical_date",
|
|
48
|
+
"is_canonical_date",
|
|
49
|
+
"is_date_mask",
|
|
50
|
+
"DATE_MASKS",
|
|
51
|
+
"canonical_date_cell",
|
|
52
|
+
"is_canonical_date_cell",
|
|
53
|
+
# cell conventions
|
|
54
|
+
"NO_FINDING",
|
|
55
|
+
"is_no_finding",
|
|
56
|
+
"is_unlabelled",
|
|
57
|
+
"parse_list_cell",
|
|
58
|
+
"format_list_cell",
|
|
59
|
+
"facet_columns",
|
|
60
|
+
"split_facet",
|
|
61
|
+
"FACET_SUFFIXES",
|
|
62
|
+
"VALUE_SUFFIX",
|
|
63
|
+
"CODE_SUFFIX",
|
|
22
64
|
]
|
|
23
65
|
|
|
24
66
|
|
|
@@ -0,0 +1,282 @@
|
|
|
1
|
+
"""The value-level conventions of a scored table: sentinels, list cells, facet columns.
|
|
2
|
+
|
|
3
|
+
`validate` compares a label column against its `Res: ` column cell by cell, and three
|
|
4
|
+
conventions decide what those cells may say. All three are defined by this package but were,
|
|
5
|
+
until now, only *implemented* inside it — so every producer and consumer of a scored table
|
|
6
|
+
(dataset builders, extraction pipelines, harnesses that serve or submit predictions)
|
|
7
|
+
re-derived them from the docs, usually as a string literal or an f-string. This module states
|
|
8
|
+
them once:
|
|
9
|
+
|
|
10
|
+
* **Sentinels.** An empty cell means *not labelled* — the row simply says nothing about this
|
|
11
|
+
field, and scoring skips it. `"-"` means *no information*: a real answer, asserting the
|
|
12
|
+
source stated nothing to find, and graded like any other. Conflating the two is the single
|
|
13
|
+
most common mistake against this contract, hence `is_unlabelled` and `is_no_finding` rather
|
|
14
|
+
than one "is it empty" helper.
|
|
15
|
+
* **List cells.** A `list` field's cell is a `literal_eval`-able list repr (`"['EGFR',
|
|
16
|
+
'KRAS']"`), with `"-"` for no finding and an empty cell for not labelled.
|
|
17
|
+
`parse_list_cell` / `format_list_cell` are that round-trip, and they carry the sentinel
|
|
18
|
+
distinction through it rather than flattening it: an unlabelled cell parses to `None`,
|
|
19
|
+
a no-finding one to `[]`.
|
|
20
|
+
* **Facet columns.** A field carrying a `code` flattens to two scored columns, `<field>-value`
|
|
21
|
+
and `<field>-code` (see `utils.flatten_structured_result`). `facet_columns` builds the pair
|
|
22
|
+
and `split_facet` takes it apart.
|
|
23
|
+
* **Date cells.** A column defined to hold a date holds one canonical rendering of one — and
|
|
24
|
+
the sentinels. `canonical_date_cell` / `is_canonical_date_cell` are the two conventions
|
|
25
|
+
together: `sortable_date`'s mask rules for a real value, and the rules above for a cell
|
|
26
|
+
that says nothing or says "nothing to find".
|
|
27
|
+
|
|
28
|
+
Std-lib only, and eagerly importable: reading or writing a cell must not cost the caller a
|
|
29
|
+
pandas import.
|
|
30
|
+
|
|
31
|
+
Missing values are accepted in every shape they arrive in — `None`, NaN (of any float
|
|
32
|
+
type), `pd.NA`, `pd.NaT` — because a cell that came out of a frame or a parser is under no
|
|
33
|
+
obligation to be a built-in, and `pd.NA` cannot even be compared without raising.
|
|
34
|
+
|
|
35
|
+
Beyond that, the predicates here read a cell **exactly as written**: `" - "` is not the
|
|
36
|
+
sentinel. That is
|
|
37
|
+
on purpose — a caller is usually checking what a file or a submission *contains*, and a cell
|
|
38
|
+
padded with spaces is a formatting problem worth seeing rather than papering over. `validate`
|
|
39
|
+
is more forgiving at compare time (it strips through `normalize` before matching), as is
|
|
40
|
+
`is_canonical_date`, whose whole job is to tell a date from a rewrite of one.
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
import math
|
|
44
|
+
from ast import literal_eval
|
|
45
|
+
from typing import Any
|
|
46
|
+
|
|
47
|
+
from .sortable_date import _precision, is_canonical_date, to_canonical_date
|
|
48
|
+
|
|
49
|
+
# The "no information" sentinel: the source was read and stated nothing to find. A real,
|
|
50
|
+
# graded answer — not the absence of one.
|
|
51
|
+
NO_FINDING = "-"
|
|
52
|
+
|
|
53
|
+
# pandas' own missing-value singletons, recognised by type name so this module stays
|
|
54
|
+
# std-lib only. `pd.NA` earns the special case twice over: it is not a float, so no NaN
|
|
55
|
+
# test finds it, and it cannot be compared either — `pd.NA == ""` is `pd.NA`, whose truth
|
|
56
|
+
# value raises.
|
|
57
|
+
_MISSING_TYPE_NAMES = frozenset({"NAType", "NaTType"})
|
|
58
|
+
|
|
59
|
+
# The two scored columns a coded field flattens into, in the order `facet_columns` returns
|
|
60
|
+
# them (value first, matching `flatten_structured_result`'s output order).
|
|
61
|
+
VALUE_SUFFIX = "-value"
|
|
62
|
+
CODE_SUFFIX = "-code"
|
|
63
|
+
FACET_SUFFIXES = (VALUE_SUFFIX, CODE_SUFFIX)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
# --- Sentinels ---------------------------------------------------------------
|
|
67
|
+
|
|
68
|
+
def _is_missing_scalar(value: Any) -> bool:
|
|
69
|
+
"""True for every shape "no value at all" arrives in.
|
|
70
|
+
|
|
71
|
+
`None`, any NaN, and pandas' `pd.NA` / `pd.NaT`. NaN is tested by conversion rather
|
|
72
|
+
than by `isinstance(value, float)`: `numpy.float64` happens to subclass `float`, but
|
|
73
|
+
`numpy.float32` and `Decimal("nan")` do not, and a cell that came out of a frame or a
|
|
74
|
+
parser is under no obligation to be a built-in.
|
|
75
|
+
"""
|
|
76
|
+
if value is None:
|
|
77
|
+
return True
|
|
78
|
+
if type(value).__name__ in _MISSING_TYPE_NAMES:
|
|
79
|
+
return True
|
|
80
|
+
try:
|
|
81
|
+
return bool(math.isnan(value))
|
|
82
|
+
except (TypeError, ValueError):
|
|
83
|
+
return False
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _equals(value: Any, other: str) -> bool:
|
|
87
|
+
"""`value == other` as a real `bool`, False when the two cannot be compared.
|
|
88
|
+
|
|
89
|
+
Guards two things a raw `==` would do to a caller: returning a `numpy.bool_` from a
|
|
90
|
+
function annotated `-> bool`, and raising on a value whose comparison is not a boolean
|
|
91
|
+
at all (an array, or `pd.NA`).
|
|
92
|
+
"""
|
|
93
|
+
try:
|
|
94
|
+
return bool(value == other)
|
|
95
|
+
except (TypeError, ValueError):
|
|
96
|
+
return False
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def is_unlabelled(value: Any) -> bool:
|
|
100
|
+
"""True when a cell says nothing about its field — `None`, `""`, NaN, `pd.NA`, `pd.NaT`.
|
|
101
|
+
|
|
102
|
+
Such a cell is **not** a prediction of "nothing to find": scoring treats it as out of
|
|
103
|
+
scope for that row (partial labelling), so it lands in neither the numerator nor the
|
|
104
|
+
denominator. Contrast `is_no_finding`.
|
|
105
|
+
"""
|
|
106
|
+
return _is_missing_scalar(value) or _equals(value, "")
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def is_no_finding(value: Any) -> bool:
|
|
110
|
+
"""True when a cell asserts "the source states nothing to find" — `"-"`, or `[]` for a list.
|
|
111
|
+
|
|
112
|
+
A graded answer: predicting it against a real label costs recall, and predicting a value
|
|
113
|
+
against it costs precision. `["-"]` is **not** this — it is a list holding one phantom
|
|
114
|
+
element, which scores as a spurious hit; the empty list is how a list field says nothing.
|
|
115
|
+
A missing value is not this either: nothing was asserted at all (see `is_unlabelled`).
|
|
116
|
+
"""
|
|
117
|
+
if isinstance(value, list):
|
|
118
|
+
return not value
|
|
119
|
+
if _is_missing_scalar(value):
|
|
120
|
+
return False
|
|
121
|
+
return _equals(value, NO_FINDING)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# --- List cells --------------------------------------------------------------
|
|
125
|
+
|
|
126
|
+
def parse_list_cell(cell: Any) -> list | None:
|
|
127
|
+
"""The elements of a `list` field's cell, in order — or **None** when it is unlabelled.
|
|
128
|
+
|
|
129
|
+
The sentinel distinction survives the parse, because collapsing it here would quietly
|
|
130
|
+
undo the point of this module: `"-"` and `[]` are the graded no-finding answer and come
|
|
131
|
+
back as `[]`, while a cell that says nothing at all (empty, NaN, `pd.NA`) comes back as
|
|
132
|
+
None. Hand `[]` to the scorer for an unlabelled row and you add an out-of-scope row to
|
|
133
|
+
the denominator.
|
|
134
|
+
|
|
135
|
+
A list repr parses to its elements. A string that is not a list repr is treated as a
|
|
136
|
+
single element — a one-element cell written without brackets is far more likely than a
|
|
137
|
+
caller wanting a crash. A malformed repr (`"['a', "`) likewise degrades to one element
|
|
138
|
+
rather than raising, matching how `validate` leaves an unparsable cell alone instead of
|
|
139
|
+
failing the run.
|
|
140
|
+
|
|
141
|
+
Bracketed-but-unquoted cells (`"[EGFR, KRAS]"`) are split on commas. That form is not a
|
|
142
|
+
Python repr and `literal_eval` rejects it, but it is what this package itself writes:
|
|
143
|
+
`flatten_structured_result` strips the quotes out of a stringified list by default. An
|
|
144
|
+
element containing a comma is therefore only safe in the *quoted* form — in the
|
|
145
|
+
unquoted one the separator is genuinely ambiguous, and splitting is the best available
|
|
146
|
+
reading.
|
|
147
|
+
|
|
148
|
+
Already a list? Returned as a list of itself, so this is safe to apply twice.
|
|
149
|
+
"""
|
|
150
|
+
if isinstance(cell, list):
|
|
151
|
+
return list(cell)
|
|
152
|
+
if _is_missing_scalar(cell):
|
|
153
|
+
return None # says nothing — neither elements nor a no-finding answer
|
|
154
|
+
text = str(cell).strip()
|
|
155
|
+
if text == "":
|
|
156
|
+
return None # an all-whitespace cell says nothing either
|
|
157
|
+
if text == NO_FINDING:
|
|
158
|
+
return []
|
|
159
|
+
if text.startswith("["):
|
|
160
|
+
try:
|
|
161
|
+
parsed = literal_eval(text)
|
|
162
|
+
except (ValueError, SyntaxError):
|
|
163
|
+
if text.endswith("]"): # bracketed but unquoted, e.g. flatten()'s "[A, B]"
|
|
164
|
+
inner = text[1:-1].strip()
|
|
165
|
+
return [part.strip() for part in inner.split(",") if part.strip()] if inner else []
|
|
166
|
+
return [text]
|
|
167
|
+
if isinstance(parsed, (list, tuple, set)):
|
|
168
|
+
return [str(x).strip() for x in parsed]
|
|
169
|
+
return [str(parsed).strip()]
|
|
170
|
+
return [text]
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def format_list_cell(items: Any) -> str:
|
|
174
|
+
"""A `list` field's cell for `items`: `"-"` when there are none, else a list repr.
|
|
175
|
+
|
|
176
|
+
The exact inverse of `parse_list_cell`, distinction included: `[]` is the no-finding
|
|
177
|
+
answer `"-"`, and None — nothing to say about this field — is the empty cell. The form a
|
|
178
|
+
dataset or export should write so the scorer reads back what it was given.
|
|
179
|
+
"""
|
|
180
|
+
if items is None:
|
|
181
|
+
return ""
|
|
182
|
+
if isinstance(items, str):
|
|
183
|
+
return items.strip() or NO_FINDING
|
|
184
|
+
elements = [str(x) for x in items]
|
|
185
|
+
return repr(elements) if elements else NO_FINDING
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
# --- Facet columns -----------------------------------------------------------
|
|
189
|
+
|
|
190
|
+
def facet_columns(field: str) -> tuple[str, str]:
|
|
191
|
+
"""The `(value_column, code_column)` pair a coded field is scored as.
|
|
192
|
+
|
|
193
|
+
Mind the order — **value first**, as in `flatten_structured_result`'s output and the
|
|
194
|
+
`FACET_SUFFIXES` tuple. A field with no `code` is a single column named `field` and has
|
|
195
|
+
no facets at all.
|
|
196
|
+
"""
|
|
197
|
+
return f"{field}{VALUE_SUFFIX}", f"{field}{CODE_SUFFIX}"
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def split_facet(column: str) -> tuple[str, str | None]:
|
|
201
|
+
"""A scored column split into `(field, facet)`, where facet is `"value"`, `"code"`, or None.
|
|
202
|
+
|
|
203
|
+
`"Primary Histology-code"` -> `("Primary Histology", "code")`; a free-form column comes
|
|
204
|
+
back unchanged with a facet of None, so a caller can group facets under their logical
|
|
205
|
+
field without special-casing.
|
|
206
|
+
"""
|
|
207
|
+
for suffix in FACET_SUFFIXES:
|
|
208
|
+
if column.endswith(suffix) and len(column) > len(suffix):
|
|
209
|
+
return column[: -len(suffix)], suffix.lstrip("-")
|
|
210
|
+
return column, None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
# --- Date cells ---------------------------------------------------------------
|
|
214
|
+
|
|
215
|
+
def canonical_date_cell(cell: Any, mask: str = "YYYY-MM-DD", dayFirst: bool = True) -> Any:
|
|
216
|
+
"""`cell`'s canonical date at `mask`, with the sentinels preserved.
|
|
217
|
+
|
|
218
|
+
The cell-level counterpart to `sortable_date.to_canonical_date`, which returns None for
|
|
219
|
+
"no usable date" precisely so a caller can decide what that means in a *cell*. Here:
|
|
220
|
+
|
|
221
|
+
* an **unlabelled** cell (empty, NaN, `pd.NA`) is returned unchanged — it says nothing
|
|
222
|
+
about the field, and turning that into an answer would put an out-of-scope row into a
|
|
223
|
+
scorer's denominator;
|
|
224
|
+
* the **no-finding** cell `"-"` stays `NO_FINDING`;
|
|
225
|
+
* other text is rendered at the mask (see `to_canonical_date` for the rules: the mask
|
|
226
|
+
truncates but never pads, a time is dropped, a year-less date is not a date), and text
|
|
227
|
+
holding **no readable date** becomes `NO_FINDING` — the honest reading of "we looked
|
|
228
|
+
and there is nothing here";
|
|
229
|
+
* anything that is **neither text nor a missing marker** — a list, a number, a `date`
|
|
230
|
+
object — is returned **unchanged**. It is not a date cell at all, so manufacturing a
|
|
231
|
+
sentinel for it would hide a wrong-column-type bug behind a plausible-looking answer.
|
|
232
|
+
`is_canonical_date_cell` rejects it, which is where such a cell should surface. Note
|
|
233
|
+
`[]` lands here: the empty list is the no-finding sentinel of a **list** column, not of
|
|
234
|
+
a date one.
|
|
235
|
+
|
|
236
|
+
For text and for missing markers — everything a cell in such a column should ever hold —
|
|
237
|
+
whatever this returns satisfies `is_canonical_date_cell` for the same `(mask, dayFirst)`,
|
|
238
|
+
so a producer can put dirty text straight through it.
|
|
239
|
+
|
|
240
|
+
An unknown `mask` raises `ValueError`, checked **before** the cell — as in
|
|
241
|
+
`to_canonical_date`. A misspelled column type has to be reported by the first cell it is
|
|
242
|
+
used on, not only by the first cell that happens to carry a date.
|
|
243
|
+
|
|
244
|
+
One caution for **label** builders: text holding no readable date is indistinguishable
|
|
245
|
+
here from a cell that recorded nothing, since both come back as `NO_FINDING`. Compare the
|
|
246
|
+
result against what the source was meant to say and fail the build when they disagree —
|
|
247
|
+
silently mislabelling a row is worse than not building.
|
|
248
|
+
"""
|
|
249
|
+
_precision(mask) # a bad mask is a bad mask, whatever this cell holds
|
|
250
|
+
if is_unlabelled(cell):
|
|
251
|
+
return cell
|
|
252
|
+
if not isinstance(cell, str):
|
|
253
|
+
return cell # not text, not missing: not a date cell — leave it visible
|
|
254
|
+
if is_no_finding(cell):
|
|
255
|
+
return NO_FINDING
|
|
256
|
+
rendered = to_canonical_date(cell, mask, dayFirst=dayFirst)
|
|
257
|
+
return rendered if rendered is not None else NO_FINDING
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def is_canonical_date_cell(cell: Any, mask: str = "YYYY-MM-DD", dayFirst: bool = True) -> bool:
|
|
261
|
+
"""True when a column defined to hold a `mask` date may hold `cell` as it stands.
|
|
262
|
+
|
|
263
|
+
That is: an unlabelled cell, the `"-"` sentinel, or a canonical date at the mask's
|
|
264
|
+
precision **or coarser** (`is_canonical_date`). A test of *cleanliness*, not of
|
|
265
|
+
correctness: a coarser value is clean and will simply score wrong against a finer label.
|
|
266
|
+
Finer than the mask is not clean, and neither is anything `dayFirst` cannot read.
|
|
267
|
+
|
|
268
|
+
A cell that is not text is not a date cell — a list, a number, a `date` object all fail
|
|
269
|
+
here, so a column carrying the wrong sort of cell shows up in validation instead of
|
|
270
|
+
passing as something else. `[]` in particular: it is the no-finding sentinel of a
|
|
271
|
+
**list** column, and this is not one.
|
|
272
|
+
|
|
273
|
+
An unknown `mask` raises `ValueError` rather than answering, checked **before** the cell:
|
|
274
|
+
a validator sweeping a column must not report a malformed schema as clean just because
|
|
275
|
+
the rows it reached were sentinels.
|
|
276
|
+
"""
|
|
277
|
+
_precision(mask) # as in `is_canonical_date`: value-independent
|
|
278
|
+
if is_unlabelled(cell):
|
|
279
|
+
return True
|
|
280
|
+
if not isinstance(cell, str):
|
|
281
|
+
return False
|
|
282
|
+
return is_no_finding(cell) or is_canonical_date(cell, mask, dayFirst=dayFirst)
|
|
@@ -78,6 +78,14 @@ would otherwise reach `.strip()` and raise.
|
|
|
78
78
|
A two-digit number is only read as a year when nothing time-like follows it: `“Feb 20, 12”` is
|
|
79
79
|
February 2012, while `“Feb 20 13:45”` is `????-02-20 13:45` – the 13 is the hour, and the year
|
|
80
80
|
stays unknown rather than being invented (ONC-12551).
|
|
81
|
+
|
|
82
|
+
Canonical dates at a fixed precision
|
|
83
|
+
------------------------------------
|
|
84
|
+
`to_sortable_date` returns *whatever precision the source stated*, optionally with a time.
|
|
85
|
+
A field that is defined to hold a date — a diagnosis date, a treatment start month — wants
|
|
86
|
+
one fixed shape instead, so `to_canonical_date` layers a **mask** on top (`YYYY-MM-DD`,
|
|
87
|
+
`YYYY-MM`, `YYYY`) and `is_canonical_date` tests whether a value already is one. See those
|
|
88
|
+
functions for the rules; both are std-lib only, like everything else here.
|
|
81
89
|
"""
|
|
82
90
|
|
|
83
91
|
import re
|
|
@@ -466,3 +474,94 @@ def to_sortable_date(raw: Any, dayFirst: bool = True) -> str | None:
|
|
|
466
474
|
return f"{int(m[1]):04d}"
|
|
467
475
|
|
|
468
476
|
return None
|
|
477
|
+
|
|
478
|
+
|
|
479
|
+
# ---------------------------------------------------------------------
|
|
480
|
+
# Canonical dates: one fixed precision, for a field defined to hold a date
|
|
481
|
+
# ---------------------------------------------------------------------
|
|
482
|
+
# A mask, mapped to how many components of `YYYY-MM-DD` it keeps.
|
|
483
|
+
DATE_MASKS = {"YYYY-MM-DD": 3, "YYYY-MM": 2, "YYYY": 1}
|
|
484
|
+
|
|
485
|
+
# The shapes a canonical date can take: a real year, optionally a month, optionally a day.
|
|
486
|
+
# Zero-padded, `-`-separated, nothing else — no time, no unknown-year `????`.
|
|
487
|
+
_CANONICAL_DATE_RE = re.compile(r"^\d{4}(-\d{2}){0,2}$")
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def is_date_mask(value: Any) -> bool:
|
|
491
|
+
"""True when `value` names one of the masks in `DATE_MASKS`.
|
|
492
|
+
|
|
493
|
+
For a caller whose schema declares a column's type as a string: this is the test for
|
|
494
|
+
"does this column hold a date", without it having to hard-code the mask names.
|
|
495
|
+
"""
|
|
496
|
+
return isinstance(value, str) and value in DATE_MASKS
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _precision(mask: str) -> int:
|
|
500
|
+
"""How many components `mask` keeps. Raises `ValueError` for a mask that isn't one."""
|
|
501
|
+
try:
|
|
502
|
+
return DATE_MASKS[mask]
|
|
503
|
+
except KeyError:
|
|
504
|
+
raise ValueError(
|
|
505
|
+
f"unknown date mask {mask!r}; expected one of {list(DATE_MASKS)}"
|
|
506
|
+
) from None
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def to_canonical_date(raw: Any, mask: str = "YYYY-MM-DD", dayFirst: bool = True) -> str | None:
|
|
510
|
+
"""`raw`'s date at `mask`'s precision, or **None** when it holds no usable date.
|
|
511
|
+
|
|
512
|
+
Built on `to_sortable_date`, with three rules on top:
|
|
513
|
+
|
|
514
|
+
1. **A date, not a timestamp.** Any time component is dropped — a date field stores a
|
|
515
|
+
date.
|
|
516
|
+
2. **The mask truncates; it never pads.** `"26/11/2024"` under `YYYY-MM` is
|
|
517
|
+
`"2024-11"`. A source *coarser* than the mask stays coarse: `"Nov 2024"` under
|
|
518
|
+
`YYYY-MM-DD` is `"2024-11"`, never `"2024-11-01"` — this function does not invent a
|
|
519
|
+
component the source did not state, so a caller can tell "the source said November"
|
|
520
|
+
from "the source said 1 November".
|
|
521
|
+
3. **No year, no date.** `to_sortable_date` reports a year-less date as `"????-11-26"`;
|
|
522
|
+
here that is None, because an unknown-year value cannot be compared with, or read
|
|
523
|
+
back as, a real date.
|
|
524
|
+
|
|
525
|
+
None is also what an unparsable value, an impossible calendar date (`"2024-02-30"`) and
|
|
526
|
+
a non-string give back. It is deliberately **not** a sentinel: `"-"`, `""` and `None`
|
|
527
|
+
mean different things to different callers (no information vs. not labelled vs. absent),
|
|
528
|
+
so mapping None onto one of them is the caller's decision — see `llmvalidate.cells`.
|
|
529
|
+
|
|
530
|
+
`dayFirst` selects the reading of an ambiguous numeric date, exactly as in
|
|
531
|
+
`to_sortable_date`: `"05/01/2023"` is 5 January when True and 1 May when False. Raises
|
|
532
|
+
`ValueError` for a mask that isn't one of `DATE_MASKS`.
|
|
533
|
+
"""
|
|
534
|
+
components = _precision(mask)
|
|
535
|
+
sortable = to_sortable_date(raw, dayFirst=dayFirst)
|
|
536
|
+
if not sortable:
|
|
537
|
+
return None
|
|
538
|
+
day_part = sortable.split(" ", 1)[0] # rule 1: drop any time
|
|
539
|
+
if not day_part[:4].isdigit(): # rule 3: `????-...` has no year
|
|
540
|
+
return None
|
|
541
|
+
return "-".join(day_part.split("-")[:components]) # rule 2: truncate only
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
def is_canonical_date(value: Any, mask: str = "YYYY-MM-DD", dayFirst: bool = True) -> bool:
|
|
545
|
+
"""True when `value` already *is* a canonical date for `mask` — at that precision or coarser.
|
|
546
|
+
|
|
547
|
+
A test of shape, not of correctness: `"2024-11"` passes for a `YYYY-MM-DD` mask (the
|
|
548
|
+
source stated only a month), while `"2024-11-26"` fails for a `YYYY-MM` mask (finer
|
|
549
|
+
than the field holds). Anything `to_canonical_date` would have rewritten fails —
|
|
550
|
+
`"26/11/2024"`, `"2024-11-26 09:30"`, `"2024-1-5"`, `"2024-02-30"`, `"????-11-26"` —
|
|
551
|
+
which makes `to_canonical_date` idempotent on everything this accepts.
|
|
552
|
+
|
|
553
|
+
Sentinels are the caller's business: `""` and `"-"` are not canonical dates and return
|
|
554
|
+
False here. Pair this with `llmvalidate.cells.is_no_finding` / `is_unlabelled` to decide
|
|
555
|
+
what a whole cell may hold. An unknown `mask` raises `ValueError` as it does in
|
|
556
|
+
`to_canonical_date`, and is checked before anything else — so a bad argument is reported
|
|
557
|
+
whatever value it was handed, not only for the values that reach the round-trip.
|
|
558
|
+
"""
|
|
559
|
+
_precision(mask)
|
|
560
|
+
if not isinstance(value, str):
|
|
561
|
+
return False
|
|
562
|
+
stripped = value.strip()
|
|
563
|
+
if not _CANONICAL_DATE_RE.match(stripped):
|
|
564
|
+
return False
|
|
565
|
+
# Round-trip: only a value this module would itself have produced is canonical. This is
|
|
566
|
+
# what rejects impossible calendar dates, which the shape check alone lets through.
|
|
567
|
+
return to_canonical_date(stripped, mask, dayFirst) == stripped
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
from typing import Any, List, Dict, Optional, Union
|
|
2
2
|
from ast import literal_eval
|
|
3
|
+
from .cells import facet_columns, parse_list_cell
|
|
3
4
|
from .structured import StructuredResult
|
|
4
5
|
import pandas as pd
|
|
5
6
|
import json
|
|
@@ -33,10 +34,9 @@ def convert_lists(data):
|
|
|
33
34
|
# Recover the elements so it is scored set-wise like any other list. The
|
|
34
35
|
# comma is the only separator left in that form, so an element containing one
|
|
35
36
|
# cannot be recovered — which is why nothing writes this form any more.
|
|
36
|
-
|
|
37
|
-
if
|
|
38
|
-
|
|
39
|
-
return [part.strip() for part in inner.split(',') if part.strip()] if inner else []
|
|
37
|
+
# `strip()` first, so padding cannot hide the closing bracket.
|
|
38
|
+
if x.strip().endswith(']'):
|
|
39
|
+
return parse_list_cell(x)
|
|
40
40
|
return x
|
|
41
41
|
return x
|
|
42
42
|
|
|
@@ -94,8 +94,9 @@ def flatten_structured_result(structured_result: StructuredResult) -> Dict[str,
|
|
|
94
94
|
|
|
95
95
|
if field.code is not None:
|
|
96
96
|
# Coded concept -> two scored facets; label columns are named the same.
|
|
97
|
-
|
|
98
|
-
flat[
|
|
97
|
+
value_column, code_column = facet_columns(base_name)
|
|
98
|
+
flat[value_column] = value
|
|
99
|
+
flat[code_column] = field.code
|
|
99
100
|
else:
|
|
100
101
|
flat[base_name] = value
|
|
101
102
|
|
|
@@ -8,6 +8,7 @@ import time
|
|
|
8
8
|
import os
|
|
9
9
|
import concurrent.futures as cf
|
|
10
10
|
from tqdm import tqdm
|
|
11
|
+
from .cells import FACET_SUFFIXES, NO_FINDING, is_no_finding, is_unlabelled
|
|
11
12
|
from .utils import convert_lists, infer_fields
|
|
12
13
|
|
|
13
14
|
def compare_results_binary(expected, actual):
|
|
@@ -277,7 +278,7 @@ def _confidence_column(field, columns):
|
|
|
277
278
|
direct = f'Res: {field} confidence'
|
|
278
279
|
if direct in columns:
|
|
279
280
|
return direct
|
|
280
|
-
for suffix in
|
|
281
|
+
for suffix in FACET_SUFFIXES:
|
|
281
282
|
if field.endswith(suffix):
|
|
282
283
|
parent = f'Res: {field[:-len(suffix)]} confidence'
|
|
283
284
|
if parent in columns:
|
|
@@ -341,7 +342,7 @@ def get_metrics(res_df, fields):
|
|
|
341
342
|
continue # Skip empty confidence groups
|
|
342
343
|
|
|
343
344
|
labeled_cases = field_df[field].count()
|
|
344
|
-
field_present_cases = field_df[field].apply(lambda x: not (is_scalar_empty(x) or x
|
|
345
|
+
field_present_cases = field_df[field].apply(lambda x: not (is_scalar_empty(x) or is_no_finding(x))).sum()
|
|
345
346
|
|
|
346
347
|
TP = TN = FP = FN = \
|
|
347
348
|
cor = inc = mis = spu = par = \
|
|
@@ -562,18 +563,21 @@ def normalize_list(values):
|
|
|
562
563
|
return result
|
|
563
564
|
|
|
564
565
|
def is_scalar_empty(value):
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
566
|
+
"""True when a scalar cell holds no value to compare — not labelled, or no finding.
|
|
567
|
+
|
|
568
|
+
Deliberately covers both: several call sites below only care that there is nothing to
|
|
569
|
+
match. Where the distinction matters (a cell that says nothing vs. one that asserts
|
|
570
|
+
nothing was found), use `llmvalidate.cells.is_unlabelled` / `is_no_finding` instead.
|
|
571
|
+
"""
|
|
572
|
+
return is_unlabelled(value) or value == NO_FINDING
|
|
570
573
|
|
|
571
574
|
def is_expected_undefined(value):
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
575
|
+
"""True when a label cell says nothing about its field (`None` / `""` / NaN).
|
|
576
|
+
|
|
577
|
+
Such a row is out of scope for that field — neither numerator nor denominator — which
|
|
578
|
+
is what makes partial labelling work. `"-"` is *not* undefined: it is a real label.
|
|
579
|
+
"""
|
|
580
|
+
return is_unlabelled(value)
|
|
577
581
|
|
|
578
582
|
def _single_row_worker(row_tuple):
|
|
579
583
|
"""Runs in a separate process / thread.
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|