File size: 1,249 Bytes
b676ee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, File, UploadFile
from PIL import Image
import easyocr
import io
import logging

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = FastAPI()

# Load the EasyOCR model once when the application starts
# This makes subsequent requests much faster
logger.info("Loading EasyOCR model...")
reader = easyocr.Reader(['en'], gpu=False)
logger.info("EasyOCR model loaded successfully.")

@app.get("/")
def read_root():
    return {"status": "OCR API is running"}

@app.post("/ocr-from-image/")
async def ocr_from_image(file: UploadFile = File(...)):
    try:
        # Read the image file from the request
        image_bytes = await file.read()
        
        # Use EasyOCR to read text from the image bytes
        logger.info("Processing image with EasyOCR...")
        result = reader.readtext(image_bytes, detail=0, paragraph=True)
        
        # Combine the detected text lines into a single string
        extracted_text = " ".join(result)
        logger.info(f"Extracted Text: {extracted_text}")
        
        return {"extracted_text": extracted_text}
    except Exception as e:
        logger.error(f"An error occurred: {e}")
        return {"error": str(e)}