thecollabagepatch commited on
Commit
cd9b5e1
Β·
1 Parent(s): 81d4369
Files changed (1) hide show
  1. app.py +256 -15
app.py CHANGED
@@ -1,18 +1,25 @@
1
  import gradio as gr
2
  import spaces
3
- import torch
4
  import torchaudio
5
  from audiocraft.models import MusicGen
6
  from audiocraft.data.audio import audio_write
 
 
 
 
 
 
 
7
 
8
- # Initialize something outside GPU function (like official example)
9
- print("Starting app...")
10
 
11
- @spaces.GPU
12
- def generate_drum_sample(trigger_input):
13
- """Generate drum sample - following official ZeroGPU pattern"""
14
- print("GPU function called") # Debug like official example
15
-
 
16
  model = MusicGen.get_pretrained('pharoAIsanders420/micro-musicgen-jungle')
17
  model.set_generation_params(duration=10)
18
  wav = model.generate_unconditional(1).squeeze(0)
@@ -24,10 +31,244 @@ def generate_drum_sample(trigger_input):
24
 
25
  return filename_with_extension
26
 
27
- # Use EXACT same pattern as official quickstart
28
- demo = gr.Interface(
29
- fn=generate_drum_sample,
30
- inputs=gr.Number(value=1, label="Trigger"),
31
- outputs=gr.Audio(type="filepath")
32
- )
33
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import spaces
 
3
  import torchaudio
4
  from audiocraft.models import MusicGen
5
  from audiocraft.data.audio import audio_write
6
+ import tempfile
7
+ import os
8
+ import logging
9
+ import torch
10
+ from pydub import AudioSegment
11
+ import io
12
+ import random
13
 
14
+ # Check if CUDA is available
15
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
16
 
17
+ def preprocess_audio(waveform):
18
+ waveform_np = waveform.cpu().squeeze().numpy()
19
+ return torch.from_numpy(waveform_np).unsqueeze(0).to(device)
20
+
21
+ @spaces.GPU(duration=10)
22
+ def generate_drum_sample():
23
  model = MusicGen.get_pretrained('pharoAIsanders420/micro-musicgen-jungle')
24
  model.set_generation_params(duration=10)
25
  wav = model.generate_unconditional(1).squeeze(0)
 
31
 
32
  return filename_with_extension
33
 
