Anita-19 commited on
Commit
8573520
·
verified ·
1 Parent(s): 8b40da9

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +134 -52
main.py CHANGED
@@ -1,19 +1,24 @@
1
  from google.colab import drive
2
  drive.mount('/content/drive')
3
 
4
- # Install Dependencies
5
- !pip install transformers librosa torch soundfile numba numpy TTS datasets gradio protobuf==3.20.3
 
 
 
 
 
6
 
7
- # Emotion Detection (Using Text Dataset)
8
  !pip install --upgrade numpy tensorflow transformers TTS
9
 
 
 
10
  from transformers import pipeline
11
 
12
- # Initialize the emotion classifier pipeline globally
13
  emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
14
 
15
  def detect_emotion(text):
16
- # Ensure the emotion_classifier is used properly
17
  result = emotion_classifier(text)
18
  emotion = result[0]['label']
19
  confidence = result[0]['score']
@@ -24,7 +29,8 @@ text = "I am feeling excited today!"
24
  emotion, confidence = detect_emotion(text)
25
  print(f"Detected Emotion: {emotion}, Confidence: {confidence}")
26
 
27
- # Emotion-Aware TTS (Using Tacotron 2 or Similar)
 
28
  import torch
29
  import librosa
30
  import numpy as np
@@ -33,14 +39,7 @@ from TTS.api import TTS # Using Coqui TTS for simplicity
33
  # Load TTS model and vocoder automatically during initialization
34
  tts_model = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC")
35
 
36
- # HiFi-GAN Vocoder (Ensure you have the model or download it)
37
- from TTS.utils.generic_utils import download_model
38
- from TTS.vocoder.hifigan import HIFIGAN
39
-
40
- vocoder_model = download_model("hifigan_ljspeech")
41
- vocoder = HIFIGAN(vocoder_model)
42
 
