Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

app.py 8.9 KB

You have to be logged in to leave a comment. Sign In
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
  1. import gradio as gr
  2. import json
  3. import torch
  4. import wavio
  5. from tqdm import tqdm
  6. from huggingface_hub import snapshot_download
  7. from models import AudioDiffusion, DDPMScheduler
  8. from audioldm.audio.stft import TacotronSTFT
  9. from audioldm.variational_autoencoder import AutoencoderKL
  10. from gradio import Markdown
  11. import spaces
  12. # Automatic device detection
  13. if torch.cuda.is_available():
  14. device_type = "cuda"
  15. device_selection = "cuda:0"
  16. else:
  17. device_type = "cpu"
  18. device_selection = "cpu"
  19. class Tango:
  20. def __init__(self, name="declare-lab/tango-full-ft-audiocaps", device=device_selection):
  21. path = snapshot_download(repo_id=name)
  22. vae_config = json.load(open("{}/vae_config.json".format(path)))
  23. stft_config = json.load(open("{}/stft_config.json".format(path)))
  24. main_config = json.load(open("{}/main_config.json".format(path)))
  25. self.vae = AutoencoderKL(**vae_config).to(device)
  26. self.stft = TacotronSTFT(**stft_config).to(device)
  27. self.model = AudioDiffusion(**main_config).to(device)
  28. vae_weights = torch.load("{}/pytorch_model_vae.bin".format(path), map_location=device)
  29. stft_weights = torch.load("{}/pytorch_model_stft.bin".format(path), map_location=device)
  30. main_weights = torch.load("{}/pytorch_model_main.bin".format(path), map_location=device)
  31. self.vae.load_state_dict(vae_weights)
  32. self.stft.load_state_dict(stft_weights)
  33. self.model.load_state_dict(main_weights)
  34. print ("Successfully loaded checkpoint from:", name)
  35. self.vae.eval()
  36. self.stft.eval()
  37. self.model.eval()
  38. self.scheduler = DDPMScheduler.from_pretrained(main_config["scheduler_name"], subfolder="scheduler")
  39. def chunks(self, lst, n):
  40. """ Yield successive n-sized chunks from a list. """
  41. for i in range(0, len(lst), n):
  42. yield lst[i:i + n]
  43. def generate(self, prompt, steps=100, guidance=3, samples=3, disable_progress=True):
  44. """ Genrate audio for a single prompt string. """
  45. with torch.no_grad():
  46. latents = self.model.inference([prompt], self.scheduler, steps, guidance, samples, disable_progress=disable_progress)
  47. mel = self.vae.decode_first_stage(latents)
  48. wave = self.vae.decode_to_waveform(mel)
  49. return wave
  50. def generate_for_batch(self, prompts, steps=200, guidance=3, samples=1, batch_size=8, disable_progress=True):
  51. """ Genrate audio for a list of prompt strings. """
  52. outputs = []
  53. for k in tqdm(range(0, len(prompts), batch_size)):
  54. batch = prompts[k: k+batch_size]
  55. with torch.no_grad():
  56. latents = self.model.inference(batch, self.scheduler, steps, guidance, samples, disable_progress=disable_progress)
  57. mel = self.vae.decode_first_stage(latents)
  58. wave = self.vae.decode_to_waveform(mel)
  59. outputs += [item for item in wave]
  60. if samples == 1:
  61. return outputs
  62. else:
  63. return list(self.chunks(outputs, samples))
  64. # Initialize TANGO
  65. tango = Tango(device="cpu")
  66. tango.vae.to(device_type)
  67. tango.stft.to(device_type)
  68. tango.model.to(device_type)
  69. @spaces.GPU(duration=120)
  70. def gradio_generate(prompt, steps, guidance):
  71. output_wave = tango.generate(prompt, steps, guidance)
  72. # output_filename = f"{prompt.replace(' ', '_')}_{steps}_{guidance}"[:250] + ".wav"
  73. output_filename_1 = "tmp1_.wav"
  74. wavio.write(output_filename_1, output_wave[0], rate=16000, sampwidth=2)
  75. output_filename_2 = "tmp2_.wav"
  76. wavio.write(output_filename_2, output_wave[1], rate=16000, sampwidth=2)
  77. output_filename_3 = "tmp3_.wav"
  78. wavio.write(output_filename_3, output_wave[2], rate=16000, sampwidth=2)
  79. return [output_filename_1, output_filename_2, output_filename_3]
  80. # description_text = """
  81. # <p><a href="https://huggingface.co/spaces/declare-lab/tango/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/>
  82. # Generate audio using TANGO by providing a text prompt.
  83. # <br/><br/>Limitations: TANGO is trained on the small AudioCaps dataset so it may not generate good audio \
  84. # samples related to concepts that it has not seen in training (e.g. singing). For the same reason, TANGO \
  85. # is not always able to finely control its generations over textual control prompts. For example, \
  86. # the generations from TANGO for prompts Chopping tomatoes on a wooden table and Chopping potatoes \
  87. # on a metal table are very similar. \
  88. # <br/><br/>We are currently training another version of TANGO on larger datasets to enhance its generalization, \
  89. # compositional and controllable generation ability.
  90. # <br/><br/>We recommend using a guidance scale of 3. The default number of steps is set to 100. More steps generally lead to better quality of generated audios but will take longer.
  91. # <br/><br/>
  92. # <h1> ChatGPT-enhanced audio generation</h1>
  93. # <br/>
  94. # As TANGO consists of an instruction-tuned LLM, it is able to process complex sound descriptions allowing us to provide more detailed instructions to improve the generation quality.
  95. # For example, ``A boat is moving on the sea'' vs ``The sound of the water lapping against the hull of the boat or splashing as you move through the waves''. The latter is obtained by prompting ChatGPT to explain the sound generated when a boat moves on the sea.
  96. # Using this ChatGPT-generated description of the sound, TANGO provides superior results.
  97. # <p/>
  98. # """
  99. description_text = """
  100. <p><a href="https://huggingface.co/spaces/declare-lab/tango/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/>
  101. Generate audio using TANGO by providing a text prompt.
  102. <br/>
  103. <br/>
  104. As TANGO consists of an instruction-tuned LLM, it is able to process complex sound descriptions allowing us to provide more detailed instructions to improve the generation quality.
  105. For example, ``A boat is moving on the sea'' vs ``The sound of the water lapping against the hull of the boat or splashing as you move through the waves''. The latter is obtained by prompting ChatGPT to explain the sound generated when a boat moves on the sea.
  106. Using this ChatGPT-generated description of the sound, TANGO provides superior results.
  107. <p/>
  108. """
  109. # Gradio input and output components
  110. input_text = gr.Textbox(lines=2, label="Prompt")
  111. output_audio_1 = gr.Audio(label="Generated Audio #1/3", type="filepath")
  112. output_audio_2 = gr.Audio(label="Generated Audio #2/3", type="filepath")
  113. output_audio_3 = gr.Audio(label="Generated Audio #3/3", type="filepath")
  114. denoising_steps = gr.Slider(minimum=100, maximum=200, value=100, step=1, label="Steps", interactive=True)
  115. guidance_scale = gr.Slider(minimum=1, maximum=10, value=3, step=0.1, label="Guidance Scale", interactive=True)
  116. # Gradio interface
  117. gr_interface = gr.Interface(
  118. fn=gradio_generate,
  119. inputs=[input_text, denoising_steps, guidance_scale],
  120. outputs=[output_audio_1, output_audio_2, output_audio_3],
  121. title="Tango: Text-to-Audio Generation using Instruction-tuned LLM and Latent Diffusion Model",
  122. description=description_text,
  123. allow_flagging=False,
  124. examples=[
  125. ["Quiet speech and then and airplane flying away"],
  126. ["A bicycle peddling on dirt and gravel followed by a man speaking then laughing"],
  127. ["Ducks quack and water splashes with some animal screeching in the background"],
  128. ["Describe the sound of the ocean"],
  129. ["A woman and a baby are having a conversation"],
  130. ["A man speaks followed by a popping noise and laughter"],
  131. ["A cup is filled from a faucet"],
  132. ["An audience cheering and clapping"],
  133. ["Rolling thunder with lightning strikes"],
  134. ["A dog barking and a cat mewing and a racing car passes by"],
  135. ["Gentle water stream, birds chirping and sudden gun shot"],
  136. ["A man talking followed by a goat baaing then a metal gate sliding shut as ducks quack and wind blows into a microphone."],
  137. ["A dog barking"],
  138. ["A cat meowing"],
  139. ["Wooden table tapping sound while water pouring"],
  140. ["Applause from a crowd with distant clicking and a man speaking over a loudspeaker"],
  141. ["two gunshots followed by birds flying away while chirping"],
  142. ["Whistling with birds chirping"],
  143. ["A person snoring"],
  144. ["Motor vehicles are driving with loud engines and a person whistles"],
  145. ["People cheering in a stadium while thunder and lightning strikes"],
  146. ["A helicopter is in flight"],
  147. ["A dog barking and a man talking and a racing car passes by"],
  148. ],
  149. cache_examples="lazy", # Turn on to cache.
  150. )
  151. # Launch Gradio app
  152. gr_interface.queue(10).launch()
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...