Files
models/models/draft/documents.py
T

215 lines
11 KiB
Python

"""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,
shared_words,
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
try:
answer = llm.ask(LAYOUT.format(studies=studies_text()), text, layout_schema(len(shown)))
except llm.Unreadable as e: # left undrawn: a person draws its route
log(f"layout of {len(members)} left out, the model's answer: {e}")
continue
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, members)) 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, layout=()) -> 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
if found := shared_words(mine, rest, study["label"], layout, only=True):
return found # the study's own name: what a person would route by
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
if found := shared_words(mine, rest, study["label"], layout):
return found
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