hungchiayu commited on
Commit
e007f49
·
verified ·
1 Parent(s): 838c300

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +111 -53
app.py CHANGED
@@ -5,93 +5,151 @@ 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
-
14
  import torch
15
- #from diffusers.models.autoencoder_kl import AutoencoderKL
16
  from diffusers import DiffusionPipeline,AudioPipelineOutput
17
  from transformers import CLIPTextModel, T5EncoderModel, AutoModel, T5Tokenizer, T5TokenizerFast
18
  from typing import Union
19
  from diffusers.utils.torch_utils import randn_tensor
20
  from tqdm import tqdm
21
  from TangoFlux import TangoFluxInference
 
22
 
23
 
24
 
25
- tangoflux = TangoFluxInference(path="declare-lab/TangoFlux")
26
 
27
 
28
 
29
  @spaces.GPU(duration=15)
30
- def gradio_generate(prompt, output_format, steps, guidance,duration=10):
 
 
 
 
 
 
 
 
 
 
 
 
31
 
32
- output_wave = tangoflux.generate(prompt,steps=steps,guidance=guidance,duration=duration)
33
- output_wave = pipe(prompt,steps,guidance) ## Using pipeliine automatically uses flash attention for torch2.0 above
34
- #output_wave = tango.generate(prompt, steps, guidance)
35
- # output_filename = f"{prompt.replace(' ', '_')}_{steps}_{guidance}"[:250] + ".wav"
36
- output_wave = output_wave.audios[0]
37
- output_filename = "temp.wav"
38
- wavio.write(output_filename, output_wave, rate=16000, sampwidth=2)
39
 
40
- if (output_format == "mp3"):
41
- AudioSegment.from_wav("temp.wav").export("temp.mp3", format = "mp3")
42
- output_filename = "temp.mp3"
43
 
44
- return output_filename
45
 
46
  description_text = """
47
- <p><a href="https://huggingface.co/spaces/declare-lab/tango2/blob/main/app.py?duplicate=true"> <img style="margin-top: 0em; margin-bottom: 0em" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a> For faster inference without waiting in queue, you may duplicate the space and upgrade to a GPU in the settings. <br/><br/>
48
- Generate audio using Tango2 by providing a text prompt. Tango2 was built from Tango and was trained on <a href="https://huggingface.co/datasets/declare-lab/audio-alpaca">Audio-alpaca</a>
49
- <br/><br/> This is the demo for Tango2 for text to audio generation: <a href="https://arxiv.org/abs/2404.09956">Read our paper.</a>
50
- <p/>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  """
52
  # Gradio input and output components
53
  input_text = gr.Textbox(lines=2, label="Prompt")
54
- output_format = gr.Radio(label = "Output format", info = "The file you can dowload", choices = ["mp3", "wav"], value = "wav")
55
  output_audio = gr.Audio(label="Generated Audio", type="filepath")
56
- denoising_steps = gr.Slider(minimum=10, maximum=100, value=25, step=1, label="Steps", interactive=True)
57
- guidance_scale = gr.Slider(minimum=1, maximum=10, value=3, step=0.1, label="Guidance Scale", interactive=True)
58
  duration_scale = gr.Slider(minimum=1, maximum=30, value=10, step=1, label="Duration", interactive=True)
59
 
 
60
  # Gradio interface
