Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from queue import Queue
|
2 |
+
from threading import Thread
|
3 |
+
from typing import Optional
|
4 |
+
import numpy as np
|
5 |
+
import torch
|
6 |
+
from transformers import MusicgenForConditionalGeneration, MusicgenProcessor, set_seed
|
7 |
+
from transformers.generation.streamers import BaseStreamer
|
8 |
+
import gradio as gr
|
9 |
+
import spaces
|
10 |
+
|
11 |
+
model = MusicgenForConditionalGeneration.from_pretrained("facebook/musicgen-small")
|
12 |
+
processor = MusicgenProcessor.from_pretrained("facebook/musicgen-small")
|
13 |
+
|
14 |
+
title, description, article = "MusicGen Streaming (by Sanchit Gandhi)"
|
15 |
+
|
16 |
+
class MusicgenStreamer(BaseStreamer):
|
17 |
+
def __init__(self, model, device=None, play_steps=10, stride=None, timeout=None):
|
18 |
+
self.decoder, self.audio_encoder, self.generation_config = model.decoder, model.audio_encoder, model.generation_config
|
19 |
+
self.device = device if device else model.device
|
20 |
+
self.play_steps = play_steps
|
21 |
+
self.stride = stride if stride else np.prod(self.audio_encoder.config.upsampling_ratios) * (play_steps - self.decoder.num_codebooks) // 6
|
22 |
+
self.token_cache, self.to_yield, self.audio_queue, self.stop_signal, self.timeout = None, 0, Queue(), None, timeout
|
23 |
+
|
24 |
+
def apply_delay_pattern_mask(self, input_ids):
|
25 |
+
_, mask = self.decoder.build_delay_pattern_mask(input_ids[:, :1], pad_token_id=self.generation_config.decoder_start_token_id, max_length=input_ids.shape[-1])
|
26 |
+
input_ids = self.decoder.apply_delay_pattern_mask(input_ids, mask)
|
27 |
+
input_ids = input_ids[input_ids != self.generation_config.pad_token_id].reshape(1, self.decoder.num_codebooks, -1)[None, ...]
|
28 |
+
return self.audio_encoder.decode(input_ids.to(self.audio_encoder.device), audio_scales=[None]).audio_values[0, 0].cpu().float().numpy()
|
29 |
+
|
30 |
+
def put(self, value):
|
31 |
+
if value.shape[0] // self.decoder.num_codebooks > 1:
|
32 |
+
raise ValueError("MusicgenStreamer only supports batch size 1")
|
33 |
+
self.token_cache = torch.concatenate([self.token_cache, value[:, None]], dim=-1) if self.token_cache else value
|
34 |
+
if self.token_cache.shape[-1] % self.play_steps == 0:
|
35 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache)
|
36 |
+
self.on_finalized_audio(audio_values[self.to_yield : -self.stride])
|
37 |
+
self.to_yield += len(audio_values) - self.to_yield - self.stride
|
38 |
+
|
39 |
+
def end(self):
|
40 |
+
audio_values = self.apply_delay_pattern_mask(self.token_cache) if self.token_cache else np.zeros(self.to_yield)
|
41 |
+
self.on_finalized_audio(audio_values[self.to_yield :], stream_end=True)
|
42 |
+
|
43 |
+
def on_finalized_audio(self, audio, stream_end=False):
|
44 |
+
self.audio_queue.put(audio, timeout=self.timeout)
|
45 |
+
if stream_end:
|
46 |
+
self.audio_queue.put(self.stop_signal, timeout=self.timeout)
|
47 |
+
|
48 |
+
def __iter__(self):
|
49 |
+
return self
|
50 |
+
|
51 |
+
def __next__(self):
|
52 |
+
value = self.audio_queue.get(timeout=self.timeout)
|
53 |
+
if not isinstance(value, np.ndarray) and value == self.stop_signal:
|
54 |
+
raise StopIteration()
|
55 |
+
return value
|
56 |
+
|
57 |
+
sampling_rate, frame_rate = model.audio_encoder.config.sampling_rate, model.audio_encoder.config.frame_rate
|
58 |
+
|
59 |
+
@spaces.GPU()
|
60 |
+
def generate_audio(text_prompt, audio_length_in_s=10.0, play_steps_in_s=2.0, seed=0):
|
61 |
+
max_new_tokens, play_steps = int(frame_rate * audio_length_in_s), int(frame_rate * play_steps_in_s)
|
62 |
+
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
63 |
+
if device != model.device:
|
64 |
+
model.to(device)
|
65 |
+
if device == "cuda:0":
|
66 |
+
model.half()
|
67 |
+
inputs = processor(text=text_prompt, padding=True, return_tensors="pt")
|
68 |
+
streamer = MusicgenStreamer(model, device=device, play_steps=play_steps)
|
69 |
+
generation_kwargs = dict(**inputs.to(device), streamer=streamer, max_new_tokens=max_new_tokens)
|
70 |
+
thread = Thread(target=model.generate, kwargs=generation_kwargs)
|
71 |
+
thread.start()
|
72 |
+
set_seed(seed)
|
73 |
+
for new_audio in streamer:
|
74 |
+
print(f"Sample of length: {round(new_audio.shape[0] / sampling_rate, 2)} seconds")
|
75 |
+
yield sampling_rate, new_audio
|
76 |
+
|
77 |
+
demo = gr.Interface(
|
78 |
+
fn=generate_audio,
|
79 |
+
inputs=[
|
80 |
+
gr.Text(label="Prompt", value="80s pop track with synth and instrumentals"),
|
81 |
+
gr.Slider(10, 30, value=15, step=5, label="Audio length in seconds"),
|
82 |
+
gr.Slider(0.5, 2.5, value=1.5, step=0.5, label="Streaming interval in seconds", info="Lower = shorter chunks, lower latency, more codec steps"),
|
83 |
+
gr.Slider(0, 10, value=5, step=1, label="Seed for random generations"),
|
84 |
+
],
|
85 |
+
outputs=[gr.Audio(label="Generated Music", streaming=True, autoplay=True)],
|
86 |
+
examples=[
|
87 |
+
["An 80s driving pop song with heavy drums and synth pads in the background", 30, 1.5, 5],
|
88 |
+
["A cheerful country song with acoustic guitars", 30, 1.5, 5],
|
89 |
+
["90s rock song with electric guitar and heavy drums", 30, 1.5, 5],
|
90 |
+
["a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions bpm: 130", 30, 1.5, 5],
|
91 |
+
["lofi slow bpm electro chill with organic samples", 30, 1.5, 5],
|
92 |
+
],
|
93 |
+
title=title,
|
94 |
+
cache_examples=False,
|
95 |
+
)
|
96 |
+
|
97 |
+
demo.queue().launch()
|
98 |
+
This compressed version maintains the core functionality while removing redundant comments and
|