File size: 1,193 Bytes
7137a53
c966651
 
 
 
 
 
 
 
600d524
7137a53
 
aa0e172
f1886c8
 
aa0e172
a7188dd
aa0e172
c966651
78d84b5
c966651
 
 
 
 
 
f1886c8
a7188dd
f1886c8
a7188dd
 
 
 
235c17e
a7188dd
c966651
 
ad48f2d
63f819a
ad48f2d
aa0e172
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
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!"}