rakhlin commited on
Commit
c3f2094
β€’
1 Parent(s): ae9ebcf

Upload folder using huggingface_hub

Browse files
README.md CHANGED
@@ -1,12 +1,6 @@
1
  ---
2
  title: SpeechT5
3
- emoji: πŸš€
4
- colorFrom: gray
5
- colorTo: purple
6
  sdk: gradio
7
  sdk_version: 3.33.1
8
- app_file: app.py
9
- pinned: false
10
  ---
11
-
12
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
  title: SpeechT5
3
+ app_file: app.py
 
 
4
  sdk: gradio
5
  sdk_version: 3.33.1
 
 
6
  ---
 
 
app.py ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import librosa
3
+ import numpy as np
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from pathlib import Path
7
+
8
+ from transformers import SpeechT5Processor, SpeechT5ForTextToSpeech, SpeechT5ForSpeechToSpeech, SpeechT5HifiGan
9
+ from speechbrain.pretrained import EncoderClassifier
10
+
11
+ title = "SpeechT5: Voice Conversion"
12
+ description = """
13
+ The <b>SpeechT5</b> model is pre-trained on text as well as speech inputs, with targets that are also a mix of text and speech.
14
+ By pre-training on text and speech at the same time, it learns unified representations for both, resulting in improved modeling capabilities.
15
+ SpeechT5 can be fine-tuned for different speech tasks. This space demonstrates the <b>text-to-speech</b> and <b>speech-to-speech</b> checkpoints for (American) English
16
+ language voice cloning.
17
+ <p><b>How to use:</b> Upload target voice audio file or select from the list [or record using the microphone -TBD]. The audio is converted to mono and resampled to 16 kHz before
18
+ being passed into the EncoderClassifier model to obtain target voice embedding. Enter text in the text box or upload source voice audio file [or record using the microphone -TBD].
19
+ The output is a mel spectrogram, which is converted to a mono 16 kHz waveform by the HiFi-GAN vocoder.
20
+ Because the model always applies random dropout, each attempt will give slightly different results.
21
+ """
22
+ article = """
23
+ <div style='margin:20px auto;'>
24
+ <p>Original demos: <a href="https://huggingface.co/spaces/Matthijs/speecht5-asr-demo">Speech recognition (ASR) demo</a> |
25
+ <a href="https://huggingface.co/spaces/Matthijs/speecht5-tts-demo">TTS demo</a> |
26
+ <a href="https://huggingface.co/spaces/Matthijs/speecht5-vc-demo">Voice Conversion demo</a> |
27
+ <a href="https://colab.research.google.com/drive/1XnOnCsmEmA3lHmzlNRNxRMcu80YZQzYf?usp=sharing">An interactive Colab notebook</a> |
28
+ <a href="https://colab.research.google.com/drive/1i7I5pzBcU3WDFarDnzweIj4-sVVoIUFJ">Fine-tunining SpeechT5 TTS</a>
29
+
30
+ <p>References: <a href="https://arxiv.org/abs/2110.07205">SpeechT5 paper</a> |
31
+ <a href="https://huggingface.co/blog/speecht5">SpeechT5 blog post</a> |
32
+ <a href="https://github.com/microsoft/SpeechT5/">original GitHub</a> |
33
+ <a href="https://huggingface.co/mechanicalsea/speecht5-vc">original weights</a></p>
34
+ <pre>
35
+ @article{Ao2021SpeechT5,
36
+ title = {SpeechT5: Unified-Modal Encoder-Decoder Pre-training for Spoken Language Processing},
37
+ author = {Junyi Ao and Rui Wang and Long Zhou and Chengyi Wang and Shuo Ren and Yu Wu and Shujie Liu and Tom Ko and Qing Li and Yu Zhang and Zhihua Wei and Yao Qian and Jinyu Li and Furu Wei},
38
+ eprint={2110.07205},
39
+ archivePrefix={arXiv},
40
+ primaryClass={eess.AS},
41
+ year={2021}
42
+ }
43
+ </pre>
44
+ <p>Speaker embeddings were generated from <a href="http://www.festvox.org/cmu_arctic/">CMU ARCTIC</a> using <a href="https://huggingface.co/mechanicalsea/speecht5-vc/blob/main/manifest/utils/prep_cmu_arctic_spkemb.py">this script</a>.</p>
45
+ </div>
46
+ """
47
+
48
+ device = "cuda" if torch.cuda.is_available() else "cpu"
49
+
50
+ checkpoint = "microsoft/speecht5_vc"
51
+ processor_vc = SpeechT5Processor.from_pretrained(checkpoint)
52
+ model_vc = SpeechT5ForSpeechToSpeech.from_pretrained(checkpoint)
53
+ checkpoint_tts = "microsoft/speecht5_tts"
54
+ processor_tts = SpeechT5Processor.from_pretrained(checkpoint_tts)
55
+ model_tts = SpeechT5ForTextToSpeech.from_pretrained(checkpoint_tts)
56
+ vocoder = SpeechT5HifiGan.from_pretrained("microsoft/speecht5_hifigan")
57
+
58
+
59
+ model_embed = {
60
+ "speechbrain/spkrec-xvect-voxceleb": 512,
61
+ "speechbrain/spkrec-ecapa-voxceleb": 192,
62
+ }
63
+ checkpoint_embed = "speechbrain/spkrec-xvect-voxceleb"
64
+ size_embed = model_embed[checkpoint_embed]
65
+ embeding_classifier = EncoderClassifier.from_hparams(source=checkpoint_embed, run_opts={"device": device}, savedir="/tmp/speaker_embed")
66
+
67
+ examples_pt = 'examples'
68
+ allowed_extentions = ['.mp3', '.wav']
69
+ examples = {f.name: f for f in Path(examples_pt).glob('*') if f.suffix in allowed_extentions}
70
+ default_voice = list(examples.keys())[0]
71
+ verse = """Mary had a little lamb,
72
+ Its fleece was white as snow.
73
+ Everywhere the child went,
74
+ The little lamb was sure to go."""
75
+
76
+ def process_audio(sampling_rate, waveform, target_sr=16000):
77
+ # convert from int16 to floating point
78
+ waveform = waveform / 32678.0
79
+
80
+ # convert to mono if stereo
81
+ if len(waveform.shape) > 1:
82
+ waveform = librosa.to_mono(waveform.T)
83
+
84
+ # resample to 16 kHz if necessary
85
+ if sampling_rate != target_sr:
86
+ waveform = librosa.resample(waveform, orig_sr=sampling_rate, target_sr=target_sr)
87
+
88
+ # limit to 30 seconds
89
+ waveform = waveform[:target_sr * 30]
90
+
91
+ # make PyTorch tensor
92
+ waveform = torch.tensor(waveform)
93
+ return waveform
94
+
95
+
96
+ def f2embed(waveform, sz):
97
+ with torch.no_grad():
98
+ embeddings = embeding_classifier.encode_batch(waveform)
99
+ embeddings = F.normalize(embeddings, dim=2)
100
+ embeddings = embeddings.squeeze().cpu().numpy()
101
+ assert embeddings.shape[0] == sz, embeddings.shape[0]
102
+ return embeddings
103
+
104
+
105
+ def on_voicedropdown(x):
106
+ return examples[x]
107
+
108
+
109
+ def on_voiceload(audio, sz=size_embed):
110
+ print("on_voiceload")
111
+ # audio = tuple (sample_rate, frames) or (sample_rate, (frames, channels))
112
+ if audio is not None:
113
+ sampling_rate, waveform = audio
114
+ else:
115
+ return np.zeros(sz)
116
+ waveform = process_audio(sampling_rate, waveform)
117
+ embed = f2embed(waveform, sz)
118
+ print("Generated embedding", embed[:5])
119
+ return embed
120
+
121
+
122
+ def voice_clone(audio, speaker_embedding, target_sr=16000):
123
+ # audio = tuple (sample_rate, frames) or (sample_rate, (frames, channels))
124
+ if audio is None or speaker_embedding is None:
125
+ return (target_sr, np.zeros(0).astype(np.int16))
126
+ else:
127
+ sampling_rate, waveform = audio
128
+
129
+ waveform = process_audio(sampling_rate, waveform)
130
+ inputs = processor_vc(audio=waveform, sampling_rate=target_sr, return_tensors="pt")
131
+
132
+ speaker_embedding = torch.tensor(speaker_embedding).unsqueeze(0)
133
+
134
+ speech = model_vc.generate_speech(inputs["input_values"], speaker_embedding, vocoder=vocoder)
135
+
136
+ speech = (speech.numpy() * 32767).astype(np.int16)
137
+ return (target_sr, speech)
138
+
139
+ def text_to_speech(text, speaker_embedding, target_sr=16000):
140
+ if len(text.strip()) == 0 or speaker_embedding is None:
141
+ return (target_sr, np.zeros(0).astype(np.int16))
142
+
143
+ inputs = processor_tts(text=text, return_tensors="pt")
144
+ # limit input length
145
+ input_ids = inputs["input_ids"]
146
+ input_ids = input_ids[..., :model_tts.config.max_text_positions]
147
+
148
+ speaker_embedding = torch.tensor(speaker_embedding).unsqueeze(0)
149
+
150
+ speech = model_tts.generate_speech(input_ids, speaker_embedding, vocoder=vocoder)
151
+
152
+ speech = (speech.numpy() * 32767).astype(np.int16)
153
+ return (target_sr, speech)
154
+
155
+ theme = gr.themes.Monochrome()
156
+ with gr.Blocks() as demo:
157
+ voice_embedding = gr.State(None)
158
+ def activate(*args):
159
+ return gr.update(interactive=True) if len(args) == 1 else [gr.update(interactive=True)] * len(args)
160
+ def deactivate(*args):
161
+ return gr.update(interactive=False) if len(args) == 1 else [gr.update(interactive=False)] * len(args)
162
+
163
+ gr.Markdown(description)
164
+
165
+ with gr.Accordion("Voice to clone", open=False) as accordion:
166
+ gr.Markdown("Upload target voice...")
167
+ with gr.Row(equal_height=True):
168
+ voice_upload = gr.Audio(label="Upload target voice", source="upload", type="numpy")
169
+ voice_dropdown = gr.Dropdown(examples, label='Examples', interactive=True)
170
+
171
+ # TODO: couldn't catch microphone stop event
172
+ # mic = gr.Audio(label="Record Speech", source="microphone", type="numpy")
173
+ # mic.stop(fn=lambda x: print('mic stop'), inputs=None, outputs=None)
174
+
175
+ with gr.Row(equal_height=True):
176
+ with gr.Column(scale=2):
177
+ with gr.Row(equal_height=True):
178
+ text_to_convert = gr.Textbox(verse)
179
+ voice_to_convert = gr.Audio(label="Upload voice to convert", source="upload", type="numpy")
180
+ with gr.Row(equal_height=True):
181
+ button_text = gr.Button("Text to speech", interactive=False)
182
+ button_audio = gr.Button("Convert audio", interactive=False)
183
+ with gr.Row(equal_height=True):
184
+ speech = gr.Audio(label="Converted Speech", type="numpy", visible=True, interactive=False)
185
+
186
+ # actions
187
+ kwargs = dict(fn=on_voiceload, inputs=voice_upload, outputs=voice_embedding)
188
+ voice_upload.upload(deactivate, [button_text, button_audio], [button_text, button_audio]).\
189
+ then(**kwargs).then(activate, [button_text, button_audio], [button_text, button_audio])
190
+ voice_dropdown.change(deactivate, [button_text, button_audio], [button_text, button_audio]).\
191
+ then(fn=on_voicedropdown, inputs=voice_dropdown, outputs=voice_upload).\
192
+ then(**kwargs).then(activate, [button_text, button_audio], [button_text, button_audio])
193
+ button_text.click(deactivate, [button_text, button_audio], [button_text, button_audio]).\
194
+ then(fn=text_to_speech, inputs=[text_to_convert, voice_embedding], outputs=speech).\
195
+ then(activate, [button_text, button_audio], [button_text, button_audio])
196
+ button_audio.click(deactivate, [button_text, button_audio], [button_text, button_audio]).\
197
+ then(fn=voice_clone, inputs=[voice_to_convert, voice_embedding], outputs=speech).\
198
+ then(activate, [button_text, button_audio], [button_text, button_audio])
199
+
200
+ gr.HTML(article)
201
+ demo.launch(share=False)
examples/arctic_a0023_bdl.wav ADDED
Binary file (168 kB). View file
 
