Download app.py from Wized2/OCR: direct link, hf CLI and curl.
- Browser
- Download file 1.56 kB
-
https://huggingface.co/spaces/Wized2/OCR/resolve/main/app.py
- Command line
-
hf download hf://spaces/Wized2/OCR/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Wized2/OCR/resolve/main/app.py
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 --- | |
| 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)} | |
| 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)} | |