nareauow commited on
Commit
494b693
·
verified ·
1 Parent(s): c4e0b50

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +89 -80
app.py CHANGED
@@ -18,7 +18,8 @@ print(f"Using device: {device}")
18
 
19
  # Load speech-to-text model
20
  try:
21
- speech_recognizer = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr").to(device)
 
22
  speech_processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")
23
  print("Speech recognition model loaded successfully!")
24
  except Exception as e:
@@ -32,7 +33,7 @@ try:
32
  tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
33
  tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts").to(device)
34
  tts_vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan").to(device)
35
-
36
  # Load speaker embeddings
37
  embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
38
  speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(device)
@@ -44,6 +45,7 @@ except Exception as e:
44
  tts_vocoder = None
45
  speaker_embeddings = None
46
 
 
47
  # Modele CNN
48
  class modele_CNN(nn.Module):
49
  def __init__(self, num_classes=7, dropout=0.3):
@@ -52,10 +54,10 @@ class modele_CNN(nn.Module):
52
  self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
53
  self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
54
  self.pool = nn.MaxPool2d(2, 2)
55
- self.fc1 = nn.Linear(64 * 1 * 62, 128)
56
  self.fc2 = nn.Linear(128, num_classes)
57
  self.dropout = nn.Dropout(dropout)
58
-
59
  def forward(self, x):
60
  x = self.pool(F.relu(self.conv1(x)))
61
  x = self.pool(F.relu(self.conv2(x)))
@@ -63,35 +65,43 @@ class modele_CNN(nn.Module):
63
  x = x.view(x.size(0), -1)
64
  x = self.dropout(F.relu(self.fc1(x)))
65
  x = self.fc2(x)
66
- return x
 
 
 
67
 
68
- # Audio processor
69
  class AudioProcessor:
70
- def Mel2Hz(self, mel): return 700 * (np.power(10, mel/2595)-1)
71
- def Hz2Mel(self, freq): return 2595 * np.log10(1+freq/700)
72
- def Hz2Ind(self, freq, fs, Tfft): return (freq*Tfft/fs).astype(int)
73
-
74
- def hamming(self, T):
 
 
 
 
 
75
  if T <= 1:
76
  return np.ones(T)
77
- return 0.54-0.46*np.cos(2*np.pi*np.arange(T)/(T-1))
78
 
79
  def FiltresMel(self, fs, nf=36, Tfft=512, fmin=100, fmax=8000):
80
- Indices = self.Hz2Ind(self.Mel2Hz(np.linspace(self.Hz2Mel(fmin), self.Hz2Mel(min(fmax, fs/2)), nf+2)), fs, Tfft)
81
- filtres = np.zeros((int(Tfft/2), nf))
82
- for i in range(nf): filtres[Indices[i]:Indices[i+2], i] = self.hamming(Indices[i+2]-Indices[i])
 
83
  return filtres
84
 
85
  def spectrogram(self, x, T, p, Tfft):
86
- S = []
87
- for i in range(0, len(x)-T, p): S.append(x[i:i+T]*self.hamming(T))
88
  S = np.fft.fft(S, Tfft)
89
  return np.abs(S), np.angle(S)
90
-
91
  def mfcc(self, data, filtres, nc=13, T=256, p=64, Tfft=512):
92
- data = (data[1]-np.mean(data[1]))/np.std(data[1])
93
  amp, ph = self.spectrogram(data, T, p, Tfft)
94
- amp_f = np.log10(np.dot(amp[:, :int(Tfft/2)], filtres)+1)
95
  return idct(amp_f, n=nc, norm='ortho')
96
 
97
  def process_audio(self, audio_data, sr, audio_length=32000):
@@ -106,29 +116,33 @@ class AudioProcessor:
106
  else:
107
  sgn = audio_data
108
  fs = sr
109
-
110
  sgn = np.array(sgn, dtype=np.float32)
111
-
112
  if len(sgn) > audio_length:
113
  sgn = sgn[:audio_length]
114
  else:
115
  sgn = np.pad(sgn, (0, audio_length - len(sgn)), mode='constant')
116
-
117
  filtres = self.FiltresMel(fs)
