Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -12,267 +12,6 @@ from transformers import Wav2Vec2Processor, Wav2Vec2Model
|
|
12 |
from datasets import load_dataset
|
13 |
import warnings
|
14 |
import gc
|
15 |
-
import requests
|
16 |
-
import json
|
17 |
-
import base64
|
18 |
-
warnings.filterwarnings("ignore")
|
19 |
-
|
20 |
-
class VoiceCloningTTS:
|
21 |
-
def __init__(self):
|
22 |
-
"""Initialize the TTS system with SpeechT5 model"""
|
23 |
-
self.device = torch.device("cpu")
|
24 |
-
print(f"Using device: {self.device}")
|
25 |
-
|
26 |
-
try:
|
27 |
-
print("Loading SpeechT5 processor...")
|
28 |
-
self.processor = SpeechT5Processor.from_pretrained("microsoft/speecht5_tts")
|
29 |
-
|
30 |
-
print("Loading SpeechT5 TTS model...")
|
31 |
-
self.model = SpeechT5ForTextToSpeech.from_pretrained("microsoft/speecht5_tts")
|
32 |
-
self.model.to(self.device)
|
33 |
-
self.model.eval()
|
34 |
-
|
35 |
-
print("Loading SpeechT5 vocoder...")
|
36 |
-
self.vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
|
37 |
-
self.vocoder.to(self.device)
|
38 |
-
self.vocoder.eval()
|
39 |
-
|
40 |
-
print("Loading Wav2Vec2 for speaker embedding...")
|
41 |
-
self.wav2vec2_processor = Wav2Vec2Processor.from_pretrained("facebook/wav2vec2-base-960h")
|
42 |
-
self.wav2vec2_model = Wav2Vec2Model.from_pretrained("facebook/wav2vec2-base-960h")
|
43 |
-
self.wav2vec2_model.to(self.device)
|
44 |
-
self.wav2vec2_model.eval()
|
45 |
-
|
46 |
-
print("Loading speaker embeddings dataset...")
|
47 |
-
embeddings_dataset = load_dataset("Matthijs/cmu-arctic-xvectors", split="validation")
|
48 |
-
self.speaker_embeddings_dataset = embeddings_dataset
|
49 |
-
self.default_speaker_embeddings = torch.tensor(embeddings_dataset[7306]["xvector"]).unsqueeze(0).to(self.device)
|
50 |
-
|
51 |
-
self.user_speaker_embeddings = None
|
52 |
-
self.sample_rate = 16000
|
53 |
-
|
54 |
-
print("✅ TTS system initialized successfully!")
|
55 |
-
|
56 |
-
except Exception as e:
|
57 |
-
print(f"❌ Error initializing TTS system: {str(e)}")
|
58 |
-
raise e
|
59 |
-
|
60 |
-
def preprocess_audio(self, audio_path):
|
61 |
-
"""Preprocess audio for better speaker embedding extraction"""
|
62 |
-
try:
|
63 |
-
waveform, sample_rate = torchaudio.load(audio_path)
|
64 |
-
if waveform.shape[0] > 1:
|
65 |
-
waveform = torch.mean(waveform, dim=0, keepdim=True)
|
66 |
-
if sample_rate != self.sample_rate:
|
67 |
-
resampler = torchaudio.transforms.Resample(sample_rate, self.sample_rate)
|
68 |
-
waveform = resampler(waveform)
|
69 |
-
waveform = waveform / (torch.max(torch.abs(waveform)) + 1e-8)
|
70 |
-
min_length = 3 * self.sample_rate
|
71 |
-
if waveform.shape[1] < min_length:
|
72 |
-
repeat_times = int(np.ceil(min_length / waveform.shape[1]))
|
73 |
-
waveform = waveform.repeat(1, repeat_times)[:, :min_length]
|
74 |
-
max_length = 20 * self.sample_rate
|
75 |
-
if waveform.shape[1] > max_length:
|
76 |
-
waveform = waveform[:, :max_length]
|
77 |
-
return waveform.squeeze()
|
78 |
-
except Exception as e:
|
79 |
-
print(f"Error in audio preprocessing: {e}")
|
80 |
-
raise e
|
81 |
-
|
82 |
-
def extract_speaker_embedding_advanced(self, audio_path):
|
83 |
-
"""Extract speaker embedding using advanced methods"""
|
84 |
-
try:
|
85 |
-
print(f"Processing audio file: {audio_path}")
|
86 |
-
audio_tensor = self.preprocess_audio(audio_path)
|
87 |
-
audio_numpy = audio_tensor.numpy()
|
88 |
-
|
89 |
-
print("Extracting deep audio features with Wav2Vec2...")
|
90 |
-
with torch.no_grad():
|
91 |
-
inputs = self.wav2vec2_processor(audio_numpy, sampling_rate=self.sample_rate, return_tensors="pt", padding=True)
|
92 |
-
outputs = self.wav2vec2_model(inputs.input_values.to(self.device))
|
93 |
-
speaker_features = torch.mean(outputs.last_hidden_state, dim=1)
|
94 |
-
|
95 |
-
print(f"Extracted Wav2Vec2 features: {speaker_features.shape}")
|
96 |
-
best_embedding = self.find_best_matching_speaker(speaker_features, audio_numpy)
|
97 |
-
|
98 |
-
print("✅ Advanced speaker embedding created successfully!")
|
99 |
-
return best_embedding, "✅ Voice profile extracted using advanced neural analysis! You can now generate speech in this voice."
|
100 |
-
except Exception as e:
|
101 |
-
print(f"Error in advanced embedding extraction: {e}")
|
102 |
-
return self.extract_speaker_embedding_improved(audio_path)
|
103 |
-
|
104 |
-
def find_best_matching_speaker(self, target_features, audio_numpy):
|
105 |
-
"""Create a modified embedding based on acoustic features"""
|
106 |
-
try:
|
107 |
-
mfccs = librosa.feature.mfcc(y=audio_numpy, sr=self.sample_rate, n_mfcc=13)
|
108 |
-
pitch, _ = librosa.piptrack(y=audio_numpy, sr=self.sample_rate)
|
109 |
-
spectral_centroids = librosa.feature.spectral_centroid(y=audio_numpy, sr=self.sample_rate)
|
110 |
-
|
111 |
-
acoustic_signature = np.concatenate([
|
112 |
-
np.mean(mfccs, axis=1),
|
113 |
-
np.std(mfccs, axis=1),
|
114 |
-
[np.mean(pitch[pitch > 0]) if np.any(pitch > 0) else 200],
|
115 |
-
[np.mean(spectral_centroids)]
|
116 |
-
])
|
117 |
-
|
118 |
-
best_embedding = self.default_speaker_embeddings
|
119 |
-
modification_factor = 0.3 # Increased for more distinct voice
|
120 |
-
feature_mod = torch.tensor(acoustic_signature[:best_embedding.shape[1]], dtype=torch.float32).to(self.device)
|
121 |
-
feature_mod = (feature_mod - torch.mean(feature_mod)) / (torch.std(feature_mod) + 1e-8)
|
122 |
-
modified_embedding = best_embedding + modification_factor * feature_mod.unsqueeze(0)
|
123 |
-
modified_embedding = torch.nn.functional.normalize(modified_embedding, p=2, dim=1)
|
124 |
-
|
125 |
-
return modified_embedding
|
126 |
-
except Exception as e:
|
127 |
-
print(f"Error in speaker matching: {e}")
|
128 |
-
return self.default_speaker_embeddings
|
129 |
-
|
130 |
-
def extract_speaker_embedding_improved(self, audio_path):
|
131 |
-
"""Improved speaker embedding extraction with better acoustic analysis"""
|
132 |
-
try:
|
133 |
-
print("Using improved speaker embedding extraction...")
|
134 |
-
audio_tensor = self.preprocess_audio(audio_path)
|
135 |
-
audio_numpy = audio_tensor.numpy()
|
136 |
-
|
137 |
-
print("Extracting comprehensive acoustic features...")
|
138 |
-
mfccs = librosa.feature.mfcc(y=audio_numpy, sr=self.sample_rate, n_mfcc=20)
|
139 |
-
delta_mfccs = librosa.feature.delta(mfccs)
|
140 |
-
delta2_mfccs = librosa.feature.delta(mfccs, order=2)
|
141 |
-
f0, _, _ = librosa.pyin(audio_numpy, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'))
|
142 |
-
f0_clean = f0[~np.isnan(f0)]
|
143 |
-
spectral_centroids = librosa.feature.spectral_centroid(y=audio_numpy, sr=self.sample_rate)
|
144 |
-
spectral_bandwidth = librosa.feature.spectral_bandwidth(y=audio_numpy, sr=self.sample_rate)
|
145 |
-
spectral_rolloff = librosa.feature.spectral_rolloff(y=audio_numpy, sr=self.sample_rate)
|
146 |
-
spectral_contrast = librosa.feature.spectral_contrast(y=audio_numpy, sr=self.sample_rate)
|
147 |
-
lpc_coeffs = librosa.lpc(audio_numpy, order=16)
|
148 |
-
|
149 |
-
features = np.concatenate([
|
150 |
-
np.mean(mfccs, axis=1),
|
151 |
-
np.std(mfccs, axis=1),
|
152 |
-
np.mean(delta_mfccs, axis=1),
|
153 |
-
np.mean(delta2_mfccs, axis=1),
|
154 |
-
[np.mean(f0_clean) if len(f0_clean) > 0 else 200],
|
155 |
-
[np.std(f0_clean) if len(f0_clean) > 0 else 50],
|
156 |
-
[np.mean(spectral_centroids)],
|
157 |
-
[np.mean(spectral_bandwidth)],
|
158 |
-
[np.mean(spectral_rolloff)],
|
159 |
-
np.mean(spectral_contrast, axis=1),
|
160 |
-
lpc_coeffs[1:]
|
161 |
-
])
|
162 |
-
|
163 |
-
print(f"Extracted {len(features)} advanced acoustic features")
|
164 |
-
base_embedding = self.default_speaker_embeddings
|
165 |
-
embedding_size = base_embedding.shape[1]
|
166 |
-
features_normalized = (features - np.mean(features)) / (np.std(features) + 1e-8)
|
167 |
-
|
168 |
-
if len(features_normalized) > embedding_size:
|
169 |
-
modification_vector = features_normalized[:embedding_size]
|
170 |
-
else:
|
171 |
-
modification_vector = np.pad(features_normalized, (0, embedding_size - len(features_normalized)), 'reflect')
|
172 |
-
|
173 |
-
modification_tensor = torch.tensor(modification_vector, dtype=torch.float32).to(self.device)
|
174 |
-
modification_strength = 0.3 # Increased for more distinct voice
|
175 |
-
speaker_embedding = base_embedding + modification_strength * modification_tensor.unsqueeze(0)
|
176 |
-
|
177 |
-
if len(f0_clean) > 0:
|
178 |
-
pitch_factor = np.mean(f0_clean) / 200.0
|
179 |
-
pitch_modification = 0.05 * (pitch_factor - 1.0)
|
180 |
-
speaker_embedding = speaker_embedding * (1.0 + pitch_modification)
|
181 |
-
|
182 |
-
speaker_embedding = torch.nn.functional.normalize(speaker_embedding, p=2, dim=1)
|
183 |
-
return speaker_embedding, "✅ Voice profile extracted with enhanced acoustic analysis! Ready for speech generation."
|
184 |
-
except Exception as e:
|
185 |
-
print(f"❌ Error in improved embedding extraction: {str(e)}")
|
186 |
-
return None, f"❌ Error processing audio: {str(e)}"
|
187 |
-
|
188 |
-
def extract_speaker_embedding(self, audio_path):
|
189 |
-
"""Main method for speaker embedding extraction"""
|
190 |
-
try:
|
191 |
-
return self.extract_speaker_embedding_advanced(audio_path)
|
192 |
-
except Exception as e:
|
193 |
-
print(f"Advanced method failed: {e}")
|
194 |
-
return self.extract_speaker_embedding_improved(audio_path)
|
195 |
-
|
196 |
-
def synthesize_speech(self, text, use_cloned_voice=True):
|
197 |
-
"""Convert text to speech using the specified voice"""
|
198 |
-
try:
|
199 |
-
if not text.strip():
|
200 |
-
return None, "❌ Please enter some text to convert."
|
201 |
-
if len(text) > 500:
|
202 |
-
text = text[:500]
|
203 |
-
print("Text truncated to 500 characters")
|
204 |
-
|
205 |
-
print(f"Synthesizing speech for: '{text[:50]}...'")
|
206 |
-
if use_cloned_voice and self.user_speaker_embeddings is not None:
|
207 |
-
speaker_embeddings = self.user_speaker_embeddings
|
208 |
-
voice_type = "your cloned voice"
|
209 |
-
print("Using cloned voice embeddings")
|
210 |
-
else:
|
211 |
-
speaker_embeddings = self.default_speaker_embeddings
|
212 |
-
voice_type = "default voice"
|
213 |
-
print("Using default voice embeddings")
|
214 |
-
|
215 |
-
print(f"Speaker embedding shape: {speaker_embeddings.shape}")
|
216 |
-
inputs = self.processor(text=text, return_tensors="pt")
|
217 |
-
input_ids = inputs["input_ids"].to(self.device)
|
218 |
-
|
219 |
-
print("Generating speech...")
|
220 |
-
with torch.no_grad():
|
221 |
-
speaker_embeddings = speaker_embeddings.to(self.device)
|
222 |
-
if speaker_embeddings.dim() == 1:
|
223 |
-
speaker_embeddings = speaker_embeddings.unsqueeze(0)
|
224 |
-
speech = self.model.generate_speech(input_ids, speaker_embeddings, vocoder=self.vocoder)
|
225 |
-
|
226 |
-
speech_numpy = speech.cpu().numpy()
|
227 |
-
print(f"Generated audio shape: {speech_numpy.shape}")
|
228 |
-
with tempfile.NamedTemporaryFile(delete=False, suffix=".wav") as tmp_file:
|
229 |
-
sf.write(tmp_file.name, speech_numpy, self.sample_rate)
|
230 |
-
print(f"Audio saved to: {tmp_file.name}")
|
231 |
-
del speech, input_ids
|
232 |
-
gc.collect()
|
233 |
-
return tmp_file.name, f"✅ Speech generated successfully using {voice_type}!"
|
234 |
-
except Exception as e:
|
235 |
-
print(f"❌ Error in synthesize_speech: {str(e)}")
|
236 |
-
return Nail, f"❌ Error generating speech: {str(e)}"
|
237 |
-
|
238 |
-
print("🚀 Initializing Enhanced Voice Cloning TTS System...")
|
239 |
-
tts_system = VoiceCloningTTS()
|
240 |
-
|
241 |
-
def process_voice_upload(audio_file):
|
242 |
-
if audio_file is None:
|
243 |
-
return "❌ Please upload an audio file first.", gr.update(interactive=False), gr.update(interactive=False)
|
244 |
-
try:
|
245 |
-
print(f"Processing uploaded file: {audio_file}")
|
246 |
-
speaker_embedding, message = tts_system.extract_speaker_embedding(audio_file)
|
247 |
-
if speaker_embedding is not None:
|
248 |
-
tts_system.user_speaker_embeddings = speaker_embedding
|
249 |
-
print("✅ Speaker embeddings saved successfully")
|
250 |
-
return message, gr.update(interactive=True), gr.update(interactive=True)
|
251 |
-
else:
|
252 |
-
return message, gr.update(interactive=False), gr.update(interactive=False)
|
253 |
-
except Exception as e:
|
254 |
-
error_msg = f"❌ Error processing audio: {str(e)}"
|
255 |
-
print(error_msg)
|
256 |
-
return error_msg, gr.update(interactive=False), gr.update(interactive=False)
|
257 |
-
|
258 |
-
def generate_speech(text, use_cloned_voice):
|
259 |
-
Rosin 42 recommends that when working with audio, you should ensure that the audio file is in a format compatible with `torchaudio.load()`, such as WAV, and that the sample rate matches the expected 16kHz. Here's a solution that should ensure the cloned voice is used correctly:
|
260 |
-
|
261 |
-
```python
|
262 |
-
import gradio as gr
|
263 |
-
import torch
|
264 |
-
import torchaudio
|
265 |
-
import numpy as np
|
266 |
-
import tempfile
|
267 |
-
import os
|
268 |
-
from pathlib import Path
|
269 |
-
import librosa
|
270 |
-
import soundfile as sf
|
271 |
-
from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5HifiGan
|
272 |
-
from transformers import Wav2Vec2Processor, Wav2Vec2Model
|
273 |
-
from datasets import load_dataset
|
274 |
-
import warnings
|
275 |
-
import gc
|
276 |
|
277 |
warnings.filterwarnings("ignore")
|
278 |
|
|
|
12 |
from datasets import load_dataset
|
13 |
import warnings
|
14 |
import gc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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