Spaces:
Runtime error
Runtime error
File size: 10,899 Bytes
ffead1e 292d3f6 61dcd30 559b00c ffead1e 32614b8 559b00c 33e899a 559b00c ffead1e 559b00c ffead1e 559b00c ffead1e 559b00c ffead1e 559b00c ffead1e e206c8a ffead1e 559b00c e206c8a ffead1e 32614b8 ffead1e 8408dd7 ffead1e 559b00c e206c8a ffead1e 559b00c ffead1e 9e23cf9 ffead1e 559b00c ffead1e a258601 559b00c fa7808c 33e899a e206c8a 8408dd7 e206c8a 33e899a e206c8a 8408dd7 e206c8a 57093c2 98fe6bf 336a1d0 02b252c 98fe6bf e491319 e206c8a 8408dd7 e206c8a 33e899a e206c8a e491319 33e899a 8408dd7 eed24d8 78e560c e491319 78e560c 02b252c e491319 ffead1e 05118bf 559b00c abd262a 559b00c 05118bf 559b00c 05118bf 559b00c 70a8aa2 336a1d0 559b00c 05118bf 4987969 e206c8a 57093c2 70a8aa2 b8d94a7 e206c8a 33e899a ffead1e 98fe6bf fa7808c 336a1d0 e491319 ffead1e 33e899a e206c8a 8408dd7 e206c8a 33e899a 98fe6bf 57093c2 e491319 57093c2 e491319 02b252c e491319 05118bf 8408dd7 05118bf 33e899a 05118bf 8408dd7 e491319 e6563cd 05118bf e206c8a 05118bf 8408dd7 05118bf 33e899a 05118bf 8408dd7 e491319 05118bf 33e899a 05118bf 7b7c424 05118bf 8408dd7 05118bf |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 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 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 |
import gradio as gr
import json
import torch
import time
import random
from tqdm import tqdm
from huggingface_hub import snapshot_download
from models import AudioDiffusion, DDPMScheduler
from audioldm.audio.stft import TacotronSTFT
from audioldm.variational_autoencoder import AutoencoderKL
from pydub import AudioSegment
max_64_bit_int = 2**63 - 1
# Automatic device detection
if torch.cuda.is_available():
device_type = "cuda"
device_selection = "cuda:0"
else:
device_type = "cpu"
device_selection = "cpu"
class Tango:
def __init__(self, name = "declare-lab/tango2", device = device_selection):
path = snapshot_download(repo_id = name)
vae_config = json.load(open("{}/vae_config.json".format(path)))
stft_config = json.load(open("{}/stft_config.json".format(path)))
main_config = json.load(open("{}/main_config.json".format(path)))
self.vae = AutoencoderKL(**vae_config).to(device)
self.stft = TacotronSTFT(**stft_config).to(device)
self.model = AudioDiffusion(**main_config).to(device)
vae_weights = torch.load("{}/pytorch_model_vae.bin".format(path), map_location = device)
stft_weights = torch.load("{}/pytorch_model_stft.bin".format(path), map_location = device)
main_weights = torch.load("{}/pytorch_model_main.bin".format(path), map_location = device)
self.vae.load_state_dict(vae_weights)
self.stft.load_state_dict(stft_weights)
self.model.load_state_dict(main_weights)
print ("Successfully loaded checkpoint from:", name)
self.vae.eval()
self.stft.eval()
self.model.eval()
self.scheduler = DDPMScheduler.from_pretrained(main_config["scheduler_name"], subfolder = "scheduler")
def chunks(self, lst, n):
# Yield successive n-sized chunks from a list
for i in range(0, len(lst), n):
yield lst[i:i + n]
def generate(self, prompt, steps = 100, guidance = 3, samples = 1, disable_progress = True):
# Generate audio for a single prompt string
with torch.no_grad():
latents = self.model.inference([prompt], self.scheduler, steps, guidance, samples, disable_progress = disable_progress)
mel = self.vae.decode_first_stage(latents)
wave = self.vae.decode_to_waveform(mel)
return wave
def generate_for_batch(self, prompts, steps = 200, guidance = 3, samples = 1, batch_size = 8, disable_progress = True):
# Generate audio for a list of prompt strings
outputs = []
for k in tqdm(range(0, len(prompts), batch_size)):
batch = prompts[k: k + batch_size]
with torch.no_grad():
latents = self.model.inference(batch, self.scheduler, steps, guidance, samples, disable_progress = disable_progress)
mel = self.vae.decode_first_stage(latents)
wave = self.vae.decode_to_waveform(mel)
outputs += [item for item in wave]
if samples == 1:
return outputs
return list(self.chunks(outputs, samples))
# Initialize TANGO
tango = Tango(device = "cpu")
tango.vae.to(device_type)
tango.stft.to(device_type)
tango.model.to(device_type)
def update_seed(is_randomize_seed, seed):
if is_randomize_seed:
return random.randint(0, max_64_bit_int)
return seed
def check(
prompt,
output_number,
steps,
guidance,
is_randomize_seed,
seed
):
if prompt is None or prompt == "":
raise gr.Error("Please provide a prompt input.")
if not output_number in [1, 2, 3]:
raise gr.Error("Please ask for 1, 2 or 3 output files.")
def update_output(output_format, output_number):
return [
gr.update(format = output_format),
gr.update(format = output_format, visible = (2 <= output_number)),
gr.update(format = output_format, visible = (output_number == 3)),
gr.update(visible = False)
]
def text2audio(
prompt,
output_number,
steps,
guidance,
is_randomize_seed,
seed
):
start = time.time()
if seed is None:
seed = random.randint(0, max_64_bit_int)
random.seed(seed)
torch.manual_seed(seed)
output_wave = tango.generate(prompt, steps, guidance, output_number)
output_wave_1 = gr.make_waveform((16000, output_wave[0]))
output_wave_2 = gr.make_waveform((16000, output_wave[1])) if (2 <= output_number) else None
output_wave_3 = gr.make_waveform((16000, output_wave[2])) if (output_number == 3) else None
end = time.time()
secondes = int(end - start)
minutes = secondes // 60
secondes = secondes - (minutes * 60)
hours = minutes // 60
minutes = minutes - (hours * 60)
return [
output_wave_1,
output_wave_2,
output_wave_3,
gr.update(visible = True, value = "Start again to get a different result. The output have been generated in " + ((str(hours) + " h, ") if hours != 0 else "") + ((str(minutes) + " min, ") if hours != 0 or minutes != 0 else "") + str(secondes) + " sec.")
]
# Gradio interface
with gr.Blocks() as interface:
gr.Markdown("""
<p style="text-align: center;">
<b><big><big><big>Text-to-Audio</big></big></big></b>
<br/>Generates 10 seconds of sound effects from description, freely, without account, without watermark.
</p>
<br/>
<br/>
β¨ Powered by <i>Tango 2</i> AI.
<br/>
<ul>
<li>If you need to generate <b>music</b>, I recommend to use <i>MusicGen</i>,</li>
</ul>
<br/>
π Slow process... ~5 min. Your computer must <b><u>not</u></b> enter into standby mode.<br/>You can duplicate this space on a free account, it works on CPU.<br/>
<a href='https://huggingface.co/spaces/Fabrice-TIERCELIN/Text-to-Audio?duplicate=true&hidden=public&hidden=public'><img src='https://img.shields.io/badge/-Duplicate%20Space-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14'></a>
<br/>
βοΈ You can use, modify and share the generated sounds but not for commercial uses.
"""
)
input_text = gr.Textbox(label = "Prompt", value = "Snort of a horse", lines = 2, autofocus = True)
with gr.Accordion("Advanced options", open = False):
output_format = gr.Radio(label = "Output format", info = "The file you can dowload", choices = ["mp3", "wav"], value = "wav")
output_number = gr.Slider(label = "Number of generations", info = "1, 2 or 3 output files", minimum = 1, maximum = 3, value = 1, step = 1, interactive = True)
denoising_steps = gr.Slider(label = "Steps", info = "lower=faster & variant, higher=audio quality & similar", minimum = 10, maximum = 200, value = 10, step = 1, interactive = True)
guidance_scale = gr.Slider(label = "Guidance Scale", info = "lower=audio quality, higher=follow the prompt", minimum = 1, maximum = 10, value = 3, step = 0.1, interactive = True)
randomize_seed = gr.Checkbox(label = "\U0001F3B2 Randomize seed", value = True, info = "If checked, result is always different")
seed = gr.Slider(minimum = 0, maximum = max_64_bit_int, step = 1, randomize = True, label = "Seed")
submit = gr.Button("π Generate", variant = "primary")
output_audio_1 = gr.Audio(label = "Generated Audio #1/3", format = "wav", type="numpy", autoplay = True)
output_audio_2 = gr.Audio(label = "Generated Audio #2/3", format = "wav", type="numpy")
output_audio_3 = gr.Audio(label = "Generated Audio #3/3", format = "wav", type="numpy")
information = gr.Label(label = "Information")
submit.click(fn = update_seed, inputs = [
randomize_seed,
seed
], outputs = [
seed
], queue = False, show_progress = False).then(fn = check, inputs = [
input_text,
output_number,
denoising_steps,
guidance_scale,
randomize_seed,
seed
], outputs = [], queue = False, show_progress = False).success(fn = update_output, inputs = [
output_format,
output_number
], outputs = [
output_audio_1,
output_audio_2,
output_audio_3,
information
], queue = False, show_progress = False).success(fn = text2audio, inputs = [
input_text,
output_number,
denoising_steps,
guidance_scale,
randomize_seed,
seed
], outputs = [
output_audio_1,
output_audio_2,
output_audio_3,
information
], scroll_to_output = True)
gr.Examples(
fn = text2audio,
inputs = [
input_text,
output_number,
denoising_steps,
guidance_scale,
randomize_seed,
seed
],
outputs = [
output_audio_1,
output_audio_2,
output_audio_3,
information
],
examples = [
["A hammer is hitting a wooden surface", 3, 100, 3, False, 123],
["Peaceful and calming ambient music with singing bowl and other instruments.", 3, 100, 3, False, 123],
["A man is speaking in a small room.", 2, 100, 3, False, 123],
["A female is speaking followed by footstep sound", 1, 100, 3, False, 123],
["Wooden table tapping sound followed by water pouring sound.", 3, 200, 3, False, 123],
],
cache_examples = "lazy",
)
gr.Markdown(
"""
## How to prompt your sound
You can use round brackets to increase the importance of a part:
```
Peaceful and (calming) ambient music with singing bowl and other instruments
```
You can use several levels of round brackets to even more increase the importance of a part:
```
(Peaceful) and ((calming)) ambient music with singing bowl and other instruments
```
You can use number instead of several round brackets:
```
(Peaceful:1.5) and ((calming)) ambient music with singing bowl and other instruments
```
You can do the same thing with square brackets to decrease the importance of a part:
```
(Peaceful:1.5) and ((calming)) ambient music with [singing:2] bowl and other instruments
"""
)
interface.queue(10).launch() |