61
  gr_interface = gr.Interface(
62
  fn=gradio_generate,
63
- inputs=[input_text, output_format, denoising_steps, guidance_scale,duration_scale],
64
- outputs=[output_audio],
65
- title="TangoFlux: Aligning Diffusion-based Text-to-Audio Generations through Direct Preference Optimization",
66
  description=description_text,
67
  allow_flagging=False,
68
  examples=[
69
- ["Quiet speech and then and airplane flying away"],
70
- ["A bicycle peddling on dirt and gravel followed by a man speaking then laughing"],
71
- ["Ducks quack and water splashes with some animal screeching in the background"],
72
- ["Describe the sound of the ocean"],
73
- ["A woman and a baby are having a conversation"],
74
- ["A man speaks followed by a popping noise and laughter"],
75
- ["A cup is filled from a faucet"],
76
- ["An audience cheering and clapping"],
77
- ["Rolling thunder with lightning strikes"],
78
- ["A dog barking and a cat mewing and a racing car passes by"],
79
- ["Gentle water stream, birds chirping and sudden gun shot"],
80
- ["A man talking followed by a goat baaing then a metal gate sliding shut as ducks quack and wind blows into a microphone."],
81
- ["A dog barking"],
82
- ["A cat meowing"],
83
- ["Wooden table tapping sound while water pouring"],
84
- ["Applause from a crowd with distant clicking and a man speaking over a loudspeaker"],
85
- ["two gunshots followed by birds flying away while chirping"],
86
- ["Whistling with birds chirping"],
87
- ["A person snoring"],
88
- ["Motor vehicles are driving with loud engines and a person whistles"],
89
- ["People cheering in a stadium while thunder and lightning strikes"],
90
- ["A helicopter is in flight"],
91
- ["A dog barking and a man talking and a racing car passes by"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  ],
93
  cache_examples="lazy", # Turn on to cache.
94
  )
95
 
96
- # Launch Gradio app
97
- gr_interface.queue(10).launch()
 
 
5
  import wavio
6
  from tqdm import tqdm
7
  from huggingface_hub import snapshot_download
 
 
 
8
  from pydub import AudioSegment
9
  from gradio import Markdown
10
+ import uuid
11
  import torch
 
12
  from diffusers import DiffusionPipeline,AudioPipelineOutput
13
  from transformers import CLIPTextModel, T5EncoderModel, AutoModel, T5Tokenizer, T5TokenizerFast
14
  from typing import Union
15
  from diffusers.utils.torch_utils import randn_tensor
16
  from tqdm import tqdm
17
  from TangoFlux import TangoFluxInference
18
+ import torchaudio
19
 
20
 
21
 
22
+ tangoflux = TangoFluxInference(name="declare-lab/TangoFlux")
23
 
24
 
25
 
26
  @spaces.GPU(duration=15)
27
+ def gradio_generate(prompt, steps, guidance,duration=10):
28
+
29
+ output = tangoflux.generate(prompt,steps=steps,guidance_scale=guidance,duration=duration)
30
+ #output = output.to(torch.float32).div(torch.max(torch.abs(output))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
31
+
32
+
33
+ #wavio.write(output_filename, output_wave, rate=44100, sampwidth=2)
34
+ filename = 'temp.wav'
35
+ #print(f"Saving audio to file: {unique_filename}")
36
+
37
+ # Save to file
38
+ torchaudio.save(filename, output, 44100)
39
+
40
 
41
+ # Return the path to the generated audio file
42
+ return filename
 
 
 
 
 
43
 
44
+ #if (output_format == "mp3"):
45
+ # AudioSegment.from_wav("temp.wav").export("temp.mp3", format = "mp3")
46
+ # output_filename = "temp.mp3"
47
 
48
+ #return output_filename
49
 
50
  description_text = """
51
+ Generate high quality and faithful audio in just a few seconds using <b>TangoFlux</b> by providing a text prompt. <b>TangoFlux</b> was trained from scratch and underwent alignment to follow human instructions using a new method called <b>Claped-Ranked Preference Optimization (CRPO)</b>.
52
+ <div style="display: flex; gap: 10px; align-items: center;">
53
+ <a href="https://arxiv.org/abs/2412.21037">
54
+ <img src="https://img.shields.io/badge/Read_the_Paper-blue?link=https%3A%2F%2Fopenreview.net%2Fattachment%3Fid%3DtpJPlFTyxd%26name%3Dpdf" alt="arXiv">
55
+ </a>
56
+ <a href="https://huggingface.co/declare-lab/TangoFlux">
57
+ <img src="https://img.shields.io/badge/TangoFlux-Huggingface-violet?logo=huggingface&link=https%3A%2F%2Fhuggingface.co%2Fdeclare-lab%2FTangoFlux" alt="Static Badge">
58
+ </a>
59
+ <a href="https://tangoflux.github.io/">
60
+ <img src="https://img.shields.io/badge/Demos-declare--lab-brightred?style=flat" alt="Static Badge">
61
+ </a>
62
+ <a href="https://huggingface.co/spaces/declare-lab/TangoFlux">
63
+ <img src="https://img.shields.io/badge/TangoFlux-Huggingface_Space-8A2BE2?logo=huggingface&link=https%3A%2F%2Fhuggingface.co%2Fspaces%2Fdeclare-lab%2FTangoFlux" alt="Static Badge">
64
+ </a>
65
+ <a href="https://huggingface.co/datasets/declare-lab/CRPO">
66
+ <img src="https://img.shields.io/badge/TangoFlux_Dataset-Huggingface-red?logo=huggingface&link=https%3A%2F%2Fhuggingface.co%2Fdatasets%2Fdeclare-lab%2FTangoFlux" alt="Static Badge">
67
+ </a>
68
+ <a href="https://github.com/declare-lab/TangoFlux">
69
+ <img src="https://img.shields.io/badge/Github-brown?logo=github&link=https%3A%2F%2Fgithub.com%2Fdeclare-lab%2FTangoFlux" alt="Static Badge">
70
+ </a>
71
+ </div>
72
  """
73
  # Gradio input and output components
74
  input_text = gr.Textbox(lines=2, label="Prompt")
75
+ #output_format = gr.Radio(label = "Output format", info = "The file you can dowload", choices = "wav"], value = "wav")
76
  output_audio = gr.Audio(label="Generated Audio", type="filepath")
77
+ denoising_steps = gr.Slider(minimum=10, maximum=100, value=25, step=5, label="Steps", interactive=True)
78
+ guidance_scale = gr.Slider(minimum=1, maximum=10, value=4.5, step=0.5, label="Guidance Scale", interactive=True)
79
  duration_scale = gr.Slider(minimum=1, maximum=30, value=10, step=1, label="Duration", interactive=True)
80
 
81
+
82
  # Gradio interface
83
  gr_interface = gr.Interface(
84
  fn=gradio_generate,
85
+ inputs=[input_text, denoising_steps, guidance_scale,duration_scale],
86
+ outputs=output_audio,
87
+ title="TangoFlux: Super Fast and Faithful Text to Audio Generation with Flow Matching and Clap-Ranked Preference Optimization",
88
  description=description_text,
89
  allow_flagging=False,
90
  examples=[
91
+ ["A parade marches through a town square, with drumbeats pounding, children clapping, and a horse neighing amidst the commotion"],
92
+ ["A soccer ball hits a goalpost with a metallic clang, followed by cheers, clapping, and the distant hum of a commentator’s voice"],
93
+ ["The deep growl of an alligator ripples through the swamp as reeds sway with a soft rustle and a turtle splashes into the murky water"],
94
+ ["A basketball bounces rhythmically on a court, shoes squeak against the floor, and a referee’s whistle cuts through the air"],
95
+ ["A train conductor blows a sharp whistle, metal wheels screech on the rails, and passengers murmur while settling into their seats"],
96
+ ["A fork scrapes a plate, water drips slowly into a sink, and the faint hum of a refrigerator lingers in the background"],
97
+ ["Alarms blare with rising urgency as fragments clatter against a metallic hull, interrupted by a faint hiss of escaping air"],
98
+ ["Tiny pops and hisses of chemical reactions intermingle with the rhythmic pumping of a centrifuge and the soft whirr of air filtration"],
99
+ ["A train conductor blows a sharp whistle, metal wheels screech on the rails, and passengers murmur while settling into their seats"],
100
+ ["Simulate a forest ambiance with birds chirping and wind rustling through the leaves"],
101
+ ["Quiet whispered conversation gradually fading into distant jet engine roar diminishing into silence"],
102
+ ["Clear sound of bicycle tires crunching on loose gravel and dirt, followed by deep male laughter echoing"],
103
+ ["Multiple ducks quacking loudly with splashing water and piercing wild animal shriek in background"],
104
+ ["Create a serene soundscape of a quiet beach at sunset"],
105
+ ["A pile of coins spills onto a wooden table with a metallic clatter, followed by the hushed murmur of a tavern crowd and the creak of a swinging door"],
106
+ ["Generate an energetic and bustling city street scene with distant traffic and close conversations"],
107
+ ["Powerful ocean waves crashing and receding on sandy beach with distant seagulls"],
108
+ ["Gentle female voice cooing and baby responding with happy gurgles and giggles"],
109
+ ["Clear male voice speaking, sharp popping sound, followed by genuine group laughter"],
110
+ ["Stream of water hitting empty ceramic cup, pitch rising as cup fills up"],
111
+ ["Massive crowd erupting in thunderous applause and excited cheering"],
112
+ ["Deep rolling thunder with bright lightning strikes crackling through sky"],
113
+ ["Aggressive dog barking and distressed cat meowing as racing car roars past at high speed"],
114
+ ["Peaceful stream bubbling and birds singing, interrupted by sudden explosive gunshot"],
115
+ ["Man speaking outdoors, goat bleating loudly, metal gate scraping closed, ducks quacking frantically, wind howling into microphone"],
116
+ ["Series of loud aggressive dog barks echoing"],
117
+ ["Multiple distinct cat meows at different pitches"],
118
+ ["Rhythmic wooden table tapping overlaid with steady water pouring sound"],
119
+ ["Sustained crowd applause with camera clicks and amplified male announcer voice"],
120
+ ["Two sharp gunshots followed by panicked birds taking flight with rapid wing flaps"],
121
+ ["Melodic human whistling harmonizing with natural birdsong"],
122
+ ["Deep rhythmic snoring with clear breathing patterns"],
123
+ ["Multiple racing engines revving and accelerating with sharp whistle piercing through"],
124
+ ["Massive stadium crowd cheering as thunder crashes and lightning strikes"],
125
+ ["Heavy helicopter blades chopping through air with engine and wind noise"],
126
+ ["Dog barking excitedly and man shouting as race car engine roars past"],
127
+ ["Quiet speech and then and airplane flying away"],
128
+ ["A bicycle peddling on dirt and gravel followed by a man speaking then laughing"],
129
+ ["Ducks quack and water splashes with some animal screeching in the background"],
130
+ ["Describe the sound of the ocean"],
131
+ ["A woman and a baby are having a conversation"],
132
+ ["A man speaks followed by a popping noise and laughter"],
133
+ ["A cup is filled from a faucet"],
134
+ ["An audience cheering and clapping"],
135
+ ["Rolling thunder with lightning strikes"],
136
+ ["A dog barking and a cat mewing and a racing car passes by"],
137
+ ["Gentle water stream, birds chirping and sudden gun shot"],
138
+ ["A dog barking"],
139
+ ["A cat meowing"],
140
+ ["Wooden table tapping sound while water pouring"],
141
+ ["Applause from a crowd with distant clicking and a man speaking over a loudspeaker"],
142
+ ["two gunshots followed by birds flying away while chirping"],
143
+ ["Whistling with birds chirping"],
144
+ ["A person snoring"],
145
+ ["Motor vehicles are driving with loud engines and a person whistles"],
146
+ ["People cheering in a stadium while thunder and lightning strikes"],
147
+ ["A helicopter is in flight"],
148
+ ["A dog barking and a man talking and a racing car passes by"],
149
  ],
150
  cache_examples="lazy", # Turn on to cache.
151
  )
152
 
153
+
154
+
155
+ gr_interface.queue(15).launch()