Spaces:
Runtime error
Runtime error
AdityaAjithKumar commited on
Commit ·
ae379dd
1
Parent(s): 22d960b
feat: add PDF support — convert first page to image before OCR
Browse files- app.py +18 -1
- requirements.txt +0 -0
- utils/pdf.py +16 -0
app.py
CHANGED
|
@@ -4,13 +4,30 @@ from fastapi import FastAPI, UploadFile, File, HTTPException
|
|
| 4 |
from ocr.gemini_service import parse_pan_with_fallback
|
| 5 |
from ocr.gemini_face_extractor import detect_face
|
| 6 |
from utils.crop import crop_face
|
|
|
|
| 7 |
|
| 8 |
app = FastAPI()
|
| 9 |
|
|
|
|
|
|
|
| 10 |
|
| 11 |
@app.post("/kyc/pan")
|
| 12 |
async def process_pan(file: UploadFile = File(...)):
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
try:
|
| 16 |
pan_result, face_result = await asyncio.gather(
|
|
|
|
| 4 |
from ocr.gemini_service import parse_pan_with_fallback
|
| 5 |
from ocr.gemini_face_extractor import detect_face
|
| 6 |
from utils.crop import crop_face
|
| 7 |
+
from utils.pdf import pdf_to_image_bytes
|
| 8 |
|
| 9 |
app = FastAPI()
|
| 10 |
|
| 11 |
+
SUPPORTED_TYPES = {"image/jpeg", "image/png", "image/webp", "application/pdf"}
|
| 12 |
+
|
| 13 |
|
| 14 |
@app.post("/kyc/pan")
|
| 15 |
async def process_pan(file: UploadFile = File(...)):
|
| 16 |
+
if file.content_type not in SUPPORTED_TYPES:
|
| 17 |
+
raise HTTPException(
|
| 18 |
+
status_code=415,
|
| 19 |
+
detail=f"Unsupported file type '{file.content_type}'. Upload a JPEG, PNG, WebP, or PDF.",
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
raw_bytes = await file.read()
|
| 23 |
+
|
| 24 |
+
if file.content_type == "application/pdf":
|
| 25 |
+
try:
|
| 26 |
+
image_bytes = pdf_to_image_bytes(raw_bytes)
|
| 27 |
+
except ValueError as e:
|
| 28 |
+
raise HTTPException(status_code=422, detail=str(e))
|
| 29 |
+
else:
|
| 30 |
+
image_bytes = raw_bytes
|
| 31 |
|
| 32 |
try:
|
| 33 |
pan_result, face_result = await asyncio.gather(
|
requirements.txt
CHANGED
|
Binary files a/requirements.txt and b/requirements.txt differ
|
|
|
utils/pdf.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import io
|
| 2 |
+
import fitz # PyMuPDF
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def pdf_to_image_bytes(pdf_bytes: bytes, dpi: int = 200) -> bytes:
|
| 6 |
+
"""Render the first page of a PDF to JPEG bytes."""
|
| 7 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 8 |
+
if doc.page_count == 0:
|
| 9 |
+
raise ValueError("The uploaded PDF has no pages.")
|
| 10 |
+
|
| 11 |
+
page = doc.load_page(0)
|
| 12 |
+
mat = fitz.Matrix(dpi / 72, dpi / 72)
|
| 13 |
+
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
|
| 14 |
+
|
| 15 |
+
buffer = io.BytesIO(pix.tobytes("jpeg"))
|
| 16 |
+
return buffer.getvalue()
|