Anita-19 commited on
Commit
afe9f6d
·
verified ·
1 Parent(s): 4635cfc

Update main.py

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