Files
ISSSTELEON/Extraction/tests/test_ranking.py
T
2026-11-13 11:53:07 -06:00

98 lines
5.1 KiB
Python

"""Choosing among candidates and learning from corrections
(`extraction.nlp.ranking`), and scoring extraction against an answer key
(`extraction.nlp.evaluation`).
Fixtures: none; candidates are built inline by `candidate` below, with the
features an extractor would give them.
"""
from datetime import date
from extraction.document import BBox
from extraction.nlp import FieldKind, FieldSpec
from extraction.nlp.evaluation import evaluate
from extraction.nlp.fields import Evidence, ExtractedValue
from extraction.nlp.ranking import TRUST_EXAMPLES, Example, HeuristicRanker, LearnedRanker, examples_for, features, same_value
GRADO = FieldSpec("bx_cin_grado", FieldKind.CHOICE, choices={"NIC I": "LIEBG", "NIC II": "LIEAG"})
def candidate(value, confidence, method, **extra) -> ExtractedValue:
evidence = Evidence("doc.pdf", 1, "línea", BBox(0, 0, 1, 0.1).as_list())
return ExtractedValue(value, confidence, method, str(value), evidence, {"assertion": "afirmado", "section": "general", **extra})
def test_the_heuristic_keeps_the_most_confident_and_respects_the_rules():
"""Fails if a hypothetical mention or an off-topic document can fill a
field without a trained ranker."""
ranker = HeuristicRanker()
assert ranker.choose(GRADO, [candidate("LIEBG", 0.4, "etiqueta"), candidate("LIEAG", 0.6, "texto_libre")]).value == "LIEAG"
assert ranker.choose(GRADO, [candidate("LIEAG", 0.9, "texto_libre", assertion="hipotetico")]) is None
assert ranker.choose(GRADO, [candidate("LIEAG", 0.9, "etiqueta", on_topic=False)]) is None
def test_corrections_teach_the_ranker_to_prefer_what_was_right():
"""People keep correcting the narrative reading to the labelled one;
after enough corrections the ranker picks the label even though its
confidence is lower. Fails if `learn` stops moving the weights toward
the corrected candidates or `score` stops using them."""
label, narrative = candidate("LIEBG", 0.5, "etiqueta"), candidate("LIEAG", 0.6, "texto_libre")
ranker = LearnedRanker()
assert ranker.choose(GRADO, [label, narrative]).value == "LIEAG"
examples = examples_for([GRADO], {"bx_cin_grado": [label, narrative]}, {"bx_cin_grado": "LIEBG"})
for _ in range(TRUST_EXAMPLES // len(examples) + 1):
ranker.learn(examples)
assert ranker.trust == 1.0
assert ranker.choose(GRADO, [label, narrative]).value == "LIEBG"
def test_the_rules_veto_holds_until_the_ranker_is_trusted():
"""A ranker that has seen few examples can reorder what the rules allow
but not revive what they rule out. Fails if a barely trained ranker
can fill a field from a hypothetical mention."""
hypothetical = candidate("LIEAG", 0.9, "texto_libre", assertion="hipotetico")
ranker = LearnedRanker()
ranker.learn([Example("bx_cin_grado", features(GRADO, hypothetical), True)] * 10)
assert ranker.trust < 1.0 and ranker.choose(GRADO, [hypothetical]) is None
def test_a_field_known_to_be_empty_makes_its_candidates_wrong():
"""Fails if `examples_for` stops teaching that a field should stay empty,
or starts learning from fields the truth leaves out."""
examples = examples_for([GRADO], {"bx_cin_grado": [candidate("LIEAG", 0.6, "texto_libre")]}, {"bx_cin_grado": None})
assert [e.label for e in examples] == [False]
assert examples_for([GRADO], {"bx_cin_grado": [candidate("LIEAG", 0.6, "texto_libre")]}, {}) == []
def test_the_ranker_survives_a_round_trip_and_holds_no_text():
"""The stored state is weights over feature names. Fails if `to_dict`
loses state or a feature name carries a candidate's value or raw text."""
ranker = LearnedRanker()
ranker.learn(examples_for([GRADO], {"bx_cin_grado": [candidate("LIEAG", 0.6, "texto_libre")]}, {"bx_cin_grado": "LIEAG"}))
again = LearnedRanker.from_dict(ranker.to_dict())
assert again.weights == ranker.weights and again.examples == ranker.examples
assert not any("LIEAG" in name for name in ranker.weights)
def test_values_compare_by_meaning():
"""Dates by day, numbers by value, text without accents or case. Fails
if a correction typed as text no longer matches the extracted value."""
assert same_value(date(2025, 3, 4), "2025-03-04")
assert same_value(0, "0") and same_value(7.5, 7.5)
assert same_value("Lesión", "LESION")
assert not same_value("LIEAG", "LIEBG") and not same_value(None, "x")
def test_evaluation_counts_wrong_values_as_both_errors():
"""A wrong value is a false positive and a false negative; a value where
the key says empty a false positive. Fails if `evaluate` changes those
conventions or puts values in errors when not asked to."""
result = evaluate(
{"a": {"f": "X", "g": "Y"}, "b": {"f": "Z"}},
{"a": {"f": "X", "g": None}, "b": {"f": "W", "g": None}},
)
assert result.fields["f"].true_positives == 1 and result.fields["f"].false_negatives == 1
assert result.fields["f"].false_positives == 1 and result.fields["g"].false_positives == 1
assert result.fields["g"].true_negatives == 1
assert result.overall.precision == 1 / 3
assert result.to_dict()["errores"] == [{"documento": "a", "campo": "g"}, {"documento": "b", "campo": "f"}]