34
+ @spaces.GPU(duration=10)
35
+ def continue_drum_sample(existing_audio_path):
36
+ if existing_audio_path is None:
37
+ return None
38
+
39
+ existing_audio, sr = torchaudio.load(existing_audio_path)
40
+ existing_audio = existing_audio.to(device)
41
+
42
+ prompt_duration = 2
43
+ output_duration = 10
44
+
45
+ num_samples = int(prompt_duration * sr)
46
+ if existing_audio.shape[1] < num_samples:
47
+ raise ValueError("The existing audio is too short for the specified prompt duration.")
48
+
49
+ start_sample = existing_audio.shape[1] - num_samples
50
+ prompt_waveform = existing_audio[..., start_sample:]
51
+
52
+ model = MusicGen.get_pretrained('pharoAIsanders420/micro-musicgen-jungle')
53
+ model.set_generation_params(duration=output_duration)
54
+
55
+ output = model.generate_continuation(prompt_waveform, prompt_sample_rate=sr, progress=True)
56
+ output = output.to(device)
57
+
58
+ if output.dim() == 3:
59
+ output = output.squeeze(0)
60
+
61
+ if output.dim() == 1:
62
+ output = output.unsqueeze(0)
63
+
64
+ combined_audio = torch.cat((existing_audio, output), dim=1)
65
+ combined_audio = combined_audio.cpu()
66
+
67
+ combined_file_path = f'./continued_jungle_{random.randint(1000, 9999)}.wav'
68
+ torchaudio.save(combined_file_path, combined_audio, sr)
69
+
70
+ return combined_file_path
71
+
72
+ @spaces.GPU(duration=120)
73
+ def generate_music(wav_filename, prompt_duration, musicgen_model, output_duration):
74
+ if wav_filename is None:
75
+ return None
76
+
77
+ song, sr = torchaudio.load(wav_filename)
78
+ song = song.to(device)
79
+
80
+ model_name = musicgen_model.split(" ")[0]
81
+ model_continue = MusicGen.get_pretrained(model_name)
82
+
83
+ model_continue.set_generation_params(
84
+ use_sampling=True,
85
+ top_k=250,
86
+ top_p=0.0,
87
+ temperature=1.0,
88
+ duration=output_duration,
89
+ cfg_coef=3
90
+ )
91
+
92
+ prompt_waveform = song[..., :int(prompt_duration * sr)]
93
+ prompt_waveform = preprocess_audio(prompt_waveform)
94
+
95
+ output = model_continue.generate_continuation(prompt_waveform, prompt_sample_rate=sr, progress=True)
96
+ output = output.cpu()
97
+
98
+ if len(output.size()) > 2:
99
+ output = output.squeeze()
100
+
101
+ filename_without_extension = f'continued_music'
102
+ filename_with_extension = f'{filename_without_extension}.wav'
103
+ audio_write(filename_without_extension, output, model_continue.sample_rate, strategy="loudness", loudness_compressor=True)
104
+
105
+ return filename_with_extension
106
+
107
+ @spaces.GPU(duration=120)
108
+ def continue_music(input_audio_path, prompt_duration, musicgen_model, output_duration):
109
+ if input_audio_path is None:
110
+ return None
111
+
112
+ song, sr = torchaudio.load(input_audio_path)
113
+ song = song.to(device)
114
+
115
+ model_continue = MusicGen.get_pretrained(musicgen_model.split(" ")[0])
116
+ model_continue.set_generation_params(
117
+ use_sampling=True,
118
+ top_k=250,
119
+ top_p=0.0,
120
+ temperature=1.0,
121
+ duration=output_duration,
122
+ cfg_coef=3
123
+ )
124
+
125
+ original_audio = AudioSegment.from_mp3(input_audio_path)
126
+ current_audio = original_audio
127
+
128
+ file_paths_for_cleanup = []
129
+
130
+ for i in range(1):
131
+ num_samples = int(prompt_duration * sr)
132
+ if current_audio.duration_seconds * 1000 < prompt_duration * 1000:
133
+ raise ValueError("The prompt_duration is longer than the current audio length.")
134
+
135
+ start_time = current_audio.duration_seconds * 1000 - prompt_duration * 1000
136
+ prompt_audio = current_audio[start_time:]
137
+
138
+ prompt_bytes = prompt_audio.export(format="wav").read()
139
+ prompt_waveform, _ = torchaudio.load(io.BytesIO(prompt_bytes))
140
+ prompt_waveform = prompt_waveform.to(device)
141
+
142
+ prompt_waveform = preprocess_audio(prompt_waveform)
143
+
144
+ output = model_continue.generate_continuation(prompt_waveform, prompt_sample_rate=sr, progress=True)
145
+ output = output.cpu()
146
+
147
+ if len(output.size()) > 2:
148
+ output = output.squeeze()
149
+
150
+ filename_without_extension = f'continue_{i}'
151
+ filename_with_extension = f'{filename_without_extension}.wav'
152
+ correct_filename_extension = f'{filename_without_extension}.wav.wav'
153
+
154
+ audio_write(filename_with_extension, output, model_continue.sample_rate, strategy="loudness", loudness_compressor=True)
155
+ generated_audio_segment = AudioSegment.from_wav(correct_filename_extension)
156
+
157
+ current_audio = current_audio[:start_time] + generated_audio_segment
158
+
159
+ file_paths_for_cleanup.append(correct_filename_extension)
160
+
161
+ combined_audio_filename = f"combined_audio_{random.randint(1, 10000)}.mp3"
162
+ current_audio.export(combined_audio_filename, format="mp3")
163
+
164
+ for file_path in file_paths_for_cleanup:
165
+ os.remove(file_path)
166
+
167
+ return combined_audio_filename
168
+
169
+ # Define the expandable sections (keeping your existing content)
170
+ musicgen_micro_blurb = """
171
+ ## musicgen_micro
172
+ musicgen micro is an experimental series of models by aaron abebe. they are incredibly fast, and extra insane. this one does goated jungle drums. we're very excited about these.
173
+ [<img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" alt="GitHub" width="20" style="vertical-align:middle"> aaron's github](https://github.com/aaronabebe/)
174
+ [<img src="https://huggingface.co/front/assets/huggingface_logo-noborder.svg" alt="Hugging Face" width="20" style="vertical-align:middle"> musicgen-micro on huggingface](https://huggingface.co/pharoAIsanders420/micro-musicgen-jungle)
175
+ """
176
+
177
+ musicgen_blurb = """
178
+ ## musicgen
179
+ musicgen is a transformer-based music model that generates audio. It can also do something called a continuation, which was initially meant to extend musicgen outputs beyond 30 seconds. it can be used with any input audio to produce surprising results.
180
+ [<img src="https://github.githubassets.com/images/modules/logos_page/GitHub-Mark.png" alt="GitHub" width="20" style="vertical-align:middle"> audiocraft github](https://github.com/facebookresearch/audiocraft)
181
+ visit https://thecollabagepatch.com/infinitepolo.mp3 or https://thecollabagepatch.com/audiocraft.mp3 to hear continuations in action.
182
+ see also https://youtube.com/@thecollabagepatch
183
+ """
184
+
185
+ finetunes_blurb = """
186
+ ## fine-tuned models
187
+ the fine-tunes hosted on the huggingface hub are provided collectively by the musicgen discord community. thanks to vanya, mj, hoenn, septicDNB and of course, lyra.
188
+ [<img src="https://cdn.iconscout.com/icon/free/png-256/discord-3691244-3073764.png" alt="Discord" width="20" style="vertical-align:middle"> musicgen discord](https://discord.gg/93kX8rGZ)
189
+ [<img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab" style="vertical-align:middle"> fine-tuning colab notebook by lyra](https://colab.research.google.com/drive/13tbcC3A42KlaUZ21qvUXd25SFLu8WIvb)
190
+ """
191
+
192
+ fine_tunes_info = """
193
+ ## thepatch/vanya_ai_dnb_0.1
194
+ thepatch/vanya_ai_dnb_0.1 was trained by vanya. [vanya's Twitter](https://twitter.com/@veryVANYA) πŸ”— - it treats almost all input audio as the beginning of a buildup to a dnb drop (can do downtempo well)
195
+
196
+ ## thepatch/bleeps-medium
197
+ thepatch/bleeps-medium was trained by kevin and lyra [lyra's Twitter](https://twitter.com/@_lyraaaa_) πŸ”— - it is a medium model. it's more melodic and ambient sometimes than vanya's, but there's a 50/50 chance it gets real heavy with the edm vibes. It can be amazing at turning your chords into pads, and is a good percussionist.
198
+
199
+ ## thepatch/budots_remix
200
+ thepatch/budots_remix was trained by MJ BERSABEph. budots is a dope niche genre from the philippines apparently. this one will often do fascinating, demonic, kinds of vocal chopping. warning: it tends to speed up and slow down tempo, which makes it hard to use in a daw.
201
+
202
+ ## thepatch/hoenn_lofi
203
+ thepatch/hoenn_lofi is a large fine-tune by hoenn. [hoenn's Twitter](https://twitter.com/@eschatolocation) πŸ”— - this model is a large boi, and it shows. even tho it is trained to do lo-fi, its ability to run with your melodies and not ruin them is unparalleled among the fine-tunes so far.
204
+
205
+ ## thepatch/PhonkV2
206
+ thepatch/PhonkV2 was trained by MJ BERSABEph. there are multiple versions in the discord.
207
+
208
+ ## foureyednymph/musicgen-sza-sos-small
209
+ foureyednymph/musicgen-sza-sos-small was just trained by foureyednymph. We're all about to find out if it does continuations well.
210
+ """
211
+
212
+ # Create the Gradio interface with explicit types
213
+ with gr.Blocks() as iface:
214
+ gr.Markdown("# the-micro-slot-machine")
215
+ gr.Markdown("two ai's jamming. warning: outputs will be very strange, likely stupid, and possibly rad.")
216
+ gr.Markdown("this is an even weirder slot machine than the other one. on the left, you get to generate some state of the art lo-fi jungle drums at incredible speed thanks to aaron's new class of model, and if you want you can have it continue its own output. Then, you can either press the generate_music button to use the first 5 seconds as a prompt, or you can re-upload the audio into the continue_music section to have a fine-tune continue from the end of the jungle drum output, however long and insane it is. think of this as a very weird relay race and you're winning.")
217
+
218
+ with gr.Accordion("more info", open=False):
219
+ gr.Markdown(musicgen_micro_blurb)
220
+ gr.Markdown(musicgen_blurb)
221
+ gr.Markdown(finetunes_blurb)
222
+
223
+ with gr.Accordion("fine-tunes info", open=False):
224
+ gr.Markdown(fine_tunes_info)
225
+
226
+ with gr.Row():
227
+ with gr.Column():
228
+ generate_button = gr.Button("Generate Drum Sample")
229
+ drum_audio = gr.Audio(
230
+ label="Generated Drum Sample",
231
+ type="filepath",
232
+ interactive=True,
233
+ show_download_button=True
234
+ )
235
+ continue_drum_sample_button = gr.Button("Continue Drum Sample")
236
+
237
+ with gr.Column():
238
+ prompt_duration = gr.Dropdown(
239
+ label="Prompt Duration (seconds)",
240
+ choices=list(range(1, 11)),
241
+ value=5
242
+ )
243
+ output_duration = gr.Slider(
244
+ label="Output Duration (seconds)",
245
+ minimum=10,
246
+ maximum=30,
247
+ step=1,
248
+ value=20
249
+ )
250
+ musicgen_model = gr.Dropdown(
251
+ label="MusicGen Model",
252
+ choices=[
253
+ "thepatch/vanya_ai_dnb_0.1 (small)",
254
+ "thepatch/budots_remix (small)",
255
+ "thepatch/PhonkV2 (small)",
256
+ "thepatch/bleeps-medium (medium)",
257
+ "thepatch/hoenn_lofi (large)",
258
+ "foureyednymph/musicgen-sza-sos-small (small)"
259
+ ],
260
+ value="thepatch/vanya_ai_dnb_0.1 (small)"
261
+ )
262
+ generate_music_button = gr.Button("Generate Music")
263
+ output_audio = gr.Audio(label="Generated Music", type="filepath")
264
+ continue_button = gr.Button("Continue Generating Music")
265
+ continue_output_audio = gr.Audio(label="Continued Music Output", type="filepath")
266
+
267
+ # Connecting the components
268
+ generate_button.click(generate_drum_sample, outputs=[drum_audio])
269
+ continue_drum_sample_button.click(continue_drum_sample, inputs=[drum_audio], outputs=[drum_audio])
270
+ generate_music_button.click(generate_music, inputs=[drum_audio, prompt_duration, musicgen_model, output_duration], outputs=[output_audio])
271
+ continue_button.click(continue_music, inputs=[output_audio, prompt_duration, musicgen_model, output_duration], outputs=continue_output_audio)
272
+
273
+ if __name__ == "__main__":
274
+ iface.launch()