Files
ISSSTELEON/Extraction/extraction/nlp/discovery.py
T
Roberto Treviño Cervantes d8ff604b6f import files in columns
2026-11-11 11:19:41 -06:00

44 lines
1.7 KiB
Python

"""Captions a document carries that no registered `FieldSpec` claims.
`LabeledValueExtractor` only looks for the labels a caller already knows
about. A source whose documents carry fields outside today's vocabulary
(a hospital's own report layout, a free-form note) still has captions in
the `"Campo: valor"` shape; this module finds them so a caller can decide,
per caption, whether it matches something in a catalog closely enough to
reuse, or is new (see `webapi.imports.schemas.catalog_matching`)."""
import re
from dataclasses import dataclass
from typing import Sequence
from extraction.nlp.extractors import LabelIndex, SegmentLine
from extraction.nlp.fields import Evidence, FieldSpec
_CAPTION_LINE = re.compile(r"^(?P<caption>[^:=]{2,60}?)\s*[:=]\s*(?P<value>\S.*)$")
@dataclass(frozen=True)
class DiscoveredField:
"""One `caption: value` line a known `FieldSpec` didn't already claim."""
caption: str
value: str
evidence: Evidence
def discover_captions(lines: Sequence[SegmentLine], specs: Sequence[FieldSpec]) -> list[DiscoveredField]:
"""Every undiscovered caption, in line order, duplicates kept (the
caller decides how to fold repeats across a record's lines)."""
index = LabelIndex(lines, specs)
found: list[DiscoveredField] = []
for line_index, line in enumerate(lines):
if index.hits[line_index]:
continue # a known label already explains this line
match = _CAPTION_LINE.match(line.text.strip())
if not match:
continue
caption, value = match.group("caption").strip(), match.group("value").strip()
if not caption or not value:
continue
found.append(DiscoveredField(caption, value, line.evidence()))
return found