Spaces:
Running
on
Zero
Running
on
Zero
Commit
•
2acc3a1
1
Parent(s):
f3f7cbd
Add code
Browse files- README.md +2 -2
- app.py +38 -181
- streamer.py +133 -0
README.md
CHANGED
@@ -1,6 +1,6 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
-
emoji:
|
4 |
colorFrom: red
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
|
|
1 |
---
|
2 |
+
title: Magic 8 Ball
|
3 |
+
emoji: 🎱
|
4 |
colorFrom: red
|
5 |
colorTo: indigo
|
6 |
sdk: gradio
|
app.py
CHANGED
@@ -1,8 +1,7 @@
|
|
1 |
import io
|
2 |
import math
|
3 |
-
from queue import Queue
|
4 |
from threading import Thread
|
5 |
-
|
6 |
|
7 |
import numpy as np
|
8 |
import spaces
|
@@ -12,10 +11,8 @@ import torch
|
|
12 |
from parler_tts import ParlerTTSForConditionalGeneration
|
13 |
from pydub import AudioSegment
|
14 |
from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
|
15 |
-
from transformers.generation.streamers import BaseStreamer
|
16 |
from huggingface_hub import InferenceClient
|
17 |
-
import
|
18 |
-
nltk.download('punkt')
|
19 |
|
20 |
|
21 |
device = "cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
@@ -38,135 +35,6 @@ SAMPLE_RATE = feature_extractor.sampling_rate
|
|
38 |
SEED = 42
|
39 |
|
40 |
|
41 |
-
class ParlerTTSStreamer(BaseStreamer):
|
42 |
-
def __init__(
|
43 |
-
self,
|
44 |
-
model: ParlerTTSForConditionalGeneration,
|
45 |
-
device: Optional[str] = None,
|
46 |
-
play_steps: Optional[int] = 10,
|
47 |
-
stride: Optional[int] = None,
|
48 |
-
timeout: Optional[float] = None,
|
49 |
-
):
|
50 |
-
"""
|
51 |
-
Streamer that stores playback-ready audio in a queue, to be used by a downstream application as an iterator. This is
|
52 |
-
useful for applications that benefit from accessing the generated audio in a non-blocking way (e.g. in an interactive
|
53 |
-
Gradio demo).
|
54 |
-
Parameters:
|
55 |
-
model (`ParlerTTSForConditionalGeneration`):
|
56 |
-
The Parler-TTS model used to generate the audio waveform.
|
57 |
-
device (`str`, *optional*):
|
58 |
-
The torch device on which to run the computation. If `None`, will default to the device of the model.
|
59 |
-
play_steps (`int`, *optional*, defaults to 10):
|
60 |
-
The number of generation steps with which to return the generated audio array. Using fewer steps will
|
61 |
-
mean the first chunk is ready faster, but will require more codec decoding steps overall. This value
|
62 |
-
should be tuned to your device and latency requirements.
|
63 |
-
stride (`int`, *optional*):
|
64 |
-
The window (stride) between adjacent audio samples. Using a stride between adjacent audio samples reduces
|
65 |
-
the hard boundary between them, giving smoother playback. If `None`, will default to a value equivalent to
|
66 |
-
play_steps // 6 in the audio space.
|
67 |
-
timeout (`int`, *optional*):
|
68 |
-
The timeout for the audio queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
|
69 |
-
in `.generate()`, when it is called in a separate thread.
|
70 |
-
"""
|
71 |
-
self.decoder = model.decoder
|
72 |
-
self.audio_encoder = model.audio_encoder
|
73 |
-
self.generation_config = model.generation_config
|
74 |
-
self.device = device if device is not None else model.device
|
75 |
-
|
76 |
-
# variables used in the streaming process
|
77 |
-
self.play_steps = play_steps
|
78 |
-
if stride is not None:
|
79 |
-
self.stride = stride
|
80 |
-
else:
|
81 |
-
hop_length = math.floor(self.audio_encoder.config.sampling_rate / self.audio_encoder.config.frame_rate)
|
82 |
-
self.stride = hop_length * (play_steps - self.decoder.num_codebooks) // 6
|
83 |
-
self.token_cache = None
|
84 |
-
self.to_yield = 0
|
85 |
-
|
86 |
-
# varibles used in the thread process
|
87 |
-
self.audio_queue = Queue()
|
88 |
-
self.stop_signal = None
|
89 |
-
self.timeout = timeout
|
90 |
-
|
91 |
-
def apply_delay_pattern_mask(self, input_ids):
|
92 |
-
# build the delay pattern mask for offsetting each codebook prediction by 1 (this behaviour is specific to Parler)
|
93 |
-
_, delay_pattern_mask = self.decoder.build_delay_pattern_mask(
|
94 |
-
input_ids[:, :1],
|
95 |
-
bos_token_id=self.generation_config.bos_token_id,
|
96 |
-
pad_token_id=self.generation_config.decoder_start_token_id,
|
97 |
-
max_length=input_ids.shape[-1],
|
98 |
-
)
|
99 |
-
# apply the pattern mask to the input ids
|
100 |
-
input_ids = self.decoder.apply_delay_pattern_mask(input_ids, delay_pattern_mask)
|
101 |
-
|
102 |
-
# revert the pattern delay mask by filtering the pad token id
|
103 |
-
mask = (delay_pattern_mask != self.generation_config.bos_token_id) & (delay_pattern_mask != self.generation_config.pad_token_id)
|
104 |
-
input_ids = input_ids[mask].reshape(1, self.decoder.num_codebooks, -1)
|
105 |
-
# append the frame dimension back to the audio codes
|
106 |
-
input_ids = input_ids[None, ...]
|
107 |
-
|
108 |
-
# send the input_ids to the correct device
|
109 |
-
input_ids = input_ids.to(self.audio_encoder.device)
|
110 |
-
|
111 |
-
decode_sequentially = (
|
112 |
-
self.generation_config.bos_token_id in input_ids
|
113 |
-
or self.generation_config.pad_token_id in input_ids
|
114 |
-
or self.generation_config.eos_token_id in input_ids
|
115 |
-
)
|
116 |
-
if not decode_sequentially:
|
117 |
-
output_values = self.audio_encoder.decode(
|
118 |
-
input_ids,
|
119 |
-
audio_scales=[None],
|
120 |
-
)
|
121 |
-
else:
|
122 |
-
sample = input_ids[:, 0]
|
123 |
-
sample_mask = (sample >= self.audio_encoder.config.codebook_size).sum(dim=(0, 1)) == 0
|
124 |
-
sample = sample[:, :, sample_mask]
|
125 |
-
output_values = self.audio_encoder.decode(sample[None, ...], [None])
|
126 |
-
|
127 |
-
audio_values = output_values.audio_values[0, 0]
|
128 |
-
return audio_values.cpu().float().numpy()
|
129 |
-
|
130 |
-
def put(self, value):
|
131 |
-
batch_size = value.shape[0] // self.decoder.num_codebooks
|
132 |
-
if batch_size > 1:
|
133 |
-
raise ValueError("ParlerTTSStreamer only supports batch size 1")
|
134 |
-
|
135 |
-
if self.token_cache is None:
|
136 |
-
self.token_cache = value
|
137 |
-
else:
|
138 |
-
self.token_cache = torch.concatenate([self.token_cache, value[:, None]], dim=-1)
|
139 |
-
|
140 |
-
if self.token_cache.shape[-1] % self.play_steps == 0:
|
141 |
-
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
142 |
-
self.on_finalized_audio(audio_values[self.to_yield : -self.stride])
|
143 |
-
self.to_yield += len(audio_values) - self.to_yield - self.stride
|
144 |
-
|
145 |
-
def end(self):
|
146 |
-
"""Flushes any remaining cache and appends the stop symbol."""
|
147 |
-
if self.token_cache is not None:
|
148 |
-
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
149 |
-
else:
|
150 |
-
audio_values = np.zeros(self.to_yield)
|
151 |
-
|
152 |
-
self.on_finalized_audio(audio_values[self.to_yield :], stream_end=True)
|
153 |
-
|
154 |
-
def on_finalized_audio(self, audio: np.ndarray, stream_end: bool = False):
|
155 |
-
"""Put the new audio in the queue. If the stream is ending, also put a stop signal in the queue."""
|
156 |
-
self.audio_queue.put(audio, timeout=self.timeout)
|
157 |
-
if stream_end:
|
158 |
-
self.audio_queue.put(self.stop_signal, timeout=self.timeout)
|
159 |
-
|
160 |
-
def __iter__(self):
|
161 |
-
return self
|
162 |
-
|
163 |
-
def __next__(self):
|
164 |
-
value = self.audio_queue.get(timeout=self.timeout)
|
165 |
-
if not isinstance(value, np.ndarray) and value == self.stop_signal:
|
166 |
-
raise StopIteration()
|
167 |
-
else:
|
168 |
-
return value
|
169 |
-
|
170 |
def numpy_to_mp3(audio_array, sampling_rate):
|
171 |
# Normalize audio_array if it's floating-point
|
172 |
if np.issubdtype(audio_array.dtype, np.floating):
|
@@ -195,75 +63,64 @@ def numpy_to_mp3(audio_array, sampling_rate):
|
|
195 |
sampling_rate = model.audio_encoder.config.sampling_rate
|
196 |
frame_rate = model.audio_encoder.config.frame_rate
|
197 |
|
198 |
-
import random
|
199 |
-
import datetime
|
200 |
-
|
201 |
@spaces.GPU
|
202 |
-
def generate_base(
|
203 |
|
204 |
-
|
205 |
-
|
206 |
-
|
207 |
-
"
|
208 |
-
|
209 |
-
|
|
|
|
|
210 |
response = client.chat_completion(messages, max_tokens=1024, seed=random.randint(1, 5000))
|
211 |
-
|
212 |
-
story = response.choices[0].message.content
|
213 |
|
214 |
-
model_input = story.replace("\n", " ").strip()
|
215 |
-
model_input_tokens = nltk.sent_tokenize(model_input)
|
216 |
|
217 |
-
play_steps_in_s =
|
218 |
play_steps = int(frame_rate * play_steps_in_s)
|
219 |
|
220 |
description = "Jenny speaks at an average pace with a calm delivery in a very confined sounding environment with clear audio quality."
|
221 |
description_tokens = tokenizer(description, return_tensors="pt").to(device)
|
222 |
|
223 |
-
|
224 |
-
|
225 |
-
|
226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
227 |
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
streamer=streamer,
|
232 |
-
do_sample=True,
|
233 |
-
temperature=1.0,
|
234 |
-
min_new_tokens=10,
|
235 |
-
)
|
236 |
|
237 |
-
|
238 |
-
|
239 |
-
|
240 |
|
241 |
-
|
242 |
-
|
243 |
-
gr.Info("Reading story", duration=3)
|
244 |
-
print(f"Sample of length: {round(new_audio.shape[0] / sampling_rate, 2)} seconds")
|
245 |
-
yield story, numpy_to_mp3(new_audio, sampling_rate=sampling_rate)
|
246 |
|
247 |
with gr.Blocks() as block:
|
248 |
gr.HTML(
|
249 |
f"""
|
250 |
-
<h1>
|
251 |
-
<p> Powered by <a href="https://github.com/huggingface/parler-tts"> Parler-TTS</a>
|
252 |
"""
|
253 |
)
|
254 |
with gr.Group():
|
255 |
with gr.Row():
|
256 |
-
|
257 |
-
|
258 |
with gr.Row():
|
259 |
-
|
260 |
-
with gr.Row():
|
261 |
-
with gr.Group():
|
262 |
-
audio_out = gr.Audio(label="Bed time story", streaming=True, autoplay=True)
|
263 |
-
story = gr.Textbox(label="Story")
|
264 |
|
265 |
-
inputs =
|
266 |
-
outputs = [story, audio_out]
|
267 |
-
run_button.click(fn=generate_base, inputs=inputs, outputs=outputs)
|
268 |
|
269 |
block.launch()
|
|
|
1 |
import io
|
2 |
import math
|
|
|
3 |
from threading import Thread
|
4 |
+
import random
|
5 |
|
6 |
import numpy as np
|
7 |
import spaces
|
|
|
11 |
from parler_tts import ParlerTTSForConditionalGeneration
|
12 |
from pydub import AudioSegment
|
13 |
from transformers import AutoTokenizer, AutoFeatureExtractor, set_seed
|
|
|
14 |
from huggingface_hub import InferenceClient
|
15 |
+
from streamer import ParlerTTSStreamer
|
|
|
16 |
|
17 |
|
18 |
device = "cuda:0" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
|
|
|
35 |
SEED = 42
|
36 |
|
37 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
38 |
def numpy_to_mp3(audio_array, sampling_rate):
|
39 |
# Normalize audio_array if it's floating-point
|
40 |
if np.issubdtype(audio_array.dtype, np.floating):
|
|
|
63 |
sampling_rate = model.audio_encoder.config.sampling_rate
|
64 |
frame_rate = model.audio_encoder.config.frame_rate
|
65 |
|
|
|
|
|
|
|
66 |
@spaces.GPU
|
67 |
+
def generate_base(audio):
|
68 |
|
69 |
+
question = client.audtomatic_speech_recognition(audio)
|
70 |
+
|
71 |
+
messages = [{"role": "sytem", "content": ("You are a magic 8 ball."
|
72 |
+
"Someone will present to you a situation or question and your job "
|
73 |
+
"is to answer with a cryptic addage or proverb such as "
|
74 |
+
"'curiosity killed the cat' or 'The early bird gets the worm'.")},
|
75 |
+
{"role": "user", "content": f"Please tell me what to do about {question}"}]
|
76 |
+
|
77 |
response = client.chat_completion(messages, max_tokens=1024, seed=random.randint(1, 5000))
|
78 |
+
response = response.choices[0].message.content
|
|
|
79 |
|
|
|
|
|
80 |
|
81 |
+
play_steps_in_s = 1.0
|
82 |
play_steps = int(frame_rate * play_steps_in_s)
|
83 |
|
84 |
description = "Jenny speaks at an average pace with a calm delivery in a very confined sounding environment with clear audio quality."
|
85 |
description_tokens = tokenizer(description, return_tensors="pt").to(device)
|
86 |
|
87 |
+
streamer = ParlerTTSStreamer(model, device=device, play_steps=play_steps)
|
88 |
+
prompt = tokenizer(sentence, return_tensors="pt").to(device)
|
89 |
+
|
90 |
+
generation_kwargs = dict(
|
91 |
+
input_ids=description_tokens.input_ids,
|
92 |
+
prompt_input_ids=prompt.input_ids,
|
93 |
+
streamer=streamer,
|
94 |
+
do_sample=True,
|
95 |
+
temperature=1.0,
|
96 |
+
min_new_tokens=10,
|
97 |
+
)
|
98 |
|
99 |
+
set_seed(SEED)
|
100 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
101 |
+
thread.start()
|
|
|
|
|
|
|
|
|
|
|
102 |
|
103 |
+
for new_audio in streamer:
|
104 |
+
print(f"Sample of length: {round(new_audio.shape[0] / sampling_rate, 2)} seconds")
|
105 |
+
yield story, numpy_to_mp3(new_audio, sampling_rate=sampling_rate)
|
106 |
|
107 |
+
css=""".my-group {max-width: 600px !important; max-height: 600 !important;}
|
108 |
+
.my-column {display: flex !important; justify-content: center !important; align-items: center !important};"""
|
|
|
|
|
|
|
109 |
|
110 |
with gr.Blocks() as block:
|
111 |
gr.HTML(
|
112 |
f"""
|
113 |
+
<h1 style='text-align: center;'> Magic 8 Ball 🎱 </h1>
|
114 |
+
<p style='text-align: center;'> Powered by <a href="https://github.com/huggingface/parler-tts"> Parler-TTS</a>
|
115 |
"""
|
116 |
)
|
117 |
with gr.Group():
|
118 |
with gr.Row():
|
119 |
+
audio_out = gr.Audio(visble=False, streaming=True)
|
120 |
+
answer = gr.Textbox(label="Answer")
|
121 |
with gr.Row():
|
122 |
+
audio_in = gr.Audio(label="Speak you question", sources="microphone", format="filepath")
|
|
|
|
|
|
|
|
|
123 |
|
124 |
+
audio_in.stop_recording(fn=generate_base, inputs=audio_in, outputs=[answer, audio_out])
|
|
|
|
|
125 |
|
126 |
block.launch()
|
streamer.py
ADDED
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from queue import Queue
|
2 |
+
from transformers.generation.streamers import BaseStreamer
|
3 |
+
from typing import Optional
|
4 |
+
|
5 |
+
|
6 |
+
class ParlerTTSStreamer(BaseStreamer):
|
7 |
+
def __init__(
|
8 |
+
self,
|
9 |
+
model: ParlerTTSForConditionalGeneration,
|
10 |
+
device: Optional[str] = None,
|
11 |
+
play_steps: Optional[int] = 10,
|
12 |
+
stride: Optional[int] = None,
|
13 |
+
timeout: Optional[float] = None,
|
14 |
+
):
|
15 |
+
"""
|
16 |
+
Streamer that stores playback-ready audio in a queue, to be used by a downstream application as an iterator. This is
|
17 |
+
useful for applications that benefit from accessing the generated audio in a non-blocking way (e.g. in an interactive
|
18 |
+
Gradio demo).
|
19 |
+
Parameters:
|
20 |
+
model (`ParlerTTSForConditionalGeneration`):
|
21 |
+
The Parler-TTS model used to generate the audio waveform.
|
22 |
+
device (`str`, *optional*):
|
23 |
+
The torch device on which to run the computation. If `None`, will default to the device of the model.
|
24 |
+
play_steps (`int`, *optional*, defaults to 10):
|
25 |
+
The number of generation steps with which to return the generated audio array. Using fewer steps will
|
26 |
+
mean the first chunk is ready faster, but will require more codec decoding steps overall. This value
|
27 |
+
should be tuned to your device and latency requirements.
|
28 |
+
stride (`int`, *optional*):
|
29 |
+
The window (stride) between adjacent audio samples. Using a stride between adjacent audio samples reduces
|
30 |
+
the hard boundary between them, giving smoother playback. If `None`, will default to a value equivalent to
|
31 |
+
play_steps // 6 in the audio space.
|
32 |
+
timeout (`int`, *optional*):
|
33 |
+
The timeout for the audio queue. If `None`, the queue will block indefinitely. Useful to handle exceptions
|
34 |
+
in `.generate()`, when it is called in a separate thread.
|
35 |
+
"""
|
36 |
+
self.decoder = model.decoder
|
37 |
+
self.audio_encoder = model.audio_encoder
|
38 |
+
self.generation_config = model.generation_config
|
39 |
+
self.device = device if device is not None else model.device
|
40 |
+
|
41 |
+
# variables used in the streaming process
|
42 |
+
self.play_steps = play_steps
|
43 |
+
if stride is not None:
|
44 |
+
self.stride = stride
|
45 |
+
else:
|
46 |
+
hop_length = math.floor(self.audio_encoder.config.sampling_rate / self.audio_encoder.config.frame_rate)
|
47 |
+
self.stride = hop_length * (play_steps - self.decoder.num_codebooks) // 6
|
48 |
+
self.token_cache = None
|
49 |
+
self.to_yield = 0
|
50 |
+
|
51 |
+
# varibles used in the thread process
|
52 |
+
self.audio_queue = Queue()
|
53 |
+
self.stop_signal = None
|
54 |
+
self.timeout = timeout
|
55 |
+
|
56 |
+
def apply_delay_pattern_mask(self, input_ids):
|
57 |
+
# build the delay pattern mask for offsetting each codebook prediction by 1 (this behaviour is specific to Parler)
|
58 |
+
_, delay_pattern_mask = self.decoder.build_delay_pattern_mask(
|
59 |
+
input_ids[:, :1],
|
60 |
+
bos_token_id=self.generation_config.bos_token_id,
|
61 |
+
pad_token_id=self.generation_config.decoder_start_token_id,
|
62 |
+
max_length=input_ids.shape[-1],
|
63 |
+
)
|
64 |
+
# apply the pattern mask to the input ids
|
65 |
+
input_ids = self.decoder.apply_delay_pattern_mask(input_ids, delay_pattern_mask)
|
66 |
+
|
67 |
+
# revert the pattern delay mask by filtering the pad token id
|
68 |
+
mask = (delay_pattern_mask != self.generation_config.bos_token_id) & (delay_pattern_mask != self.generation_config.pad_token_id)
|
69 |
+
input_ids = input_ids[mask].reshape(1, self.decoder.num_codebooks, -1)
|
70 |
+
# append the frame dimension back to the audio codes
|
71 |
+
input_ids = input_ids[None, ...]
|
72 |
+
|
73 |
+
# send the input_ids to the correct device
|
74 |
+
input_ids = input_ids.to(self.audio_encoder.device)
|
75 |
+
|
76 |
+
decode_sequentially = (
|
77 |
+
self.generation_config.bos_token_id in input_ids
|
78 |
+
or self.generation_config.pad_token_id in input_ids
|
79 |
+
or self.generation_config.eos_token_id in input_ids
|
80 |
+
)
|
81 |
+
if not decode_sequentially:
|
82 |
+
output_values = self.audio_encoder.decode(
|
83 |
+
input_ids,
|
84 |
+
audio_scales=[None],
|
85 |
+
)
|
86 |
+
else:
|
87 |
+
sample = input_ids[:, 0]
|
88 |
+
sample_mask = (sample >= self.audio_encoder.config.codebook_size).sum(dim=(0, 1)) == 0
|
89 |
+
sample = sample[:, :, sample_mask]
|
90 |
+
output_values = self.audio_encoder.decode(sample[None, ...], [None])
|
91 |
+
|
92 |
+
audio_values = output_values.audio_values[0, 0]
|
93 |
+
return audio_values.cpu().float().numpy()
|
94 |
+
|
95 |
+
def put(self, value):
|
96 |
+
batch_size = value.shape[0] // self.decoder.num_codebooks
|
97 |
+
if batch_size > 1:
|
98 |
+
raise ValueError("ParlerTTSStreamer only supports batch size 1")
|
99 |
+
|
100 |
+
if self.token_cache is None:
|
101 |
+
self.token_cache = value
|
102 |
+
else:
|
103 |
+
self.token_cache = torch.concatenate([self.token_cache, value[:, None]], dim=-1)
|
104 |
+
|
105 |
+
if self.token_cache.shape[-1] % self.play_steps == 0:
|
106 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
107 |
+
self.on_finalized_audio(audio_values[self.to_yield : -self.stride])
|
108 |
+
self.to_yield += len(audio_values) - self.to_yield - self.stride
|
109 |
+
|
110 |
+
def end(self):
|
111 |
+
"""Flushes any remaining cache and appends the stop symbol."""
|
112 |
+
if self.token_cache is not None:
|
113 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
114 |
+
else:
|
115 |
+
audio_values = np.zeros(self.to_yield)
|
116 |
+
|
117 |
+
self.on_finalized_audio(audio_values[self.to_yield :], stream_end=True)
|
118 |
+
|
119 |
+
def on_finalized_audio(self, audio: np.ndarray, stream_end: bool = False):
|
120 |
+
"""Put the new audio in the queue. If the stream is ending, also put a stop signal in the queue."""
|
121 |
+
self.audio_queue.put(audio, timeout=self.timeout)
|
122 |
+
if stream_end:
|
123 |
+
self.audio_queue.put(self.stop_signal, timeout=self.timeout)
|
124 |
+
|
125 |
+
def __iter__(self):
|
126 |
+
return self
|
127 |
+
|
128 |
+
def __next__(self):
|
129 |
+
value = self.audio_queue.get(timeout=self.timeout)
|
130 |
+
if not isinstance(value, np.ndarray) and value == self.stop_signal:
|
131 |
+
raise StopIteration()
|
132 |
+
else:
|
133 |
+
return value
|