File size: 10,136 Bytes
df80fb7
201ed31
 
103eb2f
201ed31
 
 
 
 
 
 
 
 
 
 
 
 
17454f4
 
201ed31
 
17454f4
201ed31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17454f4
 
 
201ed31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17454f4
 
 
 
 
 
 
 
 
 
201ed31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17454f4
 
201ed31
17454f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201ed31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17454f4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
import streamlit as st
import pandas as pd
import numpy as np
import os
import time
import matplotlib.pyplot as plt
from datetime import datetime
import tempfile
import io
import json
from model.transcriber import transcribe_audio
from predict import predict_emotion

# You'll need to install this package:
# pip install streamlit-audiorec
from st_audiorec import st_audiorec

AUDIO_WAV = 'audio/wav'
MAX_FILE_SIZE_MB = 10
# Page configuration
st.set_page_config(
    page_title="Emotional Report Analyzer",
    page_icon="🎤",
    layout="wide"
)

# Initialize session state variables if they don't exist
if 'audio_data' not in st.session_state:
    st.session_state.audio_data = []
if 'current_audio_index' not in st.session_state:
    st.session_state.current_audio_index = -1
if 'audio_history_csv' not in st.session_state:
    # Define columns for our CSV storage
    st.session_state.audio_history_csv = pd.DataFrame(
        columns=['timestamp', 'file_path', 'transcription', 'emotion', 'probabilities']
    )
if 'needs_rerun' not in st.session_state:
    st.session_state.needs_rerun = False

# Function to ensure we keep only the last 10 entries
def update_audio_history(new_entry):
    # Add the new entry
    st.session_state.audio_history_csv = pd.concat([st.session_state.audio_history_csv, pd.DataFrame([new_entry])], ignore_index=True)
    
    # Keep only the last 10 entries
    if len(st.session_state.audio_history_csv) > 10:
        st.session_state.audio_history_csv = st.session_state.audio_history_csv.iloc[-10:]
    
    # Save to CSV
    st.session_state.audio_history_csv.to_csv('audio_history.csv', index=False)

# Function to process audio and get results
def process_audio(audio_path):
    try:
        # Get transcription
        transcription = transcribe_audio(audio_path)
        
        # Get emotion prediction
        predicted_emotion, probabilities = predict_emotion(audio_path)
        
        # Update audio history
        new_entry = {
            'timestamp': datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            'file_path': audio_path,
            'transcription': transcription,
            'emotion': predicted_emotion,
            'probabilities': str(probabilities)  # Convert dict to string for storage
        }
        update_audio_history(new_entry)
        
        # Update current index
        st.session_state.current_audio_index = len(st.session_state.audio_history_csv) - 1
        
        return transcription, predicted_emotion, probabilities
    except Exception as e:
        st.error(f"Error processing audio: {str(e)}")
        return None, None, None

# Function to split audio into 10-second segments
def split_audio(audio_file, segment_length=10):
    # This is a placeholder - in a real implementation, you'd use a library like pydub
    # to split the audio file into segments
    st.warning("Audio splitting functionality is a placeholder. Implement with pydub or similar library.")
    # For now, we'll just return the whole file as a single segment
    return [audio_file]

# Function to display emotion visualization
def display_emotion_chart(probabilities):
    emotions = list(probabilities.keys())
    values = list(probabilities.values())
    
    fig, ax = plt.subplots(figsize=(10, 5))
    bars = ax.bar(emotions, values, color=['red', 'gray', 'green'])
    
    # Add data labels on top of bars
    for bar in bars:
        height = bar.get_height()
        ax.text(bar.get_x() + bar.get_width()/2., height + 0.02,
                f'{height:.2f}', ha='center', va='bottom')
    
    ax.set_ylim(0, 1.1)
    ax.set_ylabel('Probability')
    ax.set_title('Emotion Prediction Results')
    
    st.pyplot(fig)

# Trigger rerun if needed (replaces experimental_rerun)
if st.session_state.needs_rerun:
    st.session_state.needs_rerun = False
    st.rerun()  # Using st.rerun() instead of experimental_rerun

col_logo, col_name = st.columns([3, 1])
col_logo.image("./img/logo_01.png", width=400)
col_name.title("Emotional Report")

# Create two columns for the main layout
col1, col2 = st.columns([1, 1])

