101 lines
3.4 KiB
Python
101 lines
3.4 KiB
Python
from dataclasses import dataclass, field
|
|
from datetime import date
|
|
from enum import Enum
|
|
from typing import Any, Mapping
|
|
|
|
from extraction.nlp.text import fold
|
|
|
|
|
|
class FieldKind(str, Enum):
|
|
TEXT = "text"
|
|
IDENTIFIER = "identifier"
|
|
INTEGER = "integer"
|
|
DECIMAL = "decimal"
|
|
DATE = "date"
|
|
CHOICE = "choice"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class FieldSpec:
|
|
"""What to look for in a document to fill one column.
|
|
|
|
`labels` are the captions a form or report prints before the value
|
|
("Fecha de nacimiento", "F. Nac."). `choices` maps surface forms to the
|
|
value stored (`"NO DETECTADO" -> 0`, `"NIC II" -> "LIEAG"`); matching is
|
|
accent- and case-insensitive and prefers the longest form.
|
|
`pattern` is the shape of a valid value (the match is what's kept).
|
|
`scan_free_text` lets the field be found anywhere in the narrative, not
|
|
only after one of its labels: as a mention for CHOICE fields, by
|
|
`pattern` for the rest.
|
|
|
|
In narrative text a generic answer ("POSITIVO") only counts next to one
|
|
of `anchors` or `labels`; `severity` orders the choice values from least
|
|
to most severe, and the most severe one a report affirms is its finding;
|
|
`negated_value` is what a denied mention means ("sin actividad
|
|
epileptiforme" -> 0); `unit` is a pattern for the unit a measurement is
|
|
written in (`HZ`).
|
|
"""
|
|
|
|
name: str
|
|
kind: FieldKind = FieldKind.TEXT
|
|
labels: tuple[str, ...] = ()
|
|
choices: Mapping[str, Any] = field(default_factory=dict)
|
|
pattern: str | None = None
|
|
scan_free_text: bool = False
|
|
multiline: bool = False
|
|
required: bool = False
|
|
anchors: tuple[str, ...] = ()
|
|
severity: tuple[Any, ...] = ()
|
|
negated_value: Any = None
|
|
unit: str | None = None
|
|
|
|
def __post_init__(self):
|
|
folded = {fold(str(surface)).strip(): value for surface, value in self.choices.items() if str(surface).strip()}
|
|
object.__setattr__(self, "choices", folded)
|
|
|
|
@property
|
|
def surface_forms(self) -> list[str]:
|
|
return sorted(self.choices, key=len, reverse=True)
|
|
|
|
def severity_rank(self, value: Any) -> int:
|
|
return self.severity.index(value) if value in self.severity else -1
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class Evidence:
|
|
document: str
|
|
page_number: int
|
|
line: str
|
|
bbox: list[float] | None = None
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ExtractedValue:
|
|
"""One reading of a field. `features` describe how it was found (the
|
|
mention's assertion and section, the label's score...), for
|
|
`extraction.nlp.ranking`; they never hold the document's text."""
|
|
|
|
value: Any
|
|
confidence: float
|
|
method: str
|
|
raw: str
|
|
evidence: Evidence
|
|
features: Mapping[str, Any] = field(default_factory=dict, compare=False, hash=False)
|
|
|
|
def with_confidence(self, confidence: float, **features: Any) -> "ExtractedValue":
|
|
return ExtractedValue(self.value, confidence, self.method, self.raw, self.evidence, {**self.features, **features})
|
|
|
|
def to_dict(self) -> dict[str, Any]:
|
|
value = self.value.isoformat() if isinstance(self.value, date) else self.value
|
|
return {
|
|
"value": value,
|
|
"confidence": round(self.confidence, 3),
|
|
"method": self.method,
|
|
"raw": self.raw,
|
|
"document": self.evidence.document,
|
|
"page_number": self.evidence.page_number,
|
|
"line": self.evidence.line,
|
|
"bbox": self.evidence.bbox,
|
|
"assertion": self.features.get("assertion"),
|
|
}
|