import pymupdf from fastapi import APIRouter, HTTPException from fastapi.responses import Response from pydantic import BaseModel from app.config import settings router = APIRouter(prefix="/debug", tags=["Debug"]) class VerifyCoordsRequest(BaseModel): document_id: str page: int x: float y: float width: float height: float @router.post("/verify-coords") async def verify_coords(req: VerifyCoordsRequest): """ Test endpoint for cross-engine coordinate verification. Takes a canonical rect, draws it on the PDF using PyMuPDF, and returns the flattened PDF. """ filepath = settings.PDF_STORAGE_PATH / f"{req.document_id}.pdf" if not filepath.exists(): raise HTTPException(status_code=404, detail="Document not found") try: doc = pymupdf.open(filepath) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) if req.page < 0 or req.page >= len(doc): doc.close() raise HTTPException(status_code=400, detail="Invalid page number") page = doc[req.page] # Canonical space is defined as relative to the unrotated CropBox. # PyMuPDF naturally draws relative to the current rotation. # By temporarily setting rotation to 0, we can draw directly using canonical coordinates. original_rotation = page.rotation if original_rotation != 0: page.set_rotation(0) rect = pymupdf.Rect(req.x, req.y, req.x + req.width, req.y + req.height) page.draw_rect(rect, color=(1, 0, 0), width=2, fill=(1, 0, 0), fill_opacity=0.3) if original_rotation != 0: page.set_rotation(original_rotation) pdf_bytes = doc.write() doc.close() return Response(content=pdf_bytes, media_type="application/pdf")