File size: 1,509 Bytes
5333694 cc4df30 5333694 cc4df30 5333694 cc4df30 0a67fea cc4df30 1972325 cc4df30 1972325 cc4df30 1972325 cc4df30 92c1644 cc4df30 92c1644 cc4df30 1972325 cc4df30 5333694 cc4df30 5333694 1972325 cc4df30 5333694 |
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 51 52 53 54 |
from fastapi import FastAPI, UploadFile, File, Request
from fastapi.responses import JSONResponse
import requests
import easyocr
from PIL import Image
import numpy as np
from io import BytesIO
app = FastAPI(title="OCR API", description="OCR through URL or Buffer")
reader = easyocr.Reader(['en'], gpu=False)
def run_ocr(image_bytes):
img = Image.open(BytesIO(image_bytes)).convert("RGB")
img_np = np.array(img)
results = reader.readtext(img_np)
parsed = []
output = []
for box, text, conf in results:
parsed.append(str(text))
output.append({
"text": str(text),
"confidence": float(conf),
"bounding_box": [[float(x), float(y)] for x, y in box]
})
final_text = " ".join(parsed)
return {
"results": output,
"parsedText": parsed,
"finalText": final_text
}
@app.get("/ocr")
async def ocr_url(url: str):
try:
img_data = requests.get(url, timeout=10).content
data = run_ocr(img_data)
return JSONResponse({"success": True, **data})
except Exception as e:
return JSONResponse({"success": False, "error": str(e)}, status_code=400)
@app.post("/ocr")
async def ocr_buffer(file: UploadFile = File(...)):
try:
image_bytes = await file.read()
data = run_ocr(image_bytes)
return JSONResponse({"success": True, **data})
except Exception as e:
return JSONResponse({"success": False, "error": str(e)}, status_code=400)
|