Spaces:
Sleeping
Sleeping
| import os | |
| # Configurar variables de entorno para DeepFace ANTES de importar | |
| os.environ['HOME'] = '/tmp' | |
| os.environ['DEEPFACE_HOME'] = '/tmp/.deepface' | |
| from flask import Flask, request, jsonify | |
| from flask_cors import CORS | |
| import cv2 | |
| from deepface import DeepFace | |
| import numpy as np | |
| import base64 | |
| from io import BytesIO | |
| from PIL import Image | |
| app = Flask(__name__) | |
| CORS(app) | |
| # cargar el clasificador de rostros | |
| face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml') | |
| def home(): | |
| return jsonify({ | |
| 'message': 'API de Detecci贸n de Emociones', | |
| 'endpoints': { | |
| '/predict': 'POST - Enviar imagen para detectar emoci贸n', | |
| '/health': 'GET - Verificar estado del servicio' | |
| } | |
| }) | |
| def predict_emotion(): | |
| try: | |
| # verificar si se recibi贸 una imagen como archivo | |
| if 'file' not in request.files: | |
| return jsonify({'error': 'No se envi贸 ning煤n archivo. Usa el campo "file"'}), 400 | |
| file = request.files['file'] | |
| if file.filename == '': | |
| return jsonify({'error': 'Archivo vac铆o'}), 400 | |
| # leer imagen desde archivo | |
| image = Image.open(file.stream) | |
| frame = np.array(image) | |
| frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR) | |
| # convertir a escala de grises | |
| gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) | |
| # convertir a RGB para DeepFace | |
| rgb_frame = cv2.cvtColor(gray_frame, cv2.COLOR_GRAY2RGB) | |
| # detectar rostros en el frame | |
| faces = face_cascade.detectMultiScale( | |
| gray_frame, | |
| scaleFactor=1.1, | |
| minNeighbors=5, | |
| minSize=(30, 30) | |
| ) | |
| emocion = "Sin Emocion" | |
| all_emotions = {} | |
| faces_detected = len(faces) | |
| # si se detectaron rostros | |
| if len(faces) > 0: | |
| for (x, y, w, h) in faces: | |
| # extraer la regi贸n del rostro | |
| face_roi = rgb_frame[y:y + h, x:x + w] | |
| # realizar an谩lisis de emoci贸n | |
| result = DeepFace.analyze( | |
| face_roi, | |
| actions=['emotion'], | |
| enforce_detection=False | |
| ) | |
| # determinar la emoci贸n dominante | |
| emocion = result[0]['dominant_emotion'] | |
| all_emotions = result[0]['emotion'] | |
| break # Usar solo el primer rostro detectado | |
| else: | |
| # si no se detecta rostro, intentar an谩lisis directo | |
| try: | |
| result = DeepFace.analyze( | |
| frame, | |
| actions=['emotion'], | |
| enforce_detection=False | |
| ) | |
| emocion = result[0]['dominant_emotion'] | |
| all_emotions = result[0]['emotion'] | |
| faces_detected = 1 | |
| except: | |
| pass | |
| # formatear respuesta similar a Hugging Face API | |
| response = [] | |
| if all_emotions: | |
| for emotion, score in all_emotions.items(): | |
| response.append({ | |
| 'label': emotion, | |
| 'score': score / 100.0 | |
| }) | |
| # ordenar por score | |
| response.sort(key=lambda x: x['score'], reverse=True) | |
| return jsonify({ | |
| 'emotion': emocion, | |
| 'faces_detected': faces_detected, | |
| 'all_emotions': response if response else None | |
| }) | |
| except Exception as e: | |
| return jsonify({ | |
| 'error': str(e), | |
| 'emotion': 'Error al procesar imagen' | |
| }), 500 | |
| def health(): | |
| return jsonify({'status': 'healthy', 'service': 'Emotion Detection API'}) | |
| if __name__ == '__main__': | |
| port = int(os.environ.get('PORT', 7860)) | |
| app.run(host='0.0.0.0', port=port, debug=False) |