Anita-19 commited on
Commit
b10cf5d
Β·
verified Β·
1 Parent(s): b2af844
Files changed (1) hide show
  1. app.py +323 -0
app.py ADDED
@@ -0,0 +1,323 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from google.colab import drive
2
+ drive.mount('/content/drive')
3
+
4
+ """Install Dependencies"""
5
+
6
+ pip install transformers librosa torch soundfile numba numpy TTS datasets gradio protobuf==3.20.3
7
+
8
+ """Emotion Detection (Using Text Dataset)
9
+
10
+ """
11
+
12
+ !pip install --upgrade numpy tensorflow transformers TTS
13
+
14
+ !pip freeze > requirements.txt
15
+
16
+ from transformers import pipeline
17
+
18
+ # Load pre-trained model for emotion detection
19
+ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
20
+
21
+ def detect_emotion(text):
22
+ result = emotion_classifier(text)
23
+ emotion = result[0]['label']
24
+ confidence = result[0]['score']
25
+ return emotion, confidence
26
+
27
+ # Example usage
28
+ text = "I am feeling excited today!"
29
+ emotion, confidence = detect_emotion(text)
30
+ print(f"Detected Emotion: {emotion}, Confidence: {confidence}")
31
+
32
+ """Emotion-Aware TTS (Using Tacotron 2 or Similar)"""
33
+
34
+ import torch
35
+ import librosa
36
+ import numpy as np
37
+ from TTS.api import TTS # Using Coqui TTS for simplicity
38
+
39
+ # Load TTS model and vocoder automatically during initialization
40
+ tts_model = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC")
41
+
42
+
43
+ def generate_emotional_speech(text, emotion):
44
+ # Map emotion to voice modulation parameters (pitch, speed)
45
+ emotion_settings = {
46
+ "happy": {"pitch": 1.3, "speed": 1.2}, # Upbeat and energetic
47
+ "joy": {"pitch": 1.2, "speed": 1.1}, # Less exaggerated than 'happy'
48
+ "surprise": {"pitch": 1.5, "speed": 1.3}, # Excitement with high pitch and fast speech
49
+ "sad": {"pitch": 0.8, "speed": 0.9}, # Subdued, slow tone
50
+ "angry": {"pitch": 1.6, "speed": 1.4}, # Intense and sharp
51
+ "fear": {"pitch": 1.2, "speed": 0.95}, # Tense and slightly slow
52
+ "disgust": {"pitch": 0.9, "speed": 0.95}, # Low and deliberate
53
+ "shame": {"pitch": 0.8, "speed": 0.85}, # Quiet, subdued tone
54
+ "neutral": {"pitch": 1.0, "speed": 1.0}, # Baseline conversational tone
55
+ }
56
+
57
+
58
+
59
+ # Retrieve pitch and speed based on detected emotion
60
+ settings = emotion_settings.get(emotion, {"pitch": 1.0, "speed": 1.0})
61
+ # Generate speech with the TTS model
62
+ # Instead of directly passing speed and pitch to tts_to_file,
63
+ # We adjust the text to simulate the effect. This is a temporary solution.
64
+ # You might need to fine-tune these adjustments or consider a different TTS library
65
+ # with better control over speech parameters.
66
+ adjusted_text = text
67
+ if settings['speed'] > 1.0:
68
+ adjusted_text = adjusted_text.replace(" ", ".") # Simulate faster speech
69
+ elif settings['speed'] < 1.0:
70
+ adjusted_text = adjusted_text.replace(" ", "...") # Simulate slower speech
71
+
72
+ # Explicitly specify the output path
73
+ audio_path = "output.wav" # Or any desired filename
74
+ tts_model.tts_to_file(text=adjusted_text, file_path=audio_path) # Pass file_path argument
75
+ return audio_path
76
+
77
+ # Example usage
78
+ emotion = "happy"
79
+ output_audio = generate_emotional_speech("Welcome to the smart library!", emotion)
80
+ print(f"Generated Speech Saved At: {output_audio}")
81
+
82
+ """Integrating the Workflow"""
83
+
84
+ from IPython.display import Audio, display
85
+
86
+ def emotion_aware_tts_pipeline(text):
87
+ emotion, confidence = detect_emotion(text)
88
+ print(f"Emotion Detected: {emotion} with Confidence: {confidence:.2f}")
89
+
90
+ audio_path = generate_emotional_speech(text, emotion)
91
+ print(f"Audio Generated: {audio_path}")
92
+
93
+ # Display and play the audio
94
+ display(Audio(audio_path, autoplay=True))
95
+
96
+ # Example usage
97
+ emotion_aware_tts_pipeline("I can’t stooop smiiiling, everything feels perrrfect!")
98
+
99
+ """Fine-tuning the Emotion Detection Model"""
100
+
101
+ import os
102
+ os.environ["WANDB_DISABLED"] = "true"
103
+
104
+ from google.colab import drive
105
+ from transformers import Trainer, TrainingArguments, AutoModelForSequenceClassification, AutoTokenizer
106
+ from datasets import load_dataset
107
+
108
+ # Load dataset
109
+ dataset = load_dataset('/content/drive/MyDrive/Emotion_Model') #path_to_your_dataset
110
+
111
+ # Preprocess data
112
+ tokenizer = AutoTokenizer.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion")
113
+
114
+ # Define a function to map emotion labels to integers
115
+ def map_emotion_to_int(example):
116
+ # Assuming your dataset has an 'emotion' column with string labels
117
+ # Replace this with your actual emotion labels and their corresponding integers
118
+ # **Change 'emotion' to the actual column name in your dataset**
119
+ emotion_mapping = {
120
+ "neutral": 0,
121
+ "joy": 1,
122
+ "sad": 2,
123
+ "anger": 3,
124
+ "fear": 4,
125
+ "surprise": 5,
126
+ "disgust": 6,
127
+ "shame": 7,
128
+ }
129
+ # Assuming your emotion column is named 'label'
130
+ # example['label'] = emotion_mapping[example['emotion']] # Create a new 'label' column with integer values
131
+ example['label'] = emotion_mapping.get(example['label'], -1) # If the label is not in the emotion mapping then we set it to -1. We can later filter these examples out
132
+ return example
133
+
134
+
135
+ def preprocess_data(example):
136
+ return tokenizer(example['text'], truncation=True, padding=True, max_length=512) # Added max_length for consistency
137
+
138
+
139
+ # Apply emotion mapping before tokenization
140
+ dataset = dataset.map(map_emotion_to_int, batched=False)
141
+ # **Keep the 'label' column for training. Only remove 'text'**
142
+ # Filter out examples with labels not in emotion_mapping (-1)
143
+ dataset = dataset.filter(lambda example: example['label'] != -1) # Filter out examples with label -1
144
+ tokenized_dataset = dataset.map(preprocess_data, batched=True, remove_columns=['text'])
145
+
146
+ # Load model
147
+ # model = AutoModelForSequenceClassification.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion", num_labels=8)
148
+
149
+ # Load model with ignore_mismatched_sizes=True
150
+ model = AutoModelForSequenceClassification.from_pretrained(
151
+ "bhadresh-savani/distilbert-base-uncased-emotion",
152
+ num_labels=8,
153
+ ignore_mismatched_sizes=True
154
+ )
155
+
156
+ # Training arguments
157
+ training_args = TrainingArguments(
158
+ output_dir="./results", # Directory for model checkpoints and logs
159
+ evaluation_strategy="epoch", # Evaluate after every epoch
160
+ learning_rate=5e-5, # Start with 5e-5 (slightly higher than default 2e-5)
161
+ per_device_train_batch_size=16, # Use 16 for balance between memory usage and training speed
162
+ gradient_accumulation_steps=4, # Accumulate gradients to simulate larger batch size
163
+ num_train_epochs=5, # Train for 4-5 epochs (typically enough for fine-tuning)
164
+ weight_decay=0.01, # Regularization to avoid overfitting
165
+ save_strategy="epoch", # Save checkpoints after each epoch
166
+ logging_dir="./logs", # Directory for logging
167
+ logging_steps=100, # Log every 100 steps
168
+ warmup_steps=500, # Gradual learning rate increase for the first 500 steps
169
+ save_total_limit=3, # Keep only the last 3 checkpoints
170
+ fp16=True, # Enable mixed precision for faster training if GPU supports it
171
+ load_best_model_at_end=True, # Load the best model at the end of training
172
+ metric_for_best_model="eval_loss", # Use evaluation loss to select the best model
173
+ greater_is_better=False, # Lower loss is better
174
+ )
175
+
176
+
177
+ # Train model
178
+ trainer = Trainer(
179
+ model=model,
180
+ args=training_args,
181
+ train_dataset=tokenized_dataset['train'],
182
+ eval_dataset=tokenized_dataset['validation'],
183
+ tokenizer=tokenizer,
184
+ )
185
+
186
+ trainer.train()
187
+
188
+ # Save the model and tokenizer to Google Drive
189
+ model_save_path = "/content/drive/My Drive/emotion_detection_model1"
190
+ tokenizer_save_path = "/content/drive/My Drive/emotion_detection_model1"
191
+
192
+ # Save the fine-tuned model
193
+ model.save_pretrained(model_save_path)
194
+ tokenizer.save_pretrained(tokenizer_save_path)
195
+
196
+ print("Model and tokenizer saved to Google Drive.")
197
+
198
+ """Reload the Fine-Tuned Model"""
199
+
200
+ from transformers import AutoModelForSequenceClassification, AutoTokenizer
201
+
202
+ # Mount Google Drive
203
+ from google.colab import drive
204
+ drive.mount('/content/drive')
205
+
206
+ # Path to the saved model and tokenizer
207
+ model_save_path = "/content/drive/My Drive/emotion_detection_model"
208
+ tokenizer_save_path = "/content/drive/My Drive/emotion_detection_model"
209
+
210
+ # Load the fine-tuned model and tokenizer
211
+ model = AutoModelForSequenceClassification.from_pretrained(model_save_path)
212
+ tokenizer = AutoTokenizer.from_pretrained(tokenizer_save_path)
213
+
214
+ print("Fine-tuned model and tokenizer loaded successfully.")
215
+
216
+ """Test the Reloaded Model"""
217
+
218
+ from transformers import pipeline
219
+
220
+ # Create a text classification pipeline with the loaded model
221
+ emotion_classifier = pipeline("text-classification", model=model, tokenizer=tokenizer)
222
+
223
+ # Test with a sample text
224
+ text = "I feel so upset today!"
225
+ result = emotion_classifier(text)
226
+ print(result)
227
+
228
+ """Fine-tuning the TTS System"""
229
+
230
+ from TTS.api import TTS
231
+ from TTS.utils.audio import AudioProcessor
232
+ from TTS.tts.models.tacotron2 import Tacotron2
233
+ import torch
234
+
235
+ # Load pre-trained model
236
+ #model = Tacotron2.load_model("tts_models/en/ljspeech/tacotron2-DDC")
237
+ tts = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC") # Use TTS for model loading
238
+
239
+ # Access the Tacotron2 model from the TTS object
240
+ model = tts.synthesizer.tts_model
241
+
242
+ # Fine-tuning parameters
243
+ model.config.dataset_path = "/content/drive/MyDrive/RAVDESS"
244
+ model.config.num_epochs = 10
245
+
246
+ # Train
247
+ model.train()
248
+
249
+ # Define the save path on Google Drive
250
+ save_path = "/content/drive/My Drive/fine_tuned_tacotron2.pth"
251
+
252
+ # Save the model's state dictionary using torch.save
253
+ torch.save(model.state_dict(), save_path)
254
+
255
+ """Set up the Gradio interface"""
256
+
257
+ import gradio as gr
258
+ from transformers import pipeline
259
+ from TTS.api import TTS
260
+
261
+ # Load pre-trained emotion detection model
262
+ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
263
+
264
+ # Load TTS model
265
+ tts_model = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC")
266
+
267
+ # Emotion-specific settings for pitch and speed
268
+ emotion_settings = {
269
+ "joy": {"pitch": 1.2, "speed": 1.1},
270
+ "sadness": {"pitch": 0.8, "speed": 0.9},
271
+ "anger": {"pitch": 1.0, "speed": 1.2},
272
+ "fear": {"pitch": 0.9, "speed": 1.0},
273
+ "surprise": {"pitch": 1.3, "speed": 1.2},
274
+ "neutral": {"pitch": 1.0, "speed": 1.0},
275
+ }
276
+
277
+ # Function to process text or file input and generate audio
278
+ def emotion_aware_tts_pipeline(input_text=None, file_input=None):
279
+ try:
280
+ # Get text from input or file
281
+ if file_input:
282
+ with open(file_input.name, 'r') as file:
283
+ input_text = file.read()
284
+
285
+ if input_text:
286
+ # Detect emotion
287
+ emotion_data = emotion_classifier(input_text)[0]
288
+ emotion = emotion_data['label']
289
+ confidence = emotion_data['score']
290
+
291
+ # Adjust pitch and speed
292
+ settings = emotion_settings.get(emotion.lower(), {"pitch": 1.0, "speed": 1.0})
293
+ pitch = settings["pitch"]
294
+ speed = settings["speed"]
295
+
296
+ # Generate audio
297
+ audio_path = "output.wav"
298
+ tts_model.tts_to_file(text=input_text, file_path=audio_path, speed=speed, pitch=pitch)
299
+
300
+ return f"Detected Emotion: {emotion} (Confidence: {confidence:.2f})", audio_path
301
+ else:
302
+ return "Please provide input text or file", None
303
+ except Exception as e:
304
+ # Return error message if something goes wrong
305
+ return f"Error: {str(e)}", None
306
+
307
+ # Define Gradio interface
308
+ iface = gr.Interface(
309
+ fn=emotion_aware_tts_pipeline,
310
+ inputs=[
311
+ gr.Textbox(label="Input Text", placeholder="Enter text here"),
312
+ gr.File(label="Upload a Text File")
313
+ ],
314
+ outputs=[
315
+ gr.Textbox(label="Detected Emotion"),
316
+ gr.Audio(label="Generated Audio")
317
+ ],
318
+ title="Emotion-Aware Text-to-Speech",
319
+ description="Input text or upload a text file to detect the emotion and generate audio with emotion-aware modulation."
320
+ )
321
+
322
+ # Launch Gradio interface
323
+ iface.launch()