smartdigitalnetworks commited on
Commit
604210a
·
verified ·
1 Parent(s): 3cdba54

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -341
app.py DELETED
@@ -1,341 +0,0 @@
1
- from diffusers import StableDiffusionImg2ImgPipeline, DPMSolverMultistepScheduler, StableDiffusionImg2ImgPipeline, StableDiffusionInpaintPipeline
2
- import torch
3
- from PIL import Image, ImageDraw
4
- import os
5
- import numpy as np
6
- from scipy.io.wavfile import read
7
-
8
- from share_btn import community_icon_html, loading_icon_html, share_js
9
-
10
-
11
- os.system('pip install gradio==3.15.0')
12
- import gradio as gr
13
-
14
-
15
- os.system('git clone https://github.com/hmartiro/riffusion-inference.git riffusion')
16
- from riffusion.riffusion.riffusion_pipeline import RiffusionPipeline
17
- from riffusion.riffusion.datatypes import PromptInput, InferenceInput
18
- from riffusion.riffusion.audio import wav_bytes_from_spectrogram_image
19
- from PIL import Image
20
- import struct
21
- import random
22
-
23
- repo_id = "riffusion/riffusion-model-v1"
24
-
25
- model = RiffusionPipeline.from_pretrained(
26
- repo_id,
27
- revision="main",
28
- torch_dtype=torch.float16,
29
- safety_checker=lambda images, **kwargs: (images, False),
30
- )
31
-
32
- if torch.cuda.is_available():
33
- model.to("cuda")
34
- model.enable_xformers_memory_efficient_attention()
35
-
36
- pipe_inpaint = StableDiffusionInpaintPipeline.from_pretrained(repo_id, torch_dtype=torch.float16, safety_checker=lambda images, **kwargs: (images, False),)
37
- pipe_inpaint.scheduler = DPMSolverMultistepScheduler.from_config(pipe_inpaint.scheduler.config)
38
-
39
- # pipe_inpaint.enable_xformers_memory_efficient_attention()
40
-
41
- if torch.cuda.is_available():
42
- pipe_inpaint = pipe_inpaint.to("cuda")
43
- pipe_inpaint.enable_xformers_memory_efficient_attention()
44
-
45
-
46
- def get_init_image(image, overlap, feel):
47
-
48
- width, height = image.size
49
- init_image = Image.open(f"riffusion/seed_images/{feel}.png").convert("RGB")
50
- # Crop the right side of the original image with `overlap_width`
51
- cropped_img = image.crop((width - int(width*overlap), 0, width, height))
52
- init_image.paste(cropped_img, (0, 0))
53
-
54
- return init_image
55
-
56
- def get_mask(image, overlap):
57
-
58
- width, height = image.size
59
-
60
- mask = Image.new("RGB", (width, height), color="white")
61
- draw = ImageDraw.Draw(mask)
62
- draw.rectangle((0, 0, int(overlap * width), height), fill="black")
63
- return mask
64
-
65
- def i2i(prompt, steps, feel, seed):
66
- # return pipe_i2i(
67
- # prompt,
68
- # num_inference_steps=steps,
69
- # image=Image.open(f"riffusion/seed_images/{feel}.png").convert("RGB"),
70
- # ).images[0]
71
-
72
- prompt_input_start = PromptInput(prompt=prompt, seed=seed)
73
- prompt_input_end = PromptInput(prompt=prompt, seed=seed)
74
-
75
- return model.riffuse(
76
- inputs=InferenceInput(
77
- start=prompt_input_start,
78
- end=prompt_input_end,
79
- alpha=1.0,
80
- num_inference_steps=steps),
81
- init_image=Image.open(f"riffusion/seed_images/{feel}.png").convert("RGB")
82
- )
83
-
84
- def outpaint(prompt, init_image, mask, steps):
85
- return pipe_inpaint(
86
- prompt,
87
- num_inference_steps=steps,
88
- image=init_image,
89
- mask_image=mask,
90
- ).images[0]
91
-
92
-
93
- def generate(prompt, steps, num_iterations, feel, seed):
94
-
95
- if seed == 0:
96
- seed = random.randint(0,4294967295)
97
-
98
- num_images = num_iterations
99
- overlap = 0.5
100
- image_width, image_height = 512, 512 # dimensions of each output image
101
- total_width = num_images * image_width - (num_images - 1) * int(overlap * image_width) # total width of the stitched image
102
-
103
- # Create a blank image with the desired dimensions
104
- stitched_image = Image.new("RGB", (total_width, image_height), color="white")
105
-
106
- # Initialize the x position for pasting the next image
107
- x_pos = 0
108
-
109
- image = i2i(prompt, steps, feel, seed)
110
-
111
- for i in range(num_images):
112
- # Generate the prompt, initial image, and mask for this iteration
113
- init_image = get_init_image(image, overlap, feel)
114
- mask = get_mask(init_image, overlap)
115
-
116
- # Run the outpaint function to generate the output image
117
- steps = 25
118
- image = outpaint(prompt, init_image, mask, steps)
119
-
120
- # Paste the output image onto the stitched image
121
- stitched_image.paste(image, (x_pos, 0))
122
-
123
- # Update the x position for the next iteration
124
- x_pos += int((1 - overlap) * image_width)
125
-
126
- wav_bytes, duration_s = wav_bytes_from_spectrogram_image(stitched_image)
127
-
128
- # mask = Image.new("RGB", (512, 512), color="white")
129
- # bg_image = outpaint(prompt, init_image, mask, steps)
130
- # bg_image.save("bg_image.png")
131
- init_image.save("bg_image.png")
132
-
133
- # return read(wav_bytes)
134
- with open("output.wav", "wb") as f:
135
- f.write(wav_bytes.read())
136
-
137
- return gr.make_waveform("output.wav", bg_image="bg_image.png", bar_count=int(duration_s*25))
138
-
139
-
140
- ###############################################
141
-
142
- def riffuse(steps, feel, init_image, prompt_start, seed_start, denoising_start=0.75, guidance_start=7.0, prompt_end=None, seed_end=None, denoising_end=0.75, guidance_end=7.0, alpha=0.5):
143
-
144
- prompt_input_start = PromptInput(prompt=prompt_start, seed=seed_start, denoising=denoising_start, guidance=guidance_start)
145
-
146
- prompt_input_end = PromptInput(prompt=prompt_end, seed=seed_end, denoising=denoising_end, guidance=guidance_end)
147
-
148
- input = InferenceInput(
149
- start=prompt_input_start,
150
- end=prompt_input_end,
151
- alpha=alpha,
152
- num_inference_steps=steps,
153
- seed_image_id=feel,
154
- # mask_image_id="mask_beat_lines_80.png"
155
- )
156
-
157
- image = model.riffuse(inputs=input, init_image=init_image)
158
-
159
- wav_bytes, duration_s = wav_bytes_from_spectrogram_image(image)
160
-
161
- return wav_bytes, image
162
-
163
- def generate_riffuse(prompt_start, steps, num_iterations, feel, prompt_end=None, seed_start=None, seed_end=None, denoising_start=0.75, denoising_end=0.75, guidance_start=7.0, guidance_end=7.0):
164
- """Generate a WAV file of length seconds using the Riffusion model.
165
-
166
- Args:
167
- length (int): Length of the WAV file in seconds, must be divisible by 5.
168
- prompt_start (str): Prompt to start with.
169
- prompt_end (str, optional): Prompt to end with. Defaults to prompt_start.
170
- overlap (float, optional): Overlap between audio clips as a fraction of the image size. Defaults to 0.2.
171
- """
172
-
173
- # open the initial image and convert it to RGB
174
- init_image = Image.open(f"riffusion/seed_images/{feel}.png").convert("RGB")
175
-
176
- if prompt_end is None:
177
- prompt_end = prompt_start
178
- if seed_start == 0:
179
- seed_start = random.randint(0,4294967295)
180
- if seed_end is None:
181
- seed_end = seed_start
182
-
183
- # one riffuse() generates 5 seconds of audio
184
- wav_list = []
185
-
186
- for i in range(int(num_iterations)):
187
-
188
- alpha = i / (num_iterations - 1)
189
- print(alpha)
190
- wav_bytes, image = riffuse(steps, feel, init_image, prompt_start, seed_start, denoising_start, guidance_start, prompt_end, seed_end, denoising_end, guidance_end, alpha=alpha)
191
- wav_list.append(wav_bytes)
192
-
193
- init_image = image
194
-
195
- seed_start = seed_end
196
- seed_end = seed_start + 1
197
-
198
- # return read(wav_bytes)
199
- # return wav_list_to_wav(wav_list)
200
-
201
- # mask = Image.new("RGB", (512, 512), color="white")
202
- # bg_image = outpaint(f"{prompt_start} and {prompt_end}", init_image, mask, steps)
203
- # bg_image.save("bg_image.png")
204
- init_image.save("bg_image.png")
205
-
206
- with open("output.wav", "wb") as f:
207
- f.write(wav_list_to_wav(wav_list))
208
-
209
- return gr.make_waveform("output.wav", bg_image="bg_image.png")
210
-
211
-
212
- def wav_list_to_wav(wav_list):
213
-
214
- # remove headers from the WAV files
215
- data = [wav.read()[44:] for wav in wav_list]
216
-
217
- # concatenate the data
218
- concatenated_data = b"".join(data)
219
-
220
- # create a new RIFF header
221
- channels = 1
222
- sample_rate = 44100
223
- bytes_per_second = channels * sample_rate
224
- new_header = struct.pack("<4sI4s4sIHHIIHH4sI", b"RIFF", len(concatenated_data) + 44 - 8, b"WAVE", b"fmt ", 16, 1, channels, sample_rate, bytes_per_second, 2, 16, b"data", len(concatenated_data))
225
-
226
- # combine the header and data to create the final WAV file
227
- final_wav = new_header + concatenated_data
228
- return final_wav
229
-
230
- ###############################################
231
-
232
- def on_submit(prompt_1, prompt_2, feel, num_iterations, steps=25, seed=0):
233
- if prompt_1 == "":
234
- return None, gr.update(value="First prompt is required."), gr.update(visible=False), gr.update(visible=False), gr.update(visible=False)
235
- if prompt_2 == "":
236
- return generate(prompt_1, steps, num_iterations, feel, seed), None, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
237
- else:
238
- return generate_riffuse(prompt_1, steps, num_iterations, feel, prompt_end=prompt_2, seed_start=seed), None, gr.update(visible=True), gr.update(visible=True), gr.update(visible=True)
239
-
240
-
241
- def on_num_iterations_change(n, prompt_2):
242
- if n is None:
243
- return gr.update(value="")
244
-
245
- if prompt_2 != "":
246
- total_length = 5 * n
247
- else:
248
- total_length = 2.5 + 2.5 * n
249
- return gr.update(value=f"Total length: {total_length:.2f} seconds")
250
-
251
-
252
- css = '''
253
- #share-btn-container {
254
- display: flex; padding-left: 0.5rem !important; padding-right: 0.5rem !important; background-color: #000000; justify-content: center; align-items: center; border-radius: 9999px !important; width: 13rem;
255
- }
256
- #share-btn {
257
- all: initial; color: #ffffff;font-weight: 600; cursor:pointer; font-family: 'IBM Plex Sans', sans-serif; margin-left: 0.5rem !important; padding-top: 0.25rem !important; padding-bottom: 0.25rem !important;right:0;
258
- }
259
- #share-btn * {
260
- all: unset;
261
- }
262
- #share-btn-container div:nth-child(-n+2){
263
- width: auto !important;
264
- min-height: 0px !important;
265
- }
266
- #share-btn-container .wrap {
267
- display: none !important;
268
- }
269
- '''
270
-
271
- with gr.Blocks(css=css) as app:
272
- gr.Markdown("## Riffusion Demo")
273
- gr.Markdown("""Generate audio using the [Riffusion](https://huggingface.co/riffusion/riffusion-model-v1) model.<br>
274
- In single prompt mode you can generate up to ~1 minute of audio with smooth transitions between sections. (beta)<br>
275
- Bi-prompt mode interpolates between two prompts. It can generate up to ~2 minutes of audio, but transitions between sections are more abrupt.""")
276
- gr.Markdown(f"""Running on {"**GPU 🔥**" if torch.cuda.is_available() else f"**CPU 🥶**. For faster inference it is recommended to **upgrade to GPU in space's Settings**"}<br>
277
- [![Duplicate Space](https://bit.ly/3gLdBN6)](https://huggingface.co/spaces/anzorq/riffusion-demo?duplicate=true)""")
278
-
279
- with gr.Row():
280
- with gr.Group():
281
- with gr.Row():
282
- prompt_1 = gr.Textbox(lines=1, label="Start from", placeholder="Starting prompt", elem_id="riff-prompt_1")
283
- prompt_2 = gr.Textbox(lines=1, label="End with (optional)", placeholder="Prompt to shift towards at the end", elem_id="riff-prompt_2")
284
- with gr.Row():
285
- steps = gr.Slider(minimum=1, maximum=100, value=25, label="Steps per section")
286
- num_iterations = gr.Slider(minimum=2, maximum=25, value=2, step=1, label="Number of sections")
287
- with gr.Row():
288
- feel = gr.Dropdown(["og_beat", "agile", "vibes", "motorway", "marim"], value="og_beat", label="Feel", elem_id="riff-feel")
289
- seed = gr.Slider(minimum=0, maximum=4294967295, value=0, step=1, label="Seed (0 for random)", elem_id="riff-seed")
290
-
291
- btn_generate = gr.Button(value="Generate").style(full_width=True)
292
- info = gr.Markdown()
293
- with gr.Column():
294
- video = gr.Video(elem_id="riff-video")
295
-
296
- with gr.Group(elem_id="share-btn-container"):
297
- community_icon = gr.HTML(community_icon_html, elem_id="share-btn-share-icon", visible=False)
298
- loading_icon = gr.HTML(loading_icon_html, elem_id="share-btn-loading-icon", visible=False)
299
- share_button = gr.Button("Share to community", elem_id="share-btn", visible=False)
300
-
301
- inputs = [prompt_1, prompt_2, feel, num_iterations, steps, seed]
302
- outputs = [video, info, community_icon, loading_icon, share_button]
303
-
304
- num_iterations.change(on_num_iterations_change, [num_iterations, prompt_2], [info])
305
- prompt_1.submit(on_submit, inputs, outputs)
306
- prompt_2.submit(on_submit, inputs, outputs)
307
- btn_generate.click(on_submit, inputs, outputs)
308
-
309
- share_button.click(None, [], [], _js=share_js)
310
-
311
- examples = gr.Examples(
312
- fn=on_submit,
313
- examples=[
314
- ["typing", "dance beat", "og_beat", 10],
315
- ["synthwave", "jazz", "agile", 10],
316
- ["rap battle freestyle", "", "og_beat", 10],
317
- # ["techno club banger", "", "og_beat", 10],
318
- ["reggae dub beat", "sunset chill", "og_beat", 10],
319
- ["acoustic folk ballad", "", "agile", 10],
320
- ["blues guitar riff", "", "agile", 5],
321
- ["jazzy trumpet solo", "", "og_beat", 5],
322
- ["classical symphony orchestra", "", "vibes", 10],
323
- ["rock and roll power chord", "", "motorway", 5],
324
- ["soulful R&B love song", "", "marim", 10],
325
- ["country western twangy guitar", "", "agile", 10]],
326
- inputs=[prompt_1, prompt_2, feel, num_iterations],
327
- outputs=outputs,
328
- cache_examples=True)
329
-
330
- gr.HTML("""
331
- <div style="border-top: 1px solid #303030;">
332
- <br>
333
- <p>Space by:<br>
334
- <a href="https://twitter.com/hahahahohohe"><img src="https://img.shields.io/twitter/follow/hahahahohohe?label=%40anzorq&style=social" alt="Twitter Follow"></a><br>
335
- <a href="https://github.com/qunash"><img alt="GitHub followers" src="https://img.shields.io/github/followers/qunash?style=social" alt="Github Follow"></a></p><br>
336
- <a href="https://www.buymeacoffee.com/anzorq" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-yellow.png" alt="Buy Me A Coffee" style="height: 24px !important;width: 81px !important;" ></a><br><br>
337
- <p><img src="https://visitor-badge.glitch.me/badge?page_id=anzorq.riffusion-demo" alt="visitors"></p>
338
- </div>
339
- """)
340
-
341
- app.queue(max_size=250, concurrency_count=6).launch()