| 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: |
| |
| 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)) |
| |
| |
| if image.mode != 'RGB': |
| image = image.convert('RGB') |
| |
| image = np.asarray(image) |
| |
| existe = "NO" |
| print("Imagen shape: ", image.shape) |
| |
| |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') |
| |
| |
| gray = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) |
| |
| |
| 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" |
|
|
| |
| @app.post('/predict/') |
| 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)) |
|
|
| @app.get("/") |
| async def root(): |
| return {"message": "Servicio de detecci贸n de rostros funcionando"} |
|
|
| @app.get("/health") |
| async def health(): |
| return {"status": "OK"} |
|
|
| |
| @app.get('/predict_get/') |
| 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)) |