from fastapi import FastAPI from pydantic import BaseModel import easyocr import base64 import io from PIL import Image import numpy as np app = FastAPI() # Load the AI model into memory (runs once on startup) print("Loading EasyOCR Model...") reader = easyocr.Reader(['en']) print("Model Loaded!") class ImageData(BaseModel): image: str @app.post("/solve") def solve_captcha(data: ImageData): try: # 1. Clean the base64 string and decode it base64_data = data.image.split(",")[1] if "," in data.image else data.image img_bytes = base64.b64decode(base64_data) # 2. Convert to an image the AI can read img = Image.open(io.BytesIO(img_bytes)).convert("RGB") img_np = np.array(img) # 3. Let EasyOCR read it! results = reader.readtext(img_np, detail=0) text = "".join(results) # 4. Clean up the text (keep only letters and numbers) cleaned = "".join(e for e in text if e.isalnum()).lower() return {"text": cleaned} except Exception as e: return {"error": str(e)}