118
  sgn_features = self.mfcc([fs, sgn], filtres)
119
-
120
  mfcc_tensor = torch.tensor(sgn_features.T, dtype=torch.float32)
121
  mfcc_tensor = mfcc_tensor.unsqueeze(0).unsqueeze(0)
122
-
123
  return mfcc_tensor
124
 
 
 
125
  def recognize_speech(audio_path):
126
  if speech_recognizer is None or speech_processor is None:
127
  return "Speech recognition model not available"
128
-
129
  try:
 
130
  audio_data, sr = sf.read(audio_path)
131
-
 
132
  if sr != 16000:
133
  audio_data = np.interp(
134
  np.linspace(0, len(audio_data), int(16000 * len(audio_data) / sr)),
@@ -136,89 +150,82 @@ def recognize_speech(audio_path):
136
  audio_data
137
  )
138
  sr = 16000
139
-
140
- inputs = speech_processor(
141
- audio_data,
142
- sampling_rate=sr,
143
- return_tensors="pt"
144
- ).to(device)
145
-
146
- generated_ids = speech_recognizer.generate(
147
- input_features=inputs["input_features"],
148
- max_length=100,
149
- num_beams=5, # Changed from 1 to 5 for better results
150
- early_stopping=True,
151
- no_repeat_ngram_size=2
152
- )
153
-
154
- transcription = speech_processor.batch_decode(
155
- generated_ids,
156
- skip_special_tokens=True
157
- )[0]
158
-
159
- return transcription.strip()
160
-
161
  except Exception as e:
162
  return f"Speech recognition error: {str(e)}"
163
 
 
164
  # Speech synthesis function
165
  def synthesize_speech(text):
166
  if tts_processor is None or tts_model is None or tts_vocoder is None or speaker_embeddings is None:
167
  return None
168
-
169
  try:
170
  # Preprocess text
171
  inputs = tts_processor(text=text, return_tensors="pt").to(device)
172
-
173
  # Generate speech with speaker embeddings
174
  spectrogram = tts_model.generate_speech(inputs["input_ids"], speaker_embeddings)
175
-
176
  # Convert to waveform
177
  with torch.no_grad():
178
  speech = tts_vocoder(spectrogram)
179
-
180
  # Convert to numpy array and normalize
181
  speech = speech.cpu().numpy()
182
  speech = speech / np.max(np.abs(speech))
183
-
184
  return (16000, speech.squeeze())
185
  except Exception as e:
186
  print(f"Speech synthesis error: {str(e)}")
187
  return None
188
 
 
189
  # Fonction prédiction
190
  def predict_speaker(audio, model, processor):
191
  if audio is None:
192
- return "Aucun audio détecté.", None, None
193
-
194
  try:
195
  audio_data, sr = sf.read(audio)
 
 
196
  input_tensor = processor.process_audio(audio_data, sr)
197
-
198
  device = next(model.parameters()).device
199
  input_tensor = input_tensor.to(device)
200
-
201
  with torch.no_grad():
202
  output = model(input_tensor)
203
  print(output)
204
  probabilities = F.softmax(output, dim=1)
205
  confidence, predicted_class = torch.max(probabilities, 1)
206
-
207
  speakers = ["George", "Jackson", "Lucas", "Nicolas", "Theo", "Yweweler", "Narimene"]
208
  predicted_speaker = speakers[predicted_class.item()]
209
-
210
- result = f"Locuteur reconnu : {predicted_speaker} (confiance : {confidence.item()*100:.2f}%)"
211
-
212
  probs_dict = {speakers[i]: float(probs) for i, probs in enumerate(probabilities[0].cpu().numpy())}
213
-
214
  # Recognize speech
215
  recognized_text = recognize_speech(audio)
216
-
217
- return result, probs_dict, recognized_text,predicted_speaker
218
-
219
  except Exception as e:
220
  return f"Erreur : {str(e)}", None, None
221
 
 
222
  # Charger modèle
223
  def load_model(model_id="nareauow/my_speech_recognition", model_filename="model_3.pth"):
224
  try:
