|
| 1 | +import os |
| 2 | +import tempfile |
| 3 | +from threading import Lock |
| 4 | + |
| 5 | +import pypdfium2 as pdfium |
| 6 | +from fastapi import FastAPI, File, HTTPException, UploadFile |
| 7 | +from rapidocr import RapidOCR |
| 8 | + |
| 9 | + |
| 10 | +app = FastAPI(title="OpenAgent OCR Service") |
| 11 | +ocr_engine = RapidOCR() |
| 12 | +ocr_lock = Lock() |
| 13 | + |
| 14 | + |
| 15 | +@app.get("/health") |
| 16 | +def health(): |
| 17 | + return {"status": "ok"} |
| 18 | + |
| 19 | + |
| 20 | +@app.post("/ocr/pdf") |
| 21 | +async def ocr_pdf(file: UploadFile = File(...)): |
| 22 | + content = await file.read() |
| 23 | + if not content.startswith(b"%PDF"): |
| 24 | + raise HTTPException(status_code=400, detail="file must be a PDF") |
| 25 | + |
| 26 | + try: |
| 27 | + text = read_pdf_text(content) |
| 28 | + except Exception as err: |
| 29 | + raise HTTPException(status_code=500, detail=f"failed to OCR PDF: {err}") from err |
| 30 | + |
| 31 | + return {"text": text} |
| 32 | + |
| 33 | + |
| 34 | +def read_pdf_text(content: bytes) -> str: |
| 35 | + temp_path = write_temp_pdf(content) |
| 36 | + try: |
| 37 | + pdf = pdfium.PdfDocument(temp_path) |
| 38 | + try: |
| 39 | + page_texts = [read_page_text(pdf[index], index + 1) for index in range(len(pdf))] |
| 40 | + finally: |
| 41 | + pdf.close() |
| 42 | + finally: |
| 43 | + os.remove(temp_path) |
| 44 | + |
| 45 | + return "\n\n".join(text for text in page_texts if text) |
| 46 | + |
| 47 | + |
| 48 | +def write_temp_pdf(content: bytes) -> str: |
| 49 | + with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as temp_file: |
| 50 | + temp_file.write(content) |
| 51 | + return temp_file.name |
| 52 | + |
| 53 | + |
| 54 | +def read_page_text(page, page_number: int) -> str: |
| 55 | + try: |
| 56 | + bitmap = page.render(scale=2.0) |
| 57 | + try: |
| 58 | + image = bitmap.to_pil().convert("RGB") |
| 59 | + finally: |
| 60 | + bitmap.close() |
| 61 | + finally: |
| 62 | + page.close() |
| 63 | + |
| 64 | + with ocr_lock: |
| 65 | + result = ocr_engine(image) |
| 66 | + |
| 67 | + if result is None or result.txts is None: |
| 68 | + return "" |
| 69 | + |
| 70 | + text = "\n".join(item for item in result.txts if item) |
| 71 | + if text == "": |
| 72 | + return "" |
| 73 | + return f"Page {page_number}\n{text}" |
0 commit comments