updating nlp policies; more robust recognition beyond rules
This commit is contained in:
+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