133 lines
6.4 KiB
Python
133 lines
6.4 KiB
Python
"""Results of the catalog read from a staging row's text: a report's interpretation, a note, a PDF's text layer.
|
|
|
|
The catalog says how each result is printed (`etiquetas_fuente`, each value's `alias`;
|
|
`reference.catalogs.resultados_extraibles`); `DesdeTexto` turns that into Extraction's field specs and into the
|
|
derived columns, results and sources of a `DeStaging`. A coded value comes out as its `valor_id` when one of its
|
|
spellings matches, and always with what was read as `valor_fuente`: a spelling the catalog doesn't know yet stays
|
|
stored as text, counted as out of catalog by the silver check, and becomes a code on the next load after its alias
|
|
is added. Nothing extracted is written anywhere but silver's two tables.
|
|
"""
|
|
|
|
from collections.abc import Callable
|
|
from dataclasses import dataclass, field
|
|
from functools import lru_cache
|
|
|
|
from extraction import BBox, ExtractionError, FieldKind, FieldSpec, Line, read_document
|
|
from extraction.nlp.extractors import RecordExtractor, SegmentLine
|
|
|
|
from webapi.orchestration.reference.catalogs import ResultadoExtraible, resultados_extraibles
|
|
|
|
# A value read after a caption, kept as its source when the catalog doesn't know it: enough to recognize it.
|
|
LARGO_DE_FUENTE = 120
|
|
TIPOS = {"codigo": FieldKind.CHOICE, "numero": FieldKind.DECIMAL, "fecha": FieldKind.DATE, "texto": FieldKind.TEXT}
|
|
SUFIJO_DE_TEXTO = "#texto" # the plain-text twin of a coded field: what follows its caption, matched or not
|
|
|
|
|
|
def especificaciones(resultado: ResultadoExtraible) -> tuple[FieldSpec, ...]:
|
|
"""Extraction's fields for one result: the result itself and, if coded, the text after its caption."""
|
|
choices = {forma: valor for valor, formas in resultado.alias.items() for forma in formas}
|
|
campo = FieldSpec(
|
|
resultado.resultado_id, TIPOS[resultado.tipo_valor], labels=resultado.etiquetas_fuente,
|
|
choices=choices, scan_free_text=resultado.buscar_en_texto,
|
|
)
|
|
if resultado.tipo_valor != "codigo":
|
|
return (campo,)
|
|
return campo, FieldSpec(resultado.resultado_id + SUFIJO_DE_TEXTO, FieldKind.TEXT, labels=resultado.etiquetas_fuente)
|
|
|
|
|
|
def lineas_de_texto(texto: str, nombre: str = "texto") -> list[SegmentLine]:
|
|
"""A plain text as the lines of one page, as a reader would give them."""
|
|
renglones = [r for r in texto.splitlines() if r.strip()]
|
|
alto = 1 / max(len(renglones), 1)
|
|
return [SegmentLine(nombre, 1, Line(r, BBox(0, i * alto, 1, (i + 1) * alto))) for i, r in enumerate(renglones)]
|
|
|
|
|
|
def con_renglones_unidos(lineas: list[SegmentLine]) -> list[SegmentLine]:
|
|
"""The lines and, after them, each pair of consecutive lines of a page joined: a caption that the page wraps ("TAMAÑO
|
|
DE LA" / "LESIÓN: 25 MM") is whole in one of them. A value found in both counts as found twice, which doesn't change
|
|
which one wins."""
|
|
unidas = []
|
|
for a, b in zip(lineas, lineas[1:]):
|
|
if a.page_number != b.page_number or a.document != b.document:
|
|
continue
|
|
caja = BBox(min(a.line.bbox.x0, b.line.bbox.x0), a.line.bbox.y0, max(a.line.bbox.x1, b.line.bbox.x1), b.line.bbox.y1)
|
|
unidas.append(SegmentLine(a.document, a.page_number, Line(f"{a.line.text} {b.line.text}", caja), a.ocr or b.ocr))
|
|
return [*lineas, *unidas]
|
|
|
|
|
|
def lineas_de_pdf(contenido: bytes) -> list[SegmentLine]:
|
|
"""The text layer of a PDF, without OCR: a load doesn't run OCR, and a scan without text gives no lines."""
|
|
try:
|
|
documento = read_document("documento.pdf", contenido, ocr_mode="never")
|
|
except ExtractionError:
|
|
return []
|
|
return [SegmentLine(documento.name, p.number, linea) for p in documento.pages for linea in p.lines]
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class DesdeTexto:
|
|
"""Catalog results read from what `texto` gives for a row: a text, a PDF's bytes, or nothing.
|
|
|
|
`derivadas`, `resultados` and `fuentes` go into the `DeStaging` (or its `Hija`) as they are. The row is read
|
|
once for all its results.
|
|
"""
|
|
|
|
proyecto: str
|
|
resultado_ids: tuple[str, ...]
|
|
texto: Callable[[object], str | bytes | None]
|
|
_extraer: Callable = field(init=False, repr=False, compare=False)
|
|
|
|
def __post_init__(self):
|
|
extraibles = resultados_extraibles(self.proyecto)
|
|
faltan = [r for r in self.resultado_ids if r not in extraibles]
|
|
if faltan:
|
|
raise ValueError(f"Sin etiquetas_fuente en el catálogo de {self.proyecto}: {', '.join(faltan)}.")
|
|
tipos = {r: extraibles[r].tipo_valor for r in self.resultado_ids}
|
|
extractor = RecordExtractor([e for r in self.resultado_ids for e in especificaciones(extraibles[r])])
|
|
|
|
@lru_cache(maxsize=256)
|
|
def extraer(contenido: str | bytes) -> dict[str, tuple]:
|
|
lineas = con_renglones_unidos(lineas_de_pdf(contenido) if isinstance(contenido, bytes) else lineas_de_texto(contenido))
|
|
leidos = extractor.extract(lineas)
|
|
return {r: _valor_y_fuente(leidos.get(r), leidos.get(r + SUFIJO_DE_TEXTO), tipos[r]) for r in tipos}
|
|
|
|
object.__setattr__(self, "_extraer", extraer)
|
|
|
|
def leer(self, fila) -> dict[str, tuple]:
|
|
"""`resultado_id` -> (value, source) read from the row; (None, None) when it isn't there."""
|
|
contenido = self.texto(fila)
|
|
if not contenido or (isinstance(contenido, str) and not contenido.strip()):
|
|
return dict.fromkeys(self.resultado_ids, (None, None))
|
|
return self._extraer(contenido)
|
|
|
|
@property
|
|
def derivadas(self) -> dict[str, Callable]:
|
|
columnas = {}
|
|
for r in self.resultado_ids:
|
|
columnas[_columna(r)] = lambda f, r=r: self.leer(f)[r][0]
|
|
columnas[_columna(r) + "_fuente"] = lambda f, r=r: self.leer(f)[r][1]
|
|
return columnas
|
|
|
|
@property
|
|
def resultados(self) -> dict[str, str]:
|
|
return {_columna(r): r for r in self.resultado_ids}
|
|
|
|
@property
|
|
def fuentes(self) -> dict[str, str]:
|
|
return {_columna(r): _columna(r) + "_fuente" for r in self.resultado_ids}
|
|
|
|
|
|
def _columna(resultado_id: str) -> str:
|
|
return "extraido:" + resultado_id
|
|
|
|
|
|
def _valor_y_fuente(leido, texto, tipo_valor: str) -> tuple:
|
|
"""A coded value with the spelling it matched, or, unmatched, with what followed its caption; others as read."""
|
|
if tipo_valor != "codigo":
|
|
return (None, None) if leido is None else (leido.value, None)
|
|
if leido is not None:
|
|
return leido.value, leido.raw
|
|
if texto is not None and str(texto.value).strip():
|
|
return None, str(texto.value).strip()[:LARGO_DE_FUENTE]
|
|
return None, None
|