"""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 (another report layout, a free-form note) still has captions in the `"Campo: valor"` shape; this module finds them so a caller can use them as values of their own, or decide whether each matches something in a catalog closely enough to reuse, or is new (see `webapi.imports.schemas.catalog_matching`). Captions are found wherever a form puts them: alone on their line, several on one line, after an item number, or heading a column whose value sits on the line below. Each one found becomes a temporary `FieldSpec`, so its value is read by the same extractor, with the same layout handling, as the known fields'. """ import re from dataclasses import dataclass from typing import Sequence from extraction.nlp.extractors import LabelIndex, RecordExtractor, SegmentLine, cell_starts from extraction.nlp.fields import Evidence, FieldKind, FieldSpec MAX_CAPTION_WORDS = 6 _ITEM_NUMBER = re.compile(r"(?:^|(?<=\s))(?:\d{1,3}|[A-Za-z])\s*[.)][.\-]*(?=\s|$)") # Words a caption may carry between its first and last word. _CONNECTORS = frozenset({"de", "del", "la", "el", "los", "las", "en", "para", "por", "al", "y", "a", "que", "con", "se"}) @dataclass(frozen=True) class DiscoveredField: """One `caption: value` 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 caption no spec claims, with its value, in the order the captions first appear.""" known = LabelIndex(lines, specs) captions: list[str] = [] for line_index, line in enumerate(lines): for start, end, caption in find_captions(line): if any(hit.start < end and start < hit.end for hit in known.hits[line_index]): continue if caption.casefold() not in (seen.casefold() for seen in captions): captions.append(caption) if not captions: return [] adhoc = [FieldSpec(f"caption:{caption}", FieldKind.TEXT, labels=(caption,)) for caption in captions] values = RecordExtractor([*specs, *adhoc]).extract(lines) found = [] for caption, spec in zip(captions, adhoc): value = values.get(spec.name) if value is not None and str(value.value).strip(): found.append(DiscoveredField(caption, str(value.value).strip(), value.evidence)) return found def find_captions(line: SegmentLine) -> list[tuple[int, int, str]]: """`(start, end, caption)` for every caption on the line, in order; offsets are into the line's text and `end` is past the colon.""" text = line.text boundaries = sorted({0, *cell_starts(line), *(match.end() for match in _ITEM_NUMBER.finditer(text))}) found: list[tuple[int, int, str]] = [] previous_colon = -1 for colon in (match.start() for match in re.finditer(r":(?=\s|$)", text)): start = max([b for b in boundaries if b <= colon] + [previous_colon + 1]) words = text[start:colon].split() if not words: previous_colon = colon continue in_sentence = start == previous_colon + 1 and previous_colon >= 0 or len(words) > MAX_CAPTION_WORDS if in_sentence: words = _trailing_caption(words) if not words[0][:1].isupper(): previous_colon = colon continue caption = " ".join(words).strip(" .-") if caption and any(ch.isalpha() for ch in caption) and len(caption) <= 60: found.append((text.rindex(words[0], start, colon), colon + 1, caption)) previous_colon = colon return found def _trailing_caption(words: list[str]) -> list[str]: """The caption at the end of a run of words that also holds the value before it: the last word, plus words joined to it by connectors or abbreviations (`Fecha de nacimiento`, `Fech. solicitud`) and the capitalized words of a title-case caption (`Motivo Principal`).""" caption = [words[-1]] position = len(words) - 2 while position >= 0 and len(caption) < MAX_CAPTION_WORDS: word = words[position] if word.casefold() in _CONNECTORS and position > 0: caption[:0] = [words[position - 1], word] position -= 2 elif word.endswith(".") and len(word) <= 6 and word[0].isalpha(): caption.insert(0, word) position -= 1 elif _title_case(word) and _title_case(caption[0]): caption.insert(0, word) position -= 1 else: break return caption def _title_case(word: str) -> bool: return len(word) > 1 and word[0].isupper() and word[1:].islower()