updating nlp policies; more robust recognition beyond rules
This commit is contained in:
@@ -1,15 +1,19 @@
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import threading
|
||||
import unicodedata
|
||||
from collections import OrderedDict
|
||||
from importlib.metadata import PackageNotFoundError
|
||||
from importlib.metadata import version as package_version
|
||||
from typing import Any, ClassVar, Iterator
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from extraction import DocumentExtractor, ExtractedRecord, ExtractionError, make_segmenter, read_document, reader_for
|
||||
from extraction.readers import PdfReader, combine_pages, supported_extensions
|
||||
from extraction.nlp.ranking import examples_for, same_value
|
||||
from extraction.segmentation import SEGMENTERS
|
||||
from webapi.imports.connectors.base import decode_file
|
||||
from webapi.imports.connectors.document_columns import DocumentBatch, DocumentColumns, document_bytes # noqa: F401
|
||||
@@ -17,7 +21,7 @@ from webapi.imports.connectors.errors import ConnectorError
|
||||
from webapi.imports.connectors.registry import register_connector
|
||||
from webapi.imports.connectors.sql import SqlConnector
|
||||
from webapi.imports.connectors.tabular import DataFrameConnector
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, key_field_for
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
DOCUMENT_COLUMN = "documento"
|
||||
@@ -25,6 +29,8 @@ IMAGE_COLUMN = "imagen"
|
||||
CONFIDENCE_COLUMN = "confianza_extraccion"
|
||||
SOURCES_COLUMN = "origen"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _ResultCache:
|
||||
"""OCR over a stack of scans is slow, and the stateless API runs the
|
||||
@@ -126,6 +132,12 @@ class DocumentConnector(DataFrameConnector):
|
||||
raise ConnectorError(f"ocr_mode desconocido {ocr_mode!r}")
|
||||
self.files = files
|
||||
self.target = target
|
||||
self.domain = target.split(".", 1)[0]
|
||||
self.subject = subject_for(entity)
|
||||
self.foreign = foreign_subjects_for(entity)
|
||||
# The entity's column for the extraction version that filled it, when it has one.
|
||||
self.nlp_field = next((name for name in entity.schema.model_fields if name.endswith("_nlp_version")), None)
|
||||
self.ranker = _ranker(self.domain)
|
||||
self.specs = field_specs_for(entity, key_pattern=key_pattern)
|
||||
self.key_field = key_field_for(entity)
|
||||
self.segmentation = segmentation
|
||||
@@ -199,11 +211,19 @@ class DocumentConnector(DataFrameConnector):
|
||||
key=next((s for s in self.specs if s.name == self.key_field), None),
|
||||
pages_per_record=self.pages_per_record,
|
||||
)
|
||||
records = DocumentExtractor(self.specs, key_field=self.key_field, segmenter=segmenter).extract(
|
||||
documents, source_fields=self.source_fields, record_keys=self.record_keys
|
||||
)
|
||||
records = DocumentExtractor(
|
||||
self.specs, key_field=self.key_field, segmenter=segmenter, subject=self.subject, foreign=self.foreign, ranker=self.ranker
|
||||
).extract(documents, source_fields=self.source_fields, record_keys=self.record_keys)
|
||||
return records, skipped
|
||||
|
||||
@property
|
||||
def nlp_version(self) -> str:
|
||||
"""The extraction code's version and the ranker's (`extraccion:<n>`), when one was used."""
|
||||
try:
|
||||
code = package_version("extraction")
|
||||
except PackageNotFoundError:
|
||||
code = "dev"
|
||||
return f"extraction {code}" + (f" + {self.ranker.version}" if self.ranker is not None and self.ranker.version else "")
|
||||
|
||||
def _filtered_out(self, document) -> str | None:
|
||||
"""Why a document is left out by `include_pattern`/`exclude_pattern`,
|
||||
@@ -225,6 +245,7 @@ class DocumentConnector(DataFrameConnector):
|
||||
digest.update(hashlib.sha256(raw).digest())
|
||||
config = [
|
||||
self.target,
|
||||
self.nlp_version,
|
||||
self.segmentation,
|
||||
self.pages_per_record,
|
||||
self.ocr_mode,
|
||||
@@ -243,6 +264,7 @@ class DocumentConnector(DataFrameConnector):
|
||||
if self._df is None:
|
||||
columns = (
|
||||
[spec.name for spec in self.specs]
|
||||
+ ([self.nlp_field] if self.nlp_field else [])
|
||||
+ self.caption_columns()
|
||||
+ [DOCUMENT_COLUMN, IMAGE_COLUMN, CONFIDENCE_COLUMN, SOURCES_COLUMN]
|
||||
)
|
||||
@@ -276,6 +298,8 @@ class DocumentConnector(DataFrameConnector):
|
||||
for found in record.discovered:
|
||||
row.setdefault(_caption_column(found.caption, reserved), found.value)
|
||||
row.update(self.overrides.get(str(index), {}))
|
||||
if self.nlp_field and record.values:
|
||||
row[self.nlp_field] = self.nlp_version
|
||||
row[DOCUMENT_COLUMN] = self._record_pdf(record)
|
||||
row[IMAGE_COLUMN] = self._record_image(record)
|
||||
row[CONFIDENCE_COLUMN] = round(record.confidence, 3)
|
||||
@@ -325,7 +349,13 @@ class DocumentConnector(DataFrameConnector):
|
||||
"index": index,
|
||||
"key": record.key,
|
||||
"confidence": round(record.confidence, 3),
|
||||
"on_topic": record.on_topic,
|
||||
"fields": fields,
|
||||
"alternatives": {
|
||||
name: _alternatives(proposed, record.values.get(name))
|
||||
for name, proposed in record.candidates.items()
|
||||
if _alternatives(proposed, record.values.get(name))
|
||||
},
|
||||
"missing": [s.name for s in self.specs if s.required and s.name not in fields],
|
||||
"conflicts": [
|
||||
{"field": c.field, "kept": c.kept.to_dict(), "discarded": c.discarded.to_dict()}
|
||||
@@ -346,8 +376,67 @@ class DocumentConnector(DataFrameConnector):
|
||||
"key_field": self.key_field,
|
||||
"documents": [name for name, _ in self.files],
|
||||
"skipped": self.skipped,
|
||||
"nlp_version": self.nlp_version,
|
||||
}
|
||||
|
||||
# -- learning -------------------------------------------------------------
|
||||
|
||||
def reviewed(self) -> list[tuple[ExtractedRecord, dict[str, Any]]]:
|
||||
"""The records a person corrected while reviewing, each with what is
|
||||
known to be right about it: the corrected fields, and every other
|
||||
field as it was extracted, since whoever corrected the record read
|
||||
it. Fields a correction emptied are known to be empty."""
|
||||
reviewed = []
|
||||
for index, record in enumerate(self.records):
|
||||
corrections = self.overrides.get(str(index))
|
||||
if not corrections:
|
||||
continue
|
||||
truth: dict[str, Any] = {name: value.value for name, value in record.values.items()}
|
||||
truth.update({name: (None if value in ("", None) else value) for name, value in corrections.items()})
|
||||
known = {spec.name for spec in self.specs}
|
||||
reviewed.append((record, {name: value for name, value in truth.items() if name in known}))
|
||||
return reviewed
|
||||
|
||||
def learning_examples(self) -> tuple[list, dict[str, int], int]:
|
||||
"""Examples for the ranker from the reviewed records
|
||||
(`extraction.nlp.ranking.examples_for`), per field how many right
|
||||
values no candidate had proposed, and how many records they came from."""
|
||||
examples: list = []
|
||||
unreachable: dict[str, int] = {}
|
||||
reviewed = self.reviewed()
|
||||
for record, truth in reviewed:
|
||||
examples.extend(examples_for(self.specs, record.candidates, truth))
|
||||
for name, value in truth.items():
|
||||
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(name, ())):
|
||||
unreachable[name] = unreachable.get(name, 0) + 1
|
||||
return examples, unreachable, len(reviewed)
|
||||
|
||||
|
||||
def _ranker(domain: str):
|
||||
"""The domain's extraction ranker in the model registry, or `None` (rank by
|
||||
confidence) when there is none or the registry can't be read."""
|
||||
try:
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
return current(domain)
|
||||
except Exception as exc: # noqa: BLE001 - extraction must work without the registry
|
||||
logger.warning("sin ranker de extracción para %s: %s", domain, exc)
|
||||
return None
|
||||
|
||||
|
||||
def _alternatives(proposed: list, chosen) -> list[dict[str, Any]]:
|
||||
"""The other values the extractors proposed for a field, best first, for a reviewer to pick from."""
|
||||
seen, found = set(), []
|
||||
for candidate in sorted(proposed, key=lambda c: -c.confidence):
|
||||
if chosen is not None and same_value(candidate.value, chosen.value):
|
||||
continue
|
||||
key = json.dumps(candidate.to_dict()["value"], default=str)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
found.append({**candidate.to_dict(), "confidence": round(candidate.confidence, 3)})
|
||||
return found[:5]
|
||||
|
||||
|
||||
def _caption_column(caption: str, reserved: set[str]) -> str:
|
||||
"""A discovered caption as a column name, kept apart from the target's
|
||||
|
||||
@@ -8,7 +8,17 @@ import typing
|
||||
from datetime import date, datetime
|
||||
|
||||
from extraction.nlp import FieldKind, FieldSpec
|
||||
from extraction.nlp.vocabulary import CLINICAL_TERMS, FREE_TEXT_FIELDS, PATTERNS, labels_for
|
||||
from extraction.nlp.vocabulary import (
|
||||
ANCHORS,
|
||||
CLINICAL_TERMS,
|
||||
FREE_TEXT_FIELDS,
|
||||
NEGATED_VALUES,
|
||||
PATTERNS,
|
||||
SEVERITY,
|
||||
SUBJECTS,
|
||||
UNITS,
|
||||
labels_for,
|
||||
)
|
||||
from webapi.imports.schemas.registry import EntitySpec
|
||||
|
||||
# Surrogate keys, stored files and OCR bookkeeping are never read from a document.
|
||||
@@ -42,11 +52,28 @@ def field_specs_for(entity: EntitySpec, *, key_pattern: str | None = None) -> li
|
||||
scan_free_text=name in FREE_TEXT_FIELDS or (pattern is not None and pattern == key_pattern),
|
||||
multiline=kind is FieldKind.TEXT and bool(_LONG_TEXT.search(name)),
|
||||
required=info.is_required(),
|
||||
anchors=ANCHORS.get(name, ()),
|
||||
severity=SEVERITY.get(name, ()),
|
||||
negated_value=NEGATED_VALUES.get(name),
|
||||
unit=UNITS.get(name),
|
||||
)
|
||||
)
|
||||
return specs
|
||||
|
||||
|
||||
def subject_for(entity: EntitySpec) -> tuple[str, ...]:
|
||||
"""What a document feeding this entity is about (`vocabulary.SUBJECTS`)."""
|
||||
return SUBJECTS.get(entity.model.__table__.name, ())
|
||||
|
||||
|
||||
def foreign_subjects_for(entity: EntitySpec) -> tuple[str, ...]:
|
||||
"""What documents feeding other entities are about, less this one's own terms."""
|
||||
own = set(subject_for(entity))
|
||||
if not own:
|
||||
return ()
|
||||
return tuple(sorted({term for table, terms in SUBJECTS.items() if table != entity.model.__table__.name for term in terms} - own))
|
||||
|
||||
|
||||
def key_field_for(entity: EntitySpec) -> str | None:
|
||||
"""The field that identifies whose record a page belongs to."""
|
||||
fields = entity.schema.model_fields
|
||||
|
||||
@@ -30,6 +30,7 @@ from webapi.imports.mapping.derived import Derivation, parse_derived
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY, EntitySpec
|
||||
from webapi.imports.schemas.service import BatchValidationResult, validate_rows
|
||||
from webapi.imports.services.link_resolver import LinkResolver, dependency_rank
|
||||
from webapi.imports.services.review_learning import learn_from_reviews
|
||||
|
||||
|
||||
class ImportRequestError(Exception):
|
||||
@@ -465,4 +466,5 @@ def commit_sources(
|
||||
) from exc
|
||||
finally:
|
||||
session.close()
|
||||
learn_from_reviews(sources)
|
||||
return [results[i] for i in range(len(validated))]
|
||||
|
||||
@@ -102,4 +102,5 @@ def document_report(payload: dict[str, Any]) -> dict[str, Any]:
|
||||
"fields": fields,
|
||||
"records": connector.report(),
|
||||
"skipped": connector.skipped,
|
||||
"nlp_version": connector.nlp_version,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Learning from the corrections made while reviewing documents: once an
|
||||
import is written, each document source whose records a person corrected
|
||||
teaches its domain's extraction ranker (`models.io.extraction_ranker`), in
|
||||
the background so the import never waits for it, one batch at a time.
|
||||
|
||||
`EXTRACTION_LEARNING=0` turns it off.
|
||||
"""
|
||||
import logging
|
||||
import os
|
||||
from concurrent.futures import Future, ThreadPoolExecutor
|
||||
from typing import Sequence
|
||||
|
||||
from webapi.imports.connectors.document import DocumentConnector
|
||||
|
||||
LEARNING_ENV = "EXTRACTION_LEARNING"
|
||||
SOURCE = "revision"
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
_executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="extraction-learning")
|
||||
|
||||
|
||||
def enabled() -> bool:
|
||||
return os.environ.get(LEARNING_ENV, "1").strip().lower() not in ("0", "false", "no")
|
||||
|
||||
|
||||
def _connector(source) -> DocumentConnector | None:
|
||||
if source.source_type == "document":
|
||||
connector = source.connector()
|
||||
elif source.documents:
|
||||
connector, _, _ = source.document_connector()
|
||||
else:
|
||||
return None
|
||||
return connector if isinstance(connector, DocumentConnector) else None
|
||||
|
||||
|
||||
def learn_from_reviews(sources: Sequence) -> list[Future]:
|
||||
"""Queues one learning step per corrected document source; returns them,
|
||||
for a caller that wants to wait."""
|
||||
if not enabled():
|
||||
return []
|
||||
futures = []
|
||||
for source in sources:
|
||||
try:
|
||||
connector = _connector(source)
|
||||
if connector is None or not connector.overrides:
|
||||
continue
|
||||
examples, unreachable, records = connector.learning_examples()
|
||||
except Exception: # noqa: BLE001 - the import is already written
|
||||
logger.exception("no se pudieron preparar ejemplos de %s", getattr(source, "target", "?"))
|
||||
continue
|
||||
if examples:
|
||||
documents = len(connector.files)
|
||||
futures.append(_executor.submit(_learn, connector.domain, examples, unreachable, records, documents))
|
||||
return futures
|
||||
|
||||
|
||||
def _learn(domain: str, examples: list, unreachable: dict[str, int], records: int, documents: int) -> str | None:
|
||||
from models.io.extraction_ranker import Batch, learn
|
||||
|
||||
try:
|
||||
return learn(domain, Batch(examples, SOURCE, documents, records, unreachable))
|
||||
except Exception: # noqa: BLE001
|
||||
logger.exception("el ranker de extracción de %s no pudo aprender de la revisión", domain)
|
||||
return None
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
"""Measuring and training document extraction against an answer key (VAR-04, VARM-05).
|
||||
|
||||
python -m webapi.nlp evaluate --documents <folder> --key <key.json> [--with-values] [--no-ranker]
|
||||
python -m webapi.nlp train --documents <folder> --key <key.json>
|
||||
|
||||
The key is JSON: per document file name, per import target, per field, the right value (`null` for a field that
|
||||
must stay empty); fields left out are not scored.
|
||||
|
||||
{"reporte_01.pdf": {"cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG", "bx_fecha_reporte": "2025-01-31"}}}
|
||||
|
||||
Each document is read as one record. `evaluate` prints precision, recall and F1 per field and overall, with the
|
||||
domain's current ranker (`models.io.extraction_ranker`) unless `--no-ranker`; errors list which document and
|
||||
field, and their values only with `--with-values`. `train` first estimates how a ranker trained on the key would do
|
||||
on documents it has not seen (leaving each document out in turn), then teaches the domain's ranker the whole key and
|
||||
registers it as a new DEV version, which a person promotes like any model.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from extraction import DocumentExtractor, read_document
|
||||
from extraction.nlp.evaluation import evaluate
|
||||
from extraction.nlp.ranking import LearnedRanker, examples_for, same_value
|
||||
from extraction.readers import supported_extensions
|
||||
from extraction.segmentation import WholeDocument
|
||||
from webapi.imports.schemas.field_specs import field_specs_for, foreign_subjects_for, key_field_for, subject_for
|
||||
from webapi.imports.schemas.registry import ENTITY_REGISTRY
|
||||
|
||||
|
||||
def _documents(folder: Path, names) -> dict[str, Any]:
|
||||
extensions = tuple(supported_extensions())
|
||||
found = {}
|
||||
for name in names:
|
||||
path = folder / name
|
||||
if not path.is_file() or not path.name.lower().endswith(extensions):
|
||||
raise SystemExit(f"no se encontró el documento {name} en {folder}")
|
||||
found[name] = read_document(name, path.read_bytes())
|
||||
return found
|
||||
|
||||
|
||||
def _extractor(target: str, ranker) -> DocumentExtractor:
|
||||
entity = ENTITY_REGISTRY.get(target)
|
||||
if entity is None:
|
||||
raise SystemExit(f"destino desconocido: {target}")
|
||||
return DocumentExtractor(
|
||||
field_specs_for(entity), key_field=key_field_for(entity), segmenter=WholeDocument(), merger=None,
|
||||
subject=subject_for(entity), foreign=foreign_subjects_for(entity), ranker=ranker,
|
||||
)
|
||||
|
||||
|
||||
def _records(documents: dict[str, Any], key: dict[str, dict[str, dict[str, Any]]], rankers: dict[str, Any]):
|
||||
"""Per (document, target): the extracted record."""
|
||||
records = {}
|
||||
for name, targets in key.items():
|
||||
for target in targets:
|
||||
extractor = _extractor(target, rankers.get(target.split(".", 1)[0]))
|
||||
[records[(name, target)]] = extractor.extract([documents[name]])[:1] or [None]
|
||||
return records
|
||||
|
||||
|
||||
def _scores(records, key) -> dict[str, Any]:
|
||||
extracted = {f"{name} · {target}": {f: v.value for f, v in record.values.items()} for (name, target), record in records.items() if record}
|
||||
expected = {f"{name} · {target}": fields for name, targets in key.items() for target, fields in targets.items()}
|
||||
return evaluate(extracted, expected)
|
||||
|
||||
|
||||
def _examples(records, key) -> tuple[dict[str, list], dict[str, dict[str, int]]]:
|
||||
"""Per domain, the labelled examples of every record, and per field how many right values no candidate had."""
|
||||
examples: dict[str, list] = {}
|
||||
unreachable: dict[str, dict[str, int]] = {}
|
||||
for (name, target), record in records.items():
|
||||
if record is None:
|
||||
continue
|
||||
domain = target.split(".", 1)[0]
|
||||
specs = field_specs_for(ENTITY_REGISTRY[target])
|
||||
truth = key[name][target]
|
||||
examples.setdefault(domain, []).extend(examples_for(specs, record.candidates, truth))
|
||||
missing = unreachable.setdefault(domain, {})
|
||||
for field, value in truth.items():
|
||||
if value is not None and not any(same_value(c.value, value) for c in record.candidates.get(field, ())):
|
||||
missing[field] = missing.get(field, 0) + 1
|
||||
return examples, unreachable
|
||||
|
||||
|
||||
def _current_rankers(domains) -> dict[str, Any]:
|
||||
from models.io.extraction_ranker import current
|
||||
|
||||
return {domain: current(domain) for domain in domains}
|
||||
|
||||
|
||||
def command_evaluate(args) -> dict[str, Any]:
|
||||
key = json.loads(Path(args.key).read_text())
|
||||
documents = _documents(Path(args.documents), key)
|
||||
domains = {target.split(".", 1)[0] for targets in key.values() for target in targets}
|
||||
rankers = {} if args.no_ranker else _current_rankers(domains)
|
||||
result = _scores(_records(documents, key, rankers), key).to_dict(with_values=args.with_values)
|
||||
result["rankers"] = {domain: getattr(ranker, "version", None) for domain, ranker in rankers.items()}
|
||||
return result
|
||||
|
||||
|
||||
def command_train(args) -> dict[str, Any]:
|
||||
from models.io.extraction_ranker import Batch, learn
|
||||
|
||||
key = json.loads(Path(args.key).read_text())
|
||||
documents = _documents(Path(args.documents), key)
|
||||
records = _records(documents, key, {})
|
||||
held_out = {}
|
||||
for left_out in key:
|
||||
training = {k: v for k, v in records.items() if k[0] != left_out}
|
||||
examples, _ = _examples(training, key)
|
||||
rankers = {domain: _trained(batch) for domain, batch in examples.items()}
|
||||
held_out.update({k: v for k, v in _records({left_out: documents[left_out]}, {left_out: key[left_out]}, rankers).items()})
|
||||
estimate = _scores(held_out, key).to_dict()
|
||||
examples, unreachable = _examples(records, key)
|
||||
versions = {}
|
||||
for domain, batch in examples.items():
|
||||
documents_in_domain = len({name for (name, target) in records if target.startswith(f"{domain}.")})
|
||||
records_in_domain = sum(1 for (_, target) in records if target.startswith(f"{domain}."))
|
||||
versions[domain] = learn(domain, Batch(batch, "clave", documents_in_domain, records_in_domain, unreachable.get(domain, {})))
|
||||
return {
|
||||
"sin_ranker": _scores(records, key).to_dict()["global"],
|
||||
"estimacion_dejando_uno_fuera": estimate["global"],
|
||||
"versiones": versions,
|
||||
}
|
||||
|
||||
|
||||
def _trained(examples) -> LearnedRanker:
|
||||
ranker = LearnedRanker()
|
||||
ranker.learn(examples)
|
||||
return ranker
|
||||
|
||||
|
||||
def main(argv=None) -> int:
|
||||
parser = argparse.ArgumentParser(prog="python -m webapi.nlp", description=__doc__.split("\n\n")[0])
|
||||
commands = parser.add_subparsers(dest="command", required=True)
|
||||
for name in ("evaluate", "train"):
|
||||
command = commands.add_parser(name)
|
||||
command.add_argument("--documents", required=True, help="carpeta con los documentos")
|
||||
command.add_argument("--key", required=True, help="JSON con los valores correctos")
|
||||
if name == "evaluate":
|
||||
command.add_argument("--with-values", action="store_true", help="incluir los valores de cada error")
|
||||
command.add_argument("--no-ranker", action="store_true", help="ordenar candidatos solo por confianza")
|
||||
args = parser.parse_args(argv)
|
||||
result = command_evaluate(args) if args.command == "evaluate" else command_train(args)
|
||||
json.dump(result, sys.stdout, ensure_ascii=False, indent=1, default=str)
|
||||
sys.stdout.write("\n")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user