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)}