CesarAHO123/PCD_FinalProject
0
1import streamlit as st
2import numpy as np
3import librosa
4import tensorflow as tf
5import soundfile as sf
6import io
7
8# Cargar modelo
9model = tf.keras.models.load_model("modelo_emociones_rnn.keras")
10
11# Parámetros
12n_mfcc = 13
13max_pad_len = 173
14emotion_labels = ['angry', 'calm', 'disgust', 'fearful', 'happy', 'neutral', 'sad', 'surprised']
15emoji_dict = {
16 'angry': '😠',
17 'calm': '😌',
18 'disgust': '🤢',
19 'fearful': '😨',
20 'happy': '😃',
21 'neutral': '😐',
22 'sad': '😢',
23 'surprised': '😲'
24}
25
26# Extraer MFCC desde audio en memoria
27def extract_mfcc_sequence(file_buffer, max_pad_len=173):
28 y, sr = sf.read(file_buffer)
29 if len(y.shape) > 1:
30 y = np.mean(y, axis=1)
31 mfcc = librosa.feature.mfcc(y=y, sr=sr, n_mfcc=n_mfcc)
32 if mfcc.shape[1] < max_pad_len:
33 pad_width = max_pad_len - mfcc.shape[1]
34 mfcc = np.pad(mfcc, pad_width=((0, 0), (0, pad_width)), mode='constant')
35 else:
36 mfcc = mfcc[:, :max_pad_len]
37 return np.transpose(mfcc) # Devuelve (173, 13)
38
39
40# Configuración de la app
41st.set_page_config(page_title="IA Coach Emocional", layout="centered")
42st.title("¿Qué emoción expresas al hablar?")
43st.markdown("Graba tu voz diciendo algo y descubre qué emoción transmite tu tono 😯")
44
45# Grabación directa
46st.header("🎤 Grabación de voz")
47audio_bytes = st.audio_input("Graba una nota de voz")
48
49if audio_bytes:
50 st.success("✅ Grabación recibida")
51
52 # Procesar audio
53 audio_buffer = io.BytesIO(audio_bytes.read())
54 features = extract_mfcc_sequence(audio_buffer)
55
56 if features is not None:
57 features = np.expand_dims(np.transpose(features), axis=0)
58
59
60 # Predicción
61 prediction = model.predict(features)
62 predicted_index = np.argmax(prediction)
63 predicted_emotion = emotion_labels[predicted_index]
64
65 # Resultado visual
66 st.markdown(f"## {emoji_dict[predicted_emotion]} Emoción detectada: **{predicted_emotion.upper()}**")
67 import plotly.graph_objects as go
68
69 # Diccionario de colores por emoción
70 color_dict = {
71 'angry': '#E74C3C',
72 'calm': '#85C1E9',
73 'disgust': '#A569BD',
74 'fearful': '#F4D03F',
75 'happy': '#58D68D',
76 'neutral': '#D5DBDB',
77 'sad': '#5D6D7E',
78 'surprised': '#F1948A'
79 }
80
81 # Crear gráfica con Plotly
82 fig = go.Figure(data=[
83 go.Bar(
84 x=emotion_labels,
85 y=prediction[0],
86 marker_color=[color_dict[emotion] for emotion in emotion_labels]
87 )
88 ])
89
90 fig.update_layout(
91 title="🔍 Distribución de probabilidades por emoción",
92 xaxis_title="Emoción",
93 yaxis_title="Probabilidad",
94 yaxis=dict(range=[0, 1]),
95 template="plotly_white"
96 )
97
98 st.plotly_chart(fig)
99
100
101 