with col1:
    st.header("Audio Input")
    
    # Method selection

    tab1, tab2 = st.tabs(["Record Audio", "Upload Audio"])
    
    with tab1:
        st.write("Record your audio (max 10 seconds):")
        
        # Using streamlit-audiorec for better recording functionality
        wav_audio_data = st_audiorec()
        
        if wav_audio_data is not None:
            # Save the recorded audio to a temporary file
            with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
                tmp_file.write(wav_audio_data)
                tmp_file_path = tmp_file.name
            
            st.success("Audio recorded successfully!")
            
            # Process button
            if st.button("Process Recorded Audio"):
                # Process the audio
                with st.spinner("Processing audio..."):
                    transcription, emotion, probs = process_audio(tmp_file_path)
                    # Set flag for rerun instead of calling experimental_rerun
                    if transcription is not None:
                        st.success("Audio processed successfully!")
                        st.session_state.needs_rerun = True
    
    with tab2:
        uploaded_file = st.file_uploader("Upload an audio file (WAV format)", type=['wav'])
        
        if uploaded_file is not None and uploaded_file.type == AUDIO_WAV and uploaded_file.size < MAX_FILE_SIZE_MB * 1_000_000:
            try:
                # Save the uploaded file to a temporary location
                with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
                    tmp_file.write(uploaded_file.getbuffer())
                    tmp_file_path = tmp_file.name
            except Exception as e:
                st.error(f"Error saving uploaded file: {str(e)}")
                st.error(f"Try to record your voice directly, maybe your storage is locked.")
                
            st.audio(uploaded_file, format="audio/wav")
            
            # Process button
            if st.button("Process Uploaded Audio"):
                # Split audio into 10-second segments
                with st.spinner("Processing audio..."):
                    segments = split_audio(tmp_file_path)
                    
                    # Process each segment
                    for i, segment_path in enumerate(segments):
                        st.write(f"Processing segment {i+1}...")
                        transcription, emotion, probs = process_audio(segment_path)
                        
                    # Set flag for rerun instead of calling experimental_rerun
                    st.success("Audio processed successfully!")
                    st.session_state.needs_rerun = True
    # Audio History and Analytics Section
    st.header("Audio History and Analytics")

    if len(st.session_state.audio_history_csv) > 0:
        # Display a select box to choose from audio history
        timestamps = st.session_state.audio_history_csv['timestamp'].tolist()
        selected_timestamp = st.selectbox(
            "Select audio from history:",
            options=timestamps,
            index=len(timestamps) - 1  # Default to most recent
        )
        
        # Update current index when selection changes
        selected_index = st.session_state.audio_history_csv[
            st.session_state.audio_history_csv['timestamp'] == selected_timestamp
        ].index[0]
        
        # Only update if different
        if st.session_state.current_audio_index != selected_index:
            st.session_state.current_audio_index = selected_index
            st.session_state.needs_rerun = True
        
        # Analytics button
        if st.button("Run Analytics on Selected Audio"):
            st.subheader("Analytics Results")
            
            # Get the selected audio data
            selected_data = st.session_state.audio_history_csv.iloc[selected_index]
            
            # Display analytics (this is where you would add more sophisticated analytics)
            st.write(f"Selected Audio: {selected_data['timestamp']}")
            st.write(f"Emotion: {selected_data['emotion']}")
            st.write(f"File Path: {selected_data['file_path']}")
            
            # Add any additional analytics you want here
            
            # Try to play the selected audio
            try:
                if os.path.exists(selected_data['file_path']):
                    st.audio(selected_data['file_path'], format="audio/wav")
                else:
                    st.warning("Audio file not found - it may have been deleted or moved.")
            except Exception as e:
                st.error(f"Error playing audio: {str(e)}")
    else:
        st.info("No audio history available. Record or upload audio to create history.")
        
with col2:
    st.header("Results")
    
    # Display results if available
    if st.session_state.current_audio_index >= 0 and len(st.session_state.audio_history_csv) > 0:
        current_data = st.session_state.audio_history_csv.iloc[st.session_state.current_audio_index]
        
        # Transcription
        st.subheader("Transcription")
        st.text_area("", value=current_data['transcription'], height=100, key="transcription_area")
        
        # Emotion
        st.subheader("Detected Emotion")
        st.info(f"🎭 Predicted emotion: **{current_data['emotion']}**")
        
        # Convert string representation of dict back to actual dict
        try:
            import ast
            probs = ast.literal_eval(current_data['probabilities'])
            display_emotion_chart(probs)
        except Exception as e:
            st.error(f"Error parsing probabilities: {str(e)}")
            st.write(f"Raw probabilities: {current_data['probabilities']}")
    else:
        st.info("Record or upload audio to see results")



# Footer
st.markdown("---")
st.caption("Emotional Report Analyzer - Processes audio in 10-second segments and predicts emotions")