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') @app.route('/') 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' } }) @app.route('/predict', methods=['POST']) 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 @app.route('/health', methods=['GET']) 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)