43
- # Emotion-specific settings for pitch, speed, and prosody
44
  emotion_settings = {
45
  "neutral": {"pitch": 1.0, "speed": 1.0, "prosody": 0.5}, # Neutral tone
46
  "joy": {"pitch": 1.3, "speed": 1.2, "prosody": 1.5}, # Upbeat, energetic
@@ -52,18 +51,29 @@ emotion_settings = {
52
  "shame": {"pitch": 0.8, "speed": 0.85, "prosody": 0.5}, # Quiet, subdued tone
53
  }
54
 
55
- def adjust_pitch_and_speed(audio_path, pitch_factor, speed_factor):
56
- # Load audio file
57
- y, sr = librosa.load(audio_path)
58
 
 
 
 
 
 
 
59
  # Adjust pitch
60
- y_pitch = librosa.effects.pitch_shift(y, sr, n_steps=pitch_factor)
61
-
62
- # Adjust speed
63
- y_speed = librosa.effects.time_stretch(y_pitch, speed_factor)
64
-
 
 
 
 
 
 
65
  # Save the adjusted audio
66
- sf.write(audio_path, y_speed, sr)
 
 
67
 
68
  def generate_emotional_speech(text, emotion):
69
  # Retrieve pitch, speed, and prosody based on detected emotion
@@ -101,9 +111,12 @@ def emotion_aware_tts_pipeline(text):
101
  # Example usage
102
  emotion_aware_tts_pipeline("I can’t stooop smiiiling, everything feels perrrfect!")
103
 
104
- # Fine-tuning the Emotion Detection Model (if needed)
 
105
  import os
106
  os.environ["WANDB_DISABLED"] = "true"
 
 
107
  from transformers import Trainer, TrainingArguments, AutoModelForSequenceClassification, AutoTokenizer
108
  from datasets import load_dataset
109
 
@@ -115,6 +128,9 @@ tokenizer = AutoTokenizer.from_pretrained("bhadresh-savani/distilbert-base-uncas
115
 
116
  # Define a function to map emotion labels to integers
117
  def map_emotion_to_int(example):
 
 
 
118
  emotion_mapping = {
119
  "neutral": 0,
120
  "joy": 1,
@@ -125,18 +141,27 @@ def map_emotion_to_int(example):
125
  "disgust": 6,
126
  "shame": 7,
127
  }
128
- example['label'] = emotion_mapping.get(example['label'], -1)
 
 
129
  return example
130
 
 
131
  def preprocess_data(example):
132
- return tokenizer(example['text'], truncation=True, padding=True, max_length=512)
 
133
 
134
  # Apply emotion mapping before tokenization
135
  dataset = dataset.map(map_emotion_to_int, batched=False)
136
- dataset = dataset.filter(lambda example: example['label'] != -1)
 
 
137
  tokenized_dataset = dataset.map(preprocess_data, batched=True, remove_columns=['text'])
138
 
139
  # Load model
 
 
 
140
  model = AutoModelForSequenceClassification.from_pretrained(
141
  "bhadresh-savani/distilbert-base-uncased-emotion",
142
  num_labels=8,
@@ -145,24 +170,25 @@ model = AutoModelForSequenceClassification.from_pretrained(
145
 
146
  # Training arguments
147
  training_args = TrainingArguments(
148
- output_dir="./results",
149
- evaluation_strategy="epoch",
150
- learning_rate=5e-5,
151
- per_device_train_batch_size=16,
152
- gradient_accumulation_steps=4,
153
- num_train_epochs=5,
154
- weight_decay=0.01,
155
- save_strategy="epoch",
156
- logging_dir="./logs",
157
- logging_steps=100,
158
- warmup_steps=500,
159
- save_total_limit=3,
160
- fp16=True,
161
- load_best_model_at_end=True,
162
- metric_for_best_model="eval_loss",
163
- greater_is_better=False,
164
  )
165
 
 
166
  # Train model
167
  trainer = Trainer(
168
  model=model,
@@ -174,15 +200,18 @@ trainer = Trainer(
174
 
175
  trainer.train()
176
 
177
- # Save the model and tokenizer
178
  model_save_path = "/content/drive/My Drive/emotion_detection_model1"
179
  tokenizer_save_path = "/content/drive/My Drive/emotion_detection_model1"
 
 
180
  model.save_pretrained(model_save_path)
181
  tokenizer.save_pretrained(tokenizer_save_path)
182
 
183
  print("Model and tokenizer saved to Google Drive.")
184
 
185
- # Reload the Fine-Tuned Model
 
186
  from transformers import AutoModelForSequenceClassification, AutoTokenizer
187
 
188
  # Mount Google Drive
@@ -199,7 +228,8 @@ tokenizer = AutoTokenizer.from_pretrained(tokenizer_save_path)
199
 
200
  print("Fine-tuned model and tokenizer loaded successfully.")
201
 
202
- # Test the Reloaded Model
 
203
  from transformers import pipeline
204
 
205
  # Create a text classification pipeline with the loaded model
@@ -210,10 +240,62 @@ text = "I feel so upset today!"
210
  result = emotion_classifier(text)
211
  print(result)
212
 
213
- # Set up the Gradio interface
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
- def emotion_aware_tts_pipeline_gradio(input_text=None, file_input=None):
 
217
  try:
218
  # Get text from input or file
219
  if file_input:
@@ -233,11 +315,9 @@ def emotion_aware_tts_pipeline_gradio(input_text=None, file_input=None):
233
 
234
  # Generate audio
235
  audio_path = "output.wav"
236
- mel_spectrogram = tts_model.get_mel_spectrogram(input_text)
237
- audio = vocoder.decode(mel_spectrogram)
238
 
239
- # Post-processing: adjust pitch and speed
240
- adjust_pitch_and_speed(audio_path, pitch_factor=pitch, speed_factor=speed)
241
 
242
  return f"Detected Emotion: {emotion} (Confidence: {confidence:.2f})", audio_path
243
  else:
@@ -245,9 +325,11 @@ def emotion_aware_tts_pipeline_gradio(input_text=None, file_input=None):
245
  except Exception as e:
246
  return f"Error: {str(e)}", None
247
 
 
 
248
  # Define Gradio interface
249
  iface = gr.Interface(
250
- fn=emotion_aware_tts_pipeline_gradio,
251
  inputs=[
252
  gr.Textbox(label="Input Text", placeholder="Enter text here"),
253
  gr.File(label="Upload a Text File")
 
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']
 
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
 
39
  # Load TTS model and vocoder automatically during initialization
40
  tts_model = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC")
41
 
 
 
 
 
 
 
42
 
 
43
  emotion_settings = {
44
  "neutral": {"pitch": 1.0, "speed": 1.0, "prosody": 0.5}, # Neutral tone
45
  "joy": {"pitch": 1.3, "speed": 1.2, "prosody": 1.5}, # Upbeat, energetic
 
51
  "shame": {"pitch": 0.8, "speed": 0.85, "prosody": 0.5}, # Quiet, subdued tone
52
  }
53
 
 
 
 
54
 
55
+ import librosa
56
+ import soundfile as sf
57
+
58
+ def adjust_pitch(audio_path, pitch_factor):
59
+ # Load audio
60
+ y, sr = librosa.load(audio_path)
61
  # Adjust pitch
62
+ y_shifted = librosa.effects.pitch_shift(y, sr, n_steps=pitch_factor)
63
+ # Save adjusted audio
64
+ sf.write(audio_path, y_shifted, sr)
65
+
66
+ def adjust_speed(audio_path, speed_factor):
67
+ # Load the audio file
68
+ y, sr = librosa.load(audio_path)
69
+
70
+ # Adjust the speed (this alters the duration of the audio)
71
+ y_speeded = librosa.effects.time_stretch(y, speed_factor)
72
+
73
  # Save the adjusted audio
74
+ sf.write(audio_path, y_speeded, sr)
75
+
76
+
77
 
78
  def generate_emotional_speech(text, emotion):
79
  # Retrieve pitch, speed, and prosody based on detected emotion
 
111
  # Example usage
112
  emotion_aware_tts_pipeline("I can’t stooop smiiiling, everything feels perrrfect!")
113
 
114
+ """Fine-tuning the Emotion Detection Model"""
115
+
116
  import os
117
  os.environ["WANDB_DISABLED"] = "true"
118
+
119
+ from google.colab import drive
120
  from transformers import Trainer, TrainingArguments, AutoModelForSequenceClassification, AutoTokenizer
121
  from datasets import load_dataset
122
 
 
128
 
129
  # Define a function to map emotion labels to integers
130
  def map_emotion_to_int(example):
131
+ # Assuming your dataset has an 'emotion' column with string labels
132
+ # Replace this with your actual emotion labels and their corresponding integers
133
+ # *Change 'emotion' to the actual column name in your dataset*
134
  emotion_mapping = {
135
  "neutral": 0,
136
  "joy": 1,
 
141
  "disgust": 6,
142
  "shame": 7,
143
  }
144
+ # Assuming your emotion column is named 'label'
145
+ # example['label'] = emotion_mapping[example['emotion']] # Create a new 'label' column with integer values
146
+ 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
147
  return example
148
 
149
+
150
  def preprocess_data(example):
151
+ return tokenizer(example['text'], truncation=True, padding=True, max_length=512) # Added max_length for consistency
152
+
153
 
154
  # Apply emotion mapping before tokenization
155
  dataset = dataset.map(map_emotion_to_int, batched=False)
156
+ # *Keep the 'label' column for training. Only remove 'text'*
157
+ # Filter out examples with labels not in emotion_mapping (-1)
158
+ dataset = dataset.filter(lambda example: example['label'] != -1) # Filter out examples with label -1
159
  tokenized_dataset = dataset.map(preprocess_data, batched=True, remove_columns=['text'])
160
 
161
  # Load model
162
+ # model = AutoModelForSequenceClassification.from_pretrained("bhadresh-savani/distilbert-base-uncased-emotion", num_labels=8)
163
+
164
+ # Load model with ignore_mismatched_sizes=True
165
  model = AutoModelForSequenceClassification.from_pretrained(
166
  "bhadresh-savani/distilbert-base-uncased-emotion",
167
  num_labels=8,
 
170
 
171
  # Training arguments
172
  training_args = TrainingArguments(
173
+ output_dir="./results", # Directory for model checkpoints and logs
174
+ evaluation_strategy="epoch", # Evaluate after every epoch
175
+ learning_rate=5e-5, # Start with 5e-5 (slightly higher than default 2e-5)
176
+ per_device_train_batch_size=16, # Use 16 for balance between memory usage and training speed
177
+ gradient_accumulation_steps=4, # Accumulate gradients to simulate larger batch size
178
+ num_train_epochs=5, # Train for 4-5 epochs (typically enough for fine-tuning)
179
+ weight_decay=0.01, # Regularization to avoid overfitting
180
+ save_strategy="epoch", # Save checkpoints after each epoch
181
+ logging_dir="./logs", # Directory for logging
182
+ logging_steps=100, # Log every 100 steps
183
+ warmup_steps=500, # Gradual learning rate increase for the first 500 steps
184
+ save_total_limit=3, # Keep only the last 3 checkpoints
185
+ fp16=True, # Enable mixed precision for faster training if GPU supports it
186
+ load_best_model_at_end=True, # Load the best model at the end of training
187
+ metric_for_best_model="eval_loss", # Use evaluation loss to select the best model
188
+ greater_is_better=False, # Lower loss is better
189
  )
190
 
191
+
192
  # Train model
193
  trainer = Trainer(
194
  model=model,
 
200
 
201
  trainer.train()
202
 
203
+ # Save the model and tokenizer to Google Drive
204
  model_save_path = "/content/drive/My Drive/emotion_detection_model1"
205
  tokenizer_save_path = "/content/drive/My Drive/emotion_detection_model1"
206
+
207
+ # Save the fine-tuned model
208
  model.save_pretrained(model_save_path)
209
  tokenizer.save_pretrained(tokenizer_save_path)
210
 
211
  print("Model and tokenizer saved to Google Drive.")
212
 
213
+ """Reload the Fine-Tuned Model"""
214
+
215
  from transformers import AutoModelForSequenceClassification, AutoTokenizer
216
 
217
  # Mount Google Drive
 
228
 
229
  print("Fine-tuned model and tokenizer loaded successfully.")
230
 
231
+ """Test the Reloaded Model"""
232
+
233
  from transformers import pipeline
234
 
235
  # Create a text classification pipeline with the loaded model
 
240
  result = emotion_classifier(text)
241
  print(result)
242
 
243
+ """Fine-tuning the TTS System"""
244
+
245
+ from TTS.api import TTS
246
+ from TTS.utils.audio import AudioProcessor
247
+ from TTS.tts.models.tacotron2 import Tacotron2
248
+ import torch
249
+
250
+ # Load pre-trained model
251
+ #model = Tacotron2.load_model("tts_models/en/ljspeech/tacotron2-DDC")
252
+ tts = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC") # Use TTS for model loading
253
+
254
+ # Access the Tacotron2 model from the TTS object
255
+ model = tts.synthesizer.tts_model
256
+
257
+ # Fine-tuning parameters
258
+ model.config.dataset_path = "/content/drive/MyDrive/RAVDESS"
259
+ model.config.num_epochs = 10
260
+
261
+ # Train
262
+ model.train()
263
+
264
+ # Define the save path on Google Drive
265
+ save_path = "/content/drive/My Drive/fine_tuned_tacotron2.pth"
266
+
267
+ # Save the model's state dictionary using torch.save
268
+ torch.save(model.state_dict(), save_path)
269
+
270
+
271
+ """Set up the Gradio interface"""
272
+
273
  import gradio as gr
274
+ from transformers import pipeline
275
+ from TTS.api import TTS
276
+
277
+ # Load pre-trained emotion detection model
278
+ emotion_classifier = pipeline("text-classification", model="bhadresh-savani/distilbert-base-uncased-emotion")
279
+
280
+ # Load TTS model
281
+ tts_model = TTS(model_name="tts_models/en/ljspeech/tacotron2-DDC")
282
+
283
+ # Emotion-specific settings for pitch and speed
284
+ emotion_settings = {
285
+ "neutral": {"pitch": 1.0, "speed": 1.0, "prosody": 0.5}, # Neutral tone
286
+ "joy": {"pitch": 1.3, "speed": 1.2, "prosody": 1.5}, # Upbeat, energetic
287
+ "sadness": {"pitch": 0.8, "speed": 0.9, "prosody": 0.8}, # Subdued, slow tone
288
+ "anger": {"pitch": 1.6, "speed": 1.4, "prosody": 1.8}, # Sharp, intense
289
+ "fear": {"pitch": 1.2, "speed": 0.95, "prosody": 1.2}, # Tense, slow
290
+ "surprise": {"pitch": 1.5, "speed": 1.3, "prosody": 1.4}, # Excited, high energy
291
+ "disgust": {"pitch": 0.9, "speed": 0.95, "prosody": 0.6}, # Low, deliberate
292
+ "shame": {"pitch": 0.8, "speed": 0.85, "prosody": 0.5}, # Quiet, subdued tone
293
+ }
294
+
295
+
296
 
297
+ # Function to process text or file input and generate audio
298
+ def emotion_aware_tts_pipeline(input_text=None, file_input=None):
299
  try:
300
  # Get text from input or file
301
  if file_input:
 
315
 
316
  # Generate audio
317
  audio_path = "output.wav"
318
+ tts_model.tts_to_file(text=input_text, file_path=audio_path, speed=speed, pitch=pitch)
319
+
320
 
 
 
321
 
322
  return f"Detected Emotion: {emotion} (Confidence: {confidence:.2f})", audio_path
323
  else:
 
325
  except Exception as e:
326
  return f"Error: {str(e)}", None
327
 
328
+
329
+
330
  # Define Gradio interface
331
  iface = gr.Interface(
332
+ fn=emotion_aware_tts_pipeline,
333
  inputs=[
334
  gr.Textbox(label="Input Text", placeholder="Enter text here"),
335
  gr.File(label="Upload a Text File")