Spaces:
Build error
Build error
plop
Browse filesFiles changed (3)
- README.md+6-5
- app.py+25-10
- audiocraft/models/musicgen.py+6-2
37 unmodified lines383940414243444546474837 unmodified lines## UsageWe offer a number of way to interact with MusicGen:1. You can play with MusicGen by running the jupyter notebook at [`demo.ipynb`](./demo.ipynb) locally, or use the provided [colab notebook](https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing).2. You can use the gradio demo locally by running `python app.py`.3. A demo is also available on the [`facebook/MusicGen` HuggingFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).4. Finally, you can run the [Gradio demo with a Colab GPU](https://colab.research.google.com/drive/1-Xe9NCdIs2sCUbiSmwHXozK6AAhMm7_i?usp=sharing),as adapted from [@camenduru Colab](https://github.com/camenduru/MusicGen-colab).## API37 unmodified lines38394041424344454647484937 unmodified lines## UsageWe offer a number of way to interact with MusicGen:1. A demo is also available on the [`facebook/MusicGen` HuggingFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).2. You can run the extended demo on a Colab: [colab notebook](https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing).3. You can use the gradio demo locally by running `python app.py`.4. You can play with MusicGen by running the jupyter notebook at [`demo.ipynb`](./demo.ipynb) locally (if you have a GPU).5. Finally, checkout [@camenduru Colab page](https://github.com/camenduru/MusicGen-colab) which is regularlyupdated with contributions from @camenduru and the community.## API
3 unmodified lines45678912 unmodified lines22232425262728297 unmodified lines3738394041424344454612 unmodified lines59606162636465666716 unmodified lines8485868788899091929316 unmodified lines11011111211311411511611711817 unmodified lines13613713813914014148 unmodified lines19019119219319419519610 unmodified lines2072082092102112122133 unmodified lines# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.import argparsefrom concurrent.futures import ProcessPoolExecutorimport os12 unmodified linesMODEL = None # Last used modelIS_BATCHED = "facebook/MusicGen" in os.environ.get('SPACE_ID', '')MAX_BATCH_SIZE = 12BATCHED_DURATION = 15# We have to wrap subprocess call to clean a bit the log when using gr.make_waveform_old_call = sp.call7 unmodified linessp.call = _call_nostderr# Preallocating the pool of processes.pool = ProcessPoolExecutor(3)pool.__enter__()def make_waveform(*args, **kwargs):# Further remove some warnings.be = time.time()12 unmodified linesdef _do_predictions(texts, melodies, duration, **gen_kwargs):if duration > MODEL.lm.cfg.dataset.segment_duration:raise gr.Error("MusicGen currently supports durations of up to 30 seconds!")MODEL.set_generation_params(duration=duration, **gen_kwargs)print("new batch", len(texts), texts, [None if m is None else (m[0], m[1].shape) for m in melodies])be = time.time()16 unmodified linesdescriptions=texts,melody_wavs=processed_melodies,melody_sample_rate=target_sr,progress=False)else:outputs = MODEL.generate(texts, progress=False)outputs = outputs.detach().cpu().float()out_files = []16 unmodified linesreturn [res]def predict_full(model, text, melody, duration, topk, topp, temperature, cfg_coef):topk = int(topk)load_model(model)outs = _do_predictions([text], [melody], duration,17 unmodified linesmelody = gr.Audio(source="upload", type="numpy", label="Melody Condition (optional)", interactive=True)with gr.Row():submit = gr.Button("Submit")with gr.Row():model = gr.Radio(["melody", "medium", "small", "large"], label="Model", value="melody", interactive=True)with gr.Row():48 unmodified linesThis can take a long time, and the model might lose consistency. The model might alsodecide at arbitrary positions that the song ends.**WARNING:** Choosing long durations will take a long time to generate (2min might take ~10min).We present 4 model variations:1. Melody -- a music generation model capable of generating music condition on text and melody inputs. **Note**, you can also use text only.10 unmodified lines""")interface.queue().launch(**launch_kwargs, max_threads=1)def ui_batched(launch_kwargs):3 unmodified lines45678910111212 unmodified lines2526272829303132337 unmodified lines414243444546474849505152535412 unmodified lines67686970717216 unmodified lines8990919293949596979816 unmodified lines11511611711811912012112212312412512612712812913017 unmodified lines14814915015115215315415548 unmodified lines20420520620720820921021110 unmodified lines2222232242252262272283 unmodified lines# This source code is licensed under the license found in the# LICENSE file in the root directory of this source tree.# Updated to account for UI changes from https://github.com/rkfg/audiocraft/blob/long/app.py# also released under the MIT license.import argparsefrom concurrent.futures import ProcessPoolExecutorimport os12 unmodified linesMODEL = None # Last used modelIS_BATCHED = "facebook/MusicGen" in os.environ.get('SPACE_ID', '')MAX_BATCH_SIZE = 8BATCHED_DURATION = 15INTERRUPTING = False# We have to wrap subprocess call to clean a bit the log when using gr.make_waveform_old_call = sp.call7 unmodified linessp.call = _call_nostderr# Preallocating the pool of processes.pool = ProcessPoolExecutor(4)pool.__enter__()def interrupt():global INTERRUPTINGINTERRUPTING = Truedef make_waveform(*args, **kwargs):# Further remove some warnings.be = time.time()12 unmodified linesdef _do_predictions(texts, melodies, duration, **gen_kwargs):MODEL.set_generation_params(duration=duration, **gen_kwargs)print("new batch", len(texts), texts, [None if m is None else (m[0], m[1].shape) for m in melodies])be = time.time()16 unmodified linesdescriptions=texts,melody_wavs=processed_melodies,melody_sample_rate=target_sr,progress=True)else:outputs = MODEL.generate(texts, progress=True)outputs = outputs.detach().cpu().float()out_files = []16 unmodified linesreturn [res]def predict_full(model, text, melody, duration, topk, topp, temperature, cfg_coef, progress=gr.Progress()):global INTERRUPTINGINTERRUPTING = Falsetopk = int(topk)load_model(model)def _progress(generated, to_generate):progress((generated, to_generate))if INTERRUPTING:raise gr.Error("Interrupted.")MODEL.set_custom_progress_callback(_progress)outs = _do_predictions([text], [melody], duration,17 unmodified linesmelody = gr.Audio(source="upload", type="numpy", label="Melody Condition (optional)", interactive=True)with gr.Row():submit = gr.Button("Submit")# Adapted from https://github.com/rkfg/audiocraft/blob/long/app.py, MIT license._ = gr.Button("Interrupt").click(fn=interrupt, queue=False)with gr.Row():model = gr.Radio(["melody", "medium", "small", "large"], label="Model", value="melody", interactive=True)with gr.Row():48 unmodified linesThis can take a long time, and the model might lose consistency. The model might alsodecide at arbitrary positions that the song ends.**WARNING:** Choosing long durations will take a long time to generate (2min might take ~10min). An overlap of 12 secondsis kept with the previously generated chunk, and 18 "new" seconds are generated each time.We present 4 model variations:1. Melody -- a music generation model capable of generating music condition on text and melody inputs. **Note**, you can also use text only.10 unmodified lines""")interface.queue().launch(**launch_kwargs)def ui_batched(launch_kwargs):
98 unmodified lines9910010110210310410523 unmodified lines129130131132133134145 unmodified lines28028128228328428528628728837 unmodified lines32632732832933033198 unmodified linesdef set_generation_params(self, use_sampling: bool = True, top_k: int = 250,top_p: float = 0.0, temperature: float = 1.0,duration: float = 30.0, cfg_coef: float = 3.0,two_step_cfg: bool = False, extend_stride: float = 15):"""Set the generation parameters for MusicGen.Args:23 unmodified lines}def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):self._progress_callback = progress_callbackdef generate_unconditional(self, num_samples: int, progress: bool = False) -> torch.Tensor:145 unmodified linesdef _progress_callback(generated_tokens: int, tokens_to_generate: int):generated_tokens += current_gen_offsetif self._progress_callback is not None:self._progress_callback(generated_tokens, total_gen_len)else:print(f'{current_gen_offset + generated_tokens: 6d} / {total_gen_len: 6d}', end='\r')if prompt_tokens is not None:assert max_prompt_len >= prompt_tokens.shape[-1], \37 unmodified lines# we wouldn't have the full wav.initial_position = int(time_offset * self.sample_rate)wav_target_length = int(self.max_duration * self.sample_rate)positions = torch.arange(initial_position,initial_position + wav_target_length, device=self.device)attr.wav['self_wav'] = WavCondition(98 unmodified lines9910010110210310410523 unmodified lines129130131132133134135145 unmodified lines28128228328428528628728828929029137 unmodified lines32933033133233333433598 unmodified linesdef set_generation_params(self, use_sampling: bool = True, top_k: int = 250,top_p: float = 0.0, temperature: float = 1.0,duration: float = 30.0, cfg_coef: float = 3.0,two_step_cfg: bool = False, extend_stride: float = 18):"""Set the generation parameters for MusicGen.Args:23 unmodified lines}def set_custom_progress_callback(self, progress_callback: tp.Optional[tp.Callable[[int, int], None]] = None):"""Override the default progress callback."""self._progress_callback = progress_callbackdef generate_unconditional(self, num_samples: int, progress: bool = False) -> torch.Tensor:145 unmodified linesdef _progress_callback(generated_tokens: int, tokens_to_generate: int):generated_tokens += current_gen_offsetif self._progress_callback is not None:# Note that total_gen_len might be quite wrong depending on the# codebook pattern used, but with delay it is almost accurate.self._progress_callback(generated_tokens, total_gen_len)else:print(f'{generated_tokens: 6d} / {total_gen_len: 6d}', end='\r')if prompt_tokens is not None:assert max_prompt_len >= prompt_tokens.shape[-1], \37 unmodified lines# we wouldn't have the full wav.initial_position = int(time_offset * self.sample_rate)wav_target_length = int(self.max_duration * self.sample_rate)print(initial_position / self.sample_rate, wav_target_length / self.sample_rate)positions = torch.arange(initial_position,initial_position + wav_target_length, device=self.device)attr.wav['self_wav'] = WavCondition(
README.md+6-5
app.py+25-10
audiocraft/models/musicgen.py+6-2