Spaces:
Sleeping

File size: 1,563 Bytes
2f381b7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
42
43
44
45
46
47
48
49
50
51
52
53
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)}