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
+14 -1
View File
@@ -22,8 +22,10 @@ webapi/
│ ├── connectors/ una clase por tipo de fuente (@register_connector)
│ ├── schemas/ un esquema pydantic por tabla destino; registry.py los enlista
│ ├── mapping/ sugerencia de mapeo de columnas
│ ├── services/ validación, combinación de fuentes, enlace de llaves y escritura
│ ├── services/ validación, combinación de fuentes, enlace de llaves, escritura
│ │ y aprendizaje de las correcciones de documentos (review_learning.py)
│ └── audit.py bitácora agregada (sin datos de pacientes)
├── nlp.py python -m webapi.nlp evaluate|train: extracción contra una clave de respuestas
├── indicadores.py rutas de indicadores (del equipo de indicadores)
├── indicadores_vivos.py cola y servicio que recalcula indicadores tras cada carga
└── seguimiento.py lista de seguimiento por paciente (solo con DEV_REVISION)
@@ -74,6 +76,8 @@ Los errores de la solicitud se responden con `{"error": "..."}` y código 400
| `NOTEBOOK_JOB_TIMEOUT`, `NOTEBOOK_CELL_TIMEOUT` | `21600`, `1800` | Segundos que espera un notebook completo y una celda |
| `NOTEBOOK_MAX_IMPORT_MB` | `500` | Tope de archivos que se importan de lo que entrenó un notebook |
| `WEBAPI_NOTEBOOK_WORKERS` | `1` | Notebooks a la vez por proceso de la API |
| `EXTRACTION_RANKER` | `auto` | Ranker de extracción de documentos: `auto` (el de producción, si no el último), `produccion` (solo el de producción) o `ninguno` |
| `EXTRACTION_LEARNING` | `1` | `0` deja de aprender de las correcciones hechas al revisar documentos |
| `NOTEBOOK_RENDERER` | `quarto` si está instalado, si no `jupyter` | Con qué se corre y se arma la página |
## Ejecución
@@ -89,6 +93,15 @@ uv run python main.py # http://localhost:5050
uv run python -m webapi.indicadores_vivos # recálculo de indicadores, en otra terminal
```
Medir la extracción de documentos contra una clave de respuestas (por documento y
destino, el valor correcto de cada campo revisado; `null` si debe quedar vacío)
y entrenar con ella el ranker del dominio (`Extraction/README.md`):
```bash
uv run python -m webapi.nlp evaluate --documents carpeta/ --key clave.json [--with-values] [--no-ranker]
uv run python -m webapi.nlp train --documents carpeta/ --key clave.json
```
Con Docker, desde la raíz del repositorio: `docker compose up --build`. La
imagen se construye con `WebApi/Dockerfile` (contexto: la raíz, para copiar
los paquetes hermanos); `docker-entrypoint.sh` aplica las migraciones y
+4
View File
@@ -31,6 +31,10 @@ os.environ.setdefault("WEBAPI_SQL_ALLOWED_DIALECTS", "sqlite,mysql,mariadb,postg
_STATE_DIR = tempfile.mkdtemp(prefix="webapi-tests-")
os.environ.setdefault("WEBAPI_REPORT_DIR", os.path.join(_STATE_DIR, "reportes"))
os.environ.setdefault("INDICADORES_DIR", os.path.join(_STATE_DIR, "indicadores"))
# Extraction ranks by confidence and learns nothing unless a test sets up a
# model registry of its own (test_review_learning.py).
os.environ.setdefault("EXTRACTION_RANKER", "ninguno")
os.environ.setdefault("EXTRACTION_LEARNING", "0")
ANIO = 2025
+136
View File
@@ -0,0 +1,136 @@
"""Extraction's ranker in WebApi: the document review reports each field's
alternatives, whether the record is about the target and which extraction
version read it; an import whose records a person corrected teaches the
domain's ranker once it is written (`webapi.imports.services.
review_learning`); and `python -m webapi.nlp` scores and trains against an
answer key.
Fixtures: `client` (the app over fresh CaCu, CaMa and TEA databases),
`registry` (a SQLite MLflow per test with its files in `tmp_path`, the
ranker and learning switched on, and learning run synchronously). Documents are made up inline with
`text_pdf`.
"""
import argparse
import base64
import json
from concurrent.futures import Future
import pytest
from extraction.testing import text_pdf
from webapi import nlp
from webapi.imports.services import review_learning
REPORT = text_pdf([["LABORATORIO DE CITOLOGÍA", "Expediente: RV-0001", "No. de orden: 9001", "Prueba de VPH por PCR: POSITIVO",
"Observaciones: se sugiere colposcopía; en caso de VPH negativo repetir en un año."]])
@pytest.fixture(scope="module")
def client(wire_domain):
wire_domain("cacu")
wire_domain("cama")
wire_domain("tea")
from webapi import create_app
app = create_app()
app.config.update(TESTING=True)
with app.test_client() as test_client:
yield test_client
class _Now:
"""An executor that runs each task as it is submitted."""
def submit(self, fn, *args):
future = Future()
future.set_result(fn(*args))
return future
@pytest.fixture
def registry(tmp_path, monkeypatch):
import mlflow
from models.io import extraction_ranker
uri = f"sqlite:///{tmp_path / 'mlflow.db'}"
monkeypatch.setenv("MLFLOW_TRACKING_URI", uri)
monkeypatch.setenv("MLFLOW_ARTIFACT_ROOT", str(tmp_path / "artefactos"))
mlflow.set_tracking_uri(uri)
monkeypatch.chdir(tmp_path)
monkeypatch.setenv("EXTRACTION_RANKER", "auto")
monkeypatch.setenv("EXTRACTION_LEARNING", "1")
monkeypatch.setattr(extraction_ranker, "_cache", {})
monkeypatch.setattr(review_learning, "_executor", _Now())
from models.io.registry import registry as models_registry
yield models_registry
def _source(**options) -> dict:
return {
"source_type": "document",
"target": "cacu.CitologiaCervical",
"column_mapping": {"pac_id_hospital": "pac_id_hospital", "ord_numero_hospital": "ord_numero_hospital",
"cit_vph_resultado": "cit_vph_resultado"},
"payload": {"files": [{"name": "r.pdf", "file_base64": base64.b64encode(REPORT).decode()}], **options},
"label": "documentos",
}
def test_the_review_reports_alternatives_topic_and_version(client):
"""Fails if the review loses the other readings a person can pick, the
subject check, or the extraction version that will be stored."""
body = client.post("/imports/sources/document/extract", json={"files": _source()["payload"]["files"], "target": "cacu.CitologiaCervical"}).get_json()
[record] = body["records"]
assert record["on_topic"] is True
assert record["fields"]["cit_vph_resultado"]["value"] == "POSITIVO"
assert record["fields"]["cit_vph_resultado"]["assertion"] == "afirmado"
assert body["nlp_version"].startswith("extraction ")
assert all(isinstance(options, list) for options in record["alternatives"].values())
def test_a_corrected_import_teaches_the_ranker(client, registry):
"""Committing a document source with a correction registers a new DEV
version of the domain's ranker, learned from that record. Fails if
`commit_sources` stops calling `learn_from_reviews` or the examples are
lost on the way."""
source = _source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})
result = client.post("/imports/commit", json={"sources": [source]}).get_json()
assert result["ok"], result
[version] = registry.versions("cacu", "extraccion")
assert version["status"] == "desarrollo"
from models.io.extraction_ranker import current
assert current("cacu").examples > 0
def test_imports_without_corrections_or_with_learning_off_teach_nothing(client, registry, monkeypatch):
"""Fails if an untouched import, or one made with
`EXTRACTION_LEARNING=0`, creates ranker versions."""
client.post("/imports/commit", json={"sources": [_source()]})
monkeypatch.setenv("EXTRACTION_LEARNING", "0")
client.post("/imports/commit", json={"sources": [_source(overrides={"0": {"cit_vph_resultado": "NEGATIVO"}})]})
assert registry.versions("cacu", "extraccion") == []
def test_the_command_scores_and_trains_against_an_answer_key(tmp_path, registry):
"""`evaluate` scores per field and overall without printing values
unless asked; `train` estimates on held-out documents, then registers
a version. Fails if the command's key format or outputs change."""
folder = tmp_path / "documentos"
folder.mkdir()
(folder / "a.pdf").write_bytes(REPORT)
(folder / "b.pdf").write_bytes(text_pdf([["Biopsia cervical dirigida", "Diagnóstico:", "NIC I"]]))
key = {
"a.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": "POSITIVO", "pac_id_hospital": "RV-0001"}},
"b.pdf": {"cacu.CitologiaCervical": {"cit_vph_resultado": None}, "cacu.BiopsiaCervical": {"bx_cin_grado": "LIEBG"}},
}
(tmp_path / "clave.json").write_text(json.dumps(key))
paths = {"documents": str(folder), "key": str(tmp_path / "clave.json")}
evaluated = nlp.command_evaluate(argparse.Namespace(**paths, with_values=False, no_ranker=True))
assert evaluated["global"]["f1"] == 1.0
assert evaluated["errores"] == []
trained = nlp.command_train(argparse.Namespace(**paths))
assert set(trained) == {"sin_ranker", "estimacion_dejando_uno_fuera", "versiones"}
assert trained["versiones"] == {"cacu": "1"}
+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
+153
View File
@@ -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())