Automático: several studies per layout, loose markers, joins only across documents, unreadable answers held
This commit is contained in:
@@ -35,15 +35,17 @@ def ingest():
|
|||||||
|
|
||||||
class DraftRun(dg.Config):
|
class DraftRun(dg.Config):
|
||||||
pipeline: str
|
pipeline: str
|
||||||
|
run: bool = True # False: drawn and saved only (a large site, read later)
|
||||||
|
|
||||||
|
|
||||||
@dg.op
|
@dg.op
|
||||||
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
|
def draft_pipeline(context: dg.OpExecutionContext, config: DraftRun) -> int:
|
||||||
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
|
"""Automático: the whole pipeline drafted from its sources, saved as a new version and
|
||||||
run. Returns that version."""
|
run (unless `run` is off). Returns that version."""
|
||||||
drafted = draft.draft(config.pipeline, log=context.log.info)
|
drafted = draft.draft(config.pipeline, log=context.log.info)
|
||||||
version = config_log.save(config.pipeline, drafted)
|
version = config_log.save(config.pipeline, drafted)
|
||||||
context.log.info(f"{config.pipeline} v{version}: {len(drafted.nodes)} nodes 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)
|
graph.run(config.pipeline, drafted, log=context.log.info)
|
||||||
return version
|
return version
|
||||||
|
|
||||||
|
|||||||
+118
-102
@@ -1,140 +1,151 @@
|
|||||||
"""Documents (a column of files, read to text): grouped by layout, each layout named by the
|
"""Documents (a column of files, read to text): grouped by layout, each layout named by the
|
||||||
model with the study it reports and a phrase that marks it (a route), and read for that
|
model with the studies it reports and the phrases that mark it and each of them (a route,
|
||||||
study (joined to the documents it answers, if it needs them: joins) and for whom it is
|
and a route under it for a study only some of its documents report: the organ a
|
||||||
about (two extract nodes, with patterns for when no model answers). What no layout claims
|
pathology report is about, a note that records a death), and read for each study (joined
|
||||||
goes to the unrecognised route, for a reviewer."""
|
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
|
import re
|
||||||
from collections import Counter
|
from collections import Counter
|
||||||
|
from dataclasses import dataclass
|
||||||
from sklearn.cluster import AgglomerativeClustering
|
|
||||||
from sklearn.feature_extraction.text import CountVectorizer
|
|
||||||
|
|
||||||
from core.drafting import LAYOUT, layout_schema, studies_text
|
from core.drafting import LAYOUT, layout_schema, studies_text
|
||||||
from core.pipeline import ENTITY_TITLES, Condition, Extract, Join, Read, Route, ground
|
from core.pipeline import ENTITY_TITLES, Condition, Extract, Join, Read, Route, ground
|
||||||
from models import graph
|
from models import graph
|
||||||
from models.draft import fields, joins
|
from models.draft import fields, joins
|
||||||
from models.draft.joins import Kind
|
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
|
from persistance import llm
|
||||||
|
|
||||||
SAMPLE = 300 # documents grouped by layout at most
|
SAMPLE = 2000 # documents grouped by layout at most (grouping compares every pair)
|
||||||
PER_LAYOUT = 3 # documents of a layout the model reads
|
SHOWN = 8 # documents of a layout the model is shown to name its studies
|
||||||
DISTANCE = 0.5 # cosine distance under which two documents share a layout
|
PER_STUDY = 3 # documents of a study the model reads for where each field is written
|
||||||
COVERED = 0.9 # share of a layout's documents its marker must be found in
|
CHARS = 3000 # of each document shown to name a layout (its title and labels come first)
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
def layouts(texts: list[str]) -> list[int]:
|
@dataclass
|
||||||
"""A layout number per document: documents that print mostly the same words (a form's
|
class Layout:
|
||||||
labels) share one. Words seen in a single document (a name) don't count."""
|
label: str
|
||||||
if len(texts) < 2:
|
marker: str
|
||||||
return [0] * len(texts)
|
members: list[dict] = dataclasses.field(default_factory=list)
|
||||||
try:
|
everyone: list[dict] = dataclasses.field(default_factory=list)
|
||||||
words = CountVectorizer(token_pattern=WORDS, binary=True, min_df=2).fit_transform(texts)
|
route: Route | None = None
|
||||||
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 _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`)."""
|
|
||||||
return marker.casefold() in text.casefold()
|
|
||||||
|
|
||||||
|
|
||||||
def _holds(marker: str, members: list[dict], others: list[dict]) -> bool:
|
|
||||||
"""A marker found in nearly all of a layout's documents and in no other's."""
|
|
||||||
if len(marker) < 4:
|
|
||||||
return False
|
|
||||||
covered = sum(_marks(marker, r["text"]) for r in members) / len(members)
|
|
||||||
return covered >= COVERED and not any(_marks(marker, r["text"]) for r in others)
|
|
||||||
|
|
||||||
|
|
||||||
def printed_line(members: list[dict], others: list[dict]) -> str | None:
|
|
||||||
"""The wordiest line printed in nearly all of a layout's documents and in no other's
|
|
||||||
(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) >= COVERED]
|
|
||||||
readable = lambda line: (len(re.findall(WORDS, line)), len(line)) # noqa: E731
|
|
||||||
for line in sorted(candidates, key=readable, reverse=True):
|
|
||||||
if _holds(line, members, others):
|
|
||||||
return line
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def draft(d, read: Read, rows: list[dict], log) -> None:
|
def draft(d, read: Read, rows: list[dict], log) -> None:
|
||||||
"""Routes, extracts (and joins) and the unrecognised route for one read node's
|
"""Routes, extracts (and joins) and the unrecognised route for one read node's
|
||||||
documents."""
|
documents."""
|
||||||
documents = sorted((r for r in rows if r.get("text")), key=lambda r: r["_record"])
|
documents = sorted((r for r in rows if r.get("text")), key=lambda r: r["_record"])
|
||||||
sample = _spread(documents, SAMPLE)
|
sample = spread(documents, SAMPLE)
|
||||||
groups: dict[int, list[dict]] = {}
|
groups: dict[int, list[dict]] = {}
|
||||||
for row, group in zip(sample, layouts([r["text"] for r in sample]), strict=True):
|
for row, group in zip(sample, layouts([r["text"] for r in sample]), strict=True):
|
||||||
if group >= 0:
|
if group >= 0:
|
||||||
groups.setdefault(group, []).append(row)
|
groups.setdefault(group, []).append(row)
|
||||||
answers = []
|
answers = []
|
||||||
for members in groups.values():
|
for members in groups.values():
|
||||||
text = "\n\n---\n\n".join(r["text"] for r in _spread(members, PER_LAYOUT))
|
shown = diverse(members, SHOWN)
|
||||||
answers.append((llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema()),
|
text = "\n\n".join(f"=== Documento {i} ===\n{r['text'][:CHARS]}"
|
||||||
members)) # fmt: skip
|
for i, r in enumerate(shown, 1)) # fmt: skip
|
||||||
named = [(a, m) for a, m in answers if a["entity"] != "none"]
|
answer = llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema(len(shown)))
|
||||||
found: dict[tuple[str, str], Kind] = {}
|
answers.append((answer, members, shown))
|
||||||
for answer, members in named:
|
found, kinds = {}, {}
|
||||||
entity, marker = answer["entity"], " ".join(answer["marker"].split())
|
for answer, members, shown in answers:
|
||||||
others = [r for a, m in named if a["entity"] != entity for r in m]
|
entities = {s["entity"] for s in answer["studies"]}
|
||||||
if not _holds(marker, members, others):
|
others = [r for a, m, _ in answers if not entities & {s["entity"] for s in a["studies"]}
|
||||||
rest = [r for _, m in answers if m is not members for r in m]
|
for r in m] # fmt: skip
|
||||||
marker = printed_line(members, rest)
|
marker = " ".join(answer["marker"].split())
|
||||||
log(f"layout of {len(members)}: {entity} «{marker}»")
|
marker = phrase(marker, members, others) or printed_line(
|
||||||
if marker is None:
|
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
|
continue
|
||||||
kind = found.setdefault((entity, marker.casefold()),
|
layout = found.setdefault(marker.casefold(), Layout(answer["label"], marker))
|
||||||
Kind(entity, answer["label"], marker, [])) # fmt: skip
|
layout.members.extend(members)
|
||||||
kind.members.extend(members)
|
for one in answer["studies"]:
|
||||||
kinds = list(found.values())
|
claimed = {i for o in answer["studies"] if o is not one for i in o["documents"]}
|
||||||
labels = Counter(k.label.casefold() for k in kinds)
|
if (sub := apart(one, shown, claimed, log)) is False:
|
||||||
for kind in kinds: # two layouts the model names alike: each by what marks it
|
continue
|
||||||
if labels[kind.label.casefold()] > 1:
|
kind = kinds.setdefault((marker.casefold(), one["entity"], (sub or "").casefold()),
|
||||||
kind.label = f"{kind.label} · {kind.marker[:40]}{'…' if len(kind.marker) > 40 else ''}"
|
Kind(one["entity"], one["label"], sub or "", [],
|
||||||
for kind in kinds:
|
layout=layout)) # fmt: skip
|
||||||
marked = Condition(column="text", op="contains", value=kind.marker)
|
kind.members.extend(r for r in members if not sub or marks(sub, r["text"]))
|
||||||
kind.route = d.add(Route(id=d.id(kind.label), label=kind.label, inputs=[read.id],
|
routes(d, read, documents, list(found.values()), list(kinds.values()))
|
||||||
when=[marked])) # fmt: skip
|
for kind in kinds.values():
|
||||||
kind.everyone = [r for r in documents if _marks(kind.marker, r["text"])]
|
d.studies.setdefault(kind.entity, []).append(study(d, kind, list(kinds.values()), log))
|
||||||
for kind in kinds:
|
for layout in found.values():
|
||||||
d.studies.setdefault(kind.entity, []).append(study(d, kind, kinds, log))
|
shown = [(r["text"], r) for r in diverse(layout.members, PER_STUDY)]
|
||||||
shown = [(r["text"], r) for r in _spread(kind.members, PER_LAYOUT)]
|
texts = [r["text"] for r in layout.everyone]
|
||||||
texts = [r["text"] for r in kind.everyone]
|
d.identity.append(extract(d, layout.route, layout.route.id, "identity", "text",
|
||||||
d.identity.append(extract(d, kind.route, kind.route.id, "identity", "text",
|
|
||||||
reading("identity", shown), texts)) # fmt: skip
|
reading("identity", shown), texts)) # fmt: skip
|
||||||
d.add(Route(id=d.id("no_reconocidos"), label="Documentos no reconocidos",
|
d.add(Route(id=d.id("no_reconocidos"), label="Documentos no reconocidos",
|
||||||
inputs=[read.id], otherwise=True)) # fmt: skip
|
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:
|
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,
|
"""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
|
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)."""
|
outsourced report's sample date is the order's, not the report's own date)."""
|
||||||
shown = _spread(kind.members, PER_LAYOUT)
|
shown = diverse(kind.members, PER_STUDY)
|
||||||
read = reading(kind.entity, [(r["text"], r) for r in shown])
|
read = reading(kind.entity, [(r["text"], r) for r in shown])
|
||||||
texts = [r["text"] for r in kind.everyone]
|
texts = [r["text"] for r in kind.everyone]
|
||||||
if found := joins.partner(kind, kinds):
|
if found := joins.partner(kind, kinds):
|
||||||
@@ -146,7 +157,9 @@ def study(d, kind: Kind, kinds: list[Kind], log) -> str:
|
|||||||
on=[(column, column)],
|
on=[(column, column)],
|
||||||
how="left",
|
how="left",
|
||||||
)
|
)
|
||||||
pairs = joins.joined(node, shown, other)
|
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)
|
again = reading(kind.entity, pairs)
|
||||||
if taken := joins.taken(kind.entity, again, [r for _, r in pairs], other):
|
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")
|
log(f"{kind.label}: read with {other.label} (same {column}): {taken} is in it")
|
||||||
@@ -163,7 +176,10 @@ def reading(entity: str, shown: list[tuple[str, dict]]) -> list[tuple[str, dict,
|
|||||||
values, the text each was read from)."""
|
values, the text each was read from)."""
|
||||||
out = []
|
out = []
|
||||||
for text, row in shown:
|
for text, row in shown:
|
||||||
|
try:
|
||||||
answered = ground(graph.answer(entity, text, "", graph.images(row)), text)
|
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 ({}, {}, [])
|
values, quotes, _ = answered[0] if answered else ({}, {}, [])
|
||||||
kept = {f: v for f, v in values.items() if v is not None}
|
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}))
|
out.append((text, kept, {f: quotes[f] for f in kept}))
|
||||||
|
|||||||
+10
-2
@@ -15,7 +15,8 @@ PAIRED = 0.5 # share of a kind's documents that must find exactly one partner
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Kind:
|
class Kind:
|
||||||
"""Documents of one layout: the study they report, their route, all of them."""
|
"""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
|
entity: str
|
||||||
label: str
|
label: str
|
||||||
@@ -23,6 +24,7 @@ class Kind:
|
|||||||
members: list[dict] # those sampled
|
members: list[dict] # those sampled
|
||||||
everyone: list[dict] = field(default_factory=list)
|
everyone: list[dict] = field(default_factory=list)
|
||||||
route: Route | None = None
|
route: Route | None = None
|
||||||
|
layout: object = None # the layout these documents are of (documents.Layout)
|
||||||
|
|
||||||
|
|
||||||
def required(entity: str) -> set[str]:
|
def required(entity: str) -> set[str]:
|
||||||
@@ -69,12 +71,18 @@ def joined(node: Join, rows: list[dict], other: Kind) -> list[tuple[str, dict]]:
|
|||||||
for r in join(node, rows, other.everyone, other.route.id)] # fmt: skip
|
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]:
|
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
|
"""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."""
|
from the partner's text (not its own) in most of the documents that have one."""
|
||||||
theirs_column = text_columns(other)[0]
|
theirs_column = text_columns(other)[0]
|
||||||
partnered = [(quotes, row) for (_, _, quotes), row in zip(read, rows, strict=True)
|
partnered = [(quotes, row) for (_, _, quotes), row in zip(read, rows, strict=True)
|
||||||
if row.get(theirs_column)] # fmt: skip
|
if row.get(theirs_column) and apart_from(row, other)] # fmt: skip
|
||||||
found = set()
|
found = set()
|
||||||
for name in required(entity):
|
for name in required(entity):
|
||||||
theirs = sum(
|
theirs = sum(
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
"""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
|
||||||
@@ -234,7 +234,10 @@ def run_extract(p: str, node: Extract):
|
|||||||
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(answer(node.entity, text, node.hints, images(row)), 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:
|
||||||
|
|||||||
+10
-2
@@ -17,13 +17,21 @@ def _side(row: dict, prefix: str) -> dict:
|
|||||||
if k.startswith(prefix) and v is not None} # fmt: skip
|
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:
|
def persons(pipeline_id: str, link: str) -> None:
|
||||||
"""Suggestions for the link node's queue (pairs) and its torn persons."""
|
"""Suggestions for the link node's queue (pairs) and its torn persons."""
|
||||||
pairs = []
|
pairs = []
|
||||||
for row in nodes.rows(pipeline_id, f"{link}__review"):
|
for row in nodes.rows(pipeline_id, f"{link}__review"):
|
||||||
case = {"a": _side(row, "person_"), "b": _side(row, "candidate_"), "why": row["reason"]}
|
case = {"a": _side(row, "person_"), "b": _side(row, "candidate_"), "why": row["reason"]}
|
||||||
text = json.dumps(case, default=str, ensure_ascii=False)
|
text = json.dumps(case, default=str, ensure_ascii=False)
|
||||||
answer = llm.ask(SAME_PERSON, text, same_person_schema())
|
answer = _ask(SAME_PERSON, text, same_person_schema(), {"same": None})
|
||||||
pairs.append({"person": row["person"], "candidate": row["candidate"],
|
pairs.append({"person": row["person"], "candidate": row["candidate"],
|
||||||
"same": answer["same"], "reason": answer["reason"]}) # fmt: skip
|
"same": answer["same"], "reason": answer["reason"]}) # fmt: skip
|
||||||
nodes.write(pipeline_id, f"{link}{PAIRS}", pairs)
|
nodes.write(pipeline_id, f"{link}{PAIRS}", pairs)
|
||||||
@@ -35,6 +43,6 @@ def persons(pipeline_id: str, link: str) -> None:
|
|||||||
found = []
|
found = []
|
||||||
for person, records in torn.items():
|
for person, records in torn.items():
|
||||||
text = json.dumps(records, default=str, ensure_ascii=False)
|
text = json.dumps(records, default=str, ensure_ascii=False)
|
||||||
answer = llm.ask(TORN, text, torn_schema([r["id"] for r in records]))
|
answer = _ask(TORN, text, torn_schema([r["id"] for r in records]), {"record": None})
|
||||||
found.append({"person": person, "record": answer["record"], "reason": answer["reason"]})
|
found.append({"person": person, "record": answer["record"], "reason": answer["reason"]})
|
||||||
nodes.write(pipeline_id, f"{link}{TORN_PERSONS}", found)
|
nodes.write(pipeline_id, f"{link}{TORN_PERSONS}", found)
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ column's date format, and the site's codes as a ConceptMap the platform accepts.
|
|||||||
from core import concept_map
|
from core import concept_map
|
||||||
from core.drafting import codes_schema, layout_schema, table_schema
|
from core.drafting import codes_schema, layout_schema, table_schema
|
||||||
from models.draft import fields
|
from models.draft import fields
|
||||||
from models.draft.documents import layouts
|
from models.draft.layouts import layouts
|
||||||
|
|
||||||
FORM = (
|
FORM = (
|
||||||
"SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: {date}\n"
|
"SOLICITUD DE CITOLOGÍA CERVICAL\nNombre: {name}\nFecha de recepción: {date}\n"
|
||||||
@@ -63,8 +63,12 @@ def test_a_columns_dates_get_the_format_every_value_parses_with():
|
|||||||
|
|
||||||
|
|
||||||
def test_answers_are_held_to_the_platforms_terms():
|
def test_answers_are_held_to_the_platforms_terms():
|
||||||
layout = layout_schema()["properties"]["entity"]["enum"]
|
layout = layout_schema(3)["$defs"]["Study"]["properties"]
|
||||||
assert "cervical_cytology" in layout and "none" in layout and "identity" not in layout
|
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"])
|
codes = codes_schema(["NEGATIVO", "BAJO GRADO"], ["NILM", "LSIL"])
|
||||||
one = codes["$defs"]["Code"]["properties"]
|
one = codes["$defs"]["Code"]["properties"]
|
||||||
assert one["raw"]["enum"] == ["NEGATIVO", "BAJO GRADO"]
|
assert one["raw"]["enum"] == ["NEGATIVO", "BAJO GRADO"]
|
||||||
|
|||||||
@@ -3,8 +3,8 @@ garbles is still marked by a line it prints, and a report that leaves its sample
|
|||||||
the order it answers is paired with that order by the column both carry."""
|
the order it answers is paired with that order by the column both carry."""
|
||||||
|
|
||||||
from core.pipeline import Join, Route
|
from core.pipeline import Join, Route
|
||||||
from models.draft.documents import printed_line
|
from models.draft.joins import Kind, apart_from, joined, partner
|
||||||
from models.draft.joins import Kind, joined, partner
|
from models.draft.layouts import printed_line
|
||||||
|
|
||||||
HPV = (
|
HPV = (
|
||||||
"No.Proceso {n}\nPaciente {name}\nDDDDEEEETTTTEEEECCCCCCCCIIIIOOOONNNN\n"
|
"No.Proceso {n}\nPaciente {name}\nDDDDEEEETTTTEEEECCCCCCCCIIIIOOOONNNN\n"
|
||||||
@@ -38,5 +38,11 @@ def test_a_report_is_read_with_the_order_the_same_column_pairs_it_with():
|
|||||||
found = dict((r["_record"], t) for t, r in joined(node, reports.everyone, orders))
|
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["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 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])
|
lone = Kind("cervical_cytology", "VPH", "x", [], reports.everyone[:1])
|
||||||
assert partner(lone, [lone, orders]) is None
|
assert partner(lone, [lone, orders]) is None
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
"""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