Download app.py from alonb19/ocr: direct link, hf CLI and curl.
- Browser
- Download file 2.12 kB
-
https://huggingface.co/spaces/alonb19/ocr/resolve/main/app.py
- Command line
-
hf download hf://spaces/alonb19/ocr/app.py
-
curl -L -o app.py https://huggingface.co/spaces/alonb19/ocr/resolve/main/app.py
2.12 kB
| from fastapi import FastAPI, UploadFile, File, HTTPException | |
| from fastapi.responses import JSONResponse | |
| import numpy as np | |
| from PIL import Image | |
| import io | |
| import uvicorn | |
| import os | |
| # Configurar variables de entorno para EasyOCR antes de importarlo | |
| os.environ['EASYOCR_MODULE_PATH'] = '/app/model' | |
| os.environ['HOME'] = '/app' | |
| import easyocr | |
| app = FastAPI() | |
| # Inicializar el lector OCR | |
| reader = easyocr.Reader(['es', 'en']) | |
| async def extract_text(file: UploadFile = File(...)): | |
| """ | |
| Extrae texto de una imagen usando OCR | |
| """ | |
| try: | |
| # Verificar que el archivo sea una imagen | |
| if not file.content_type.startswith('image/'): | |
| raise HTTPException(status_code=400, detail="El archivo debe ser una imagen") | |
| # Leer el archivo | |
| contents = await file.read() | |
| # Convertir a PIL Image | |
| image = Image.open(io.BytesIO(contents)) | |
| # Convertir a RGB si es necesario | |
| if image.mode != 'RGB': | |
| image = image.convert('RGB') | |
| # Convertir a numpy array | |
| image_array = np.array(image) | |
| # Realizar OCR | |
| results = reader.readtext(image_array) | |
| # Formatear resultados | |
| extracted_text = [] | |
| for (bbox, text, confidence) in results: | |
| extracted_text.append({ | |
| "text": text, | |
| "confidence": float(confidence), | |
| "bbox": bbox | |
| }) | |
| # Texto completo concatenado | |
| full_text = " ".join([item["text"] for item in extracted_text]) | |
| return JSONResponse(content={ | |
| "success": True, | |
| "full_text": full_text, | |
| "detailed_results": extracted_text | |
| }) | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=f"Error procesando la imagen: {str(e)}") | |
| async def root(): | |
| return {"message": "OCR API funcionando", "endpoint": "/ocr"} | |
| if __name__ == "__main__": | |
| port = int(os.environ.get("PORT", 7860)) | |
| uvicorn.run(app, host="0.0.0.0", port=port) | |