Spaces:
Sleeping
Sleeping
Download app.py from Sudhansh26/ocr-fastapi: direct link, hf CLI and curl.
- Browser
- Download file 1.67 kB
-
https://huggingface.co/spaces/Sudhansh26/ocr-fastapi/resolve/main/app.py
- Command line
-
hf download hf://spaces/Sudhansh26/ocr-fastapi/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Sudhansh26/ocr-fastapi/resolve/main/app.py
1.67 kB
| from fastapi import FastAPI, UploadFile, File | |
| import fitz # PyMuPDF | |
| import easyocr | |
| from pdf2image import convert_from_bytes | |
| import pytesseract | |
| import numpy as np | |
| app = FastAPI(title="High Accuracy Hindi + English PDF Text Extraction API") | |
| # Linux Tesseract path | |
| pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' | |
| # Initialize EasyOCR | |
| easy_reader = easyocr.Reader(['en', 'hi'], gpu=False) | |
| # Root route to test server | |
| def home(): | |
| return {"message": "OCR API is running!"} | |
| # OCR Endpoint | |
| async def extract_text(file: UploadFile = File(...)): | |
| pdf_bytes = await file.read() | |
| text = "" | |
| try: | |
| # Step 1: Text-based extraction | |
| with fitz.open(stream=pdf_bytes, filetype="pdf") as pdf: | |
| for page in pdf: | |
| text += page.get_text("text") + "\n\n" | |
| # Step 2: EasyOCR fallback | |
| if len(text.strip()) < 40: | |
| with fitz.open(stream=pdf_bytes, filetype="pdf") as pdf: | |
| for i, page in enumerate(pdf): | |
| pix = page.get_pixmap(dpi=150) | |
| img_bytes = pix.tobytes("png") | |
| results = easy_reader.readtext(img_bytes, detail=0, paragraph=True) | |
| text += " ".join(results) | |
| # Step 3: Tesseract fallback for Hindi | |
| if len(text.strip()) < 40: | |
| images = convert_from_bytes(pdf_bytes, dpi=300) | |
| for img in images: | |
| text += pytesseract.image_to_string(np.array(img), lang="hin+eng") | |
| return {"status": "success", "text": text[:10000]} | |
| except Exception as e: | |
| return {"status": "error", "message": str(e)} | |