Download app.py from alonb19/EP: direct link, hf CLI and curl.
- Browser
- Download file 2.57 kB
-
https://huggingface.co/spaces/alonb19/EP/resolve/main/app.py
- Command line
-
hf download hf://spaces/alonb19/EP/app.py
-
curl -L -o app.py https://huggingface.co/spaces/alonb19/EP/resolve/main/app.py
2.57 kB
| from fastapi import FastAPI, HTTPException | |
| from pydantic import BaseModel | |
| import cv2 | |
| from PIL import Image | |
| import numpy as np | |
| from io import BytesIO | |
| import requests | |
| app = FastAPI() | |
| class ImageRequest(BaseModel): | |
| image_url: str | |
| def buscar_existe(image_url): | |
| try: | |
| # Descargar la imagen desde la URL | |
| headers = { | |
| 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' | |
| } | |
| response = requests.get(image_url, headers=headers, timeout=30) | |
| response.raise_for_status() | |
| image = Image.open(BytesIO(response.content)) | |
| # Convertir a RGB si es necesario | |
| if image.mode != 'RGB': | |
| image = image.convert('RGB') | |
| image = np.asarray(image) | |
| existe = "NO" | |
| print("Imagen shape: ", image.shape) | |
| # Usar cascada de detección facial | |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
| # Convertir a escala de grises | |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) | |
| # Detectar rostros | |
| faces = face_cascade.detectMultiScale( | |
| gray, | |
| scaleFactor=1.1, | |
| minNeighbors=5, | |
| minSize=(30, 30), | |
| flags=cv2.CASCADE_SCALE_IMAGE | |
| ) | |
| if len(faces) > 0: | |
| existe = "SI" | |
| print(f"Se detectaron {len(faces)} rostro(s)") | |
| else: | |
| print("No se detectaron rostros") | |
| return existe | |
| except Exception as e: | |
| print(f"Error procesando imagen: {str(e)}") | |
| return "NO" | |
| # Cambiar para aceptar JSON en el body | |
| async def predict_from_url(request: ImageRequest): | |
| try: | |
| print(f"Recibida URL: {request.image_url}") | |
| prediction = buscar_existe(request.image_url) | |
| return {"prediction": prediction} | |
| except Exception as e: | |
| print(f"Error en predict_from_url: {str(e)}") | |
| raise HTTPException(status_code=500, detail=str(e)) | |
| async def root(): | |
| return {"message": "Servicio de detección de rostros funcionando"} | |
| async def health(): | |
| return {"status": "OK"} | |
| # Ruta alternativa usando query parameter (por si acaso) | |
| async def predict_get(image_url: str): | |
| try: | |
| prediction = buscar_existe(image_url) | |
| return {"prediction": prediction} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) |