Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,109 +1,136 @@
|
|
1 |
import gradio as gr
|
2 |
-
import
|
3 |
-
|
4 |
-
|
5 |
-
from
|
6 |
-
import
|
7 |
-
import tempfile
|
8 |
import os
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
classifier = EncoderClassifier.from_hparams(source="speechbrain/spkrec-ecapa-voxceleb")
|
13 |
-
hifi_gan = HIFIGAN.from_hparams(source="speechbrain/tts-hifigan-ljspeech")
|
14 |
-
|
15 |
-
def extract_speaker_embedding(audio_file):
|
16 |
-
"""Extract speaker embedding from audio file"""
|
17 |
-
signal, fs = torchaudio.load(audio_file)
|
18 |
-
|
19 |
-
# Resample if needed
|
20 |
-
if fs != 16000:
|
21 |
-
resampler = torchaudio.transforms.Resample(fs, 16000)
|
22 |
-
signal = resampler(signal)
|
23 |
-
fs = 16000
|
24 |
-
|
25 |
-
# Handle stereo audio
|
26 |
-
if signal.shape[0] > 1:
|
27 |
-
signal = torch.mean(signal, dim=0, keepdim=True)
|
28 |
-
|
29 |
-
embeddings = classifier.encode_batch(signal)
|
30 |
-
return embeddings.squeeze(0)
|
31 |
-
|
32 |
-
def voice_conversion(source_audio, target_audio):
|
33 |
-
"""Convert source voice to sound like target voice"""
|
34 |
-
# Create temp files
|
35 |
-
with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as source_tmp, \
|
36 |
-
tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as target_tmp:
|
37 |
-
|
38 |
-
source_path = source_tmp.name
|
39 |
-
target_path = target_tmp.name
|
40 |
-
|
41 |
-
# Save uploaded files
|
42 |
-
source_audio.save(source_path)
|
43 |
-
target_audio.save(target_path)
|
44 |
-
|
45 |
try:
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
finally:
|
71 |
-
# Clean up
|
72 |
-
os.
|
73 |
-
|
|
|
|
|
74 |
|
75 |
-
# Gradio
|
76 |
with gr.Blocks() as demo:
|
77 |
-
gr.Markdown(
|
78 |
-
|
79 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
80 |
with gr.Row():
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
inputs=[source_audio, target_audio],
|
92 |
outputs=output_audio
|
93 |
)
|
94 |
-
|
95 |
-
gr.Examples(
|
96 |
-
examples=[
|
97 |
-
[os.path.join(os.path.dirname(__file__), "examples/source1.wav"),
|
98 |
-
os.path.join(os.path.dirname(__file__), "examples/target1.wav")],
|
99 |
-
[os.path.join(os.path.dirname(__file__), "examples/source2.wav"),
|
100 |
-
os.path.join(os.path.dirname(__file__), "examples/target2.wav")]
|
101 |
-
],
|
102 |
-
inputs=[source_audio, target_audio],
|
103 |
-
outputs=output_audio,
|
104 |
-
fn=voice_conversion,
|
105 |
-
cache_examples=True
|
106 |
-
)
|
107 |
|
108 |
if __name__ == "__main__":
|
|
|
109 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
2 |
+
import librosa
|
3 |
+
import librosa.display
|
4 |
+
import numpy as np
|
5 |
+
from pydub import AudioSegment
|
6 |
+
import io
|
|
|
7 |
import os
|
8 |
+
|
9 |
+
# Function to convert any audio to WAV using pydub
|
10 |
+
def convert_to_wav(audio_file_path):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
try:
|
12 |
+
audio = AudioSegment.from_file(audio_file_path)
|
13 |
+
wav_file_path = audio_file_path + ".wav"
|
14 |
+
audio.export(wav_file_path, format="wav")
|
15 |
+
return wav_file_path
|
16 |
+
except Exception as e:
|
17 |
+
raise gr.Error(f"Error converting audio to WAV: {e}")
|
18 |
+
|
19 |
+
# Main voice changer function (simplified)
|
20 |
+
def voice_changer(source_audio_path, target_audio_path):
|
21 |
+
if source_audio_path is None or target_audio_path is None:
|
22 |
+
raise gr.Error("Please upload both source and target audio files.")
|
23 |
+
|
24 |
+
# Ensure audio files are in WAV format
|
25 |
+
source_wav_path = convert_to_wav(source_audio_path)
|
26 |
+
target_wav_path = convert_to_wav(target_audio_path)
|
27 |
+
|
28 |
+
try:
|
29 |
+
# Load audio files
|
30 |
+
y_source, sr_source = librosa.load(source_wav_path, sr=None)
|
31 |
+
y_target, sr_target = librosa.load(target_wav_path, sr=None)
|
32 |
+
|
33 |
+
# Resample target audio to source sample rate if different
|
34 |
+
if sr_source != sr_target:
|
35 |
+
y_target = librosa.resample(y_target, orig_sr=sr_target, target_sr=sr_source)
|
36 |
+
print(f"Resampled target audio from {sr_target} to {sr_source} Hz.")
|
37 |
+
|
38 |
+
|
39 |
+
# --- Simplified Voice Transfer Logic (Melody/Rhythm Transfer) ---
|
40 |
+
# This is a very basic approach and not a full timbre transfer.
|
41 |
+
# It tries to align the dominant pitch of the target with the source.
|
42 |
+
|
43 |
+
# 1. Pitch Estimation for Source
|
44 |
+
f0_source, voiced_flag_source, voiced_probs_source = librosa.display.cqt_frequencies(n_bins=84, fmin=librosa.note_to_hz('C1')).T, None, None
|
45 |
+
try:
|
46 |
+
f0_source, _, _ = librosa.pyin(y_source, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'), sr=sr_source, frame_length=2048)
|
47 |
+
except Exception as e:
|
48 |
+
print(f"Pyin failed for source, trying different params or fallback: {e}")
|
49 |
+
f0_source, _, _ = librosa.pyin(y_source, fmin=60, fmax=500, sr=sr_source, frame_length=2048) # More robust range
|
50 |
+
|
51 |
+
|
52 |
+
# 2. Estimate F0 for Target
|
53 |
+
f0_target, voiced_flag_target, voiced_probs_target = librosa.display.cqt_frequencies(n_bins=84, fmin=librosa.note_to_hz('C1')).T, None, None
|
54 |
+
try:
|
55 |
+
f0_target, _, _ = librosa.pyin(y_target, fmin=librosa.note_to_hz('C2'), fmax=librosa.note_to_hz('C7'), sr=sr_target, frame_length=2048)
|
56 |
+
except Exception as e:
|
57 |
+
print(f"Pyin failed for target, trying different params or fallback: {e}")
|
58 |
+
f0_target, _, _ = librosa.pyin(y_target, fmin=60, fmax=500, sr=sr_target, frame_length=2048) # More robust range
|
59 |
+
|
60 |
+
|
61 |
+
# Handle NaN values in f0_source (unvoiced segments)
|
62 |
+
f0_source_interpolated = np.nan_to_num(f0_source, nan=0.0)
|
63 |
+
f0_target_interpolated = np.nan_to_num(f0_target, nan=0.0)
|
64 |
+
|
65 |
+
# Calculate a simple pitch shift ratio based on mean F0
|
66 |
+
# This is very simplistic and doesn't account for variations over time.
|
67 |
+
# A more advanced approach would involve temporal alignment and mapping.
|
68 |
+
mean_f0_source = np.mean(f0_source_interpolated[f0_source_interpolated > 0])
|
69 |
+
mean_f0_target = np.mean(f0_target_interpolated[f0_target_interpolated > 0])
|
70 |
+
|
71 |
+
if mean_f0_target > 0 and mean_f0_source > 0:
|
72 |
+
pitch_shift_factor = mean_f0_source / mean_f0_target
|
73 |
+
else:
|
74 |
+
pitch_shift_factor = 1.0 # No pitch shift if no valid pitch detected
|
75 |
+
|
76 |
+
# Apply a pitch shift to the target audio
|
77 |
+
# Using a simple `librosa.effects.pitch_shift` which is based on phase vocoder.
|
78 |
+
# This is not PSOLA and can introduce artifacts.
|
79 |
+
# The `n_steps` argument is in semitones.
|
80 |
+
n_steps = 12 * np.log2(pitch_shift_factor) if pitch_shift_factor > 0 else 0
|
81 |
+
|
82 |
+
# Adjust the duration of the target audio to roughly match the source
|
83 |
+
# This is a crude time stretching/compressing
|
84 |
+
duration_ratio = len(y_source) / len(y_target)
|
85 |
+
y_target_adjusted_tempo = librosa.effects.time_stretch(y_target, rate=duration_ratio)
|
86 |
+
|
87 |
+
# Apply pitch shift to the tempo-adjusted target audio
|
88 |
+
y_output = librosa.effects.pitch_shift(y_target_adjusted_tempo, sr=sr_source, n_steps=n_steps)
|
89 |
+
|
90 |
+
# Normalize the output audio to prevent clipping
|
91 |
+
y_output = librosa.util.normalize(y_output)
|
92 |
+
|
93 |
+
# Create a temporary file to save the output audio
|
94 |
+
output_file_path = "output_voice_changed.wav"
|
95 |
+
sf.write(output_file_path, y_output, sr_source)
|
96 |
+
|
97 |
+
return output_file_path
|
98 |
+
|
99 |
+
except Exception as e:
|
100 |
+
raise gr.Error(f"An error occurred during voice processing: {e}")
|
101 |
finally:
|
102 |
+
# Clean up temporary WAV files
|
103 |
+
if os.path.exists(source_wav_path):
|
104 |
+
os.remove(source_wav_path)
|
105 |
+
if os.path.exists(target_wav_path):
|
106 |
+
os.remove(target_wav_path)
|
107 |
|
108 |
+
# Gradio Interface
|
109 |
with gr.Blocks() as demo:
|
110 |
+
gr.Markdown(
|
111 |
+
"""
|
112 |
+
# Simple Audio Style Transfer (Voice Changer - Experimental)
|
113 |
+
Upload two audio files. The goal is to make the "Target Audio" mimic the pitch/melody of the "Source Audio".
|
114 |
+
**Note:** This is a very basic implementation and **not a full voice cloning/timbre transfer**.
|
115 |
+
It performs a simplified pitch and tempo adjustment based on the source's characteristics.
|
116 |
+
Expect artifacts and limited "voice changing" effect. For true voice cloning, more advanced models are needed.
|
117 |
+
"""
|
118 |
+
)
|
119 |
+
|
120 |
with gr.Row():
|
121 |
+
source_audio_input = gr.Audio(type="filepath", label="Source Audio (Reference Voice/Style)", sources=["upload"])
|
122 |
+
target_audio_input = gr.Audio(type="filepath", label="Target Audio (Voice to be Changed)", sources=["upload"])
|
123 |
+
|
124 |
+
output_audio = gr.Audio(label="Transformed Audio")
|
125 |
+
|
126 |
+
voice_changer_button = gr.Button("Transform Voice")
|
127 |
+
|
128 |
+
voice_changer_button.click(
|
129 |
+
fn=voice_changer,
|
130 |
+
inputs=[source_audio_input, target_audio_input],
|
|
|
131 |
outputs=output_audio
|
132 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
133 |
|
134 |
if __name__ == "__main__":
|
135 |
+
import soundfile as sf # Required for sf.write
|
136 |
demo.launch()
|