updating nlp policies; more robust recognition beyond rules

This commit is contained in:
Roberto Treviño Cervantes
2026-11-13 11:52:36 -06:00
parent ce67de17bc
commit 8f84253205
9 changed files with 495 additions and 6 deletions
+93 -4
View File
@@ -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
+28 -1
View File
@@ -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