Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 8548eb8d9e |
@@ -115,6 +115,13 @@ def last_screening_cytology(events: pd.DataFrame) -> pd.Series:
|
|||||||
key = ["person_id", "source_table", "source_id"]
|
key = ["person_id", "source_table", "source_id"]
|
||||||
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
samples = events.loc[(events["type"] == "cytology") & ~events["person_id"].isin(referred),
|
||||||
[*key, "date"]] # fmt: skip
|
[*key, "date"]] # fmt: skip
|
||||||
|
hysterectomy = events.loc[
|
||||||
|
(events["source_table"] == "cervical_cytology")
|
||||||
|
& (events["type"] == "gynecologic_condition")
|
||||||
|
& (events["value_code"] == "hysterectomy")
|
||||||
|
].groupby("person_id")["date"].min()
|
||||||
|
recorded = samples["person_id"].map(hysterectomy)
|
||||||
|
samples = samples[recorded.isna() | (samples["date"] < recorded)]
|
||||||
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
results = events[events["type"].isin(RESULTS) & events["value_code"].notna()]
|
||||||
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
has = results.pivot_table(index=key, columns="type", values="value_code", aggfunc="first")
|
||||||
has = has.reindex(columns=list(RESULTS))
|
has = has.reindex(columns=list(RESULTS))
|
||||||
|
|||||||
+2
-24
@@ -6,7 +6,7 @@ from datetime import date
|
|||||||
|
|
||||||
import dagster as dg
|
import dagster as dg
|
||||||
|
|
||||||
from models import draft, graph
|
from models import graph
|
||||||
from models.jobs import EmptyCohort
|
from models.jobs import EmptyCohort
|
||||||
from persistance import backup as backups
|
from persistance import backup as backups
|
||||||
from persistance import config_log, silver
|
from persistance import config_log, silver
|
||||||
@@ -33,28 +33,6 @@ def ingest():
|
|||||||
run_pipeline()
|
run_pipeline()
|
||||||
|
|
||||||
|
|
||||||
class DraftRun(dg.Config):
|
|
||||||
pipeline: str
|
|
||||||
run: bool = True # False: drawn and saved only (a large site, read later)
|
|
||||||
|
|
||||||
|
|
||||||
@dg.op
|
|
||||||
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
|
|
||||||
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
|
|
||||||
run (unless `run` is off). Returns that version."""
|
|
||||||
drafted = draft.draft(config.pipeline, log=context.log.info)
|
|
||||||
version = config_log.save(config.pipeline, drafted)
|
|
||||||
context.log.info(f"{config.pipeline} v{version}: {len(drafted.nodes)} nodes drafted")
|
|
||||||
if config.run:
|
|
||||||
graph.run(config.pipeline, drafted, log=context.log.info)
|
|
||||||
return version
|
|
||||||
|
|
||||||
|
|
||||||
@dg.job(name="draft", tags=WRITES)
|
|
||||||
def draft_job():
|
|
||||||
draft_pipeline()
|
|
||||||
|
|
||||||
|
|
||||||
def _jobs(domain: str):
|
def _jobs(domain: str):
|
||||||
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
"""The domain's model jobs (`models.<domain>.jobs`: MODELS, train, score)."""
|
||||||
try:
|
try:
|
||||||
@@ -153,4 +131,4 @@ nightly = (
|
|||||||
else []
|
else []
|
||||||
)
|
)
|
||||||
|
|
||||||
defs = dg.Definitions(jobs=[ingest, draft_job, train, score, analyze, backup], schedules=nightly)
|
defs = dg.Definitions(jobs=[ingest, train, score, analyze, backup], schedules=nightly)
|
||||||
|
|||||||
@@ -1,87 +0,0 @@
|
|||||||
"""Automático: a whole pipeline drafted from the sources an operator connected. Each source
|
|
||||||
is loaded and its files read as a run would; documents are drafted by layout
|
|
||||||
(models.draft.documents), tables by column (models.draft.tables); one link node gathers
|
|
||||||
every record's identity and one target per study saves it. The model only fills typed
|
|
||||||
slots that code checks; who is the same patient stays with the reviewers."""
|
|
||||||
|
|
||||||
import re
|
|
||||||
import unicodedata
|
|
||||||
from collections.abc import Callable
|
|
||||||
|
|
||||||
from core.pipeline import ENTITY_TITLES, Link, Pipeline, Read, Target
|
|
||||||
from models import graph
|
|
||||||
from models.draft import documents, fields, tables
|
|
||||||
from persistance import config_log, files, nodes
|
|
||||||
|
|
||||||
FILE_KEY = re.compile(r"^[0-9a-f]{64}$") # a kept file's key (persistance.files)
|
|
||||||
SCANNED = 50 # rows looked at to tell a column of files
|
|
||||||
|
|
||||||
|
|
||||||
class Draft:
|
|
||||||
"""The nodes drafted so far, their ids unique, and the site's codes found."""
|
|
||||||
|
|
||||||
def __init__(self, pipeline_id: str, sources: list):
|
|
||||||
self.pipeline_id, self.nodes = pipeline_id, list(sources)
|
|
||||||
self.identity: list[str] = []
|
|
||||||
self.studies: dict[str, list[str]] = {}
|
|
||||||
self.codes = fields.Codes(pipeline_id)
|
|
||||||
|
|
||||||
def id(self, text: str) -> str:
|
|
||||||
plain = unicodedata.normalize("NFKD", text).encode("ascii", "ignore").decode().lower()
|
|
||||||
base = re.sub(r"[^a-z0-9]+", "_", plain).strip("_")[:34] or "nodo"
|
|
||||||
base = base if base[0].isalpha() else f"n_{base}"[:34]
|
|
||||||
taken, found, n = {n.id for n in self.nodes}, base, 1
|
|
||||||
while found in taken:
|
|
||||||
n += 1
|
|
||||||
found = f"{base}_{n}"
|
|
||||||
return found
|
|
||||||
|
|
||||||
def add(self, node):
|
|
||||||
self.nodes.append(node)
|
|
||||||
return node
|
|
||||||
|
|
||||||
def finish(self) -> Pipeline:
|
|
||||||
"""The site's codes saved as its ConceptMap, one link node, a target per study."""
|
|
||||||
if not self.identity:
|
|
||||||
raise ValueError("nothing read says whom a record is about: nothing to link")
|
|
||||||
if (found := self.codes.concept_map()) is not None:
|
|
||||||
config_log.save(self.codes.map_id, found, "concept_maps")
|
|
||||||
link = self.add(Link(id=self.id("personas"), label="Quién es quién",
|
|
||||||
inputs=self.identity)) # fmt: skip
|
|
||||||
for entity, inputs in self.studies.items():
|
|
||||||
self.add(Target(id=self.id(f"guardar_{entity}"), label=ENTITY_TITLES[entity],
|
|
||||||
inputs=[*inputs, link.id], entity=entity)) # fmt: skip
|
|
||||||
return Pipeline(nodes=self.nodes)
|
|
||||||
|
|
||||||
|
|
||||||
def file_columns(rows: list[dict]) -> list[str]:
|
|
||||||
"""Columns whose values are kept files (a source keeps each file once and passes its key)."""
|
|
||||||
found = []
|
|
||||||
for column in sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")}):
|
|
||||||
values = {r.get(column) for r in rows[:SCANNED]} - {None}
|
|
||||||
if values and all(isinstance(v, str) and FILE_KEY.match(v) for v in values):
|
|
||||||
if files.known(values):
|
|
||||||
found.append(column)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def draft(pipeline_id: str, log: Callable[[str], None] = print) -> Pipeline:
|
|
||||||
"""The pipeline Automático draws from a saved pipeline made of sources only."""
|
|
||||||
_, saved = config_log.get(pipeline_id)
|
|
||||||
sources = [n for n in saved.nodes if n.kind == "source"]
|
|
||||||
if not sources or len(sources) != len(saved.nodes):
|
|
||||||
raise ValueError("Automático starts from a pipeline that holds only its sources")
|
|
||||||
d = Draft(pipeline_id, sources)
|
|
||||||
for source in sources:
|
|
||||||
nodes.run_source(pipeline_id, source)
|
|
||||||
rows = list(nodes.rows(pipeline_id, source.id))
|
|
||||||
log(f"{source.id}: {len(rows)} rows")
|
|
||||||
found = file_columns(rows)
|
|
||||||
for column in found:
|
|
||||||
read = d.add(Read(id=d.id(f"texto_{source.id}"), label="Texto de cada documento",
|
|
||||||
inputs=[source.id], column=column)) # fmt: skip
|
|
||||||
graph.run_read(pipeline_id, read)
|
|
||||||
documents.draft(d, read, list(nodes.rows(pipeline_id, read.id)), log)
|
|
||||||
if not found:
|
|
||||||
tables.draft(d, source, rows, log)
|
|
||||||
return d.finish()
|
|
||||||
@@ -1,205 +0,0 @@
|
|||||||
"""Documents (a column of files, read to text): grouped by layout, each layout named by the
|
|
||||||
model with the studies it reports and the phrases that mark it and each of them (a route,
|
|
||||||
and a route under it for a study only some of its documents report: the organ a
|
|
||||||
pathology report is about, a note that records a death), and read for each study (joined
|
|
||||||
to the documents it answers, if it needs them: joins) and for whom it is about (extract
|
|
||||||
nodes, with patterns for when no model answers). What no layout claims goes to the
|
|
||||||
unrecognised route, for a reviewer."""
|
|
||||||
|
|
||||||
import dataclasses
|
|
||||||
import re
|
|
||||||
from collections import Counter
|
|
||||||
from dataclasses import dataclass
|
|
||||||
|
|
||||||
from core.drafting import LAYOUT, layout_schema, studies_text
|
|
||||||
from core.pipeline import ENTITY_TITLES, Condition, Extract, Join, Read, Route, ground
|
|
||||||
from models import graph
|
|
||||||
from models.draft import fields, joins
|
|
||||||
from models.draft.joins import Kind
|
|
||||||
from models.draft.layouts import (
|
|
||||||
LOOSE,
|
|
||||||
condition,
|
|
||||||
diverse,
|
|
||||||
kinds_of,
|
|
||||||
layouts,
|
|
||||||
marks,
|
|
||||||
phrase,
|
|
||||||
printed_line,
|
|
||||||
spread,
|
|
||||||
)
|
|
||||||
from persistance import llm
|
|
||||||
|
|
||||||
SAMPLE = 2000 # documents grouped by layout at most (grouping compares every pair)
|
|
||||||
SHOWN = 8 # documents of a layout the model is shown to name its studies
|
|
||||||
PER_STUDY = 3 # documents of a study the model reads for where each field is written
|
|
||||||
CHARS = 3000 # of each document shown to name a layout (its title and labels come first)
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Layout:
|
|
||||||
label: str
|
|
||||||
marker: str
|
|
||||||
members: list[dict] = dataclasses.field(default_factory=list)
|
|
||||||
everyone: list[dict] = dataclasses.field(default_factory=list)
|
|
||||||
route: Route | None = None
|
|
||||||
|
|
||||||
|
|
||||||
def draft(d, read: Read, rows: list[dict], log) -> None:
|
|
||||||
"""Routes, extracts (and joins) and the unrecognised route for one read node's
|
|
||||||
documents."""
|
|
||||||
documents = sorted((r for r in rows if r.get("text")), key=lambda r: r["_record"])
|
|
||||||
sample = spread(documents, SAMPLE)
|
|
||||||
groups: dict[int, list[dict]] = {}
|
|
||||||
for row, group in zip(sample, layouts([r["text"] for r in sample]), strict=True):
|
|
||||||
if group >= 0:
|
|
||||||
groups.setdefault(group, []).append(row)
|
|
||||||
answers = []
|
|
||||||
for members in groups.values():
|
|
||||||
shown = diverse(members, SHOWN)
|
|
||||||
text = "\n\n".join(f"=== Documento {i} ===\n{r['text'][:CHARS]}"
|
|
||||||
for i, r in enumerate(shown, 1)) # fmt: skip
|
|
||||||
answer = llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema(len(shown)))
|
|
||||||
answers.append((answer, members, shown))
|
|
||||||
found, kinds = {}, {}
|
|
||||||
for answer, members, shown in answers:
|
|
||||||
entities = {s["entity"] for s in answer["studies"]}
|
|
||||||
others = [r for a, m, _ in answers if not entities & {s["entity"] for s in a["studies"]}
|
|
||||||
for r in m] # fmt: skip
|
|
||||||
marker = " ".join(answer["marker"].split())
|
|
||||||
marker = phrase(marker, members, others) or printed_line(
|
|
||||||
members, [r for _, m, _ in answers if m is not members for r in m]
|
|
||||||
)
|
|
||||||
log(f"layout of {len(members)}: «{marker}» {sorted(entities) or 'no study'}")
|
|
||||||
if marker is None or not entities:
|
|
||||||
continue
|
|
||||||
layout = found.setdefault(marker.casefold(), Layout(answer["label"], marker))
|
|
||||||
layout.members.extend(members)
|
|
||||||
for one in answer["studies"]:
|
|
||||||
claimed = {i for o in answer["studies"] if o is not one for i in o["documents"]}
|
|
||||||
if (sub := apart(one, shown, claimed, log)) is False:
|
|
||||||
continue
|
|
||||||
kind = kinds.setdefault((marker.casefold(), one["entity"], (sub or "").casefold()),
|
|
||||||
Kind(one["entity"], one["label"], sub or "", [],
|
|
||||||
layout=layout)) # fmt: skip
|
|
||||||
kind.members.extend(r for r in members if not sub or marks(sub, r["text"]))
|
|
||||||
routes(d, read, documents, list(found.values()), list(kinds.values()))
|
|
||||||
for kind in kinds.values():
|
|
||||||
d.studies.setdefault(kind.entity, []).append(study(d, kind, list(kinds.values()), log))
|
|
||||||
for layout in found.values():
|
|
||||||
shown = [(r["text"], r) for r in diverse(layout.members, PER_STUDY)]
|
|
||||||
texts = [r["text"] for r in layout.everyone]
|
|
||||||
d.identity.append(extract(d, layout.route, layout.route.id, "identity", "text",
|
|
||||||
reading("identity", shown), texts)) # fmt: skip
|
|
||||||
d.add(Route(id=d.id("no_reconocidos"), label="Documentos no reconocidos",
|
|
||||||
inputs=[read.id], otherwise=True)) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def apart(study: dict, shown: list[dict], claimed: set[int], log) -> str | None | bool:
|
|
||||||
"""What marks the documents of a layout that report `study`: None when all of them do,
|
|
||||||
or when those the model left out report no other study (`claimed`: those another does;
|
|
||||||
the model is not asked to be exhaustive), a phrase found in each of those it named and
|
|
||||||
in none of the others, False when no such phrase is found (the study is left out)."""
|
|
||||||
named = {i for i in study["documents"] if 1 <= i <= len(shown)}
|
|
||||||
if not named:
|
|
||||||
return False
|
|
||||||
if not (set(range(1, len(shown) + 1)) - named) & claimed:
|
|
||||||
return None
|
|
||||||
mine = [r for i, r in enumerate(shown, 1) if i in named]
|
|
||||||
rest = [r for i, r in enumerate(shown, 1) if i not in named]
|
|
||||||
if found := phrase(" ".join((study["marker"] or "").split()), mine, rest, share=1.0):
|
|
||||||
return found
|
|
||||||
telling = lambda line: (-kinds_of(line, shown), len(line)) # noqa: E731
|
|
||||||
line = printed_line(mine, rest, share=1.0, rank=telling)
|
|
||||||
if line and kinds_of(line, shown) < len(shown): # a value others share: no one's name
|
|
||||||
return line
|
|
||||||
log(f"{study['label']}: nothing marks its documents apart from the layout's others")
|
|
||||||
return False
|
|
||||||
|
|
||||||
|
|
||||||
def routes(d, read: Read, documents, found: list[Layout], kinds: list[Kind]) -> None:
|
|
||||||
"""A route per layout, and under it one per study only some of its documents report;
|
|
||||||
two named alike are told apart by what marks them."""
|
|
||||||
routed = [*found, *(k for k in kinds if k.marker)]
|
|
||||||
named, seen = Counter(x.label.casefold() for x in routed), Counter()
|
|
||||||
for x in routed:
|
|
||||||
if named[x.label.casefold()] > 1:
|
|
||||||
seen[x.label.casefold()] += 1
|
|
||||||
said = x.marker[:40] + ("…" if len(x.marker) > 40 else "")
|
|
||||||
x.label += (
|
|
||||||
f" {seen[x.label.casefold()]}" if x.marker.startswith(LOOSE) else f" · {said}"
|
|
||||||
)
|
|
||||||
for layout in found:
|
|
||||||
layout.route = d.add(Route(id=d.id(layout.label), label=layout.label, inputs=[read.id],
|
|
||||||
when=[Condition(**condition(layout.marker))])) # fmt: skip
|
|
||||||
layout.everyone = [r for r in documents if marks(layout.marker, r["text"])]
|
|
||||||
for kind in kinds:
|
|
||||||
kind.route, kind.everyone = kind.layout.route, kind.layout.everyone
|
|
||||||
if kind.marker:
|
|
||||||
kind.route = d.add(Route(id=d.id(kind.label), label=kind.label,
|
|
||||||
inputs=[kind.layout.route.id],
|
|
||||||
when=[Condition(**condition(kind.marker))])) # fmt: skip
|
|
||||||
kind.everyone = [r for r in kind.everyone if marks(kind.marker, r["text"])]
|
|
||||||
|
|
||||||
|
|
||||||
def study(d, kind: Kind, kinds: list[Kind], log) -> str:
|
|
||||||
"""The extract node of a kind's study; on a join with the kind that pairs with it when,
|
|
||||||
reading both, the model takes a field the study requires from the other document (an
|
|
||||||
outsourced report's sample date is the order's, not the report's own date)."""
|
|
||||||
shown = diverse(kind.members, PER_STUDY)
|
|
||||||
read = reading(kind.entity, [(r["text"], r) for r in shown])
|
|
||||||
texts = [r["text"] for r in kind.everyone]
|
|
||||||
if found := joins.partner(kind, kinds):
|
|
||||||
other, column = found
|
|
||||||
node = Join(
|
|
||||||
id=d.id(f"{kind.route.id}_con_{other.route.id}"),
|
|
||||||
label=f"{kind.label} con {other.label}",
|
|
||||||
inputs=[kind.route.id, other.route.id],
|
|
||||||
on=[(column, column)],
|
|
||||||
how="left",
|
|
||||||
)
|
|
||||||
paired = [(t, r) for t, r in joins.joined(node, kind.members, other)
|
|
||||||
if joins.apart_from(r, other)] # fmt: skip
|
|
||||||
pairs = spread(paired, PER_STUDY) or joins.joined(node, shown, other)
|
|
||||||
again = reading(kind.entity, pairs)
|
|
||||||
if taken := joins.taken(kind.entity, again, [r for _, r in pairs], other):
|
|
||||||
log(f"{kind.label}: read with {other.label} (same {column}): {taken} is in it")
|
|
||||||
d.add(node)
|
|
||||||
texts = [t for t, _ in joins.joined(node, kind.everyone, other)]
|
|
||||||
return extract(d, node, kind.route.id, kind.entity, joins.text_columns(other),
|
|
||||||
again, texts) # fmt: skip
|
|
||||||
log(f"{kind.label}: pairs with {other.label} (same {column}), needs nothing of it")
|
|
||||||
return extract(d, kind.route, kind.route.id, kind.entity, "text", read, texts)
|
|
||||||
|
|
||||||
|
|
||||||
def reading(entity: str, shown: list[tuple[str, dict]]) -> list[tuple[str, dict, dict]]:
|
|
||||||
"""What the model reads of `entity` in each text, only what the text says: (text,
|
|
||||||
values, the text each was read from)."""
|
|
||||||
out = []
|
|
||||||
for text, row in shown:
|
|
||||||
try:
|
|
||||||
answered = ground(graph.answer(entity, text, "", graph.images(row)), text)
|
|
||||||
except llm.Unreadable: # nothing read from this one
|
|
||||||
answered = []
|
|
||||||
values, quotes, _ = answered[0] if answered else ({}, {}, [])
|
|
||||||
kept = {f: v for f, v in values.items() if v is not None}
|
|
||||||
out.append((text, kept, {f: quotes[f] for f in kept}))
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def extract(d, source, name: str, entity: str, column, read, texts: list[str]) -> str:
|
|
||||||
"""An extract node of `entity` on `source`'s rows: the model's reading of a few of them
|
|
||||||
gives each field's pattern (and the site's codes), kept if it checks out."""
|
|
||||||
patterns, formats = fields.rules(entity, [(t, v) for t, v, _ in read], d.codes)
|
|
||||||
for field, pattern in patterns.items():
|
|
||||||
if fields.coded(entity, field):
|
|
||||||
raws = set()
|
|
||||||
for text in texts:
|
|
||||||
if found := re.search(pattern, text, re.IGNORECASE):
|
|
||||||
raws.add(" ".join(found.group(1).split()))
|
|
||||||
d.codes.ask(entity, field, raws)
|
|
||||||
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
|
||||||
node = Extract(id=d.id(f"{entity}_{name}"), label=f"{title} ({source.label})",
|
|
||||||
inputs=[source.id], column=column, entity=entity, method="auto",
|
|
||||||
patterns=patterns, formats=formats,
|
|
||||||
concept_map=d.codes.for_node(entity, patterns)) # fmt: skip
|
|
||||||
return d.add(node).id
|
|
||||||
@@ -1,179 +0,0 @@
|
|||||||
"""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")
|
|
||||||
answer = llm.ask(system, "\n".join(new), codes_schema(new, sorted(allowed or ())))
|
|
||||||
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
|
|
||||||
)
|
|
||||||
proposed = llm.ask(PATTERNS, shown, patterns_schema(fields))
|
|
||||||
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
|
|
||||||
@@ -1,99 +0,0 @@
|
|||||||
"""A kind of document that leaves a date its study requires to another (an outsourced
|
|
||||||
lab's report leaves the sample's date to the order it answers) is read together with
|
|
||||||
it: the kind of the same source a column both carry pairs each of its documents with, one
|
|
||||||
to one. The pairing is kept only if the model, reading both, takes such a field from the
|
|
||||||
other document."""
|
|
||||||
|
|
||||||
from dataclasses import dataclass, field
|
|
||||||
|
|
||||||
from core.pipeline import Join, Route, grounded, join
|
|
||||||
from core.schema import ENTITIES
|
|
||||||
from models.graph import FILE, READ_COLUMNS
|
|
||||||
|
|
||||||
PAIRED = 0.5 # share of a kind's documents that must find exactly one partner
|
|
||||||
|
|
||||||
|
|
||||||
@dataclass
|
|
||||||
class Kind:
|
|
||||||
"""Documents of a layout that report one study (all of the layout's, or those `marker`
|
|
||||||
sets apart): their route, those sampled, all of them."""
|
|
||||||
|
|
||||||
entity: str
|
|
||||||
label: str
|
|
||||||
marker: str
|
|
||||||
members: list[dict] # those sampled
|
|
||||||
everyone: list[dict] = field(default_factory=list)
|
|
||||||
route: Route | None = None
|
|
||||||
layout: object = None # the layout these documents are of (documents.Layout)
|
|
||||||
|
|
||||||
|
|
||||||
def required(entity: str) -> set[str]:
|
|
||||||
return {f for f, info in ENTITIES[entity].model_fields.items() if info.is_required()}
|
|
||||||
|
|
||||||
|
|
||||||
def _keys(row: dict) -> dict:
|
|
||||||
"""The columns of a row that may pair it: the source's own, never its text or file."""
|
|
||||||
return {
|
|
||||||
c: v
|
|
||||||
for c, v in row.items()
|
|
||||||
if not c.startswith("_") and c not in READ_COLUMNS and c != FILE
|
|
||||||
and isinstance(v, str | int) and v != ""
|
|
||||||
} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def partner(kind: Kind, kinds: list[Kind]) -> tuple[Kind, str] | None:
|
|
||||||
"""The other kind and the column that pair most of this kind's documents with exactly
|
|
||||||
one document each (never with themselves); None if none pairs half."""
|
|
||||||
best = None
|
|
||||||
for other in kinds:
|
|
||||||
if other is kind or not kind.everyone:
|
|
||||||
continue
|
|
||||||
index: dict[tuple[str, object], set] = {}
|
|
||||||
for row in other.everyone:
|
|
||||||
for c, v in _keys(row).items():
|
|
||||||
index.setdefault((c, v), set()).add(row["_record"])
|
|
||||||
paired: dict[str, int] = {}
|
|
||||||
for row in kind.everyone:
|
|
||||||
for c, v in _keys(row).items():
|
|
||||||
if len(index.get((c, v), set()) - {row["_record"]}) == 1:
|
|
||||||
paired[c] = paired.get(c, 0) + 1
|
|
||||||
for c, n in paired.items():
|
|
||||||
share = n / len(kind.everyone)
|
|
||||||
if share >= PAIRED and (best is None or share > best[0]):
|
|
||||||
best = (share, other, c)
|
|
||||||
return (best[1], best[2]) if best else None
|
|
||||||
|
|
||||||
|
|
||||||
def joined(node: Join, rows: list[dict], other: Kind) -> list[tuple[str, dict]]:
|
|
||||||
"""Each row with its partner's text before its own, as the extract node will read it."""
|
|
||||||
columns = text_columns(other)
|
|
||||||
return [("\n".join(str(r[c]) for c in columns if r.get(c)), r)
|
|
||||||
for r in join(node, rows, other.everyone, other.route.id)] # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def apart_from(row: dict, other: Kind) -> bool:
|
|
||||||
"""A joined row whose partner is another document (a file holding both the order and
|
|
||||||
the report pairs with itself: it needs no join)."""
|
|
||||||
return row.get(f"_record__{other.route.id}") not in (None, row["_record"])
|
|
||||||
|
|
||||||
|
|
||||||
def taken(entity: str, read, rows: list[dict], other: Kind) -> set[str]:
|
|
||||||
"""Fields the study requires that the model, reading a document with its partner, took
|
|
||||||
from the partner's text (not its own) in most of the documents that have one."""
|
|
||||||
theirs_column = text_columns(other)[0]
|
|
||||||
partnered = [(quotes, row) for (_, _, quotes), row in zip(read, rows, strict=True)
|
|
||||||
if row.get(theirs_column) and apart_from(row, other)] # fmt: skip
|
|
||||||
found = set()
|
|
||||||
for name in required(entity):
|
|
||||||
theirs = sum(
|
|
||||||
name in quotes and grounded(quotes[name], row[theirs_column])
|
|
||||||
and not grounded(quotes[name], row["text"])
|
|
||||||
for quotes, row in partnered
|
|
||||||
) # fmt: skip
|
|
||||||
if partnered and theirs * 2 > len(partnered):
|
|
||||||
found.add(name)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def text_columns(other: Kind) -> list[str]:
|
|
||||||
return [f"text__{other.route.id}", "text"]
|
|
||||||
@@ -1,137 +0,0 @@
|
|||||||
"""Documents told apart by their layout (the words a form prints), the documents of a
|
|
||||||
layout the model is shown (as unlike each other as they come, so a rare kind of note is
|
|
||||||
among them), and the phrases that mark documents (what a route tests)."""
|
|
||||||
|
|
||||||
import re
|
|
||||||
import unicodedata
|
|
||||||
from collections import Counter
|
|
||||||
|
|
||||||
import numpy as np
|
|
||||||
from sklearn.cluster import AgglomerativeClustering
|
|
||||||
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
|
|
||||||
|
|
||||||
DISTANCE = 0.5 # cosine distance under which two documents share a layout
|
|
||||||
COVERED = 0.9 # share of a layout's documents its marker must be found in
|
|
||||||
WORDS = r"(?u)\b[^\W\d_]{3,}\b" # words, never numbers: a layout, not its values
|
|
||||||
LINE = re.compile(r"^(?=.*[^\W\d_]{4})[^\d]{8,}$") # a printed label: words, no values
|
|
||||||
LOOSE = "(?i)" # a marker written as a pattern (op `matches`), not a phrase (`contains`)
|
|
||||||
ACCENTED = {"a": "aá", "e": "eé", "i": "ií", "o": "oó", "u": "uúü", "n": "nñ"}
|
|
||||||
GAP = r"\W+(?:[^\W_]+\W+){0,2}?" # up to two words the model left out (DERECHA)
|
|
||||||
|
|
||||||
|
|
||||||
def layouts(texts: list[str]) -> list[int]:
|
|
||||||
"""A layout number per document: documents that print mostly the same words (a form's
|
|
||||||
labels) share one. Words seen in a single document (a name) don't count."""
|
|
||||||
if len(texts) < 2:
|
|
||||||
return [0] * len(texts)
|
|
||||||
try:
|
|
||||||
words = CountVectorizer(token_pattern=WORDS, binary=True, min_df=2).fit_transform(texts)
|
|
||||||
except ValueError: # no word in two documents: nothing to tell them apart by
|
|
||||||
return [0] * len(texts)
|
|
||||||
found = [-1] * len(texts)
|
|
||||||
worded = [i for i in range(len(texts)) if words[i].nnz]
|
|
||||||
if len(worded) < 2:
|
|
||||||
return [0 if i in worded else -1 for i in range(len(texts))]
|
|
||||||
groups = AgglomerativeClustering(
|
|
||||||
n_clusters=None, metric="cosine", linkage="average", distance_threshold=DISTANCE
|
|
||||||
).fit_predict(words[worded].toarray())
|
|
||||||
for i, group in zip(worded, groups, strict=True):
|
|
||||||
found[i] = int(group)
|
|
||||||
return found
|
|
||||||
|
|
||||||
|
|
||||||
def diverse(rows: list[dict], n: int) -> list[dict]:
|
|
||||||
"""`n` of a layout's documents, each the least like those already taken (the first, the
|
|
||||||
most typical): what sets a few documents apart (an organ, a death) is among them."""
|
|
||||||
if len(rows) <= n:
|
|
||||||
return rows
|
|
||||||
try:
|
|
||||||
x = TfidfVectorizer(token_pattern=WORDS).fit_transform([r["text"] for r in rows])
|
|
||||||
except ValueError:
|
|
||||||
return spread(rows, n)
|
|
||||||
alike = (x @ x.T).toarray()
|
|
||||||
taken = [int(alike.sum(axis=1).argmax())]
|
|
||||||
nearest = alike[taken[0]].copy()
|
|
||||||
while len(taken) < n:
|
|
||||||
nearest[taken] = np.inf
|
|
||||||
taken.append(int(nearest.argmin()))
|
|
||||||
nearest = np.maximum(nearest, alike[taken[-1]])
|
|
||||||
return [rows[i] for i in sorted(taken)]
|
|
||||||
|
|
||||||
|
|
||||||
def spread(items: list, n: int) -> list:
|
|
||||||
"""`n` items from first to last."""
|
|
||||||
if len(items) <= n:
|
|
||||||
return items
|
|
||||||
return [items[round(i * (len(items) - 1) / (n - 1))] for i in range(n)]
|
|
||||||
|
|
||||||
|
|
||||||
def marks(marker: str, text: str) -> bool:
|
|
||||||
"""As the route will test it (core.pipeline.matches: `contains`, or `matches`)."""
|
|
||||||
if marker.startswith(LOOSE):
|
|
||||||
return re.search(marker, text) is not None
|
|
||||||
return marker.casefold() in text.casefold()
|
|
||||||
|
|
||||||
|
|
||||||
def condition(marker: str) -> dict:
|
|
||||||
"""The route condition that tests a marker."""
|
|
||||||
return {"column": "text", "op": "matches" if marker.startswith(LOOSE) else "contains",
|
|
||||||
"value": marker} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def loose(phrase: str | None) -> str | None:
|
|
||||||
"""A phrase the model wrote as a pattern its document may write a little apart: its
|
|
||||||
words in order, accents either way, up to two words between them ("MAMA, BIOPSIA"
|
|
||||||
finds "MAMA DERECHA, BIOPSIA:")."""
|
|
||||||
words = re.findall(r"[^\W_]+", phrase or "")
|
|
||||||
if len(words) < 2:
|
|
||||||
return None
|
|
||||||
|
|
||||||
def letter(c: str) -> str:
|
|
||||||
bare = unicodedata.normalize("NFD", c.casefold())[0]
|
|
||||||
return f"[{ACCENTED[bare]}]" if bare in ACCENTED else re.escape(c)
|
|
||||||
|
|
||||||
return LOOSE + r"\b" + GAP.join("".join(letter(c) for c in w) for w in words) + r"\b"
|
|
||||||
|
|
||||||
|
|
||||||
def phrase(marker: str | None, members, others, share=COVERED) -> str | None:
|
|
||||||
"""The model's marker as written if it holds, else written loosely if that holds."""
|
|
||||||
for found in (marker, loose(marker)):
|
|
||||||
if found and holds(found, members, others, share):
|
|
||||||
return found
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def kinds_of(line: str, documents: list[dict]) -> int:
|
|
||||||
"""How many different lines these documents print under this line's label (`ÓRGANO:
|
|
||||||
MAMA` → the organs): few for what tells studies apart, many for a diagnosis."""
|
|
||||||
label = line.split(":", 1)[0].strip().casefold() if ":" in line else None
|
|
||||||
if label is None:
|
|
||||||
return 2 # a line some print and others don't
|
|
||||||
return len({x.strip().casefold() for r in documents for x in r["text"].splitlines()
|
|
||||||
if x.strip().casefold().startswith(label + ":")}) # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def holds(marker: str | None, members: list[dict], others: list[dict], share=COVERED) -> bool:
|
|
||||||
"""A marker found in (nearly) all of these documents and in none of the others."""
|
|
||||||
if not marker or len(marker) < 4:
|
|
||||||
return False
|
|
||||||
covered = sum(marks(marker, r["text"]) for r in members) / len(members)
|
|
||||||
return covered >= share and not any(marks(marker, r["text"]) for r in others)
|
|
||||||
|
|
||||||
|
|
||||||
def printed_line(members: list[dict], others: list[dict], share=COVERED, rank=None) -> str | None:
|
|
||||||
"""The wordiest line printed in (nearly) all of these documents and in none of the
|
|
||||||
others (a form's label): the marker when the model's isn't (a title the printer
|
|
||||||
overstrikes reads "DDDDEEEE" in the text layer, so the title the model sees is not
|
|
||||||
in the text)."""
|
|
||||||
counts = Counter(
|
|
||||||
line for r in members for line in {x.strip() for x in r["text"].splitlines()}
|
|
||||||
if LINE.match(line)
|
|
||||||
) # fmt: skip
|
|
||||||
candidates = [line for line, n in counts.items() if n / len(members) >= share]
|
|
||||||
readable = lambda line: (len(re.findall(WORDS, line)), len(line)) # noqa: E731
|
|
||||||
for line in sorted(candidates, key=rank or readable, reverse=True):
|
|
||||||
if holds(line, members, others, share):
|
|
||||||
return line
|
|
||||||
return None
|
|
||||||
@@ -1,56 +0,0 @@
|
|||||||
"""A table (columns, no files): the model says which column holds each fact about whom a
|
|
||||||
row is about and each field of the studies its rows report; dates get the format all of
|
|
||||||
a column's values parse with, and coded columns their values in platform terms."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
|
|
||||||
from core.drafting import TABLE, is_date, studies_text, table_schema
|
|
||||||
from core.pipeline import ENTITY_TITLES, Map, Source
|
|
||||||
from core.schema import ENTITIES
|
|
||||||
from models.draft import fields
|
|
||||||
from persistance import llm
|
|
||||||
|
|
||||||
SHOWN = 15 # rows the model sees
|
|
||||||
SCANNED = 2000 # rows whose values give the date formats and the codes
|
|
||||||
LONG = 80 # characters of a value shown
|
|
||||||
|
|
||||||
|
|
||||||
def _shown(value):
|
|
||||||
text = value if isinstance(value, str) else json.dumps(value, default=str)
|
|
||||||
return text[:LONG]
|
|
||||||
|
|
||||||
|
|
||||||
def draft(d, source: Source, rows: list[dict], log) -> None:
|
|
||||||
"""One map node for identity and one per study the table reports."""
|
|
||||||
columns = sorted({c for r in rows[:SCANNED] for c in r if not c.startswith("_")})
|
|
||||||
if not columns:
|
|
||||||
return
|
|
||||||
shown = "\n".join(json.dumps({c: _shown(r.get(c)) for c in columns}, ensure_ascii=False)
|
|
||||||
for r in rows[:SHOWN]) # fmt: skip
|
|
||||||
answer = llm.ask(TABLE.format(studies=studies_text()), f"{columns}\n{shown}",
|
|
||||||
table_schema(columns)) # fmt: skip
|
|
||||||
wanted = [("identity", answer["identity"])]
|
|
||||||
wanted += [(s["entity"], s["fields"]) for s in answer["studies"]]
|
|
||||||
for entity, held in wanted:
|
|
||||||
mapped = {h["field"]: h["column"] for h in held
|
|
||||||
if h["field"] in ENTITIES[entity].model_fields} # fmt: skip
|
|
||||||
if not mapped:
|
|
||||||
continue
|
|
||||||
node = mapping(d, source, entity, mapped, rows[:SCANNED])
|
|
||||||
(d.identity if entity == "identity" else d.studies.setdefault(entity, [])).append(node)
|
|
||||||
log(f"{source.id}: {entity} from {sorted(mapped.values())}")
|
|
||||||
|
|
||||||
|
|
||||||
def mapping(d, source: Source, entity: str, mapped: dict[str, str], rows: list[dict]) -> str:
|
|
||||||
formats = {}
|
|
||||||
for field, column in mapped.items():
|
|
||||||
values = [r.get(column) for r in rows]
|
|
||||||
if is_date(entity, field) and (fmt := fields.date_format(values)):
|
|
||||||
formats[field] = fmt
|
|
||||||
elif fields.coded(entity, field):
|
|
||||||
d.codes.ask(entity, field, {str(v).strip() for v in values if v not in (None, "")})
|
|
||||||
title = "Identidad" if entity == "identity" else ENTITY_TITLES[entity]
|
|
||||||
node = Map(id=d.id(f"{source.id}_{entity}"), label=f"{title} ({source.label or source.id})",
|
|
||||||
inputs=[source.id], fields=mapped, formats=formats,
|
|
||||||
concept_map=d.codes.for_node(entity, mapped)) # fmt: skip
|
|
||||||
return d.add(node).id
|
|
||||||
+39
-38
@@ -1,8 +1,10 @@
|
|||||||
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
"""Runs a pipeline graph: each node, after its inputs, writes its output table; then dbt
|
||||||
places what the targets staged into silver."""
|
places what the targets staged into silver."""
|
||||||
|
|
||||||
|
import hashlib
|
||||||
import io
|
import io
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
import unicodedata
|
import unicodedata
|
||||||
from collections.abc import Callable
|
from collections.abc import Callable
|
||||||
from concurrent.futures import ProcessPoolExecutor
|
from concurrent.futures import ProcessPoolExecutor
|
||||||
@@ -15,12 +17,12 @@ import pdfplumber
|
|||||||
import pikepdf
|
import pikepdf
|
||||||
import splink.comparison_library as cl
|
import splink.comparison_library as cl
|
||||||
from markitdown import MarkItDown
|
from markitdown import MarkItDown
|
||||||
|
from openai import OpenAI, OpenAIError
|
||||||
from splink import Linker, SettingsCreator, block_on
|
from splink import Linker, SettingsCreator, block_on
|
||||||
from splink.backends.duckdb import DuckDBAPI
|
from splink.backends.duckdb import DuckDBAPI
|
||||||
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
from splink.clustering import cluster_pairwise_predictions_at_threshold
|
||||||
|
|
||||||
from core import catalog, concept_map, fhir_in
|
from core import catalog, concept_map, fhir_in
|
||||||
from core.drafting import extract_prompt
|
|
||||||
from core.pipeline import (
|
from core.pipeline import (
|
||||||
HELD,
|
HELD,
|
||||||
IDENTIFIERS,
|
IDENTIFIERS,
|
||||||
@@ -43,19 +45,16 @@ from core.pipeline import (
|
|||||||
matches,
|
matches,
|
||||||
validate,
|
validate,
|
||||||
)
|
)
|
||||||
from models import suggest
|
from persistance import config_log, files, nodes, silver
|
||||||
from persistance import config_log, files, llm, nodes, silver
|
|
||||||
|
|
||||||
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
|
MIN_WORDS = 5 # fewer than this from a PDF page means it has no text layer
|
||||||
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
|
READ_BATCH = 32 # files read at a time (a read is kept as soon as its batch is done)
|
||||||
FILE = "_file" # the read file's key (persistance.files): its pages, for a model that sees
|
|
||||||
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
READ_COLUMNS = { # declared, so a load where every file read cleanly still has `error`
|
||||||
"text": {"data_type": "text", "nullable": True},
|
"text": {"data_type": "text", "nullable": True},
|
||||||
"ocr": {"data_type": "bool"},
|
"ocr": {"data_type": "bool"},
|
||||||
"error": {"data_type": "text", "nullable": True},
|
"error": {"data_type": "text", "nullable": True},
|
||||||
"format": {"data_type": "text", "nullable": True},
|
"format": {"data_type": "text", "nullable": True},
|
||||||
}
|
}
|
||||||
ROW_COLUMNS = {**READ_COLUMNS, FILE: {"data_type": "text", "nullable": True}}
|
|
||||||
|
|
||||||
|
|
||||||
def file_format(content: bytes) -> str:
|
def file_format(content: bytes) -> str:
|
||||||
@@ -158,10 +157,9 @@ def run_read(p: str, node: Read):
|
|||||||
READ_COLUMNS) # fmt: skip
|
READ_COLUMNS) # fmt: skip
|
||||||
found |= read
|
found |= read
|
||||||
for row in rows:
|
for row in rows:
|
||||||
row[FILE] = row.pop("key")
|
result = found.get(row.pop("key"), {"text": None, "ocr": False, "error": "empty"})
|
||||||
result = found.get(row[FILE], {"text": None, "ocr": False, "error": "empty"})
|
|
||||||
row |= {k: result[k] for k in READ_COLUMNS}
|
row |= {k: result[k] for k in READ_COLUMNS}
|
||||||
return nodes.write(p, node.id, rows, ROW_COLUMNS)
|
return nodes.write(p, node.id, rows, READ_COLUMNS)
|
||||||
|
|
||||||
|
|
||||||
def run_route(p: str, node: Route, others: list[Route] = ()):
|
def run_route(p: str, node: Route, others: list[Route] = ()):
|
||||||
@@ -201,43 +199,51 @@ def run_join(p: str, node: Join):
|
|||||||
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
return nodes.write(p, node.id, join(node, left, right, node.inputs[1]))
|
||||||
|
|
||||||
|
|
||||||
def page_images(content: bytes, pages: int = 2) -> list[bytes]:
|
@cache
|
||||||
"""The first pages of a PDF as PNG pictures, for a model that reads images (a scan's
|
def _llm() -> tuple[OpenAI, str] | None:
|
||||||
OCR text misses what the picture still shows)."""
|
"""The configured OpenAI-compatible endpoint, if it answers; None otherwise."""
|
||||||
out = []
|
if not (url := os.environ.get("LLM_URL")):
|
||||||
with pdfplumber.open(io.BytesIO(content)) as pdf:
|
return None
|
||||||
for page in pdf.pages[:pages]:
|
client = OpenAI(base_url=url, api_key=os.environ.get("LLM_API_KEY", "none"), timeout=600)
|
||||||
picture = io.BytesIO()
|
try:
|
||||||
page.to_image(resolution=110).original.save(picture, format="PNG")
|
client.models.list()
|
||||||
out.append(picture.getvalue())
|
except OpenAIError:
|
||||||
return out
|
return None
|
||||||
|
return client, os.environ["LLM_MODEL"]
|
||||||
|
|
||||||
|
|
||||||
def images(row: dict) -> list[bytes]:
|
PROMPT = (
|
||||||
"""A scanned document's pages as pictures, when the model reads them."""
|
"Extract every {entity} record stated in the document. For each field give its value "
|
||||||
if not (row.get("ocr") and row.get(FILE) and llm.vision()):
|
"in the schema's terms and `quote`: the exact text of the document it was read from, "
|
||||||
return []
|
"copied character by character. Leave out fields the document does not state.{hints}"
|
||||||
content = files.content(row[FILE])
|
)
|
||||||
return page_images(content) if content and file_format(content) == "pdf" else []
|
|
||||||
|
|
||||||
|
|
||||||
def answer(entity: str, text: str, hints: str = "", pictures: list[bytes] = ()) -> dict:
|
def _ask_llm(node: Extract, text: str) -> dict:
|
||||||
"""The model's records of `entity` in `text`, each value with the text it was read
|
client, model = _llm()
|
||||||
from (the same question for the same document is asked once)."""
|
system = PROMPT.format(entity=node.entity, hints=f"\n{node.hints}" if node.hints else "")
|
||||||
return llm.ask(extract_prompt(entity, hints), text, answer_schema(entity), pictures)
|
key = hashlib.sha256(json.dumps([model, system, text]).encode()).hexdigest()
|
||||||
|
if found := nodes.cached("llm_cache", {key}):
|
||||||
|
return json.loads(found[key]["answer"])
|
||||||
|
reply = client.chat.completions.create(
|
||||||
|
model=model, temperature=0, seed=7,
|
||||||
|
messages=[{"role": "system", "content": system}, {"role": "user", "content": text}],
|
||||||
|
response_format={"type": "json_schema", "json_schema": {
|
||||||
|
"name": "answer", "schema": answer_schema(node.entity), "strict": True}},
|
||||||
|
) # fmt: skip
|
||||||
|
answer = reply.choices[0].message.content
|
||||||
|
nodes.remember("llm_cache", [{"key": key, "answer": answer, "model": model}], {})
|
||||||
|
return json.loads(answer)
|
||||||
|
|
||||||
|
|
||||||
def run_extract(p: str, node: Extract):
|
def run_extract(p: str, node: Extract):
|
||||||
use_llm = node.method == "llm" or (node.method == "auto" and llm.available())
|
use_llm = node.method == "llm" or (node.method == "auto" and _llm() is not None)
|
||||||
codes = _codes(node, node.patterns)
|
codes = _codes(node, node.patterns)
|
||||||
out = []
|
out = []
|
||||||
for row in nodes.rows(p, node.inputs[0]):
|
for row in nodes.rows(p, node.inputs[0]):
|
||||||
text = node.text(row)
|
text = node.text(row)
|
||||||
if use_llm:
|
if use_llm:
|
||||||
try:
|
found = ground(_ask_llm(node, text), text)
|
||||||
found = ground(answer(node.entity, text, node.hints, images(row)), text)
|
|
||||||
except llm.Unreadable as e: # this document waits for a reviewer, not the run
|
|
||||||
found = [({}, {}, [f"the model's answer could not be read: {e}"])]
|
|
||||||
elif node.patterns:
|
elif node.patterns:
|
||||||
found = apply_patterns(node, text, codes)
|
found = apply_patterns(node, text, codes)
|
||||||
else:
|
else:
|
||||||
@@ -529,8 +535,3 @@ def run(pipeline_id: str, pipeline: Pipeline, log: Callable[[str], None] = print
|
|||||||
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
if entities := sorted({n.entity for n in pipeline.nodes if n.kind == "target"}):
|
||||||
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
silver.build(["silver+"]) # every entity (empty if never staged) and what derives
|
||||||
log(f"silver and gold, from {', '.join(entities)}")
|
log(f"silver and gold, from {', '.join(entities)}")
|
||||||
links = [n.id for n in pipeline.nodes if n.kind == "link"]
|
|
||||||
if links and llm.available(): # the model's reading beside what waits for reviewers
|
|
||||||
for link in links:
|
|
||||||
suggest.persons(pipeline_id, link)
|
|
||||||
log(f"suggestions for review: {', '.join(links)}")
|
|
||||||
|
|||||||
@@ -1,48 +0,0 @@
|
|||||||
"""The model's reading of what a link node leaves to reviewers, shown beside each case:
|
|
||||||
whether a person and a possible owner are one patient, and which record of a torn person
|
|
||||||
belongs to someone else, each with its reason. A suggestion decides nothing: reviewers
|
|
||||||
still answer every case (persistance.nodes)."""
|
|
||||||
|
|
||||||
import json
|
|
||||||
|
|
||||||
from core.drafting import SAME_PERSON, TORN, same_person_schema, torn_schema
|
|
||||||
from core.pipeline import HELD, RECORD
|
|
||||||
from persistance import llm, nodes
|
|
||||||
|
|
||||||
PAIRS, TORN_PERSONS = "__suggestions", "__torn_suggestions"
|
|
||||||
|
|
||||||
|
|
||||||
def _side(row: dict, prefix: str) -> dict:
|
|
||||||
return {k.removeprefix(prefix): v for k, v in row.items()
|
|
||||||
if k.startswith(prefix) and v is not None} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def _ask(system: str, text: str, schema: dict, unsure: dict) -> dict:
|
|
||||||
"""The model's suggestion; an answer it couldn't give says so to the reviewer."""
|
|
||||||
try:
|
|
||||||
return llm.ask(system, text, schema)
|
|
||||||
except llm.Unreadable:
|
|
||||||
return {**unsure, "reason": "El modelo no dio una respuesta legible para este caso."}
|
|
||||||
|
|
||||||
|
|
||||||
def persons(pipeline_id: str, link: str) -> None:
|
|
||||||
"""Suggestions for the link node's queue (pairs) and its torn persons."""
|
|
||||||
pairs = []
|
|
||||||
for row in nodes.rows(pipeline_id, f"{link}__review"):
|
|
||||||
case = {"a": _side(row, "person_"), "b": _side(row, "candidate_"), "why": row["reason"]}
|
|
||||||
text = json.dumps(case, default=str, ensure_ascii=False)
|
|
||||||
answer = _ask(SAME_PERSON, text, same_person_schema(), {"same": None})
|
|
||||||
pairs.append({"person": row["person"], "candidate": row["candidate"],
|
|
||||||
"same": answer["same"], "reason": answer["reason"]}) # fmt: skip
|
|
||||||
nodes.write(pipeline_id, f"{link}{PAIRS}", pairs)
|
|
||||||
torn: dict[str, list[dict]] = {}
|
|
||||||
for row in nodes.rows(pipeline_id, link):
|
|
||||||
if "disagree" in (row.get(HELD) or ""):
|
|
||||||
record = {k: v for k, v in row.items() if not k.startswith("_") and v is not None}
|
|
||||||
torn.setdefault(row["person_id"], []).append({**record, "id": row[RECORD]})
|
|
||||||
found = []
|
|
||||||
for person, records in torn.items():
|
|
||||||
text = json.dumps(records, default=str, ensure_ascii=False)
|
|
||||||
answer = _ask(TORN, text, torn_schema([r["id"] for r in records]), {"record": None})
|
|
||||||
found.append({"person": person, "record": answer["record"], "reason": answer["reason"]})
|
|
||||||
nodes.write(pipeline_id, f"{link}{TORN_PERSONS}", found)
|
|
||||||
@@ -9,6 +9,7 @@ dependencies = [
|
|||||||
"dagster",
|
"dagster",
|
||||||
"dagster-webserver",
|
"dagster-webserver",
|
||||||
"mlflow-skinny",
|
"mlflow-skinny",
|
||||||
|
"openai>=3.59.0",
|
||||||
"splink>=5.0.0",
|
"splink>=5.0.0",
|
||||||
"duckdb>=2.0.1",
|
"duckdb>=2.0.1",
|
||||||
"markitdown[docx,xlsx]>=0.1.9",
|
"markitdown[docx,xlsx]>=0.1.9",
|
||||||
|
|||||||
@@ -1,77 +0,0 @@
|
|||||||
"""What Automático checks without asking the model: documents grouped by the words their
|
|
||||||
layout prints, a proposed pattern kept only when it captures what the model read, a
|
|
||||||
column's date format, and the site's codes as a ConceptMap the platform accepts."""
|
|
||||||
|
|
||||||
from core import concept_map
|
|
||||||
from core.drafting import codes_schema, layout_schema, table_schema
|
|
||||||
from models.draft import fields
|
|
||||||
from models.draft.layouts import layouts
|
|
||||||
|
|
||||||
FORM = (
|
|
||||||
"SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: {date}\n"
|
|
||||||
"Calidad de la muestra: SATISFACTORIO\nResultado: {result}\nObservaciones: ninguna"
|
|
||||||
)
|
|
||||||
MAMMOGRAM = (
|
|
||||||
"REPORTE DE MASTOGRAFÍA BILATERAL\nPaciente: {name}\nFecha del estudio: {date}\n"
|
|
||||||
"Hallazgos: densidad mamaria tipo B, sin masas\nBI-RADS: 2"
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def test_documents_of_one_layout_group_together_whoever_they_are_about():
|
|
||||||
texts = [
|
|
||||||
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
|
||||||
MAMMOGRAM.format(name="LUISA ORTIZ MENA", date="11/04/2025"),
|
|
||||||
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
|
||||||
MAMMOGRAM.format(name="MARTA SOLÍS GIL", date="01/07/2025"),
|
|
||||||
FORM.format(name="EVA RUIZ CANO", date="20/08/2025", result="ASC-US"),
|
|
||||||
]
|
|
||||||
found = layouts(texts)
|
|
||||||
assert found[0] == found[2] == found[4] != found[1] == found[3]
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_pattern_is_kept_only_if_it_captures_the_values_read():
|
|
||||||
texts = [
|
|
||||||
FORM.format(name="ANA LÓPEZ RUIZ", date="02/03/2025", result="NEGATIVO"),
|
|
||||||
FORM.format(name="ROSA DÍAZ PAZ", date="15/06/2025", result="LSIL"),
|
|
||||||
]
|
|
||||||
read = [
|
|
||||||
(texts[0], {"sample_date": "2025-03-02", "result": "NILM"}),
|
|
||||||
(texts[1], {"sample_date": "2025-06-15", "result": "LSIL"}),
|
|
||||||
]
|
|
||||||
codes = fields.Codes("sitio")
|
|
||||||
entity = "cervical_cytology"
|
|
||||||
date = r"recepci[oó]n:\s*(\d{2}/\d{2}/\d{4})"
|
|
||||||
assert fields.checks(entity, "sample_date", date, "%d/%m/%Y", read, codes)
|
|
||||||
assert not fields.checks(entity, "sample_date", date, "%m/%d/%Y", read, codes) # 15th month
|
|
||||||
assert not fields.checks(entity, "sample_date", r"(\d{2}/\d{2})", None, read, codes)
|
|
||||||
assert not fields.checks(entity, "sample_date", r"recepci[oó]n:", None, read, codes) # no group
|
|
||||||
assert not fields.checks(entity, "result", r"resultado:(\s*)", None, read, codes) # nothing
|
|
||||||
# A coded field: what the site writes becomes its ConceptMap, unless it is the code.
|
|
||||||
assert fields.checks(entity, "result", r"resultado:\s*(\S+)", None, read, codes)
|
|
||||||
assert codes.table() == {(entity, "result"): {"negativo": "NILM"}}
|
|
||||||
# A pattern taking text that means two things is the wrong text.
|
|
||||||
assert not fields.checks(entity, "result", r"(calidad)", None, read, fields.Codes("x"))
|
|
||||||
found = codes.concept_map()
|
|
||||||
assert concept_map.problems(found) == []
|
|
||||||
assert concept_map.table([found], "result") == {"negativo": "NILM"}
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_columns_dates_get_the_format_every_value_parses_with():
|
|
||||||
assert fields.date_format(["02/03/2025", "15/06/2025"]) == "%d/%m/%Y"
|
|
||||||
assert fields.date_format(["2025-03-02", None]) == "%Y-%m-%d"
|
|
||||||
assert fields.date_format(["mañana"]) is None
|
|
||||||
|
|
||||||
|
|
||||||
def test_answers_are_held_to_the_platforms_terms():
|
|
||||||
layout = layout_schema(3)["$defs"]["Study"]["properties"]
|
|
||||||
assert (
|
|
||||||
"cervical_cytology" in layout["entity"]["enum"]
|
|
||||||
and "identity" not in layout["entity"]["enum"]
|
|
||||||
)
|
|
||||||
assert layout["documents"]["items"]["enum"] == [1, 2, 3]
|
|
||||||
codes = codes_schema(["NEGATIVO", "BAJO GRADO"], ["NILM", "LSIL"])
|
|
||||||
one = codes["$defs"]["Code"]["properties"]
|
|
||||||
assert one["raw"]["enum"] == ["NEGATIVO", "BAJO GRADO"]
|
|
||||||
assert {"enum": ["NILM", "LSIL"], "type": "string"} in one["code"]["anyOf"]
|
|
||||||
table = table_schema(["num", "nombre"])
|
|
||||||
assert table["$defs"]["Who"]["properties"]["column"]["enum"] == ["num", "nombre"]
|
|
||||||
@@ -1,48 +0,0 @@
|
|||||||
"""Automático's judgements that need no model: a layout whose title the text layer
|
|
||||||
garbles is still marked by a line it prints, and a report that leaves its sample's date to
|
|
||||||
the order it answers is paired with that order by the column both carry."""
|
|
||||||
|
|
||||||
from core.pipeline import Join, Route
|
|
||||||
from models.draft.joins import Kind, apart_from, joined, partner
|
|
||||||
from models.draft.layouts import printed_line
|
|
||||||
|
|
||||||
HPV = (
|
|
||||||
"No.Proceso {n}\nPaciente {name}\nDDDDEEEETTTTEEEECCCCCCCCIIIIOOOONNNN\n"
|
|
||||||
"ESPECIMEN: CEPILLADO CERVICOVAGINAL\nVVVVPPPPHHHH . . . . . NNNNEEEEGGGG"
|
|
||||||
)
|
|
||||||
FORM = "SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: 0{n}/03/2025"
|
|
||||||
|
|
||||||
|
|
||||||
def row(record: str, text: str, order) -> dict:
|
|
||||||
return {"_record": record, "_file": f"{record:0>64}", "text": text, "format": "pdf",
|
|
||||||
"orden_servicio_id": order, "tipo": "resultado"} # fmt: skip
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_layout_is_marked_by_a_line_only_it_prints():
|
|
||||||
hpv = [row(f"h{n}", HPV.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
|
||||||
forms = [row(f"c{n}", FORM.format(n=n, name=f"PACIENTE {n}"), n) for n in range(5)]
|
|
||||||
assert printed_line(hpv, forms) == "ESPECIMEN: CEPILLADO CERVICOVAGINAL"
|
|
||||||
assert printed_line(forms, forms[:1] + hpv) is None # what it prints, another prints too
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_report_is_read_with_the_order_the_same_column_pairs_it_with():
|
|
||||||
reports = Kind("cervical_cytology", "VPH", "cervicovaginal", [],
|
|
||||||
[row(f"h{n}", HPV.format(n=n, name="X"), n) for n in range(4)]) # fmt: skip
|
|
||||||
orders = Kind("cervical_cytology", "Citología", "citología", [],
|
|
||||||
[row(f"c{n}", FORM.format(n=n, name="X"), n) for n in range(1, 6)]) # fmt: skip
|
|
||||||
# `tipo` and `format` pair every document with every other: they pair nothing.
|
|
||||||
assert partner(reports, [reports, orders]) == (orders, "orden_servicio_id")
|
|
||||||
orders.route = Route(id="citologia", label="Citología", inputs=["texto"])
|
|
||||||
node = Join(id="vph_con_citologia", inputs=["vph", "citologia"],
|
|
||||||
on=[("orden_servicio_id", "orden_servicio_id")], how="left") # fmt: skip
|
|
||||||
found = dict((r["_record"], t) for t, r in joined(node, reports.everyone, orders))
|
|
||||||
assert found["h1"].startswith("SOLICITUD DE CITOLOGÍA") and "Proceso 1" in found["h1"]
|
|
||||||
assert found["h0"].startswith("No.Proceso 0") # no order: its own text alone
|
|
||||||
assert apart_from(next(r for _, r in joined(node, reports.everyone, orders)
|
|
||||||
if r["_record"] == "h1"), orders) # fmt: skip
|
|
||||||
both = row("c1", FORM.format(n=1, name="X") + "\n" + HPV.format(n=1, name="X"), 1)
|
|
||||||
(_, itself), = joined(node, [both], Kind("cervical_cytology", "", "", [], [both],
|
|
||||||
orders.route)) # fmt: skip
|
|
||||||
assert not apart_from(itself, orders) # one file, order and report: paired with itself
|
|
||||||
lone = Kind("cervical_cytology", "VPH", "x", [], reports.everyone[:1])
|
|
||||||
assert partner(lone, [lone, orders]) is None
|
|
||||||
@@ -1,55 +0,0 @@
|
|||||||
"""One layout, several studies: the model is shown a layout's documents as unlike each
|
|
||||||
other as they come (so the one note that records a death is among them), and a study only
|
|
||||||
some of them report is kept only with a phrase that marks those and none of the others."""
|
|
||||||
|
|
||||||
from models.draft.documents import apart
|
|
||||||
from models.draft.layouts import diverse, marks
|
|
||||||
|
|
||||||
NOTE = "INFORME MÉDICO\nNOMBRE: {name}\nMOTIVO DE LA CONSULTA: {why}\nPLAN: {plan}"
|
|
||||||
ROUTINE = [
|
|
||||||
NOTE.format(name=f"PACIENTE {n}", why="control anual", plan="cita en un año") for n in range(20)
|
|
||||||
]
|
|
||||||
DEATH = NOTE.format(name="PACIENTE 99", why="NOTA DE DEFUNCIÓN: falleció en urgencias",
|
|
||||||
plan="certificado de defunción, causa: choque séptico") # fmt: skip
|
|
||||||
PATHOLOGY = "ESTUDIO PATOLÓGICO\nNOMBRE: {name}\nÓRGANO: {organ}\nDIAGNÓSTICO: {dx}"
|
|
||||||
|
|
||||||
|
|
||||||
def docs(texts: list[str]) -> list[dict]:
|
|
||||||
return [{"_record": str(i), "text": t} for i, t in enumerate(texts)]
|
|
||||||
|
|
||||||
|
|
||||||
def test_the_one_unlike_note_is_among_those_shown():
|
|
||||||
notes = docs(ROUTINE[:10] + [DEATH] + ROUTINE[10:])
|
|
||||||
assert any("DEFUNCIÓN" in r["text"] for r in diverse(notes, 3))
|
|
||||||
assert len(diverse(notes, 30)) == len(notes)
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_study_some_documents_report_is_kept_with_what_marks_them():
|
|
||||||
shown = docs([PATHOLOGY.format(name="A", organ="CÉRVIX", dx="NIC 2"),
|
|
||||||
PATHOLOGY.format(name="B", organ="MAMA", dx="CARCINOMA DUCTAL"),
|
|
||||||
PATHOLOGY.format(name="C", organ="CÉRVIX", dx="NIC 1")]) # fmt: skip
|
|
||||||
log = []
|
|
||||||
cervix = {"label": "Biopsia cervical", "documents": [1, 3], "marker": "ÓRGANO: CÉRVIX"}
|
|
||||||
assert apart(cervix, shown, {2}, log.append) == "ÓRGANO: CÉRVIX"
|
|
||||||
# The model's phrase marks the wrong documents: a printed line that does is taken.
|
|
||||||
breast = {"label": "Biopsia de mama", "documents": [2], "marker": "DIAGNÓSTICO"}
|
|
||||||
assert apart(breast, shown, {1, 3}, log.append) == "ÓRGANO: MAMA"
|
|
||||||
# A study the model gives all but one, the one no other study claims: all of them.
|
|
||||||
assert apart({**cervix, "documents": [1, 3]}, shown, set(), log.append) is None
|
|
||||||
every = {"label": "Patología", "documents": [1, 2, 3], "marker": "ESTUDIO"}
|
|
||||||
assert apart(every, shown, set(), log.append) is None # all of them: the layout's own route
|
|
||||||
assert apart({**every, "documents": []}, shown, set(), log.append) is False
|
|
||||||
alike = {"label": "x", "documents": [1], "marker": None} # nothing sets A apart from C
|
|
||||||
assert apart(alike, shown, {3}, log.append) is False and log
|
|
||||||
|
|
||||||
|
|
||||||
def test_a_phrase_the_model_tidied_still_finds_what_the_document_writes():
|
|
||||||
organs = ["CÉRVIX", "MAMA DERECHA", "CERVIX", "MAMA IZQUIERDA"]
|
|
||||||
shown = docs([PATHOLOGY.format(name=n, organ=f"{o}, BIOPSIA:", dx="X")
|
|
||||||
for n, o in zip("ABCD", organs, strict=True)]) # fmt: skip
|
|
||||||
breast = {"label": "Biopsia de mama", "documents": [2, 4], "marker": "MAMA, BIOPSIA"}
|
|
||||||
found = apart(breast, shown, {1, 3}, print)
|
|
||||||
assert [marks(found, r["text"]) for r in shown] == [False, True, False, True]
|
|
||||||
cervix = {"label": "Biopsia cervical", "documents": [1, 3], "marker": "CÉRVIX, BIOPSIA"}
|
|
||||||
found = apart(cervix, shown, {2, 4}, print) # written without its accent in C
|
|
||||||
assert [marks(found, r["text"]) for r in shown] == [True, False, True, False]
|
|
||||||
Reference in New Issue
Block a user