328 lines
12 KiB
Python
328 lines
12 KiB
Python
"""Tests for `PdfConnector`. PDF fixtures are generated at test time with
|
|
reportlab.
|
|
|
|
- `build_table_pdf()`: a ruled table with selectable text, for the table
|
|
detection path.
|
|
- `build_scanned_like_pdf()` / `build_three_column_pdf()`: text rendered into
|
|
an image that fills the page, so there is no text layer and only the
|
|
OCR/region path applies. The three-column variant uses known values per
|
|
row so alignment can be checked.
|
|
"""
|
|
|
|
import difflib
|
|
import io
|
|
|
|
import pytest
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
from reportlab.lib import colors
|
|
from reportlab.lib.pagesizes import letter
|
|
from reportlab.lib.utils import ImageReader
|
|
from reportlab.pdfgen import canvas
|
|
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
|
|
|
|
from webapi.imports.connectors.errors import ConnectorError
|
|
from webapi.imports.connectors.pdf import PdfConnector, RegionSpec
|
|
|
|
# The synthetic "scanned" pages are drawn onto an image this size, then
|
|
# stretched to fill the whole (letter-size) PDF page, so a normalized
|
|
# 0..1 bbox computed from these pixel coordinates lines up with the region
|
|
# regardless of the DPI used to re-render the page for OCR.
|
|
IMG_W, IMG_H = 900, 1200
|
|
COL_X = {"name": 40, "age": 340, "city": 620}
|
|
COL_WIDTH = 260
|
|
ROW_YS = [120, 320, 520]
|
|
ROW_HEIGHT = 100
|
|
|
|
|
|
def _font(size: int = 34) -> ImageFont.ImageFont:
|
|
for path in (
|
|
"/System/Library/Fonts/Helvetica.ttc",
|
|
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
|
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
):
|
|
try:
|
|
return ImageFont.truetype(path, size)
|
|
except Exception:
|
|
continue
|
|
return ImageFont.load_default()
|
|
|
|
|
|
def build_table_pdf(rows: list[tuple[str, str]]) -> bytes:
|
|
buffer = io.BytesIO()
|
|
doc = SimpleDocTemplate(buffer, pagesize=letter)
|
|
data = [["pac_id_hospital", "pac_sexo"], *[[a, b] for a, b in rows]]
|
|
table = Table(data)
|
|
table.setStyle(
|
|
TableStyle(
|
|
[
|
|
("GRID", (0, 0), (-1, -1), 1, colors.black),
|
|
("FONTSIZE", (0, 0), (-1, -1), 12),
|
|
("BOTTOMPADDING", (0, 0), (-1, -1), 8),
|
|
("TOPPADDING", (0, 0), (-1, -1), 8),
|
|
]
|
|
)
|
|
)
|
|
doc.build([table])
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _page_image(lines: list[str]) -> Image.Image:
|
|
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
|
draw = ImageDraw.Draw(img)
|
|
font = _font()
|
|
y = 40
|
|
for line in lines:
|
|
draw.text((40, y), line, fill="black", font=font)
|
|
y += 60
|
|
return img
|
|
|
|
|
|
def build_scanned_like_pdf(pages_lines: list[list[str]]) -> bytes:
|
|
buffer = io.BytesIO()
|
|
c = canvas.Canvas(buffer, pagesize=letter)
|
|
page_w, page_h = letter
|
|
for lines in pages_lines:
|
|
img = _page_image(lines)
|
|
reader_buf = io.BytesIO()
|
|
img.save(reader_buf, format="PNG")
|
|
reader_buf.seek(0)
|
|
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
|
c.showPage()
|
|
c.save()
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _three_column_page_image(rows: list[tuple[str, str, str]]) -> Image.Image:
|
|
img = Image.new("RGB", (IMG_W, IMG_H), "white")
|
|
draw = ImageDraw.Draw(img)
|
|
font = _font()
|
|
for y, (name, age, city) in zip(ROW_YS, rows):
|
|
draw.text((COL_X["name"], y), name, fill="black", font=font)
|
|
draw.text((COL_X["age"], y), age, fill="black", font=font)
|
|
draw.text((COL_X["city"], y), city, fill="black", font=font)
|
|
return img
|
|
|
|
|
|
def build_three_column_pdf(pages_rows: list[list[tuple[str, str, str]]]) -> bytes:
|
|
buffer = io.BytesIO()
|
|
c = canvas.Canvas(buffer, pagesize=letter)
|
|
page_w, page_h = letter
|
|
for rows in pages_rows:
|
|
img = _three_column_page_image(rows)
|
|
reader_buf = io.BytesIO()
|
|
img.save(reader_buf, format="PNG")
|
|
reader_buf.seek(0)
|
|
c.drawImage(ImageReader(reader_buf), 0, 0, width=page_w, height=page_h)
|
|
c.showPage()
|
|
c.save()
|
|
return buffer.getvalue()
|
|
|
|
|
|
def _norm_bbox(field: str) -> tuple[float, float, float, float]:
|
|
x0 = COL_X[field]
|
|
x1 = x0 + COL_WIDTH
|
|
y0 = ROW_YS[0] - 60
|
|
y1 = ROW_YS[-1] + ROW_HEIGHT
|
|
return (x0 / IMG_W, y0 / IMG_H, x1 / IMG_W, y1 / IMG_H)
|
|
|
|
|
|
def _similar(a: str, b: str, threshold: float = 0.7) -> bool:
|
|
return difflib.SequenceMatcher(None, a.strip().lower(), b.strip().lower()).ratio() >= threshold
|
|
|
|
|
|
ROWS = [("Ana Garcia", "30", "Monterrey"), ("Luis Perez", "40", "Saltillo"), ("Marta Ruiz", "50", "Torreon")]
|
|
ROWS_PAGE_2 = [("Elena Diaz", "60", "Chihuahua"), ("Jorge Nava", "22", "Durango"), ("Sofia Reyes", "35", "Culiacan")]
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# Classification
|
|
# ---------------------------------------------------------------------
|
|
|
|
|
|
def test_has_text_layer_true_for_table_pdf():
|
|
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
|
assert connector.has_text_layer() is True
|
|
|
|
|
|
def test_has_text_layer_false_for_scanned_pdf():
|
|
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
|
assert connector.has_text_layer() is False
|
|
|
|
|
|
def test_malformed_pdf_bytes_raise_connector_error():
|
|
with pytest.raises(ConnectorError):
|
|
PdfConnector(b"not a pdf at all")
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# Ruled table detection
|
|
# ---------------------------------------------------------------------
|
|
|
|
|
|
def test_detect_tables_finds_candidate_with_right_shape_on_table_pdf():
|
|
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M"), ("H-TAB-3", "F")]))
|
|
candidates = connector.detect_tables()
|
|
assert len(candidates) == 1
|
|
candidate = candidates[0]
|
|
assert candidate.page_number == 1
|
|
assert len(candidate.grid) == 4 # header + 3 data rows
|
|
assert len(candidate.grid[0]) == 2
|
|
assert candidate.grid[0] == ["pac_id_hospital", "pac_sexo"]
|
|
assert candidate.grid[1][0] == "H-TAB-1"
|
|
|
|
|
|
def test_detect_tables_empty_on_scanned_pdf():
|
|
connector = PdfConnector(build_scanned_like_pdf([["Ana Garcia", "Luis Perez"]]))
|
|
assert connector.detect_tables() == []
|
|
|
|
|
|
def test_select_table_then_connector_abc_roundtrip():
|
|
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F"), ("H-TAB-2", "M")]))
|
|
candidate = connector.detect_tables()[0]
|
|
connector.select_table(candidate.page_number, candidate.bbox)
|
|
|
|
columns = {c.name for c in connector.preview().columns}
|
|
assert columns == {"pac_id_hospital", "pac_sexo"}
|
|
|
|
preview = connector.preview(limit=1)
|
|
assert preview.total_rows == 2
|
|
assert len(preview.sample_rows) == 1
|
|
|
|
rows = list(connector.read_rows({"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo"}))
|
|
assert rows == [
|
|
{"pac_id_hospital": "H-TAB-1", "pac_sexo": "F"},
|
|
{"pac_id_hospital": "H-TAB-2", "pac_sexo": "M"},
|
|
]
|
|
|
|
|
|
def test_select_table_out_of_range_page_raises_connector_error():
|
|
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
|
with pytest.raises(ConnectorError):
|
|
connector.select_table(99, (0, 0, 100, 100))
|
|
|
|
|
|
def test_read_rows_before_resolution_raises_connector_error():
|
|
connector = PdfConnector(build_table_pdf([("H-TAB-1", "F")]))
|
|
with pytest.raises(ConnectorError):
|
|
connector.preview().columns
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# Rendering
|
|
# ---------------------------------------------------------------------
|
|
|
|
|
|
def test_render_page_image_returns_valid_png_with_expected_aspect_ratio():
|
|
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
|
png_bytes = connector.render_page_image(1, dpi=150)
|
|
image = Image.open(io.BytesIO(png_bytes))
|
|
assert image.format == "PNG"
|
|
page_w, page_h = letter
|
|
expected_ratio = page_w / page_h
|
|
actual_ratio = image.width / image.height
|
|
assert abs(actual_ratio - expected_ratio) < 0.01
|
|
|
|
|
|
def test_render_page_image_out_of_range_raises_connector_error():
|
|
connector = PdfConnector(build_scanned_like_pdf([["hello"]]))
|
|
with pytest.raises(ConnectorError):
|
|
connector.render_page_image(7)
|
|
|
|
|
|
# ---------------------------------------------------------------------
|
|
# OCR / region path
|
|
# ---------------------------------------------------------------------
|
|
|
|
|
|
def test_single_region_ocr_matches_known_column():
|
|
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
|
region = RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name"))
|
|
result = connector.extract_regions([region])
|
|
assert len(result["name"]) == 3
|
|
for actual, (expected, _, _) in zip(result["name"], ROWS):
|
|
assert _similar(actual, expected), f"{actual!r} not close enough to {expected!r}"
|
|
|
|
|
|
def test_multi_region_row_alignment_matches_ground_truth():
|
|
"""Three columns OCR'd independently must recombine into the rows they
|
|
came from."""
|
|
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
|
regions = [
|
|
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
|
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
|
RegionSpec(target_field="city", page_numbers=[1], bbox=_norm_bbox("city")),
|
|
]
|
|
result = connector.extract_regions(regions)
|
|
|
|
assert len(result["name"]) == len(result["age"]) == len(result["city"]) == 3
|
|
for i, (expected_name, expected_age, expected_city) in enumerate(ROWS):
|
|
assert _similar(result["name"][i], expected_name), f"row {i} name mismatch: {result['name'][i]!r}"
|
|
assert _similar(result["age"][i], expected_age), f"row {i} age mismatch: {result['age'][i]!r}"
|
|
assert _similar(result["city"][i], expected_city), f"row {i} city mismatch: {result['city'][i]!r}"
|
|
|
|
rows = list(
|
|
connector.read_rows({"name": "name", "age": "age", "city": "city"})
|
|
)
|
|
assert len(rows) == 3
|
|
assert _similar(rows[0]["name"], ROWS[0][0])
|
|
|
|
|
|
def test_two_page_apply_to_every_page_regions():
|
|
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
|
regions = [
|
|
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
|
RegionSpec(target_field="age", page_numbers=[1, 2], bbox=_norm_bbox("age")),
|
|
RegionSpec(target_field="city", page_numbers=[1, 2], bbox=_norm_bbox("city")),
|
|
]
|
|
result = connector.extract_regions(regions)
|
|
|
|
all_rows = ROWS + ROWS_PAGE_2
|
|
assert len(result["name"]) == 6
|
|
for i, (expected_name, expected_age, expected_city) in enumerate(all_rows):
|
|
assert _similar(result["name"][i], expected_name), f"row {i}: {result['name']}"
|
|
assert _similar(result["age"][i], expected_age)
|
|
assert _similar(result["city"][i], expected_city)
|
|
|
|
# page 1's rows precede page 2's, not just correct as a set
|
|
assert _similar(result["name"][0], ROWS[0][0])
|
|
assert _similar(result["name"][3], ROWS_PAGE_2[0][0])
|
|
|
|
|
|
def test_regions_on_different_pages_still_give_rectangular_rows():
|
|
connector = PdfConnector(build_three_column_pdf([ROWS, ROWS_PAGE_2]))
|
|
regions = [
|
|
RegionSpec(target_field="name", page_numbers=[1, 2], bbox=_norm_bbox("name")),
|
|
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
|
]
|
|
result = connector.extract_regions(regions)
|
|
|
|
assert len(result["name"]) == len(result["age"]) == 6
|
|
assert result["age"][3:] == [None, None, None]
|
|
assert len(list(connector.read_rows({"name": "name", "age": "age"}))) == 6
|
|
|
|
|
|
def test_extract_regions_before_resolution_then_read_rows_uses_region_mode():
|
|
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
|
regions = [
|
|
RegionSpec(target_field="name", page_numbers=[1], bbox=_norm_bbox("name")),
|
|
RegionSpec(target_field="age", page_numbers=[1], bbox=_norm_bbox("age")),
|
|
]
|
|
connector.extract_regions(regions)
|
|
columns = {c.name for c in connector.preview().columns}
|
|
assert columns == {"name", "age"}
|
|
|
|
|
|
def test_split_conflict_records_warning_without_dropping_data():
|
|
connector = PdfConnector(build_three_column_pdf([ROWS]))
|
|
connector.warnings = []
|
|
lines = [
|
|
{"target_field": "a", "y": 100, "height": 20, "text": "A1"},
|
|
{"target_field": "b", "y": 108, "height": 20, "text": "B1"},
|
|
{"target_field": "a", "y": 116, "height": 20, "text": "A2"},
|
|
]
|
|
rows = connector._cluster_rows(lines, page_number=1)
|
|
total_values = sum(len(row) for row in rows)
|
|
assert total_values == 3 # nothing silently dropped
|
|
assert len(connector.warnings) == 1
|
|
assert connector.warnings[0].page_number == 1
|