Spaces:
Sleeping
Sleeping
sanchit-gandhi
commited on
Commit
·
ab3a30c
1
Parent(s):
a823a34
from musicgen
Browse files- README.md +3 -2
- app.py +288 -0
- requirements.txt +1 -0
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
-
title: Parler
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: red
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: gradio
|
|
@@ -8,6 +8,7 @@ sdk_version: 4.27.0
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
|
|
|
| 11 |
---
|
| 12 |
|
| 13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Parler-TTS Streaming
|
| 3 |
+
emoji: 📝
|
| 4 |
colorFrom: red
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: gradio
|
|
|
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
license: apache-2.0
|
| 11 |
+
short_description: High-fidelity Text-To-Speech
|
| 12 |
---
|
| 13 |
|
| 14 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from queue import Queue
|
| 2 |
+
from threading import Thread
|
| 3 |
+
from typing import Optional
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import spaces
|
| 7 |
+
import gradio as gr
|
| 8 |
+
import torch
|
| 9 |
+
|
| 10 |
+
from parler_tts import ParlerTTSForConditionalGeneration
|
| 11 |
+
from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
|
| 12 |
+
from transformers.generation.streamers import BaseStreamer
|
| 13 |
+
|
| 14 |
+
device = "cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
| 15 |
+
torch_dtype = torch.float16 if device != "cpu" else torch.float32
|
| 16 |
+
|
| 17 |
+
repo_id = "parler-tts/parler_tts_mini_v0.1"
|
| 18 |
+
|
| 19 |
+
model = ParlerTTSForConditionalGeneration.from_pretrained(repo_id, torch_dtype=torch_dtype).to(device)
|
| 20 |
+
tokenizer = AutoTokenizer.from_pretrained(repo_id)
|
| 21 |
+
feature_extractor = AutoFeatureExtractor.from_pretrained(repo_id)
|
| 22 |
+
|
| 23 |
+
SAMPLE_RATE = feature_extractor.sampling_rate
|
| 24 |
+
SEED = 42
|
| 25 |
+
|
| 26 |
+
default_text = "Please surprise me and speak in whatever voice you enjoy."
|
| 27 |
+
examples = [
|
| 28 |
+
[
|
| 29 |
+
"Remember - this is only the first iteration of the model! To improve the prosody and naturalness of the speech further, we're scaling up the amount of training data by a factor of five times.",
|
| 30 |
+
"A male speaker with a low-pitched voice delivering his words at a fast pace in a small, confined space with a very clear audio and an animated tone."
|
| 31 |
+
],
|
| 32 |
+
[
|
| 33 |
+
"'This is the best time of my life, Bartley,' she said happily.",
|
| 34 |
+
"A female speaker with a slightly low-pitched, quite monotone voice delivers her words at a slightly faster-than-average pace in a confined space with very clear audio.",
|
| 35 |
+
],
|
| 36 |
+
[
|
| 37 |
+
"Montrose also, after having experienced still more variety of good and bad fortune, threw down his arms, and retired out of the kingdom.",
|
| 38 |
+
"A male speaker with a slightly high-pitched voice delivering his words at a slightly slow pace in a small, confined space with a touch of background noise and a quite monotone tone.",
|
| 39 |
+
],
|
| 40 |
+
[
|
| 41 |
+
"Montrose also, after having experienced still more variety of good and bad fortune, threw down his arms, and retired out of the kingdom.",
|
| 42 |
+
"A male speaker with a low-pitched voice delivers his words at a fast pace and an animated tone, in a very spacious environment, accompanied by noticeable background noise.",
|
| 43 |
+
],
|
| 44 |
+
]
|
| 45 |
+
|
| 46 |
+
class ParlerTTSStreamer(BaseStreamer):
|
| 47 |
+
def __init__(
|
| 48 |
+
self,
|
| 49 |
+
model: ParlerTTSForConditionalGeneration,
|
| 50 |
+
device: Optional[str] = None,
|
| 51 |
+
play_steps: Optional[int] = 10,
|
| 52 |
+
stride: Optional[int] = None,
|
| 53 |
+
timeout: Optional[float] = None,
|
| 54 |
+
):
|
| 55 |
+
"""
|
| 56 |
+
Streamer that stores playback-ready audio in a queue, to be used by a downstream application as an iterator. This is
|
| 57 |
+
useful for applications that benefit from accessing the generated audio in a non-blocking way (e.g. in an interactive
|
| 58 |
+
Gradio demo).
|
| 59 |
+
Parameters:
|
| 60 |
+
model (`ParlerTTSForConditionalGeneration`):
|
| 61 |
+
The Parler-TTS model used to generate the audio waveform.
|
| 62 |
+
device (`str`, *optional*):
|
| 63 |
+
The torch device on which to run the computation. If `None`, will default to the device of the model.
|
| 64 |
+
play_steps (`int`, *optional*, defaults to 10):
|
| 65 |
+
The number of generation steps with which to return the generated audio array. Using fewer steps will
|
| 66 |
+
mean the first chunk is ready faster, but will require more codec decoding steps overall. This value
|
| 67 |
+
should be tuned to your device and latency requirements.
|
| 68 |
+
stride (`int`, *optional*):
|
| 69 |
+
The window (stride) between adjacent audio samples. Using a stride between adjacent audio samples reduces
|
| 70 |
+
the hard boundary between them, giving smoother playback. If `None`, will default to a value equivalent to
|
| 71 |
+
play_steps // 6 in the audio space.
|
| 72 |
+
timeout (`int`, *optional*):
|
| 73 |
+
The timeout for the audio queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
|
| 74 |
+
in `.generate()`, when it is called in a separate thread.
|
| 75 |
+
"""
|
| 76 |
+
self.decoder = model.decoder
|
| 77 |
+
self.audio_encoder = model.audio_encoder
|
| 78 |
+
self.generation_config = model.generation_config
|
| 79 |
+
self.device = device if device is not None else model.device
|
| 80 |
+
|
| 81 |
+
# variables used in the streaming process
|
| 82 |
+
self.play_steps = play_steps
|
| 83 |
+
if stride is not None:
|
| 84 |
+
self.stride = stride
|
| 85 |
+
else:
|
| 86 |
+
hop_length = np.prod(self.audio_encoder.config.upsampling_ratios)
|
| 87 |
+
self.stride = hop_length * (play_steps - self.decoder.num_codebooks) // 6
|
| 88 |
+
self.token_cache = None
|
| 89 |
+
self.to_yield = 0
|
| 90 |
+
|
| 91 |
+
# varibles used in the thread process
|
| 92 |
+
self.audio_queue = Queue()
|
| 93 |
+
self.stop_signal = None
|
| 94 |
+
self.timeout = timeout
|
| 95 |
+
|
| 96 |
+
def apply_delay_pattern_mask(self, input_ids):
|
| 97 |
+
# build the delay pattern mask for offsetting each codebook prediction by 1 (this behaviour is specific to MusicGen)
|
| 98 |
+
_, decoder_delay_pattern_mask = self.decoder.build_delay_pattern_mask(
|
| 99 |
+
input_ids[:, :1],
|
| 100 |
+
pad_token_id=self.generation_config.decoder_start_token_id,
|
| 101 |
+
max_length=input_ids.shape[-1],
|
| 102 |
+
)
|
| 103 |
+
# apply the pattern mask to the input ids
|
| 104 |
+
input_ids = self.decoder.apply_delay_pattern_mask(input_ids, decoder_delay_pattern_mask)
|
| 105 |
+
|
| 106 |
+
# revert the pattern delay mask by filtering the pad token id
|
| 107 |
+
input_ids = input_ids[input_ids != self.generation_config.pad_token_id].reshape(
|
| 108 |
+
1, self.decoder.num_codebooks, -1
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
# append the frame dimension back to the audio codes
|
| 112 |
+
input_ids = input_ids[None, ...]
|
| 113 |
+
|
| 114 |
+
# send the input_ids to the correct device
|
| 115 |
+
input_ids = input_ids.to(self.audio_encoder.device)
|
| 116 |
+
|
| 117 |
+
output_values = self.audio_encoder.decode(
|
| 118 |
+
input_ids,
|
| 119 |
+
audio_scales=[None],
|
| 120 |
+
)
|
| 121 |
+
audio_values = output_values.audio_values[0, 0]
|
| 122 |
+
return audio_values.cpu().float().numpy()
|
| 123 |
+
|
| 124 |
+
def put(self, value):
|
| 125 |
+
batch_size = value.shape[0] // self.decoder.num_codebooks
|
| 126 |
+
if batch_size > 1:
|
| 127 |
+
raise ValueError("MusicgenStreamer only supports batch size 1")
|
| 128 |
+
|
| 129 |
+
if self.token_cache is None:
|
| 130 |
+
self.token_cache = value
|
| 131 |
+
else:
|
| 132 |
+
self.token_cache = torch.concatenate([self.token_cache, value[:, None]], dim=-1)
|
| 133 |
+
|
| 134 |
+
if self.token_cache.shape[-1] % self.play_steps == 0:
|
| 135 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
| 136 |
+
self.on_finalized_audio(audio_values[self.to_yield : -self.stride])
|
| 137 |
+
self.to_yield += len(audio_values) - self.to_yield - self.stride
|
| 138 |
+
|
| 139 |
+
def end(self):
|
| 140 |
+
"""Flushes any remaining cache and appends the stop symbol."""
|
| 141 |
+
if self.token_cache is not None:
|
| 142 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
| 143 |
+
else:
|
| 144 |
+
audio_values = np.zeros(self.to_yield)
|
| 145 |
+
|
| 146 |
+
self.on_finalized_audio(audio_values[self.to_yield :], stream_end=True)
|
| 147 |
+
|
| 148 |
+
def on_finalized_audio(self, audio: np.ndarray, stream_end: bool = False):
|
| 149 |
+
"""Put the new audio in the queue. If the stream is ending, also put a stop signal in the queue."""
|
| 150 |
+
self.audio_queue.put(audio, timeout=self.timeout)
|
| 151 |
+
if stream_end:
|
| 152 |
+
self.audio_queue.put(self.stop_signal, timeout=self.timeout)
|
| 153 |
+
|
| 154 |
+
def __iter__(self):
|
| 155 |
+
return self
|
| 156 |
+
|
| 157 |
+
def __next__(self):
|
| 158 |
+
value = self.audio_queue.get(timeout=self.timeout)
|
| 159 |
+
if not isinstance(value, np.ndarray) and value == self.stop_signal:
|
| 160 |
+
raise StopIteration()
|
| 161 |
+
else:
|
| 162 |
+
return value
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
sampling_rate = model.audio_encoder.config.sampling_rate
|
| 166 |
+
frame_rate = model.audio_encoder.config.frame_rate
|
| 167 |
+
|
| 168 |
+
target_dtype = np.int16
|
| 169 |
+
max_range = np.iinfo(target_dtype).max
|
| 170 |
+
|
| 171 |
+
@spaces.GPU
|
| 172 |
+
def gen_tts(text, description, play_steps_in_s=2.0):
|
| 173 |
+
play_steps = int(frame_rate * play_steps_in_s)
|
| 174 |
+
streamer = ParlerTTSStreamer(model, device=device, play_steps=play_steps)
|
| 175 |
+
|
| 176 |
+
inputs = tokenizer(description, return_tensors="pt").to(device)
|
| 177 |
+
prompt = tokenizer(text, return_tensors="pt").to(device)
|
| 178 |
+
|
| 179 |
+
generation_kwargs = dict(
|
| 180 |
+
input_ids=inputs.input_ids,
|
| 181 |
+
prompt_input_ids=prompt.input_ids,
|
| 182 |
+
streamer=streamer,
|
| 183 |
+
do_sample=True,
|
| 184 |
+
temperature=1.0,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
set_seed(SEED)
|
| 188 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
| 189 |
+
thread.start()
|
| 190 |
+
|
| 191 |
+
for new_audio in streamer:
|
| 192 |
+
print(f"Sample of length: {round(new_audio.shape[0] / sampling_rate, 2)} seconds")
|
| 193 |
+
new_audio = (new_audio * max_range).astype(np.int16)
|
| 194 |
+
yield sampling_rate, new_audio
|
| 195 |
+
|
| 196 |
+
css = """
|
| 197 |
+
#share-btn-container {
|
| 198 |
+
display: flex;
|
| 199 |
+
padding-left: 0.5rem !important;
|
| 200 |
+
padding-right: 0.5rem !important;
|
| 201 |
+
background-color: #000000;
|
| 202 |
+
justify-content: center;
|
| 203 |
+
align-items: center;
|
| 204 |
+
border-radius: 9999px !important;
|
| 205 |
+
width: 13rem;
|
| 206 |
+
margin-top: 10px;
|
| 207 |
+
margin-left: auto;
|
| 208 |
+
flex: unset !important;
|
| 209 |
+
}
|
| 210 |
+
#share-btn {
|
| 211 |
+
all: initial;
|
| 212 |
+
color: #ffffff;
|
| 213 |
+
font-weight: 600;
|
| 214 |
+
cursor: pointer;
|
| 215 |
+
font-family: 'IBM Plex Sans', sans-serif;
|
| 216 |
+
margin-left: 0.5rem !important;
|
| 217 |
+
padding-top: 0.25rem !important;
|
| 218 |
+
padding-bottom: 0.25rem !important;
|
| 219 |
+
right:0;
|
| 220 |
+
}
|
| 221 |
+
#share-btn * {
|
| 222 |
+
all: unset !important;
|
| 223 |
+
}
|
| 224 |
+
#share-btn-container div:nth-child(-n+2){
|
| 225 |
+
width: auto !important;
|
| 226 |
+
min-height: 0px !important;
|
| 227 |
+
}
|
| 228 |
+
#share-btn-container .wrap {
|
| 229 |
+
display: none !important;
|
| 230 |
+
}
|
| 231 |
+
"""
|
| 232 |
+
with gr.Blocks(css=css) as block:
|
| 233 |
+
gr.HTML(
|
| 234 |
+
"""
|
| 235 |
+
<div style="text-align: center; max-width: 700px; margin: 0 auto;">
|
| 236 |
+
<div
|
| 237 |
+
style="
|
| 238 |
+
display: inline-flex; align-items: center; gap: 0.8rem; font-size: 1.75rem;
|
| 239 |
+
"
|
| 240 |
+
>
|
| 241 |
+
<h1 style="font-weight: 900; margin-bottom: 7px; line-height: normal;">
|
| 242 |
+
Parler-TTS 🗣️
|
| 243 |
+
</h1>
|
| 244 |
+
</div>
|
| 245 |
+
</div>
|
| 246 |
+
"""
|
| 247 |
+
)
|
| 248 |
+
gr.HTML(
|
| 249 |
+
f"""
|
| 250 |
+
<p><a href="https://github.com/huggingface/parler-tts"> Parler-TTS</a> is a training and inference library for
|
| 251 |
+
high-fidelity text-to-speech (TTS) models. The model demonstrated here, <a href="https://huggingface.co/parler-tts/parler_tts_mini_v0.1"> Parler-TTS Mini v0.1</a>,
|
| 252 |
+
is the first iteration model trained using 10k hours of narrated audiobooks. It generates high-quality speech
|
| 253 |
+
with features that can be controlled using a simple text prompt (e.g. gender, background noise, speaking rate, pitch and reverberation).</p>
|
| 254 |
+
|
| 255 |
+
<p>Tips for ensuring good generation:
|
| 256 |
+
<ul>
|
| 257 |
+
<li>Include the term "very clear audio" to generate the highest quality audio, and "very noisy audio" for high levels of background noise</li>
|
| 258 |
+
<li>Punctuation can be used to control the prosody of the generations, e.g. use commas to add small breaks in speech</li>
|
| 259 |
+
<li>The remaining speech features (gender, speaking rate, pitch and reverberation) can be controlled directly through the prompt</li>
|
| 260 |
+
</ul>
|
| 261 |
+
</p>
|
| 262 |
+
"""
|
| 263 |
+
)
|
| 264 |
+
with gr.Row():
|
| 265 |
+
with gr.Column():
|
| 266 |
+
input_text = gr.Textbox(label="Input Text", lines=2, value=default_text, elem_id="input_text")
|
| 267 |
+
description = gr.Textbox(label="Description", lines=2, value="", elem_id="input_description")
|
| 268 |
+
run_button = gr.Button("Generate Audio", variant="primary")
|
| 269 |
+
with gr.Column():
|
| 270 |
+
audio_out = gr.Audio(label="Parler-TTS generation", type="numpy", elem_id="audio_out")
|
| 271 |
+
|
| 272 |
+
inputs = [input_text, description]
|
| 273 |
+
outputs = [audio_out]
|
| 274 |
+
gr.Examples(examples=examples, fn=gen_tts, inputs=inputs, outputs=outputs, cache_examples=True)
|
| 275 |
+
run_button.click(fn=gen_tts, inputs=inputs, outputs=outputs, queue=True)
|
| 276 |
+
gr.HTML(
|
| 277 |
+
"""
|
| 278 |
+
<p>To improve the prosody and naturalness of the speech further, we're scaling up the amount of training data to 50k hours of speech.
|
| 279 |
+
The v1 release of the model will be trained on this data, as well as inference optimisations, such as flash attention
|
| 280 |
+
and torch compile, that will improve the latency by 2-4x. If you want to find out more about how this model was trained and even fine-tune it yourself, check-out the
|
| 281 |
+
<a href="https://github.com/huggingface/parler-tts"> Parler-TTS</a> repository on GitHub.</p>
|
| 282 |
+
|
| 283 |
+
<p>The Parler-TTS codebase and its associated checkpoints are licensed under <a href='https://github.com/huggingface/parler-tts?tab=Apache-2.0-1-ov-file#readme'> Apache 2.0</a>.</p>
|
| 284 |
+
"""
|
| 285 |
+
)
|
| 286 |
+
|
| 287 |
+
block.queue()
|
| 288 |
+
block.launch(share=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
git+https://github.com/huggingface/parler-tts.git
|