@@ -233,14 +240,15 @@ def load_model(model_id="nareauow/my_speech_recognition", model_filename="model_
233
  print(f"Erreur de chargement: {e}")
234
  return None
235
 
 
236
  # Gradio Interface
237
  def create_interface():
238
  processor = AudioProcessor()
239
-
240
  with gr.Blocks(title="Reconnaissance de Locuteur") as interface:
241
  gr.Markdown("# 🗣️ Reconnaissance de Locuteur")
242
  gr.Markdown("Enregistrez votre voix pendant 2 secondes pour identifier qui parle.")
243
-
244
  with gr.Row():
245
  with gr.Column():
246
  model_selector = gr.Dropdown(
@@ -255,11 +263,11 @@ def create_interface():
255
  plot_output = gr.Plot(label="Confiance par locuteur")
256
  recognized_text = gr.Textbox(label="Texte reconnu")
257
  audio_output = gr.Audio(label="Synthèse vocale", type="numpy")
258
-
259
  def recognize(audio, selected_model):
260
  model = load_model(model_filename=selected_model)
261
- res, probs, text,locuteur = predict_speaker(audio, model, processor)
262
-
263
  # Generate plot
264
  fig = None
265
  if probs:
@@ -269,28 +277,29 @@ def create_interface():
269
  ax.set_ylabel("Confiance")
270
  ax.set_xlabel("Locuteurs")
271
  plt.xticks(rotation=45)
272
-
273
  # Generate speech synthesis if text was recognized
274
  synth_audio = None
275
  if text and "error" not in text.lower():
276
  synth_text = f"{locuteur} said : {text}"
277
  synth_audio = synthesize_speech(synth_text)
278
-
279
  return res, fig, text, synth_audio
280
-
281
- record_btn.click(fn=recognize,
282
- inputs=[audio_input, model_selector],
283
- outputs=[result_text, plot_output, recognized_text, audio_output])
284
-
285
  gr.Markdown("""### Comment utiliser ?
286
  - Choisissez le modèle.
287
  - Cliquez sur pour enregistrer votre voix.
288
  - Cliquez sur **Reconnaître** pour obtenir la prédiction.
289
  """)
290
-
291
  return interface
292
 
 
293
  # Lancer
294
  if __name__ == "__main__":
295
  app = create_interface()
296
- app.launch()
 
18
 
19
  # Load speech-to-text model
20
  try:
21
+ speech_recognizer = Speech2TextForConditionalGeneration.from_pretrained("facebook/s2t-small-librispeech-asr").to(
22
+ device)
23
  speech_processor = Speech2TextProcessor.from_pretrained("facebook/s2t-small-librispeech-asr")
24
  print("Speech recognition model loaded successfully!")
25
  except Exception as e:
 
33
  tts_processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
34
  tts_model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts").to(device)
35
  tts_vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan").to(device)
36
+
37
  # Load speaker embeddings
38
  embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
39
  speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(device)
 
45
  tts_vocoder = None
46
  speaker_embeddings = None
47
 
48
+
49
  # Modele CNN
50
  class modele_CNN(nn.Module):
51
  def __init__(self, num_classes=7, dropout=0.3):
 
54
  self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
55
  self.conv3 = nn.Conv2d(32, 64, 3, padding=1)
56
  self.pool = nn.MaxPool2d(2, 2)
57
+ self.fc1 = nn.Linear(64 * 1 * 62, 128)
58
  self.fc2 = nn.Linear(128, num_classes)
59
  self.dropout = nn.Dropout(dropout)
60
+
61
  def forward(self, x):
62
  x = self.pool(F.relu(self.conv1(x)))
63
  x = self.pool(F.relu(self.conv2(x)))
 
65
  x = x.view(x.size(0), -1)
66
  x = self.dropout(F.relu(self.fc1(x)))
67
  x = self.fc2(x)
68
+ return x
69
+
70
+ # Audio processor
71
+
72
 
 
73
  class AudioProcessor:
74
+ def Mel2Hz(self, mel):
75
+ return 700 * (np.power(10, mel / 2595) - 1)
76
+
77
+ def Hz2Mel(self, freq):
78
+ return 2595 * np.log10(1 + freq / 700)
79
+
80
+ def Hz2Ind(self, freq, fs, Tfft):
81
+ return (freq * Tfft / fs).astype(int)
82
+
83
+ def hamming(self, T):
84
  if T <= 1:
85
  return np.ones(T)
86
+ return 0.54 - 0.46 * np.cos(2 * np.pi * np.arange(T) / (T - 1))
87
 
88
  def FiltresMel(self, fs, nf=36, Tfft=512, fmin=100, fmax=8000):
89
+ Indices = self.Hz2Ind(self.Mel2Hz(np.linspace(self.Hz2Mel(fmin), self.Hz2Mel(min(fmax, fs / 2)), nf + 2)), fs,
90
+ Tfft)
91
+ filtres = np.zeros((int(Tfft / 2), nf))
92
+ for i in range(nf): filtres[Indices[i]:Indices[i + 2], i] = self.hamming(Indices[i + 2] - Indices[i])
93
  return filtres
94
 
95
  def spectrogram(self, x, T, p, Tfft):
96
+ S = []
97
+ for i in range(0, len(x) - T, p): S.append(x[i:i + T] * self.hamming(T))
98
  S = np.fft.fft(S, Tfft)
99
  return np.abs(S), np.angle(S)
100
+
101
  def mfcc(self, data, filtres, nc=13, T=256, p=64, Tfft=512):
102
+ data = (data[1] - np.mean(data[1])) / np.std(data[1])
103
  amp, ph = self.spectrogram(data, T, p, Tfft)
104
+ amp_f = np.log10(np.dot(amp[:, :int(Tfft / 2)], filtres) + 1)
105
  return idct(amp_f, n=nc, norm='ortho')
106
 
107
  def process_audio(self, audio_data, sr, audio_length=32000):
 
116
  else:
117
  sgn = audio_data
118
  fs = sr
119
+
120
  sgn = np.array(sgn, dtype=np.float32)
121
+
122
  if len(sgn) > audio_length:
123
  sgn = sgn[:audio_length]
124
  else:
125
  sgn = np.pad(sgn, (0, audio_length - len(sgn)), mode='constant')
126
+
127
  filtres = self.FiltresMel(fs)
128
  sgn_features = self.mfcc([fs, sgn], filtres)
129
+
130
  mfcc_tensor = torch.tensor(sgn_features.T, dtype=torch.float32)
131
  mfcc_tensor = mfcc_tensor.unsqueeze(0).unsqueeze(0)
132
+
133
  return mfcc_tensor
134
 
135
+
136
+ # Speech recognition function
137
  def recognize_speech(audio_path):
138
  if speech_recognizer is None or speech_processor is None:
139
  return "Speech recognition model not available"
140
+
141
  try:
142
+ # Read audio file
143
  audio_data, sr = sf.read(audio_path)
144
+
145
+ # Resample to 16kHz if needed
146
  if sr != 16000:
147
  audio_data = np.interp(
148
  np.linspace(0, len(audio_data), int(16000 * len(audio_data) / sr)),
 
150
  audio_data
151
  )
152
  sr = 16000
153
+
154
+ # Process audio
155
+ inputs = speech_processor(audio_data, sampling_rate=sr, return_tensors="pt")
156
+ inputs = {k: v.to(device) for k, v in inputs.items()}
157
+
158
+ # Generate transcription
159
+ generated_ids = speech_recognizer.generate(**inputs)
160
+ transcription = speech_processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
161
+
162
+ return transcription
 
 
 
 
 
 
 
 
 
 
 
 
163
  except Exception as e:
164
  return f"Speech recognition error: {str(e)}"
165
 
166
+
167
  # Speech synthesis function
168
  def synthesize_speech(text):
169
  if tts_processor is None or tts_model is None or tts_vocoder is None or speaker_embeddings is None:
170
  return None
171
+
172
  try:
173
  # Preprocess text
174
  inputs = tts_processor(text=text, return_tensors="pt").to(device)
175
+
176
  # Generate speech with speaker embeddings
177
  spectrogram = tts_model.generate_speech(inputs["input_ids"], speaker_embeddings)
178
+
179
  # Convert to waveform
180
  with torch.no_grad():
181
  speech = tts_vocoder(spectrogram)
182
+
183
  # Convert to numpy array and normalize
184
  speech = speech.cpu().numpy()
185
  speech = speech / np.max(np.abs(speech))
186
+
187
  return (16000, speech.squeeze())
188
  except Exception as e:
189
  print(f"Speech synthesis error: {str(e)}")
190
  return None
191
 
192
+
193
  # Fonction prédiction
194
  def predict_speaker(audio, model, processor):
195
  if audio is None:
196
+ return "Aucun audio détecté.", None, None,None
197
+
198
  try:
199
  audio_data, sr = sf.read(audio)
200
+
201
+
202
  input_tensor = processor.process_audio(audio_data, sr)
203
+
204
  device = next(model.parameters()).device
205
  input_tensor = input_tensor.to(device)
206
+
207
  with torch.no_grad():
208
  output = model(input_tensor)
209
  print(output)
210
  probabilities = F.softmax(output, dim=1)
211
  confidence, predicted_class = torch.max(probabilities, 1)
212
+
213
  speakers = ["George", "Jackson", "Lucas", "Nicolas", "Theo", "Yweweler", "Narimene"]
214
  predicted_speaker = speakers[predicted_class.item()]
215
+
216
+ result = f"Locuteur reconnu : {predicted_speaker} (confiance : {confidence.item() * 100:.2f}%)"
217
+
218
  probs_dict = {speakers[i]: float(probs) for i, probs in enumerate(probabilities[0].cpu().numpy())}
219
+
220
  # Recognize speech
221
  recognized_text = recognize_speech(audio)
222
+
223
+ return result, probs_dict, recognized_text, predicted_speaker
224
+
225
  except Exception as e:
226
  return f"Erreur : {str(e)}", None, None
227
 
228
+
229
  # Charger modèle
230
  def load_model(model_id="nareauow/my_speech_recognition", model_filename="model_3.pth"):
231
  try:
 
240
  print(f"Erreur de chargement: {e}")
241
  return None
242
 
243
+
244
  # Gradio Interface
245
  def create_interface():
246
  processor = AudioProcessor()
247
+
248
  with gr.Blocks(title="Reconnaissance de Locuteur") as interface:
249
  gr.Markdown("# 🗣️ Reconnaissance de Locuteur")
250
  gr.Markdown("Enregistrez votre voix pendant 2 secondes pour identifier qui parle.")
251
+
252
  with gr.Row():
253
  with gr.Column():
254
  model_selector = gr.Dropdown(
 
263
  plot_output = gr.Plot(label="Confiance par locuteur")
264
  recognized_text = gr.Textbox(label="Texte reconnu")
265
  audio_output = gr.Audio(label="Synthèse vocale", type="numpy")
266
+
267
  def recognize(audio, selected_model):
268
  model = load_model(model_filename=selected_model)
269
+ res, probs, text, locuteur = predict_speaker(audio, model, processor)
270
+
271
  # Generate plot
272
  fig = None
273
  if probs:
 
277
  ax.set_ylabel("Confiance")
278
  ax.set_xlabel("Locuteurs")
279
  plt.xticks(rotation=45)
280
+
281
  # Generate speech synthesis if text was recognized
282
  synth_audio = None
283
  if text and "error" not in text.lower():
284
  synth_text = f"{locuteur} said : {text}"
285
  synth_audio = synthesize_speech(synth_text)
286
+
287
  return res, fig, text, synth_audio
288
+
289
+ record_btn.click(fn=recognize,
290
+ inputs=[audio_input, model_selector],
291
+ outputs=[result_text, plot_output, recognized_text, audio_output])
292
+
293
  gr.Markdown("""### Comment utiliser ?
294
  - Choisissez le modèle.
295
  - Cliquez sur pour enregistrer votre voix.
296
  - Cliquez sur **Reconnaître** pour obtenir la prédiction.
297
  """)
298
+
299
  return interface
300
 
301
+
302
  # Lancer
303
  if __name__ == "__main__":
304
  app = create_interface()
305
+ app.launch(share=True)