jfforero commited on
Commit
2f2ec24
·
verified ·
1 Parent(s): a585b58

first commit

Browse files
Files changed (1) hide show
  1. app.py +423 -0
app.py ADDED
@@ -0,0 +1,423 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import pyvista as pv
3
+ from pyvista import examples
4
+ import numpy as np
5
+ import librosa
6
+ import requests
7
+ from io import BytesIO
8
+ from PIL import Image
9
+ import os
10
+ from tensorflow.keras.models import load_model
11
+ from faster_whisper import WhisperModel
12
+ import random
13
+ from textblob import TextBlob
14
+ import torch
15
+ import scipy.io.wavfile
16
+ from transformers import AutoProcessor, MusicgenForConditionalGeneration
17
+ import tempfile
18
+ import base64
19
+ import plotly.graph_objects as go
20
+ from plotly.subplots import make_subplots
21
+ import soundfile as sf
22
+ from pydub import AudioSegment
23
+ import math
24
+ import json
25
+
26
+ # Load the emotion prediction model
27
+ def load_emotion_model(model_path):
28
+ try:
29
+ model = load_model(model_path)
30
+ print("Emotion model loaded successfully")
31
+ return model
32
+ except Exception as e:
33
+ print("Error loading emotion prediction model:", e)
34
+ return None
35
+
36
+ model_path = 'mymodel_SER_LSTM_RAVDESS.h5'
37
+ model = load_emotion_model(model_path)
38
+
39
+ # Initialize WhisperModel
40
+ model_size = "small"
41
+ model2 = WhisperModel(model_size, device="cpu", compute_type="int8")
42
+
43
+ # Load MusicGen model
44
+ def load_musicgen_model():
45
+ try:
46
+ device = "cuda" if torch.cuda.is_available() else "cpu"
47
+ processor = AutoProcessor.from_pretrained("facebook/musicgen-small")
48
+ music_model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
49
+ music_model.to(device)
50
+ print("MusicGen model loaded successfully")
51
+ return processor, music_model, device
52
+ except Exception as e:
53
+ print("Error loading MusicGen model:", e)
54
+ return None, None, None
55
+
56
+ processor, music_model, device = load_musicgen_model()
57
+
58
+ # Function to chunk audio into 5-second segments
59
+ def chunk_audio(audio_path, chunk_duration=5):
60
+ """Split audio into 5-second chunks and return list of chunk file paths"""
61
+ try:
62
+ # Load audio file
63
+ audio = AudioSegment.from_file(audio_path)
64
+ duration_ms = len(audio)
65
+ chunk_ms = chunk_duration * 1000
66
+
67
+ chunks = []
68
+ chunk_files = []
69
+
70
+ # Calculate number of chunks
71
+ num_chunks = math.ceil(duration_ms / chunk_ms)
72
+
73
+ for i in range(num_chunks):
74
+ start_ms = i * chunk_ms
75
+ end_ms = min((i + 1) * chunk_ms, duration_ms)
76
+
77
+ # Extract chunk
78
+ chunk = audio[start_ms:end_ms]
79
+ chunks.append(chunk)
80
+
81
+ # Save chunk to temporary file
82
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
83
+ chunk.export(tmp_file.name, format="wav")
84
+ chunk_files.append(tmp_file.name)
85
+
86
+ return chunk_files, num_chunks
87
+
88
+ except Exception as e:
89
+ print("Error chunking audio:", e)
90
+ # Return original file as single chunk if chunking fails
91
+ return [audio_path], 1
92
+
93
+ # Function to transcribe audio
94
+ def transcribe(wav_filepath):
95
+ try:
96
+ segments, _ = model2.transcribe(wav_filepath, beam_size=5)
97
+ return "".join([segment.text for segment in segments])
98
+ except Exception as e:
99
+ print("Error transcribing audio:", e)
100
+ return "Transcription failed"
101
+
102
+ # Function to extract MFCC features from audio
103
+ def extract_mfcc(wav_file_name):
104
+ try:
105
+ y, sr = librosa.load(wav_file_name)
106
+ mfccs = np.mean(librosa.feature.mfcc(y=y, sr=sr, n_mfcc=40).T, axis=0)
107
+ return mfccs
108
+ except Exception as e:
109
+ print("Error extracting MFCC features:", e)
110
+ return None
111
+
112
+ # Emotions dictionary
113
+ emotions = {0: 'neutral', 1: 'calm', 2: 'happy', 3: 'sad', 4: 'angry', 5: 'fearful', 6: 'disgust', 7: 'surprised'}
114
+
115
+ # Function to predict emotion from audio
116
+ def predict_emotion_from_audio(wav_filepath):
117
+ try:
118
+ if model is None:
119
+ return "Model not loaded"
120
+
121
+ test_point = extract_mfcc(wav_filepath)
122
+ if test_point is not None:
123
+ test_point = np.reshape(test_point, newshape=(1, 40, 1))
124
+ predictions = model.predict(test_point)
125
+ predicted_emotion_label = np.argmax(predictions[0])
126
+ return emotions.get(predicted_emotion_label, "Unknown emotion")
127
+ else:
128
+ return "Error: Unable to extract features"
129
+ except Exception as e:
130
+ print("Error predicting emotion:", e)
131
+ return "Prediction error"
132
+
133
+ # Function to analyze sentiment from text
134
+ def analyze_sentiment(text):
135
+ try:
136
+ if not text or text.strip() == "":
137
+ return "neutral", 0.0
138
+
139
+ analysis = TextBlob(text)
140
+ polarity = analysis.sentiment.polarity
141
+
142
+ if polarity > 0.1:
143
+ sentiment = "positive"
144
+ elif polarity < -0.1:
145
+ sentiment = "negative"
146
+ else:
147
+ sentiment = "neutral"
148
+
149
+ return sentiment, polarity
150
+ except Exception as e:
151
+ print("Error analyzing sentiment:", e)
152
+ return "neutral", 0.0
153
+
154
+ # Function to get image prompt based on sentiment
155
+ def get_image_prompt(sentiment, transcribed_text, chunk_idx, total_chunks):
156
+ base_prompt = f"Chunk {chunk_idx+1}/{total_chunks}: "
157
+
158
+ if sentiment == "positive":
159
+ return base_prompt + f"Generate a vibrant, uplifting equirectangular 360 image texture with bright colors, joyful atmosphere, and optimistic vibes representing: [{transcribed_text}]. The scene should evoke happiness and positivity."
160
+
161
+ elif sentiment == "negative":
162
+ return base_prompt + f"Generate a moody, dramatic equirectangular 360 image texture with dark tones, intense atmosphere, and emotional depth representing: [{transcribed_text}]. The scene should convey melancholy and intensity."
163
+
164
+ else: # neutral
165
+ return base_prompt + f"Generate a balanced, serene equirectangular 360 image texture with harmonious colors, peaceful atmosphere, and calm vibes representing: [{transcribed_text}]. The scene should evoke tranquility and balance."
166
+
167
+ # Function to get music prompt based on emotion
168
+ def get_music_prompt(emotion, transcribed_text, chunk_idx, total_chunks):
169
+ base_prompt = f"Chunk {chunk_idx+1}/{total_chunks}: "
170
+
171
+ emotion_prompts = {
172
+ 'neutral': f"Create ambient, background music with neutral tones, subtle melodies, and unobtrusive atmosphere that complements: {transcribed_text}. The music should be calm and balanced.",
173
+ 'calm': f"Generate soothing, peaceful music with gentle melodies, soft instrumentation, and relaxing vibes that represents: {transcribed_text}. The music should evoke tranquility and serenity.",
174
+ 'happy': f"Create joyful, upbeat music with cheerful melodies, bright instrumentation, and energetic rhythms that celebrates: {transcribed_text}. The music should evoke happiness and positivity.",
175
+ 'sad': f"Generate emotional, melancholic music with poignant melodies, soft strings, and heartfelt atmosphere that reflects: {transcribed_text}. The music should evoke sadness and reflection.",
176
+ 'angry': f"Create intense, powerful music with driving rhythms, aggressive instrumentation, and strong dynamics that expresses: {transcribed_text}. The music should evoke anger and intensity.",
177
+ 'fearful': f"Generate suspenseful, tense music with eerie melodies, atmospheric sounds, and unsettling vibes that represents: {transcribed_text}. The music should evoke fear and anticipation.",
178
+ 'disgust': f"Create dark, unsettling music with dissonant harmonies, unusual sounds, and uncomfortable atmosphere that reflects: {transcribed_text}. The music should evoke discomfort and unease.",
179
+ 'surprised': f"Generate dynamic, unexpected music with sudden changes, playful melodies, and surprising elements that represents: {transcribed_text}. The music should evoke surprise and wonder."
180
+ }
181
+
182
+ return base_prompt + emotion_prompts.get(emotion.lower(),
183
+ f"Create background music with {emotion} atmosphere that represents: {transcribed_text}")
184
+
185
+ # Function to generate music with MusicGen (using acoustic emotion prediction)
186
+ def generate_music(transcribed_text, emotion_prediction, chunk_idx, total_chunks):
187
+ try:
188
+ if processor is None or music_model is None:
189
+ return None
190
+
191
+ # Get specific prompt based on emotion
192
+ prompt = get_music_prompt(emotion_prediction, transcribed_text, chunk_idx, total_chunks)
193
+
194
+ # Limit prompt length to avoid model issues
195
+ if len(prompt) > 200:
196
+ prompt = prompt[:200] + "..."
197
+
198
+ inputs = processor(
199
+ text=[prompt],
200
+ padding=True,
201
+ return_tensors="pt",
202
+ ).to(device)
203
+
204
+ # Generate audio
205
+ audio_values = music_model.generate(**inputs, max_new_tokens=512)
206
+
207
+ # Convert to numpy array and sample rate
208
+ sampling_rate = music_model.config.audio_encoder.sampling_rate
209
+ audio_data = audio_values[0, 0].cpu().numpy()
210
+
211
+ # Normalize audio data
212
+ audio_data = audio_data / np.max(np.abs(audio_data))
213
+
214
+ # Create a temporary file to save the audio
215
+ with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as tmp_file:
216
+ scipy.io.wavfile.write(tmp_file.name, rate=sampling_rate, data=audio_data)
217
+ return tmp_file.name
218
+
219
+ except Exception as e:
220
+ print("Error generating music:", e)
221
+ return None
222
+
223
+ # --- DeepAI Image Generation (Text2Img) ---
224
+ api_key = os.getenv("DeepAI_api_key")
225
+
226
+ def generate_image(sentiment_prediction, transcribed_text, chunk_idx, total_chunks):
227
+ try:
228
+ if not api_key:
229
+ # fallback white image if no API key
230
+ return Image.new('RGB', (1024, 512), color='white')
231
+
232
+ # Get specific prompt based on sentiment
233
+ prompt = get_image_prompt(sentiment_prediction, transcribed_text, chunk_idx, total_chunks)
234
+
235
+ # Make request to DeepAI text2img API
236
+ response = requests.post(
237
+ "https://api.deepai.org/api/text2img",
238
+ data={
239
+ 'text': prompt,
240
+ 'width': 1024,
241
+ 'height': 512,
242
+ 'image_generator_version': 'hd'
243
+ },
244
+ headers={'api-key': api_key}
245
+ )
246
+
247
+ data = response.json()
248
+ if 'output_url' in data:
249
+ # Download the generated image
250
+ img_resp = requests.get(data['output_url'])
251
+ return Image.open(BytesIO(img_resp.content))
252
+ else:
253
+ print("Error in DeepAI response:", data)
254
+ # Return a fallback image
255
+ return Image.new('RGB', (1024, 512), color='white')
256
+ except Exception as e:
257
+ print("Error generating image:", e)
258
+ # Return a fallback image
259
+ return Image.new('RGB', (1024, 512), color='white')
260
+
261
+ # Function to process a single chunk
262
+ def process_chunk(chunk_path, chunk_idx, total_chunks):
263
+ try:
264
+ # Get acoustic emotion prediction (for music)
265
+ emotion_prediction = predict_emotion_from_audio(chunk_path)
266
+
267
+ # Get transcribed text
268
+ transcribed_text = transcribe(chunk_path)
269
+
270
+ # Analyze sentiment of transcribed text (for image)
271
+ sentiment, polarity = analyze_sentiment(transcribed_text)
272
+
273
+ # Generate image using SENTIMENT analysis with specific prompt
274
+ image = generate_image(sentiment, transcribed_text, chunk_idx, total_chunks)
275
+
276
+ # Generate music using ACOUSTIC EMOTION prediction with specific prompt
277
+ music_path = generate_music(transcribed_text, emotion_prediction, chunk_idx, total_chunks)
278
+
279
+
280
+ #'sentiment': f"Sentiment: {sentiment} (Polarity: {polarity:.2f})",
281
+ return {
282
+ 'chunk_index': chunk_idx + 1,
283
+ 'emotion': emotion_prediction,
284
+ 'transcription': transcribed_text,
285
+ 'sentiment': sentiment,
286
+ 'image': image,
287
+ 'music': music_path
288
+ }
289
+ except Exception as e:
290
+ print(f"Error processing chunk {chunk_idx + 1}:", e)
291
+ # Return a fallback result with all required keys
292
+ return {
293
+ 'chunk_index': chunk_idx + 1,
294
+ 'emotion': "Error",
295
+ 'transcription': "Transcription failed",
296
+ 'sentiment': "Sentiment: error",
297
+ 'image': Image.new('RGB', (1024, 512), color='white'),
298
+ 'music': None
299
+ }
300
+
301
+ # Function to get predictions for all chunks
302
+ def get_predictions(audio_input):
303
+ # Chunk the audio into 5-second segments
304
+ chunk_files, total_chunks = chunk_audio(audio_input, chunk_duration=5)
305
+
306
+ results = []
307
+
308
+ # Process each chunk
309
+ for i, chunk_path in enumerate(chunk_files):
310
+ print(f"Processing chunk {i+1}/{total_chunks}")
311
+ result = process_chunk(chunk_path, i, total_chunks)
312
+ results.append(result)
313
+
314
+ # Clean up temporary chunk files
315
+ for chunk_path in chunk_files:
316
+ try:
317
+ if chunk_path != audio_input: # Don't delete original input file
318
+ os.unlink(chunk_path)
319
+ except:
320
+ pass
321
+
322
+ return results
323
+
324
+ # ... (your existing imports remain the same)
325
+
326
+ # Create the Gradio interface with proper output handling
327
+ with gr.Blocks(title="Affective Virtual Environments - Chunked Processing") as interface:
328
+ gr.Markdown("# Affective Virtual Environments")
329
+ gr.Markdown("Create an AVE using your voice. Audio is split into 5-second chunks, with separate predictions and generations for each segment.")
330
+
331
+ with gr.Row():
332
+ audio_input = gr.Audio(label="Input Audio", type="filepath", sources=["microphone", "upload"])
333
+ process_btn = gr.Button("Process Audio", variant="primary")
334
+
335
+ # Add a loading indicator
336
+ loading_indicator = gr.HTML("""
337
+ <div id="loading" style="display: none; text-align: center; margin: 20px;">
338
+ <p style="font-size: 18px; color: #4a4a4a;">Processing audio chunks...</p>
339
+ <div style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite; margin: 0 auto;"></div>
340
+ <style>@keyframes spin {0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }}</style>
341
+ </div>
342
+ """)
343
+
344
+ # Create output components for each chunk type
345
+ output_containers = []
346
+ group_components = [] # Store group components separately
347
+
348
+ # We'll create up to 10 chunk slots (adjust as needed)
349
+ for i in range(10):
350
+ with gr.Group(visible=False) as chunk_group:
351
+ gr.Markdown(f"### Chunk {i+1} Results")
352
+ with gr.Row():
353
+ emotion_output = gr.Label(label="Acoustic Emotion Prediction")
354
+ transcription_output = gr.Label(label="Transcribed Text")
355
+ sentiment_output = gr.Label(label="Sentiment Analysis")
356
+ with gr.Row():
357
+ image_output = gr.Image(label="Generated Equirectangular Image")
358
+ audio_output = gr.Audio(label="Generated Music")
359
+ gr.HTML("<hr style='margin: 20px 0; border: 1px solid #ccc;'>")
360
+
361
+ group_components.append(chunk_group) # Store the group component
362
+ output_containers.append({
363
+ 'transcription': transcription_output,
364
+ 'emotion': emotion_output,
365
+ 'sentiment': sentiment_output,
366
+ 'image': image_output,
367
+ 'music': audio_output
368
+ })
369
+
370
+ def process_and_display(audio_input):
371
+ # Show loading indicator
372
+ yield [gr.HTML("""
373
+ <div style="text-align: center; margin: 20px;">
374
+ <p style="font-size: 18px; color: #4a4a4a;">Processing audio chunks...</p>
375
+ <div style="border: 4px solid #f3f3f3; border-top: 4px solid #3498db; border-radius: 50%; width: 30px; height: 30px; animation: spin 2s linear infinite; margin: 0 auto;"></div>
376
+ <style>@keyframes spin {0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); }}</style>
377
+ </div>
378
+ """)] + [gr.Group(visible=False)] * len(group_components) + [None] * (len(output_containers) * 5)
379
+
380
+ results = get_predictions(audio_input)
381
+
382
+ # Initialize outputs list
383
+ outputs = []
384
+ group_visibility = []
385
+
386
+ # Process each result
387
+ for i, result in enumerate(results):
388
+ if i < len(output_containers):
389
+ group_visibility.append(gr.Group(visible=True))
390
+ outputs.extend([
391
+ result['transcription'],
392
+ result['emotion'],
393
+ result['sentiment'],
394
+ result['image'],
395
+ result['music']
396
+ ])
397
+ else:
398
+ # If we have more results than containers, just extend with None
399
+ group_visibility.append(gr.Group(visible=False))
400
+ outputs.extend([None] * 5)
401
+
402
+ # Hide remaining containers
403
+ for i in range(len(results), len(output_containers)):
404
+ group_visibility.append(gr.Group(visible=False))
405
+ outputs.extend([None] * 5)
406
+
407
+ # Hide loading indicator and show results
408
+ yield [gr.HTML("")] + group_visibility + outputs
409
+
410
+ # Set up the button click
411
+ process_btn.click(
412
+ fn=process_and_display,
413
+ inputs=audio_input,
414
+ outputs=[loading_indicator] + group_components + [comp for container in output_containers for comp in [
415
+ container['transcription'],
416
+ container['emotion'],
417
+ container['sentiment'],
418
+ container['image'],
419
+ container['music']
420
+ ]]
421
+ )
422
+
423
+ interface.launch()