Update main.py
Browse files
main.py
CHANGED
|
@@ -1,7 +1,8 @@
|
|
| 1 |
-
from fastapi import FastAPI, UploadFile, File
|
| 2 |
from paddleocr import PaddleOCR
|
| 3 |
from PIL import Image
|
| 4 |
import io, numpy as np
|
|
|
|
| 5 |
|
| 6 |
app = FastAPI()
|
| 7 |
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
|
|
@@ -12,16 +13,38 @@ def health():
|
|
| 12 |
|
| 13 |
@app.post("/ocr")
|
| 14 |
async def run_ocr(file: UploadFile = File(...)):
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
result = ocr.ocr(img_array, cls=True)
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 2 |
from paddleocr import PaddleOCR
|
| 3 |
from PIL import Image
|
| 4 |
import io, numpy as np
|
| 5 |
+
import fitz # pymupdf
|
| 6 |
|
| 7 |
app = FastAPI()
|
| 8 |
ocr = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=False)
|
|
|
|
| 13 |
|
| 14 |
@app.post("/ocr")
|
| 15 |
async def run_ocr(file: UploadFile = File(...)):
|
| 16 |
+
try:
|
| 17 |
+
contents = await file.read()
|
| 18 |
+
all_texts = []
|
|
|
|
| 19 |
|
| 20 |
+
# Handle PDF
|
| 21 |
+
if file.filename.lower().endswith(".pdf"):
|
| 22 |
+
pdf = fitz.open(stream=contents, filetype="pdf")
|
| 23 |
+
for page in pdf:
|
| 24 |
+
pix = page.get_pixmap(dpi=200)
|
| 25 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 26 |
+
img_array = np.array(img)
|
| 27 |
+
result = ocr.ocr(img_array, cls=True)
|
| 28 |
+
if result and result[0]:
|
| 29 |
+
for line in result[0]:
|
| 30 |
+
all_texts.append({
|
| 31 |
+
"text": line[1][0],
|
| 32 |
+
"confidence": round(line[1][1], 4)
|
| 33 |
+
})
|
| 34 |
|
| 35 |
+
# Handle image (JPG, PNG, etc)
|
| 36 |
+
else:
|
| 37 |
+
image = Image.open(io.BytesIO(contents)).convert("RGB")
|
| 38 |
+
img_array = np.array(image)
|
| 39 |
+
result = ocr.ocr(img_array, cls=True)
|
| 40 |
+
if result and result[0]:
|
| 41 |
+
for line in result[0]:
|
| 42 |
+
all_texts.append({
|
| 43 |
+
"text": line[1][0],
|
| 44 |
+
"confidence": round(line[1][1], 4)
|
| 45 |
+
})
|
| 46 |
+
|
| 47 |
+
return {"filename": file.filename, "results": all_texts}
|
| 48 |
+
|
| 49 |
+
except Exception as e:
|
| 50 |
+
raise HTTPException(status_code=500, detail=str(e))
|