File size: 1,743 Bytes
c9331c8
5b739e4
 
 
c9331c8
5b739e4
 
 
 
 
 
 
 
 
 
c9331c8
 
 
5b739e4
c9331c8
 
 
 
 
 
 
 
 
 
 
 
 
 
5b739e4
c9331c8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
from fastapi import FastAPI, UploadFile, File, HTTPException
from paddleocr import PaddleOCR
from PIL import Image
import io, numpy as np
import fitz  # pymupdf

app = FastAPI()
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)

@app.get("/")
def health():
    return {"status": "ok"}

@app.post("/ocr")
async def run_ocr(file: UploadFile = File(...)):
    try:
        contents = await file.read()
        all_texts = []

        # Handle PDF
        if file.filename.lower().endswith(".pdf"):
            pdf = fitz.open(stream=contents, filetype="pdf")
            for page in pdf:
                pix = page.get_pixmap(dpi=200)
                img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
                img_array = np.array(img)
                result = ocr.ocr(img_array, cls=True)
                if result and result[0]:
                    for line in result[0]:
                        all_texts.append({
                            "text": line[1][0],
                            "confidence": round(line[1][1], 4)
                        })

        # Handle image (JPG, PNG, etc)
        else:
            image = Image.open(io.BytesIO(contents)).convert("RGB")
            img_array = np.array(image)
            result = ocr.ocr(img_array, cls=True)
            if result and result[0]:
                for line in result[0]:
                    all_texts.append({
                        "text": line[1][0],
                        "confidence": round(line[1][1], 4)
                    })

        return {"filename": file.filename, "results": all_texts}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))