"""Endpoint tests for the PDF routes. One round trip per resolution path: - detect -> table/preview -> validate -> commit, for the ruled-table path, writing into `cacu.Paciente`. - detect -> page-image -> regions/extract -> validate -> commit, for the OCR/region path, writing into `cacu.Paciente` as well. """ import base64 import io import json 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 def _patients(client) -> dict[str, dict]: rows = client.get("/data/cacu.Paciente", query_string={"limit": 500}).get_json()["rows"] return {row["pac_id_hospital"]: row for row in rows} @pytest.fixture(scope="module") def client(wire_domain): wire_domain("cacu") wire_domain("tea") from webapi import create_app app = create_app() app.config.update(TESTING=True) with app.test_client() as test_client: yield test_client # --------------------------------------------------------------------- # Fixture PDFs # --------------------------------------------------------------------- def _build_table_pdf(rows: list[tuple[str, str, str]]) -> bytes: buffer = io.BytesIO() doc = SimpleDocTemplate(buffer, pagesize=letter) data = [["pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"], *[list(row) for row 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() _IMG_W, _IMG_H = 900, 1200 def _font(size: int = 34): 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_scanned_form_pdf(id_hospital: str, sexo: str, nacimiento: str = "1980-05-17") -> bytes: """A scanned-like page with three text blocks on one line at known pixel positions and no text layer, so only the OCR/region path applies. The birth date is there because a patient row is not valid without it.""" img = Image.new("RGB", (_IMG_W, _IMG_H), "white") draw = ImageDraw.Draw(img) font = _font() draw.text((40, 100), id_hospital, fill="black", font=font) draw.text((400, 100), sexo, fill="black", font=font) draw.text((560, 100), nacimiento, fill="black", font=font) buffer = io.BytesIO() c = canvas.Canvas(buffer, pagesize=letter) page_w, page_h = letter 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() _ID_HOSPITAL_BBOX = (20 / _IMG_W, 60 / _IMG_H, 350 / _IMG_W, 180 / _IMG_H) _SEXO_BBOX = (380 / _IMG_W, 60 / _IMG_H, 500 / _IMG_W, 180 / _IMG_H) _NACIMIENTO_BBOX = (540 / _IMG_W, 60 / _IMG_H, 880 / _IMG_W, 180 / _IMG_H) # --------------------------------------------------------------------- # Table path: detect -> table/preview -> validate -> commit (cacu.Paciente) # --------------------------------------------------------------------- def test_pdf_table_round_trip_detect_preview_validate_commit(client): pdf_bytes = _build_table_pdf([("H-PDF-TAB-1", "F", "1990-01-01"), ("H-PDF-TAB-2", "M", "1985-06-15")]) detect_response = client.post( "/imports/sources/pdf/detect", data={"file": (io.BytesIO(pdf_bytes), "table.pdf")}, content_type="multipart/form-data", ) assert detect_response.status_code == 200 detect_body = detect_response.get_json() assert detect_body["page_count"] == 1 assert detect_body["has_text_layer"] is True assert len(detect_body["table_candidates"]) == 1 candidate = detect_body["table_candidates"][0] assert candidate["row_count"] == 2 assert candidate["column_count"] == 3 preview_response = client.post( "/imports/sources/pdf/table/preview", data={ "file": (io.BytesIO(pdf_bytes), "table.pdf"), "page_number": str(candidate["page_number"]), "bbox": json.dumps(candidate["bbox"]), "target": "cacu.Paciente", }, content_type="multipart/form-data", ) assert preview_response.status_code == 200 preview_body = preview_response.get_json() assert {c["name"] for c in preview_body["columns"]} == {"pac_id_hospital", "pac_sexo", "pac_fecha_nacimiento"} assert preview_body["total_rows"] == 2 suggested = {m["source_column"]: m["target_field"] for m in preview_body["suggested_mapping"]} assert suggested["pac_id_hospital"] == "pac_id_hospital" source = { "source_type": "pdf", "target": "cacu.Paciente", "column_mapping": { "pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento", }, "payload": { "file_base64": base64.b64encode(pdf_bytes).decode(), "mode": "table", "page_number": candidate["page_number"], "bbox": candidate["bbox"], }, } validate_response = client.post("/imports/validate", json={"source": source}) assert validate_response.status_code == 200 validate_body = validate_response.get_json() assert validate_body["total_rows"] == 2 assert validate_body["valid_count"] == 2 assert validate_body["error_count"] == 0 commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"}) assert commit_response.status_code == 200 commit_body = commit_response.get_json() assert commit_body["ok"] is True result = commit_body["results"][0] assert result["target"] == "cacu.Paciente" assert result["created"] == 2 assert "H-PDF-TAB-1" in _patients(client) # --------------------------------------------------------------------- # page-image endpoint # --------------------------------------------------------------------- def test_pdf_page_image_returns_png(client): pdf_bytes = _build_scanned_form_pdf("H-IMG-1", "F") response = client.post( "/imports/sources/pdf/page-image", data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"}, content_type="multipart/form-data", ) assert response.status_code == 200 assert response.content_type == "image/png" image = Image.open(io.BytesIO(response.data)) assert image.format == "PNG" def test_pdf_page_image_missing_file_returns_400(client): response = client.post( "/imports/sources/pdf/page-image", data={"page_number": "1"}, content_type="multipart/form-data" ) assert response.status_code == 400 # --------------------------------------------------------------------- # OCR/region path: detect -> page-image -> regions/extract -> validate -> # commit (cacu.Paciente) # --------------------------------------------------------------------- def test_pdf_region_round_trip_detect_image_extract_validate_commit(client): pdf_bytes = _build_scanned_form_pdf("H-PDF-OCR-1", "F") detect_response = client.post( "/imports/sources/pdf/detect", data={"file": (io.BytesIO(pdf_bytes), "form.pdf")}, content_type="multipart/form-data", ) assert detect_response.status_code == 200 detect_body = detect_response.get_json() assert detect_body["has_text_layer"] is False assert detect_body["table_candidates"] == [] image_response = client.post( "/imports/sources/pdf/page-image", data={"file": (io.BytesIO(pdf_bytes), "form.pdf"), "page_number": "1"}, content_type="multipart/form-data", ) assert image_response.status_code == 200 assert Image.open(io.BytesIO(image_response.data)).format == "PNG" regions = [ {"target_field": "pac_id_hospital", "page_numbers": [1], "bbox": list(_ID_HOSPITAL_BBOX)}, {"target_field": "pac_sexo", "page_numbers": [1], "bbox": list(_SEXO_BBOX)}, {"target_field": "pac_fecha_nacimiento", "page_numbers": [1], "bbox": list(_NACIMIENTO_BBOX)}, ] extract_response = client.post( "/imports/sources/pdf/regions/extract", json={"file_base64": base64.b64encode(pdf_bytes).decode(), "regions": regions}, ) assert extract_response.status_code == 200 extract_body = extract_response.get_json() assert extract_body["rows"] == [{"pac_id_hospital": "H-PDF-OCR-1", "pac_sexo": "F", "pac_fecha_nacimiento": "1980-05-17"}] assert extract_body["warnings"] == [] source = { "source_type": "pdf", "target": "cacu.Paciente", "column_mapping": {"pac_id_hospital": "pac_id_hospital", "pac_sexo": "pac_sexo", "pac_fecha_nacimiento": "pac_fecha_nacimiento"}, "payload": { "file_base64": base64.b64encode(pdf_bytes).decode(), "mode": "regions", "regions": regions, }, } validate_response = client.post("/imports/validate", json={"source": source}) assert validate_response.status_code == 200 validate_body = validate_response.get_json() assert validate_body["total_rows"] == 1 assert validate_body["valid_count"] == 1 commit_response = client.post("/imports/commit", json={"sources": [source], "on_conflict": "reject"}) assert commit_response.status_code == 200 commit_body = commit_response.get_json() assert commit_body["ok"] is True result = commit_body["results"][0] assert result["target"] == "cacu.Paciente" assert result["created"] == 1 def test_pdf_detect_missing_file_returns_400(client): response = client.post("/imports/sources/pdf/detect", data={}, content_type="multipart/form-data") assert response.status_code == 400 def test_pdf_regions_extract_missing_field_returns_400(client): response = client.post("/imports/sources/pdf/regions/extract", json={"regions": []}) assert response.status_code == 400