Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, File, UploadFile, HTTPException | |
| from fastapi.responses import HTMLResponse | |
| from pydantic import BaseModel | |
| from typing import List | |
| import cv2 | |
| from PIL import Image | |
| import numpy as np | |
| from io import BytesIO | |
| from deepface import DeepFace | |
| import requests | |
| class InputData(BaseModel): | |
| data: str | |
| app = FastAPI() | |
| def buscar_existe(imagen): | |
| face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') | |
| #imagen = cv2.imread('carro.jpg') | |
| gray_frame = cv2.cvtColor(imagen, cv2.COLOR_BGR2GRAY) | |
| # Convert grayscale frame to RGB format | |
| rgb_frame = cv2.cvtColor(gray_frame, cv2.COLOR_GRAY2RGB) | |
| # Detect faces in the frame | |
| faces = face_cascade.detectMultiScale(gray_frame, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30)) | |
| emocion = "Sin Emocion" | |
| for (x, y, w, h) in faces: | |
| face_roi = rgb_frame[y:y + h, x:x + w] | |
| # Perform emotion analysis on the face ROI | |
| result = DeepFace.analyze(face_roi, actions=['emotion'], enforce_detection=False) | |
| # Determine the dominant emotion | |
| emocion = result[0]['dominant_emotion'] | |
| return emocion | |
| # Ruta de predicción | |
| async def predict(input: InputData): | |
| try: | |
| image_url = input.data | |
| # Descargar la imagen desde la URL | |
| response = requests.get(image_url) | |
| if response.status_code != 200: | |
| raise HTTPException(status_code=400, detail="No se pudo descargar la imagen") | |
| # Leer la imagen y convertir a formato OpenCV | |
| image_bytes = BytesIO(response.content) | |
| image = Image.open(image_bytes).convert("RGB") | |
| image_np = np.array(image) | |
| image_cv = cv2.cvtColor(image_np, cv2.COLOR_RGB2BGR) | |
| prediction = buscar_existe(image_cv) | |
| return {"prediction": prediction} | |
| except Exception as e: | |
| raise HTTPException(status_code=500, detail=str(e)) |