Spaces:
Sleeping

OCR / app.py
Wized2's picture
Rename main.py to app.py
8605f29 verified
Raw History Blame Contribute Delete
1.56 kB
from fastapi import FastAPI, UploadFile, File
from fastapi.middleware.cors import CORSMiddleware
import easyocr
import io
from PIL import Image
app = FastAPI()
# 1. Enable global frontend access (CORS) so your site can use it directly
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# 2. Pre-initialize the OCR engines once during bootup
# EasyOCR requires English ('en') to be loaded alongside Urdu ('ur') for best accuracy
print("Loading English OCR engine...")
en_reader = easyocr.Reader(['en'])
print("Loading Urdu OCR engine...")
ur_reader = easyocr.Reader(['ur', 'en'])
# --- ENDPOINTS ---
@app.post("/api/en")
async def ocr_english(file: UploadFile = File(...)):
try:
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes))
# Extract English text
text_results = en_reader.readtext(image, detail=0)
return {"success": True, "language": "english", "text": " ".join(text_results)}
except Exception as e:
return {"success": False, "error": str(e)}
@app.post("/api/ur")
async def ocr_urdu(file: UploadFile = File(...)):
try:
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes))
# Extract Urdu text
text_results = ur_reader.readtext(image, detail=0)
return {"success": True, "language": "urdu", "text": " ".join(text_results)}
except Exception as e:
return {"success": False, "error": str(e)}