examples/arctic_a0023_clb.wav ADDED
Binary file (189 kB). View file
 
examples/arctic_a0023_rms.wav ADDED
Binary file (172 kB). View file
 
examples/arctic_a0023_slt.wav ADDED
Binary file (153 kB). View file
 
examples/arctic_a0366_bdl.wav ADDED
Binary file (166 kB). View file
 
examples/arctic_a0366_rms.wav ADDED
Binary file (184 kB). View file
 
examples/arctic_a0407_bdl.wav ADDED
Binary file (183 kB). View file
 
examples/arctic_a0407_clb.wav ADDED
Binary file (200 kB). View file
 
examples/arctic_a0407_rms.wav ADDED
Binary file (216 kB). View file
 
examples/arctic_a0407_slt.wav ADDED
Binary file (171 kB). View file
 
examples/arctic_b0496_clb.wav ADDED
Binary file (192 kB). View file
 
examples/arctic_b0496_slt.wav ADDED
Binary file (171 kB). View file
 
examples/henry5.mp3 ADDED
Binary file (375 kB). View file
 
examples/hmm_i_dont_know.wav ADDED
Binary file (203 kB). View file
 
examples/see_in_eyes.wav ADDED
Binary file (65.2 kB). View file
 
examples/yearn_for_time.mp3 ADDED
Binary file (56.3 kB). View file