355 lines
15 KiB
Python
355 lines
15 KiB
Python
"""PDF tables. Two ways to turn a PDF into rows:
|
|
|
|
- `select_table`: a ruled table found by pdfplumber in the text layer;
|
|
- `extract_regions`: one drawn box per column over the rendered page. Each
|
|
box is read from the text layer or OCR'd, and lines from all boxes on a
|
|
page are aligned into rows by their vertical position.
|
|
|
|
Documents that are not tables (one report per patient, free text) go
|
|
through `DocumentConnector` instead.
|
|
"""
|
|
import io
|
|
import statistics
|
|
from dataclasses import dataclass
|
|
from typing import Any
|
|
|
|
import pandas as pd
|
|
import pdfplumber
|
|
import pytesseract
|
|
from pytesseract import Output
|
|
|
|
from extraction.ocr import DEFAULT_LANG, group_words
|
|
from webapi.imports.connectors.base import decode_file
|
|
from webapi.imports.connectors.errors import ConnectorError
|
|
from webapi.imports.connectors.registry import register_connector
|
|
from webapi.imports.connectors.tabular import DataFrameConnector
|
|
|
|
_DEFAULT_SAMPLE_PAGES = 3
|
|
_DEFAULT_CHAR_THRESHOLD = 20
|
|
_DEFAULT_DPI = 150
|
|
# Rendering memory grows with dpi². Past ~300 dpi OCR gains nothing and a
|
|
# single request could exhaust the worker.
|
|
_MIN_DPI, _MAX_DPI = 50, 300
|
|
# PSM 6 (one uniform block): a region is a narrow column of stacked lines;
|
|
# full-page segmentation (PSM 3) drops short crops such as a lone "F".
|
|
_OCR_CONFIG = "--psm 6"
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class TableCandidate:
|
|
page_number: int # 1-indexed
|
|
bbox: tuple[float, float, float, float] # PDF points, pdfplumber's native space
|
|
grid: list[list[str | None]] # header row + data rows
|
|
confidence: float # ranking heuristic only, not ML
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class RegionSpec:
|
|
target_field: str
|
|
page_numbers: list[int] # 1-indexed
|
|
bbox: tuple[float, float, float, float] # normalized 0..1 over the rendered page
|
|
|
|
@classmethod
|
|
def parse(cls, raw: dict[str, Any]) -> "RegionSpec":
|
|
try:
|
|
return cls(str(raw["target_field"]), [int(n) for n in raw["page_numbers"]], tuple(float(v) for v in raw["bbox"]))
|
|
except (KeyError, TypeError, ValueError) as exc:
|
|
raise ConnectorError(f"región inválida: {exc}") from exc
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class ExtractionWarning:
|
|
page_number: int
|
|
message: str
|
|
|
|
|
|
@register_connector
|
|
class PdfConnector(DataFrameConnector):
|
|
kind = "pdf"
|
|
label = "PDF (tablas)"
|
|
description = "Tablas detectadas o columnas dibujadas sobre la página (OCR para escaneos)"
|
|
category = "document"
|
|
icon = "picture_as_pdf"
|
|
extensions = ("pdf",)
|
|
|
|
@classmethod
|
|
def from_payload(cls, payload: dict[str, Any]) -> "PdfConnector":
|
|
connector = cls(decode_file(payload))
|
|
mode = payload.get("mode", "table")
|
|
if mode == "table":
|
|
connector.select_table(int(payload["page_number"]), tuple(float(v) for v in payload["bbox"]))
|
|
elif mode == "regions":
|
|
connector.extract_regions([RegionSpec.parse(r) for r in payload["regions"]], dpi=int(payload.get("dpi", _DEFAULT_DPI)))
|
|
else:
|
|
raise ConnectorError(f"modo de PDF desconocido: {mode!r}")
|
|
return connector
|
|
|
|
def __init__(self, file_bytes: bytes):
|
|
self.file_bytes = file_bytes
|
|
try:
|
|
self._pdf = pdfplumber.open(io.BytesIO(file_bytes))
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudo abrir el PDF: {exc}") from exc
|
|
|
|
self._table_grid: list[list[str | None]] | None = None
|
|
self._region_rows: dict[str, list[str | None]] | None = None
|
|
self.warnings: list[ExtractionWarning] = []
|
|
|
|
@property
|
|
def page_count(self) -> int:
|
|
return len(self._pdf.pages)
|
|
|
|
def has_text_layer(self, sample_pages: int = _DEFAULT_SAMPLE_PAGES, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
|
return any(self._page_has_text(page, char_threshold) for page in self._pdf.pages[:sample_pages])
|
|
|
|
@staticmethod
|
|
def _page_has_text(page, char_threshold: int = _DEFAULT_CHAR_THRESHOLD) -> bool:
|
|
try:
|
|
text = page.extract_text() or ""
|
|
except Exception:
|
|
return False
|
|
return len(text.strip()) >= char_threshold
|
|
|
|
# ------------------------------------------------------------------
|
|
# Ruled tables found by pdfplumber in the text layer
|
|
# ------------------------------------------------------------------
|
|
|
|
def detect_tables(self) -> list[TableCandidate]:
|
|
candidates: list[TableCandidate] = []
|
|
for page in self._pdf.pages:
|
|
try:
|
|
tables = page.find_tables()
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudieron detectar tablas en la página {page.page_number}: {exc}") from exc
|
|
for table in tables:
|
|
try:
|
|
grid = table.extract()
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudo extraer la tabla de la página {page.page_number}: {exc}") from exc
|
|
if len(grid) < 2:
|
|
continue # header + >=1 data row required
|
|
candidates.append(
|
|
TableCandidate(
|
|
page_number=page.page_number,
|
|
bbox=tuple(table.bbox),
|
|
grid=grid,
|
|
confidence=_table_confidence(grid),
|
|
)
|
|
)
|
|
candidates.sort(key=lambda c: c.confidence, reverse=True)
|
|
return candidates
|
|
|
|
def select_table(self, page_number: int, bbox: tuple[float, float, float, float]) -> None:
|
|
page = self._page(page_number)
|
|
try:
|
|
cropped = page.within_bbox(bbox, strict=False)
|
|
grid = cropped.extract_table()
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudo extraer la tabla en {bbox} de la página {page_number}: {exc}") from exc
|
|
if not grid or len(grid) < 2:
|
|
raise ConnectorError(f"no se encontró una tabla utilizable en {bbox} de la página {page_number}")
|
|
self._table_grid = grid
|
|
self._region_rows = None
|
|
|
|
# ------------------------------------------------------------------
|
|
# Drawn regions over the rendered page, read from text or OCR, then aligned
|
|
# ------------------------------------------------------------------
|
|
|
|
def render_page_image(self, page_number: int, dpi: int = _DEFAULT_DPI) -> bytes:
|
|
_check_dpi(dpi)
|
|
page = self._page(page_number)
|
|
try:
|
|
image = page.to_image(resolution=dpi).original
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudo dibujar la página {page_number}: {exc}") from exc
|
|
buffer = io.BytesIO()
|
|
image.save(buffer, format="PNG")
|
|
return buffer.getvalue()
|
|
|
|
def extract_regions(self, regions: list[RegionSpec], dpi: int = _DEFAULT_DPI) -> dict[str, list[str | None]]:
|
|
if not regions:
|
|
raise ConnectorError("no se indicaron regiones")
|
|
_check_dpi(dpi)
|
|
|
|
by_page: dict[int, list[RegionSpec]] = {}
|
|
for region in regions:
|
|
for page_number in region.page_numbers:
|
|
by_page.setdefault(page_number, []).append(region)
|
|
|
|
self.warnings = []
|
|
result: dict[str, list[str | None]] = {region.target_field: [] for region in regions}
|
|
|
|
for page_number in sorted(by_page):
|
|
page = self._page(page_number)
|
|
lines = self._lines_for_page(page, by_page[page_number], dpi)
|
|
for row in self._cluster_rows(lines, page_number):
|
|
# Every field gets a cell per row, even regions not drawn on this page.
|
|
for field_name in result:
|
|
result[field_name].append(row.get(field_name))
|
|
|
|
self._region_rows = result
|
|
self._table_grid = None
|
|
return result
|
|
|
|
def _lines_for_page(self, page, regions_on_page: list[RegionSpec], dpi: int) -> list[dict[str, Any]]:
|
|
"""Collect `(target_field, y, height, text)` lines for every region
|
|
on one page. Y is in page pixels at `dpi` whether the region was read
|
|
from the text layer or OCR'd, so lines from all regions can be aligned."""
|
|
scale = dpi / 72.0
|
|
use_text_layer = self._page_has_text(page)
|
|
rendered_image = None
|
|
lines: list[dict[str, Any]] = []
|
|
|
|
for region in regions_on_page:
|
|
x0n, y0n, x1n, y1n = region.bbox
|
|
|
|
if use_text_layer:
|
|
point_bbox = self._clamp_to_page(
|
|
(x0n * page.width, y0n * page.height, x1n * page.width, y1n * page.height),
|
|
page,
|
|
)
|
|
try:
|
|
region_lines = page.within_bbox(point_bbox, strict=False).extract_text_lines()
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudo extraer el texto de la región {region.target_field!r}: {exc}") from exc
|
|
for line in region_lines:
|
|
text = (line.get("text") or "").strip()
|
|
if not text:
|
|
continue
|
|
lines.append(
|
|
{
|
|
"target_field": region.target_field,
|
|
"y": ((line["top"] + line["bottom"]) / 2) * scale,
|
|
"height": (line["bottom"] - line["top"]) * scale,
|
|
"text": text,
|
|
}
|
|
)
|
|
else:
|
|
if rendered_image is None:
|
|
try:
|
|
rendered_image = page.to_image(resolution=dpi).original
|
|
except Exception as exc:
|
|
raise ConnectorError(f"no se pudo dibujar la página {page.page_number}: {exc}") from exc
|
|
img_w, img_h = rendered_image.size
|
|
crop_box = (
|
|
max(0, round(x0n * img_w)),
|
|
max(0, round(y0n * img_h)),
|
|
min(img_w, round(x1n * img_w)),
|
|
min(img_h, round(y1n * img_h)),
|
|
)
|
|
if crop_box[2] <= crop_box[0] or crop_box[3] <= crop_box[1]:
|
|
continue
|
|
cropped = rendered_image.crop(crop_box)
|
|
try:
|
|
data = pytesseract.image_to_data(cropped, output_type=Output.DICT, lang=DEFAULT_LANG, config=_OCR_CONFIG)
|
|
except Exception as exc:
|
|
raise ConnectorError(f"falló el OCR de la región {region.target_field!r}: {exc}") from exc
|
|
for words in group_words(data):
|
|
text = " ".join(w["text"] for w in words).strip()
|
|
if not text:
|
|
continue
|
|
top_local = min(w["top"] for w in words)
|
|
bottom_local = max(w["top"] + w["height"] for w in words)
|
|
lines.append(
|
|
{
|
|
"target_field": region.target_field,
|
|
"y": crop_box[1] + (top_local + bottom_local) / 2,
|
|
"height": bottom_local - top_local,
|
|
"text": text,
|
|
}
|
|
)
|
|
return lines
|
|
|
|
def _cluster_rows(self, lines: list[dict[str, Any]], page_number: int) -> list[dict[str, str]]:
|
|
if not lines:
|
|
return []
|
|
heights = [line["height"] for line in lines if line["height"] > 0]
|
|
median_height = statistics.median(heights) if heights else 10.0
|
|
gap_tolerance = 0.6 * median_height
|
|
|
|
ordered = sorted(lines, key=lambda line: line["y"])
|
|
clusters: list[list[dict[str, Any]]] = [[ordered[0]]]
|
|
for line in ordered[1:]:
|
|
if line["y"] - clusters[-1][-1]["y"] <= gap_tolerance:
|
|
clusters[-1].append(line)
|
|
else:
|
|
clusters.append([line])
|
|
|
|
resolved: list[list[dict[str, Any]]] = []
|
|
for cluster in clusters:
|
|
resolved.extend(self._split_conflicts(cluster, page_number))
|
|
|
|
rows = []
|
|
for cluster in resolved:
|
|
row: dict[str, str] = {}
|
|
for line in cluster:
|
|
if line["target_field"] in row:
|
|
row[line["target_field"]] = f"{row[line['target_field']]} {line['text']}".strip()
|
|
else:
|
|
row[line["target_field"]] = line["text"]
|
|
rows.append(row)
|
|
return rows
|
|
|
|
def _split_conflicts(self, cluster: list[dict[str, Any]], page_number: int) -> list[list[dict[str, Any]]]:
|
|
"""A row cluster holds at most one line per target field. When two
|
|
lines of the same region land in one cluster, split it at its largest
|
|
internal gap (recursively) and record a warning rather than drop data."""
|
|
fields = [line["target_field"] for line in cluster]
|
|
if len(fields) == len(set(fields)) or len(cluster) < 2:
|
|
return [cluster]
|
|
|
|
ordered = sorted(cluster, key=lambda line: line["y"])
|
|
gaps = [(ordered[i + 1]["y"] - ordered[i]["y"], i) for i in range(len(ordered) - 1)]
|
|
_, split_at = max(gaps, key=lambda g: g[0])
|
|
left, right = ordered[: split_at + 1], ordered[split_at + 1 :]
|
|
|
|
duplicated = sorted({f for f in fields if fields.count(f) > 1})
|
|
self.warnings.append(
|
|
ExtractionWarning(
|
|
page_number=page_number,
|
|
message=f"conflicto de alineación en {duplicated}: el grupo se dividió en el mayor espacio interno",
|
|
)
|
|
)
|
|
return self._split_conflicts(left, page_number) + self._split_conflicts(right, page_number)
|
|
|
|
# ------------------------------------------------------------------
|
|
# Connector interface, usable once select_table() or extract_regions() ran
|
|
# ------------------------------------------------------------------
|
|
|
|
def _dataframe(self) -> pd.DataFrame:
|
|
if self._table_grid is not None:
|
|
header, *data_rows = self._table_grid
|
|
columns = [name if name else f"column_{i}" for i, name in enumerate(header)]
|
|
return pd.DataFrame(data_rows, columns=columns)
|
|
if self._region_rows is not None:
|
|
return pd.DataFrame(self._region_rows)
|
|
raise ConnectorError("no hay tabla ni regiones seleccionadas")
|
|
|
|
# ------------------------------------------------------------------
|
|
|
|
def _page(self, page_number: int):
|
|
if not (1 <= page_number <= self.page_count):
|
|
raise ConnectorError(f"page_number fuera de rango: {page_number}")
|
|
return self._pdf.pages[page_number - 1]
|
|
|
|
@staticmethod
|
|
def _clamp_to_page(bbox: tuple[float, float, float, float], page) -> tuple[float, float, float, float]:
|
|
x0, top, x1, bottom = bbox
|
|
px0, ptop, px1, pbottom = page.bbox
|
|
return (max(x0, px0), max(top, ptop), min(x1, px1), min(bottom, pbottom))
|
|
|
|
|
|
def _check_dpi(dpi: int) -> None:
|
|
if not (_MIN_DPI <= dpi <= _MAX_DPI):
|
|
raise ConnectorError(f"dpi debe estar entre {_MIN_DPI} y {_MAX_DPI} (se recibió {dpi})")
|
|
|
|
|
|
def _table_confidence(grid: list[list[str | None]]) -> float:
|
|
"""Ranking heuristic for the UI: capped row count plus non-empty cell rate."""
|
|
data_rows = len(grid) - 1
|
|
total_cells = sum(len(row) for row in grid) or 1
|
|
filled_cells = sum(1 for row in grid for cell in row if cell not in (None, ""))
|
|
fill_rate = filled_cells / total_cells
|
|
row_score = min(data_rows / 5, 1.0)
|
|
return round(0.5 * row_score + 0.5 * fill_rate, 4)
|