186 lines
7.6 KiB
Python
186 lines
7.6 KiB
Python
"""Where each field is written, checked against the documents: the model proposes a pattern
|
|
per field from a few documents and the values it read there; a pattern is kept only when
|
|
it captures those very values (through its date format and the site's codes). And the
|
|
site's codes in platform terms, gathered into one ConceptMap."""
|
|
|
|
import re
|
|
from datetime import datetime
|
|
|
|
from fhir.resources.R4B.conceptmap import ConceptMap
|
|
|
|
from core import catalog, concept_map
|
|
from core.drafting import CODES, PATTERNS, codes_schema, is_date, patterns_schema
|
|
from core.pipeline import Extract, convert
|
|
from core.schema import ENTITIES
|
|
from persistance import llm
|
|
|
|
DATE_FORMATS = ("%d/%m/%Y", "%Y-%m-%d", "%d-%m-%Y", "%d.%m.%Y", "%Y/%m/%d", "%m/%d/%Y")
|
|
MANY_CODES = 200 # distinct values of a coded column asked about at most
|
|
|
|
|
|
def _plain(value) -> str:
|
|
return " ".join(str(value).split()).casefold()
|
|
|
|
|
|
def _same(got, want) -> bool:
|
|
"""A captured value, converted, is the value the model read (dates, numbers, text)."""
|
|
got = got.isoformat() if hasattr(got, "isoformat") else got
|
|
try:
|
|
return float(got) == float(want)
|
|
except (TypeError, ValueError):
|
|
return _plain(got) == _plain(want)
|
|
|
|
|
|
def _code(value) -> str:
|
|
"""A model's value as a code: booleans as the platform's yes/no codes."""
|
|
return str(value).lower() if isinstance(value, bool) else str(value)
|
|
|
|
|
|
def target(entity: str, field: str) -> tuple[str | None, set[str] | None]:
|
|
"""The system a field of this study takes codes from (None: not coded) and its allowed
|
|
codes (None: any of the system's)."""
|
|
if entity == "identity":
|
|
return (concept_map.GENDER, {"female", "male"}) if field == "sex" else (None, set())
|
|
found = catalog.studies()[entity].fields[field]
|
|
if found.type == "boolean":
|
|
return concept_map.BOOLEAN, {"true", "false"}
|
|
if found.type == "code":
|
|
return catalog.systems()[found.system].url, set(found.codes) or None
|
|
return None, set()
|
|
|
|
|
|
def coded(entity: str, field: str) -> bool:
|
|
return target(entity, field)[0] is not None
|
|
|
|
|
|
class Codes:
|
|
"""The site's codes found so far: (study, field) -> site value (case ignored) ->
|
|
platform code."""
|
|
|
|
def __init__(self, map_id: str):
|
|
self.map_id, self.found = map_id, {}
|
|
|
|
def known(self, entity: str, field: str, raw: str) -> bool:
|
|
allowed = target(entity, field)[1]
|
|
mapped = self.found.get((entity, field), {})
|
|
return raw.casefold() in mapped or (allowed is not None and raw in allowed)
|
|
|
|
def add(self, entity: str, field: str, raw: str, code: str) -> None:
|
|
if not raw.strip():
|
|
return # nothing written is no code
|
|
self.found.setdefault((entity, field), {})[raw.casefold()] = code
|
|
|
|
def table(self) -> dict[tuple[str, str], dict[str, str]]:
|
|
return self.found
|
|
|
|
def ask(self, entity: str, field: str, raws: set[str]) -> None:
|
|
"""What the platform code is of each value the site writes for `field` that isn't
|
|
one already."""
|
|
new = sorted(r for r in raws if r and not self.known(entity, field, r))[:MANY_CODES]
|
|
if not new:
|
|
return
|
|
allowed = target(entity, field)[1]
|
|
title = ENTITIES[entity].model_fields[field].title or field
|
|
system = CODES.format(title=title, codes=", ".join(sorted(allowed)) if allowed else "any")
|
|
try:
|
|
answer = llm.ask(system, "\n".join(new), codes_schema(new, sorted(allowed or ())))
|
|
except llm.Unreadable: # left uncoded: the run holds them for a reviewer
|
|
return
|
|
for item in answer["codes"]:
|
|
if item["code"] is not None and (allowed is None or item["code"] in allowed):
|
|
self.add(entity, field, item["raw"], item["code"])
|
|
|
|
def for_node(self, entity: str, fields) -> str | None:
|
|
return self.map_id if any((entity, f) in self.found for f in fields) else None
|
|
|
|
def concept_map(self) -> ConceptMap | None:
|
|
"""One group per platform system the codes go to; None when there are none."""
|
|
groups: dict[str, list] = {}
|
|
for (entity, field), codes in self.found.items():
|
|
system = target(entity, field)[0]
|
|
for raw, code in sorted(codes.items()):
|
|
element = {"code": raw, "target": [{"code": code, "equivalence": "equivalent"}]}
|
|
if element not in groups.setdefault(system, []):
|
|
groups[system].append(element)
|
|
if not groups:
|
|
return None
|
|
found = ConceptMap.model_validate({
|
|
"resourceType": "ConceptMap", "status": "active", "id": self.map_id.replace("_", "-"),
|
|
"title": f"{self.map_id}: los códigos del sitio, como los leyó Automático",
|
|
"group": [{"source": f"urn:isssteleon:site:{self.map_id}", "target": t, "element": e}
|
|
for t, e in groups.items()],
|
|
}) # fmt: skip
|
|
if problems := concept_map.problems(found):
|
|
raise ValueError(f"drafted codes refused: {problems}")
|
|
return found
|
|
|
|
|
|
def rules(entity: str, read: list[tuple[str, dict]], codes: Codes) -> tuple[dict, dict]:
|
|
"""Patterns and date formats for the fields the model read in these documents (text,
|
|
values): one per field, kept only if it captures every value read."""
|
|
fields = sorted({f for _, values in read for f in values})
|
|
if not fields:
|
|
return {}, {}
|
|
shown = "\n\n---\n\n".join(
|
|
f"{text}\n\nVALUES: " + "; ".join(f"{f} = {v}" for f, v in values.items())
|
|
for text, values in read
|
|
)
|
|
try:
|
|
proposed = llm.ask(PATTERNS, shown, patterns_schema(fields))
|
|
except llm.Unreadable: # no patterns: these fields are read by the model alone
|
|
return {}, {}
|
|
patterns, formats = {}, {}
|
|
for field in fields:
|
|
rule = proposed.get(field) or {}
|
|
fmt = rule.get("format") if is_date(entity, field) else None
|
|
if checks(entity, field, rule.get("pattern") or "", fmt, read, codes):
|
|
patterns[field] = rule["pattern"]
|
|
if fmt:
|
|
formats[field] = fmt
|
|
return patterns, formats
|
|
|
|
|
|
def checks(entity, field, pattern, fmt, read, codes: Codes) -> bool:
|
|
try:
|
|
if re.compile(pattern, re.IGNORECASE).groups != 1:
|
|
return False
|
|
except re.error:
|
|
return False
|
|
probe = Extract(id="probe", column="text", entity=entity, formats={field: fmt} if fmt else {})
|
|
pairs = {}
|
|
for text, values in read:
|
|
if field not in values:
|
|
continue
|
|
found = re.search(pattern, text, re.IGNORECASE)
|
|
if not found or not (found.group(1) or "").strip():
|
|
return False # where the model read a value, the pattern takes text
|
|
raw, want = " ".join(found.group(1).split()), values[field]
|
|
if coded(entity, field):
|
|
pairs.setdefault(raw.casefold(), set()).add(_code(want))
|
|
elif not _same(convert(probe, field, raw, {}), want):
|
|
return False
|
|
if any(len(v) > 1 for v in pairs.values()):
|
|
return False # one written value, two meanings: the pattern takes the wrong text
|
|
for raw, (code,) in pairs.items():
|
|
if raw != code.casefold():
|
|
codes.add(entity, field, raw, code)
|
|
return True
|
|
|
|
|
|
def date_format(values: list) -> str | None:
|
|
"""The strptime format every written date of a column parses with (None: they are
|
|
dates already, or none fits)."""
|
|
written = [v.strip() for v in values if isinstance(v, str) and v.strip()]
|
|
for fmt in DATE_FORMATS:
|
|
if written and all(_parses(v, fmt) for v in written):
|
|
return fmt
|
|
return None
|
|
|
|
|
|
def _parses(value: str, fmt: str) -> bool:
|
|
try:
|
|
datetime.strptime(value, fmt)
|
|
except ValueError:
|
|
return False
|
|
return True
|