ocr_api_easyocr / app.py
Icosar's picture
Update app.py
63f819a verified
import os
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse
import easyocr
import cv2
import numpy as np
app = FastAPI()
MODEL_DIR = '/data/models'
os.makedirs(MODEL_DIR, exist_ok=True)
reader = easyocr.Reader(
['en', 'hr'],
gpu=False,
model_storage_directory=MODEL_DIR,
user_network_directory=MODEL_DIR
)
@app.post("/ocr")
async def perform_ocr(file: UploadFile = File(...)):
contents = await file.read()
np_array = np.frombuffer(contents, np.uint8)
image = cv2.imdecode(np_array, cv2.IMREAD_GRAYSCALE)
if image is None:
return JSONResponse(content={"error": "Invalid image"}, status_code=400)
image = cv2.equalizeHist(image)
results = reader.readtext(
image,
contrast_ths=0.1, # Lower contrast threshold for text detection
adjust_contrast=0.5, # Adjust contrast for better detection
allowlist='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789čćšžđ%,.:-!?', # Support diacritics
)
texts = [text for (_, text, _) in results]
return {"text": texts}
@app.get("/")
async def hello():
return {"message": "Hello from FastAPI!"}