awacke1 commited on
Commit
0be985e
1 Parent(s): 3210700

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +231 -0
app.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torchaudio
3
+ from einops import rearrange
4
+ import gradio as gr
5
+ import spaces
6
+ import os
7
+ import uuid
8
+ from stable_audio_tools import get_pretrained_model
9
+ from stable_audio_tools.inference.generation import generate_diffusion_cond
10
+
11
+ PAGE_SIZE = 10
12
+ FILE_DIR_PATH = "/data"
13
+ theme = gr.themes.Base(
14
+ font=[gr.themes.GoogleFont('Libre Franklin'), gr.themes.GoogleFont('Public Sans'), 'system-ui', 'sans-serif'],
15
+ )
16
+
17
+
18
+ def load_model():
19
+ model, model_config = get_pretrained_model("stabilityai/stable-audio-open-1.0")
20
+ print("Loading model...Done")
21
+ return model, model_config
22
+
23
+ @spaces.GPU(duration=120)
24
+ def generate_audio(prompt, sampler_type_dropdown, seconds_total=30, steps=100, cfg_scale=7,sigma_min_slider=0.3,sigma_max_slider=500, progress=gr.Progress(track_tqdm=True)):
25
+ print(f"Prompt received: {prompt}")
26
+ print(f"Settings: Duration={seconds_total}s, Steps={steps}, CFG Scale={cfg_scale}")
27
+
28
+ device = "cuda" if torch.cuda.is_available() else "cpu"
29
+ print(f"Using device: {device}")
30
+
31
+ # Fetch the Hugging Face token from the environment variable
32
+ hf_token = os.getenv('HF_TOKEN')
33
+ print(f"Hugging Face token: {hf_token}")
34
+
35
+ # Use pre-loaded model and configuration
36
+ model, model_config = load_model()
37
+ sample_rate = model_config["sample_rate"]
38
+ sample_size = model_config["sample_size"]
39
+
40
+ print(f"Sample rate: {sample_rate}, Sample size: {sample_size}")
41
+
42
+ model = model.to(device)
43
+ print("Model moved to device.")
44
+
45
+ # Set up text and timing conditioning
46
+ conditioning = [{
47
+ "prompt": prompt,
48
+ "seconds_start": 0,
49
+ "seconds_total": seconds_total
50
+ }]
51
+ print(f"Conditioning: {conditioning}")
52
+
53
+ print("Generating audio...")
54
+ output = generate_diffusion_cond(
55
+ model,
56
+ steps=steps,
57
+ cfg_scale=cfg_scale,
58
+ conditioning=conditioning,
59
+ sample_size=sample_size,
60
+ sigma_min=sigma_min_slider,
61
+ sigma_max=sigma_max_slider,
62
+ sampler_type=sampler_type_dropdown,#"dpmpp-3m-sde",
63
+ device=device
64
+ )
65
+ print("Audio generated.")
66
+ output = rearrange(output, "b d n -> d (b n)")
67
+ print("Audio rearranged.")
68
+ output = output.to(torch.float32).div(torch.max(torch.abs(output))).clamp(-1, 1).mul(32767).to(torch.int16).cpu()
69
+ max_length = sample_rate * seconds_total
70
+ if output.shape[1] > max_length:
71
+ output = output[:, :max_length]
72
+ print(f"Audio trimmed to {seconds_total} seconds.")
73
+ random_uuid = uuid.uuid4().hex
74
+ unique_filename = f"/data/output_{random_uuid}.wav"
75
+ unique_textfile = f"/data/output_{random_uuid}.txt"
76
+ print(f"Saving audio to file: {unique_filename}")
77
+ torchaudio.save(unique_filename, output, sample_rate)
78
+ print(f"Audio saved: {unique_filename}")
79
+ with open(unique_textfile, "w") as file:
80
+ file.write(prompt)
81
+ return unique_filename
82
+
83
+ def list_all_outputs(generation_history):
84
+ directory_path = FILE_DIR_PATH
85
+ files_in_directory = os.listdir(directory_path)
86
+ wav_files = [os.path.join(directory_path, file) for file in files_in_directory if file.endswith('.wav')]
87
+ wav_files.sort(key=lambda x: os.path.getmtime(os.path.join(directory_path, x)), reverse=True)
88
+ history_list = generation_history.split(',') if generation_history else []
89
+ updated_files = [file for file in wav_files if file not in history_list]
90
+ updated_history = updated_files + history_list
91
+ return ','.join(updated_history), gr.update(visible=True)
92
+
93
+ def increase_list_size(list_size):
94
+ return list_size+PAGE_SIZE
95
+
96
+ css = '''
97
+ #live_gen:before {
98
+ content: '';
99
+ animation: svelte-z7cif2-pulseStart 1s cubic-bezier(.4,0,.6,1), svelte-z7cif2-pulse 2s cubic-bezier(.4,0,.6,1) 1s infinite;
100
+ border: 2px solid var(--color-accent);
101
+ background: transparent;
102
+ z-index: var(--layer-1);
103
+ pointer-events: none;
104
+ position: absolute;
105
+ height: 100%;
106
+ width: 100%;
107
+ border-radius: 7px;
108
+ }
109
+ #live_gen_items{
110
+ max-height: 570px;
111
+ overflow-y: scroll;
112
+ }
113
+ '''
114
+
115
+ examples = [
116
+ [
117
+ "serene soundscape of a beach at sunset.", # Text prompt
118
+ "dpmpp-2m-sde", # Sampler type
119
+ 45, # Duration in Seconds
120
+ 100, # Number of Diffusion Steps
121
+ 10, # CFG Scale
122
+ 0.5, # Sigma min
123
+ 800 # Sigma max
124
+ ],
125
+ [
126
+ "clapping crowd", # Text prompt
127
+ "dpmpp-3m-sde", # Sampler type
128
+ 30, # Duration in Seconds
129
+ 100, # Number of Diffusion Steps
130
+ 7, # CFG Scale
131
+ 0.5, # Sigma min
132
+ 500 # Sigma max
133
+ ],
134
+ [
135
+ "forest ambiance birds chirping wind rustling.", # Text prompt
136
+ "k-dpm-fast", # Sampler type
137
+ 60, # Duration in Seconds
138
+ 140, # Number of Diffusion Steps
139
+ 7.5, # CFG Scale
140
+ 0.3, # Sigma min
141
+ 700 # Sigma max
142
+ ],
143
+ [
144
+ "gentle rainfall distant thunder.", # Text prompt
145
+ "dpmpp-3m-sde", # Sampler type
146
+ 35, # Duration in Seconds
147
+ 110, # Number of Diffusion Steps
148
+ 8, # CFG Scale
149
+ 0.1, # Sigma min
150
+ 500 # Sigma max
151
+ ],
152
+ [
153
+ "cafe environment soft edm techno music ambient chatter.", # Text prompt
154
+ "k-lms", # Sampler type
155
+ 25, # Duration in Seconds
156
+ 90, # Number of Diffusion Steps
157
+ 6, # CFG Scale
158
+ 0.4, # Sigma min
159
+ 650 # Sigma max
160
+ ],
161
+ ["Rock beat drumming acoustic guitar.",
162
+ "dpmpp-2m-sde", # Sampler type
163
+ 30, # Duration in Seconds
164
+ 100, # Number of Diffusion Steps
165
+ 7, # CFG Scale
166
+ 0.3, # Sigma min
167
+ 500 # Sigma max
168
+ ]
169
+ ]
170
+
171
+ with gr.Blocks(theme=theme, css=css) as demo:
172
+ gr.Markdown("# Stable Audio Multiplayer Live")
173
+ gr.Markdown("Generate audio with text, share and learn from others how to best prompt this new model")
174
+ generation_history = gr.Textbox(visible=False)
175
+ list_size = gr.Number(value=PAGE_SIZE, visible=False)
176
+ with gr.Row():
177
+ with gr.Column():
178
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your text prompt here")
179
+ btn_run = gr.Button("Generate")
180
+ with gr.Accordion("Parameters", open=True):
181
+ with gr.Row():
182
+ duration = gr.Slider(0, 47, value=20, step=1, label="Duration in Seconds")
183
+
184
+ with gr.Accordion("Advanced parameters", open=False):
185
+ steps = gr.Slider(10, 150, value=80, step=10, label="Number of Diffusion Steps")
186
+ sampler_type = gr.Dropdown(["dpmpp-2m-sde", "dpmpp-3m-sde", "k-heun", "k-lms",
187
+ "k-dpmpp-2s-ancestral", "k-dpm-2", "k-dpm-fast"],
188
+ label="Sampler type", value="dpmpp-3m-sde")
189
+ with gr.Row():
190
+ cfg_scale = gr.Slider(1, 15, value=7, step=0.1, label="CFG Scale")
191
+ sigma_min = gr.Slider(0.0, 5.0, step=0.01, value=0.3, label="Sigma min")
192
+ sigma_max = gr.Slider(0.0, 1000.0, step=0.1, value=500, label="Sigma max")
193
+ with gr.Column() as output_list:
194
+ output = gr.Audio(type="filepath", label="Generated Audio")
195
+ with gr.Column(elem_id="live_gen") as community_list:
196
+ gr.Markdown("# Community generations")
197
+ with gr.Column(elem_id="live_gen_items"):
198
+ @gr.render(inputs=[generation_history, list_size])
199
+ def show_output_list(generation_history, list_size):
200
+ history_list = generation_history.split(',') if generation_history else []
201
+ history_list_latest = history_list[:list_size]
202
+ for generation in history_list_latest:
203
+ generation_prompt_file = generation.replace('.wav', '.txt')
204
+ with open(generation_prompt_file, 'r') as file:
205
+ generation_prompt = file.read()
206
+ with gr.Group():
207
+ gr.Markdown(value=f"### {generation_prompt}")
208
+ gr.Audio(value=generation)
209
+
210
+
211
+ load_more = gr.Button("Load more")
212
+ load_more.click(fn=increase_list_size, inputs=list_size, outputs=list_size)
213
+
214
+ gr.Examples(
215
+ fn=generate_audio,
216
+ examples=examples,
217
+ inputs=[prompt, sampler_type, duration, steps, cfg_scale, sigma_min, sigma_max],
218
+ outputs=output,
219
+ cache_examples="lazy"
220
+ )
221
+ gr.on(
222
+ triggers=[btn_run.click, prompt.submit],
223
+ fn=generate_audio,
224
+ inputs=[prompt, sampler_type, duration, steps, cfg_scale, sigma_min, sigma_max],
225
+ outputs=output
226
+ )
227
+ demo.load(fn=list_all_outputs, inputs=generation_history, outputs=[generation_history, community_list], every=2)
228
+
229
+ model, model_config = load_model()
230
+
231
+ demo.launch()