from fastapi import APIRouter, HTTPException, status, Response from app.services import engine from app.services.store import document_store router = APIRouter(prefix="/documents/{document_id}/pages", tags=["render"]) compat_router = APIRouter(tags=["render"]) @router.get("/{page_index}/render") def render_page(document_id: str, page_index: int, dpi: int = 96) -> Response: if not engine.is_available(): raise HTTPException( status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Engine bridge (bindings/python) not yet available." ) doc_info = document_store.get_document(document_id) if not doc_info: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") try: doc = doc_info["doc_instance"] page = doc.get_page(page_index) img = page.render(dpi) return Response(content=img.data, media_type="image/png") except IndexError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Page index out of bounds") except Exception as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) @router.get("/{page_index}/text") def extract_page_text(document_id: str, page_index: int): if not engine.is_available(): raise HTTPException( status_code=status.HTTP_501_NOT_IMPLEMENTED, detail="Engine bridge (bindings/python) not yet available." ) doc_info = document_store.get_document(document_id) if not doc_info: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Document not found") try: doc = doc_info["doc_instance"] page = doc.get_page(page_index) text = page.extract_text() return {"text": text} except IndexError: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Page index out of bounds") except Exception as e: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e)) @compat_router.get("/render/{document_id}") def render_page_compat(document_id: str, page: int = 0, zoom: float = 1.0, rotation: int = 0) -> Response: dpi = int(96 * zoom) return render_page(document_id, page, dpi)