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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import spaces
|
2 |
+
import gradio as gr
|
3 |
+
import json
|
4 |
+
import torch
|
5 |
+
import wavio
|
6 |
+
from tqdm import tqdm
|
7 |
+
from huggingface_hub import snapshot_download
|
8 |
+
from models import AudioDiffusion, DDPMScheduler
|
9 |
+
from audioldm.audio.stft import TacotronSTFT
|
10 |
+
from audioldm.variational_autoencoder import AutoencoderKL
|
11 |
+
from pydub import AudioSegment
|
12 |
+
from gradio import Markdown
|
13 |
+
import torch
|
14 |
+
from diffusers.models.unet_2d_condition import UNet2DConditionModel
|
15 |
+
from diffusers import DiffusionPipeline,AudioPipelineOutput
|
16 |
+
from transformers import CLIPTextModel, T5EncoderModel, AutoModel, T5Tokenizer, T5TokenizerFast
|
17 |
+
from typing import Union
|
18 |
+
from diffusers.utils.torch_utils import randn_tensor
|
19 |
+
from tqdm import tqdm
|
20 |
+
|
21 |
+
class Tango2Pipeline(DiffusionPipeline):
|
22 |
+
def __init__(
|
23 |
+
self,
|
24 |
+
vae: AutoencoderKL,
|
25 |
+
text_encoder: T5EncoderModel,
|
26 |
+
tokenizer: Union[T5Tokenizer, T5TokenizerFast],
|
27 |
+
unet: UNet2DConditionModel,
|
28 |
+
scheduler: DDPMScheduler
|
29 |
+
):
|
30 |
+
|
31 |
+
super().__init__()
|
32 |
+
|
33 |
+
self.register_modules(vae=vae,
|
34 |
+
text_encoder=text_encoder,
|
35 |
+
tokenizer=tokenizer,
|
36 |
+
unet=unet,
|
37 |
+
scheduler=scheduler
|
38 |
+
)
|
39 |
+
|
40 |
+
def _encode_prompt(self, prompt):
|
41 |
+
device = self.text_encoder.device
|
42 |
+
|
43 |
+
batch = self.tokenizer(
|
44 |
+
prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
|
45 |
+
)
|
46 |
+
input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
|
47 |
+
|
48 |
+
|
49 |
+
encoder_hidden_states = self.text_encoder(
|
50 |
+
input_ids=input_ids, attention_mask=attention_mask
|
51 |
+
)[0]
|
52 |
+
|
53 |
+
boolean_encoder_mask = (attention_mask == 1).to(device)
|
54 |
+
|
55 |
+
return encoder_hidden_states, boolean_encoder_mask
|
56 |
+
|
57 |
+
def _encode_text_classifier_free(self, prompt, num_samples_per_prompt):
|
58 |
+
device = self.text_encoder.device
|
59 |
+
batch = self.tokenizer(
|
60 |
+
prompt, max_length=self.tokenizer.model_max_length, padding=True, truncation=True, return_tensors="pt"
|
61 |
+
)
|
62 |
+
input_ids, attention_mask = batch.input_ids.to(device), batch.attention_mask.to(device)
|
63 |
+
|
64 |
+
with torch.no_grad():
|
65 |
+
prompt_embeds = self.text_encoder(
|
66 |
+
input_ids=input_ids, attention_mask=attention_mask
|
67 |
+
)[0]
|
68 |
+
|
69 |
+
prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
70 |
+
attention_mask = attention_mask.repeat_interleave(num_samples_per_prompt, 0)
|
71 |
+
|
72 |
+
# get unconditional embeddings for classifier free guidance
|
73 |
+
uncond_tokens = [""] * len(prompt)
|
74 |
+
|
75 |
+
max_length = prompt_embeds.shape[1]
|
76 |
+
uncond_batch = self.tokenizer(
|
77 |
+
uncond_tokens, max_length=max_length, padding="max_length", truncation=True, return_tensors="pt",
|
78 |
+
)
|
79 |
+
uncond_input_ids = uncond_batch.input_ids.to(device)
|
80 |
+
uncond_attention_mask = uncond_batch.attention_mask.to(device)
|
81 |
+
|
82 |
+
with torch.no_grad():
|
83 |
+
negative_prompt_embeds = self.text_encoder(
|
84 |
+
input_ids=uncond_input_ids, attention_mask=uncond_attention_mask
|
85 |
+
)[0]
|
86 |
+
|
87 |
+
negative_prompt_embeds = negative_prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
88 |
+
uncond_attention_mask = uncond_attention_mask.repeat_interleave(num_samples_per_prompt, 0)
|
89 |
+
|
90 |
+
# For classifier free guidance, we need to do two forward passes.
|
91 |
+
# We concatenate the unconditional and text embeddings into a single batch to avoid doing two forward passes
|
92 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
|
93 |
+
prompt_mask = torch.cat([uncond_attention_mask, attention_mask])
|
94 |
+
boolean_prompt_mask = (prompt_mask == 1).to(device)
|
95 |
+
|
96 |
+
return prompt_embeds, boolean_prompt_mask
|
97 |
+
|
98 |
+
def prepare_latents(self, batch_size, inference_scheduler, num_channels_latents, dtype, device):
|
99 |
+
shape = (batch_size, num_channels_latents, 256, 16)
|
100 |
+
latents = randn_tensor(shape, generator=None, device=device, dtype=dtype)
|
101 |
+
# scale the initial noise by the standard deviation required by the scheduler
|
102 |
+
latents = latents * inference_scheduler.init_noise_sigma
|
103 |
+
return latents
|
104 |
+
|
105 |
+
@torch.no_grad()
|
106 |
+
def inference(self, prompt, inference_scheduler, num_steps=20, guidance_scale=3, num_samples_per_prompt=1,
|
107 |
+
disable_progress=True):
|
108 |
+
device = self.text_encoder.device
|
109 |
+
classifier_free_guidance = guidance_scale > 1.0
|
110 |
+
batch_size = len(prompt) * num_samples_per_prompt
|
111 |
+
|
112 |
+
if classifier_free_guidance:
|
113 |
+
prompt_embeds, boolean_prompt_mask = self._encode_text_classifier_free(prompt, num_samples_per_prompt)
|
114 |
+
else:
|
115 |
+
prompt_embeds, boolean_prompt_mask = self._encode_text(prompt)
|
116 |
+
prompt_embeds = prompt_embeds.repeat_interleave(num_samples_per_prompt, 0)
|
117 |
+
boolean_prompt_mask = boolean_prompt_mask.repeat_interleave(num_samples_per_prompt, 0)
|
118 |
+
|
119 |
+
inference_scheduler.set_timesteps(num_steps, device=device)
|
120 |
+
timesteps = inference_scheduler.timesteps
|
121 |
+
|
122 |
+
num_channels_latents = self.unet.config.in_channels
|
123 |
+
latents = self.prepare_latents(batch_size, inference_scheduler, num_channels_latents, prompt_embeds.dtype, device)
|
124 |
+
|
125 |
+
num_warmup_steps = len(timesteps) - num_steps * inference_scheduler.order
|
126 |
+
progress_bar = tqdm(range(num_steps), disable=disable_progress)
|
127 |
+
|
128 |
+
for i, t in enumerate(timesteps):
|
129 |
+
# expand the latents if we are doing classifier free guidance
|
130 |
+
latent_model_input = torch.cat([latents] * 2) if classifier_free_guidance else latents
|
131 |
+
latent_model_input = inference_scheduler.scale_model_input(latent_model_input, t)
|
132 |
+
|
133 |
+
noise_pred = self.unet(
|
134 |
+
latent_model_input, t, encoder_hidden_states=prompt_embeds,
|
135 |
+
encoder_attention_mask=boolean_prompt_mask
|
136 |
+
).sample
|
137 |
+
|
138 |
+
# perform guidance
|
139 |
+
if classifier_free_guidance:
|
140 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
141 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
142 |
+
|
143 |
+
# compute the previous noisy sample x_t -> x_t-1
|
144 |
+
latents = inference_scheduler.step(noise_pred, t, latents).prev_sample
|
145 |
+
|
146 |
+
# call the callback, if provided
|
147 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % inference_scheduler.order == 0):
|
148 |
+
progress_bar.update(1)
|
149 |
+
|
150 |
+
return latents
|
151 |
+
|
152 |
+
@torch.no_grad()
|
153 |
+
def __call__(self, prompt, steps=100, guidance=3, samples=1, disable_progress=True):
|
154 |
+
""" Genrate audio for a single prompt string. """
|
155 |
+
with torch.no_grad():
|
156 |
+
latents = self.inference([prompt], self.scheduler, steps, guidance, samples, disable_progress=disable_progress)
|
157 |
+
mel = self.vae.decode_first_stage(latents)
|
158 |
+
wave = self.vae.decode_to_waveform(mel)
|
159 |
+
|
160 |
+
|
161 |
+
return AudioPipelineOutput(audios=wave)
|
162 |
+
|
163 |
+
|
164 |
+
# Automatic device detection
|
165 |
+
if torch.cuda.is_available():
|
166 |
+
device_type = "cuda"
|
167 |
+
device_selection = "cuda:0"
|
168 |
+
else:
|
169 |
+
device_type = "cpu"
|
170 |
+
device_selection = "cpu"
|
171 |
+
|
172 |
+
class Tango:
|
173 |
+
def __init__(self, name="declare-lab/tango2", device=device_selection):
|
174 |
+
|
175 |
+
path = snapshot_download(repo_id=name)
|
176 |
+
|
177 |
+
vae_config = json.load(open("{}/vae_config.json".format(path)))
|
178 |
+
stft_config = json.load(open("{}/stft_config.json".format(path)))
|
179 |
+
main_config = json.load(open("{}/main_config.json".format(path)))
|
180 |
+
|
181 |
+
self.vae = AutoencoderKL(**vae_config).to(device)
|
182 |
+
self.stft = TacotronSTFT(**stft_config).to(device)
|
183 |
+
self.model = AudioDiffusion(**main_config).to(device)
|
184 |
+
|
185 |
+
vae_weights = torch.load("{}/pytorch_model_vae.bin".format(path), map_location=device)
|
186 |
+
stft_weights = torch.load("{}/pytorch_model_stft.bin".format(path), map_location=device)
|
187 |
+
main_weights = torch.load("{}/pytorch_model_main.bin".format(path), map_location=device)
|
188 |
+
|
189 |
+
self.vae.load_state_dict(vae_weights)
|
190 |
+
self.stft.load_state_dict(stft_weights)
|
191 |
+
self.model.load_state_dict(main_weights)
|
192 |
+
|
193 |
+
print ("Successfully loaded checkpoint from:", name)
|
194 |
+
|
195 |
+
self.vae.eval()
|
196 |
+
self.stft.eval()
|
197 |
+
self.model.eval()
|
198 |
+
|
199 |
+
self.scheduler = DDPMScheduler.from_pretrained(main_config["scheduler_name"], subfolder="scheduler")
|
200 |
+
|
201 |
+
def chunks(self, lst, n):
|
202 |
+
""" Yield successive n-sized chunks from a list. """
|
203 |
+
for i in range(0, len(lst), n):
|
204 |
+
yield lst[i:i + n]
|
205 |
+
|
206 |
+
def generate(self, prompt, steps=100, guidance=3, samples=1, disable_progress=True):
|
207 |
+
""" Genrate audio for a single prompt string. """
|
208 |
+
with torch.no_grad():
|
209 |
+
latents = self.model.inference([prompt], self.scheduler, steps, guidance, samples, disable_progress=disable_progress)
|
210 |
+
mel = self.vae.decode_first_stage(latents)
|
211 |
+
wave = self.vae.decode_to_waveform(mel)
|
212 |
+
return wave[0]
|
213 |
+
|
214 |
+
def generate_for_batch(self, prompts, steps=200, guidance=3, samples=1, batch_size=8, disable_progress=True):
|
215 |
+
""" Genrate audio for a list of prompt strings. """
|
216 |
+
outputs = []
|
217 |
+
for k in tqdm(range(0, len(prompts), batch_size)):
|
218 |
+
batch = prompts[k: k+batch_size]
|
219 |
+
with torch.no_grad():
|
220 |
+
latents = self.model.inference(batch, self.scheduler, steps, guidance, samples, disable_progress=disable_progress)
|
221 |
+
mel = self.vae.decode_first_stage(latents)
|
222 |
+
wave = self.vae.decode_to_waveform(mel)
|
223 |
+
outputs += [item for item in wave]
|
224 |
+
if samples == 1:
|
225 |
+
return outputs
|
226 |
+
else:
|
227 |
+
return list(self.chunks(outputs, samples))
|
228 |
+
|
229 |
+
# Initialize TANGO
|
230 |
+
|
231 |
+
tango = Tango(device="cpu")
|
232 |
+
tango.vae.to(device_type)
|
233 |
+
tango.stft.to(device_type)
|
234 |
+
tango.model.to(device_type)
|
235 |
+
|
236 |
+
pipe = Tango2Pipeline(vae=tango.vae,
|
237 |
+
text_encoder=tango.model.text_encoder,
|
238 |
+
tokenizer=tango.model.tokenizer,
|
239 |
+
unet=tango.model.unet,
|
240 |
+
scheduler=tango.scheduler
|
241 |
+
)
|
242 |
+
|
243 |
+
|
244 |
+
@spaces.GPU(duration=60)
|
245 |
+
def gradio_generate(prompt, output_format, steps, guidance):
|
246 |
+
output_wave = pipe(prompt,steps,guidance) ## Using pipeliine automatically uses flash attention for torch2.0 above
|
247 |
+
#output_wave = tango.generate(prompt, steps, guidance)
|
248 |
+
# output_filename = f"{prompt.replace(' ', '_')}_{steps}_{guidance}"[:250] + ".wav"
|
249 |
+
output_wave = output_wave.audios[0]
|
250 |
+
output_filename = "temp.wav"
|
251 |
+
wavio.write(output_filename, output_wave, rate=16000, sampwidth=2)
|
252 |
+
|
253 |
+
if (output_format == "mp3"):
|
254 |
+
AudioSegment.from_wav("temp.wav").export("temp.mp3", format = "mp3")
|
255 |
+
output_filename = "temp.mp3"
|
256 |
+
|
257 |
+
return output_filename
|
258 |
+
|
259 |
+
|
260 |
+
input_text = gr.Textbox(lines=2, label="Prompt")
|
261 |
+
output_format = gr.Radio(label = "Output format", info = "The file you can dowload", choices = ["mp3", "wav"], value = "wav")
|
262 |
+
output_audio = gr.Audio(label="Generated Audio", type="filepath")
|
263 |
+
denoising_steps = gr.Slider(minimum=100, maximum=200, value=200, step=1, label="Steps", interactive=True)
|
264 |
+
guidance_scale = gr.Slider(minimum=1, maximum=10, value=3, step=0.1, label="Guidance Scale", interactive=True)
|
265 |
+
|
266 |
+
css = """
|
267 |
+
footer {
|
268 |
+
visibility: hidden;
|
269 |
+
}
|
270 |
+
"""
|
271 |
+
|
272 |
+
gr_interface = gr.Interface(
|
273 |
+
fn=gradio_generate,
|
274 |
+
inputs=[input_text, output_format, denoising_steps, guidance_scale],
|
275 |
+
outputs=[output_audio],
|
276 |
+
title="SoundAI by tango",
|
277 |
+
theme="Yntec/HaleyCH_Theme_Orange",
|
278 |
+
css=css,
|
279 |
+
allow_flagging=False,
|
280 |
+
examples=[
|
281 |
+
["Quiet whispered conversation gradually fading into distant jet engine roar diminishing into silence"],
|
282 |
+
["Clear sound of bicycle tires crunching on loose gravel and dirt, followed by deep male laughter echoing"],
|
283 |
+
["Multiple ducks quacking loudly with splashing water and piercing wild animal shriek in background"],
|
284 |
+
["Powerful ocean waves crashing and receding on sandy beach with distant seagulls"],
|
285 |
+
["Gentle female voice cooing and baby responding with happy gurgles and giggles"],
|
286 |
+
["Clear male voice speaking, sharp popping sound, followed by genuine group laughter"],
|
287 |
+
["Stream of water hitting empty ceramic cup, pitch rising as cup fills up"],
|
288 |
+
["Massive crowd erupting in thunderous applause and excited cheering"],
|
289 |
+
["Deep rolling thunder with bright lightning strikes crackling through sky"],
|
290 |
+
["Aggressive dog barking and distressed cat meowing as racing car roars past at high speed"],
|
291 |
+
["Peaceful stream bubbling and birds singing, interrupted by sudden explosive gunshot"],
|
292 |
+
["Man speaking outdoors, goat bleating loudly, metal gate scraping closed, ducks quacking frantically, wind howling into microphone"],
|
293 |
+
["Series of loud aggressive dog barks echoing"],
|
294 |
+
["Multiple distinct cat meows at different pitches"],
|
295 |
+
["Rhythmic wooden table tapping overlaid with steady water pouring sound"],
|
296 |
+
["Sustained crowd applause with camera clicks and amplified male announcer voice"],
|
297 |
+
["Two sharp gunshots followed by panicked birds taking flight with rapid wing flaps"],
|
298 |
+
["Melodic human whistling harmonizing with natural birdsong"],
|
299 |
+
["Deep rhythmic snoring with clear breathing patterns"],
|
300 |
+
["Multiple racing engines revving and accelerating with sharp whistle piercing through"],
|
301 |
+
["Massive stadium crowd cheering as thunder crashes and lightning strikes"],
|
302 |
+
["Heavy helicopter blades chopping through air with engine and wind noise"],
|
303 |
+
["Dog barking excitedly and man shouting as race car engine roars past"]
|
304 |
+
],
|
305 |
+
cache_examples="lazy", # Turn on to cache.
|
306 |
+
)
|
307 |
+
|
308 |
+
gr_interface.queue(10).launch()
|