Spaces:
Runtime error
Runtime error
Merge branch 'main' into our_hf2
Browse filesFiles changed (11)
3 unmodified lines4567893 unmodified linesThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).## [0.0.1a] - TBDInitial release, with model evaluation only.3 unmodified lines4567891011121314151617183 unmodified linesThe format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/).## [0.0.2a] - TBDImproved demo, fixed top p (thanks @jnordberg).Compressor tanh on output to avoid clipping with some style (especially piano).Now repeating the conditioning periodically if it is too short.More options when launching Gradio app locally (thanks @ashleykleynhans).## [0.0.1] - 2023-06-09Initial release, with model evaluation only.
51 unmodified lines525354555657583 unmodified lines6263646566676851 unmodified lines## Training datasetsThe model was trained using the following sources: the [Meta Music Initiative Sound Collection](https://www.fb.com/sound), [Shutterstock music collection](https://www.shutterstock.com/music) and the [Pond5 music collection](https://www.pond5.com/). See the paper for more details about the training set and corresponding preprocessing.## Quantitative analysis3 unmodified lines**Data:** The data sources used to train the model are created by music professionals and covered by legal agreements with the right holders. The model is trained on 20K hours of data, we believe that scaling the model on larger datasets can further improve the performance of the model.**Mitigations:** All vocals have been removed from the data source using a state-of-the-art music source separation method, namely using the open source [Hybrid Transformer for Music Source Separation](https://github.com/facebookresearch/demucs) (HT-Demucs). The model is therefore not able to produce vocals.**Limitations:**51 unmodified lines525354555657583 unmodified lines6263646566676851 unmodified lines## Training datasetsThe model was trained on licensed data using the following sources: the [Meta Music Initiative Sound Collection](https://www.fb.com/sound), [Shutterstock music collection](https://www.shutterstock.com/music) and the [Pond5 music collection](https://www.pond5.com/). See the paper for more details about the training set and corresponding preprocessing.## Quantitative analysis3 unmodified lines**Data:** The data sources used to train the model are created by music professionals and covered by legal agreements with the right holders. The model is trained on 20K hours of data, we believe that scaling the model on larger datasets can further improve the performance of the model.**Mitigations:** Vocals have been removed from the data source using corresponding tags, and then using using a state-of-the-art music source separation method, namely using the open source [Hybrid Transformer for Music Source Separation](https://github.com/facebookresearch/demucs) (HT-Demucs).**Limitations:**
23 unmodified lines2425262728293031323334351 unmodified line3738394041428 unmodified lines5152535455565710 unmodified lines6869707172737415 unmodified lines909192939495968 unmodified lines10510610710810911023 unmodified lines## MusicGenAudiocraft provides the code and models for MusicGen, [a simple and controllable model for music generation][arxiv]. MusicGen is a single stage auto-regressiveTransformer model trained over a 32kHz <a href="https://github.com/facebookresearch/encodec">EnCodec tokenizer</a> with 4 codebooks sampled at 50 Hz. Unlike existing methods like [MusicLM](https://arxiv.org/abs/2301.11325), MusicGen doesn't not require a self-supervised semantic representation, and it generatesall 4 codebooks in one pass. By introducing a small delay between the codebooks, we show we can predictthem in parallel, thus having only 50 auto-regressive steps per second of audio.Check out our [sample page][musicgen_samples] or test the available demo!<a target="_blank" href="https://colab.research.google.com/drive/1fxGqfg96RBUvGxZ1XXN07s3DthrKUl4-?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a><a target="_blank" href="https://huggingface.co/spaces/facebook/MusicGen">1 unmodified line</a><br>## InstallationAudiocraft requires Python 3.9, PyTorch 2.0.0, and a GPU with at least 16 GB of memory (for the medium-sized model). To install Audiocraft, you can run the following:8 unmodified lines```## UsageYou 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). Finally, a demo is also available on the [`facebook/MusiGen` HugginFace Space](https://huggingface.co/spaces/facebook/MusicGen) (huge thanks to all the HF team for their support).## API10 unmodified lines**Note**: Please make sure to have [ffmpeg](https://ffmpeg.org/download.html) installed when using newer version of `torchaudio`.You can install it with:```apt get install ffmpeg```See after a quick example for using the API.15 unmodified linesfor idx, one_wav in enumerate(wav):# Will save under {idx}.wav, with loudness normalization at -14 db LUFS.audio_write(f'{idx}', one_wav.cpu(), model.sample_rate, strategy="loudness")```8 unmodified linesYes. We will soon release the training code for MusicGen and EnCodec.## Citation```@article{copet2023simple,23 unmodified lines2425262728293031323334351 unmodified line37383940414243448 unmodified lines53545556575859606162636410 unmodified lines7576777879808115 unmodified lines9798991001011021038 unmodified lines11211311411511611711811912012112223 unmodified lines## MusicGenAudiocraft provides the code and models for MusicGen, [a simple and controllable model for music generation][arxiv]. MusicGen is a single stage auto-regressiveTransformer model trained over a 32kHz <a href="https://github.com/facebookresearch/encodec">EnCodec tokenizer</a> with 4 codebooks sampled at 50 Hz. Unlike existing methods like [MusicLM](https://arxiv.org/abs/2301.11325), MusicGen doesn't require a self-supervised semantic representation, and it generatesall 4 codebooks in one pass. By introducing a small delay between the codebooks, we show we can predictthem in parallel, thus having only 50 auto-regressive steps per second of audio.Check out our [sample page][musicgen_samples] or test the available demo!<a target="_blank" href="https://colab.research.google.com/drive/1-Xe9NCdIs2sCUbiSmwHXozK6AAhMm7_i?usp=sharing"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"/></a><a target="_blank" href="https://huggingface.co/spaces/facebook/MusicGen">1 unmodified line</a><br>We use 20K hours of licensed music to train MusicGen. Specifically, we rely on an internal dataset of 10K high-quality music tracks, and on the ShutterStock and Pond5 music data.## InstallationAudiocraft requires Python 3.9, PyTorch 2.0.0, and a GPU with at least 16 GB of memory (for the medium-sized model). To install Audiocraft, you can run the following:8 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).## API10 unmodified lines**Note**: Please make sure to have [ffmpeg](https://ffmpeg.org/download.html) installed when using newer version of `torchaudio`.You can install it with:```apt-get install ffmpeg```See after a quick example for using the API.15 unmodified linesfor idx, one_wav in enumerate(wav):# Will save under {idx}.wav, with loudness normalization at -14 db LUFS.audio_write(f'{idx}', one_wav.cpu(), model.sample_rate, strategy="loudness", loudness_compressor=True)```8 unmodified linesYes. We will soon release the training code for MusicGen and EnCodec.#### I need help on Windows@FurkanGozukara made a complete tutorial for [Audiocraft/MusicGen on Windows](https://youtu.be/v-YpvPkhdO4)## Citation```@article{copet2023simple,
6 unmodified lines789101112131415161718192035 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491506 unmodified lines"""from tempfile import NamedTemporaryFileimport torchimport gradio as grfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_writeMODEL = Nonedef load_model(version):35 unmodified linesoutput = output.detach().cpu().float()[0]with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:audio_write(file.name, output, MODEL.sample_rate, strategy="loudness", add_suffix=False)waveform_video = gr.make_waveform(file.name)return waveform_videowith gr.Blocks() as demo:gr.Markdown("""# MusicGenThis is the demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generationpresented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284).<br/><a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank"><img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>for longer sequences, more control and no queue.</p>""")with gr.Row():with gr.Column():with gr.Row():text = gr.Text(label="Input Text", interactive=True)melody = 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():duration = gr.Slider(minimum=1, maximum=30, value=10, label="Duration", interactive=True)with gr.Row():topk = gr.Number(label="Top-k", value=250, interactive=True)topp = gr.Number(label="Top-p", value=0, interactive=True)temperature = gr.Number(label="Temperature", value=1.0, interactive=True)cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)with gr.Column():output = gr.Video(label="Generated Music")submit.click(predict, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])gr.Examples(fn=predict,examples=[["An 80s driving pop song with heavy drums and synth pads in the background","./assets/bach.mp3","melody"],["A cheerful country song with acoustic guitars","./assets/bolero_ravel.mp3","melody"],["90s rock song with electric guitar and heavy drums",None,"medium"],["a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions","./assets/bach.mp3","melody"],["lofi slow bpm electro chill with organic samples",None,"medium",],],inputs=[text, melody, model],outputs=[output])gr.Markdown("""### More detailsThe model will generate a short music extract based on the description you provided.You can generate up to 30 seconds of audio.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.2. Small -- a 300M transformer decoder conditioned on text only.3. Medium -- a 1.5B transformer decoder conditioned on text only.4. Large -- a 3.3B transformer decoder conditioned on text only (might OOM for the longest sequences.)When using `melody`, ou can optionaly provide a reference audio fromwhich a broad melody will be extracted. The model will then try to follow both the description and melody provided.You can also use your own GPU or a Google Colab by following the instructions on our repo.See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)for more details.""")demo.launch()6 unmodified lines78910111213141516171819202135 unmodified lines575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152166 unmodified lines"""from tempfile import NamedTemporaryFileimport argparseimport torchimport gradio as grimport osfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_writeMODEL = NoneIS_SHARED_SPACE = "musicgen/MusicGen" in os.environ['SPACE_ID']def load_model(version):35 unmodified linesoutput = output.detach().cpu().float()[0]with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:audio_write(file.name, output, MODEL.sample_rate, strategy="loudness",loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)waveform_video = gr.make_waveform(file.name)return waveform_videodef ui(**kwargs):with gr.Blocks() as interface:gr.Markdown("""# MusicGenThis is your private demo for [MusicGen](https://github.com/facebookresearch/audiocraft), a simple and controllable model for music generationpresented at: ["Simple and Controllable Music Generation"](https://huggingface.co/papers/2306.05284)""")if IS_SHARED_SPACE:gr.Markdown("""⚠ This Space doesn't work in this shared UI ⚠<a href="https://huggingface.co/spaces/musicgen/MusicGen?duplicate=true" style="display: inline-block;margin-top: .5em;margin-right: .25em;" target="_blank"><img style="margin-bottom: 0em;display: inline;margin-top: -.25em;" src="https://bit.ly/3gLdBN6" alt="Duplicate Space"></a>to use it privately, or use the <a href="https://huggingface.co/spaces/facebook/MusicGen">public demo</a>""")with gr.Row():with gr.Column():with gr.Row():text = gr.Text(label="Input Text", interactive=True)melody = 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():duration = gr.Slider(minimum=1, maximum=30, value=10, label="Duration", interactive=True)with gr.Row():topk = gr.Number(label="Top-k", value=250, interactive=True)topp = gr.Number(label="Top-p", value=0, interactive=True)temperature = gr.Number(label="Temperature", value=1.0, interactive=True)cfg_coef = gr.Number(label="Classifier Free Guidance", value=3.0, interactive=True)with gr.Column():output = gr.Video(label="Generated Music")submit.click(predict, inputs=[model, text, melody, duration, topk, topp, temperature, cfg_coef], outputs=[output])gr.Examples(fn=predict,examples=[["An 80s driving pop song with heavy drums and synth pads in the background","./assets/bach.mp3","melody"],["A cheerful country song with acoustic guitars","./assets/bolero_ravel.mp3","melody"],["90s rock song with electric guitar and heavy drums",None,"medium"],["a light and cheerly EDM track, with syncopated drums, aery pads, and strong emotions","./assets/bach.mp3","melody"],["lofi slow bpm electro chill with organic samples",None,"medium",],],inputs=[text, melody, model],outputs=[output])gr.Markdown("""### More detailsThe model will generate a short music extract based on the description you provided.You can generate up to 30 seconds of audio.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.2. Small -- a 300M transformer decoder conditioned on text only.3. Medium -- a 1.5B transformer decoder conditioned on text only.4. Large -- a 3.3B transformer decoder conditioned on text only (might OOM for the longest sequences.)When using `melody`, ou can optionaly provide a reference audio fromwhich a broad melody will be extracted. The model will then try to follow both the description and melody provided.You can also use your own GPU or a Google Colab by following the instructions on our repo.See [github.com/facebookresearch/audiocraft](https://github.com/facebookresearch/audiocraft)for more details.""")# Show the interfacelaunch_kwargs = {}username = kwargs.get('username')password = kwargs.get('password')server_port = kwargs.get('server_port', 0)inbrowser = kwargs.get('inbrowser', False)share = kwargs.get('share', False)server_name = kwargs.get('listen')launch_kwargs['server_name'] = server_nameif username and password:launch_kwargs['auth'] = (username, password)if server_port > 0:launch_kwargs['server_port'] = server_portif inbrowser:launch_kwargs['inbrowser'] = inbrowserif share:launch_kwargs['share'] = shareinterface.queue().launch(**launch_kwargs, max_threads=1)if __name__ == "__main__":parser = argparse.ArgumentParser()parser.add_argument('--listen',type=str,default='127.0.0.1',help='IP to listen on for connections to Gradio',)parser.add_argument('--username', type=str, default='', help='Username for authentication')parser.add_argument('--password', type=str, default='', help='Password for authentication')parser.add_argument('--server_port',type=int,default=0,help='Port to run the server listener on',)parser.add_argument('--inbrowser', action='store_true', help='Open in browser')parser.add_argument('--share', action='store_true', help='Share the gradio UI')args = parser.parse_args()ui(username=args.username,password=args.password,inbrowser=args.inbrowser,server_port=args.server_port,share=args.share,listen=args.listen)
56 unmodified lines5758596061626356 unmodified linesout_files = []for output in outputs:with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:audio_write(file.name, output, MODEL.sample_rate, strategy="loudness", add_suffix=False)waveform_video = gr.make_waveform(file.name)out_files.append(waveform_video)return [out_files]56 unmodified lines57585960616263646556 unmodified linesout_files = []for output in outputs:with NamedTemporaryFile("wb", suffix=".wav", delete=False) as file:audio_write(file.name, output, MODEL.sample_rate, strategy="loudness",loudness_headroom_db=16, loudness_compressor=True, add_suffix=False)waveform_video = gr.make_waveform(file.name)out_files.append(waveform_video)return [out_files]
6 unmodified lines789106 unmodified lines# flake8: noqafrom . import data, modules, models__version__ = '0.0.1'6 unmodified lines789106 unmodified lines# flake8: noqafrom . import data, modules, models__version__ = '0.0.2a1'
154 unmodified lines15515615715815916012 unmodified lines173174175176177178179154 unmodified linesformat: str = 'wav', mp3_rate: int = 320, normalize: bool = True,strategy: str = 'peak', peak_clip_headroom_db: float = 1,rms_headroom_db: float = 18, loudness_headroom_db: float = 14,log_clipping: bool = True, make_parent_dir: bool = True,add_suffix: bool = True) -> Path:"""Convenience function for saving audio to disk. Returns the filename the audio was written to.12 unmodified linesrms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much largerthan the `peak_clip` one to avoid further clipping.loudness_headroom_db (float): Target loudness for loudness normalization.log_clipping (bool): If True, basic logging on stderr when clipping stilloccurs despite strategy (only for 'rms').make_parent_dir (bool): Make parent directory if it doesn't exist.Returns:154 unmodified lines15515615715815916016112 unmodified lines174175176177178179180181154 unmodified linesformat: str = 'wav', mp3_rate: int = 320, normalize: bool = True,strategy: str = 'peak', peak_clip_headroom_db: float = 1,rms_headroom_db: float = 18, loudness_headroom_db: float = 14,loudness_compressor: bool = False,log_clipping: bool = True, make_parent_dir: bool = True,add_suffix: bool = True) -> Path:"""Convenience function for saving audio to disk. Returns the filename the audio was written to.12 unmodified linesrms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much largerthan the `peak_clip` one to avoid further clipping.loudness_headroom_db (float): Target loudness for loudness normalization.loudness_compressor (bool): Uses tanh for soft clipping when strategy is 'loudness'.when strategy is 'loudness'log_clipping (bool): If True, basic logging on stderr when clipping stilloccurs despite strategy (only for 'rms').make_parent_dir (bool): Make parent directory if it doesn't exist.Returns:
53 unmodified lines54555657585960611 unmodified line6364656667687 unmodified lines76777879808111 unmodified lines939495969798999 unmodified lines10911011111211311417 unmodified lines13213313413513613713853 unmodified linesreturn wavdef normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 12,energy_floor: float = 2e-3):"""Normalize an input signal to a user loudness in dB LKFS.Audio loudness is defined according to the ITU-R BS.1770-4 recommendation.1 unmodified linewav (torch.Tensor): Input multichannel audio data.sample_rate (int): Sample rate.loudness_headroom_db (float): Target loudness of the output in dB LUFS.energy_floor (float): anything below that RMS level will not be rescaled.Returns:output (torch.Tensor): Loudness normalized output data.7 unmodified linesdelta_loudness = -loudness_headroom_db - input_loudness_dbgain = 10.0 ** (delta_loudness / 20.0)output = gain * wavassert output.isfinite().all(), (input_loudness_db, wav.pow(2).mean().sqrt())return output11 unmodified linesdef normalize_audio(wav: torch.Tensor, normalize: bool = True,strategy: str = 'peak', peak_clip_headroom_db: float = 1,rms_headroom_db: float = 18, loudness_headroom_db: float = 14,log_clipping: bool = False, sample_rate: tp.Optional[int] = None,stem_name: tp.Optional[str] = None) -> torch.Tensor:"""Normalize the audio according to the prescribed strategy (see after).9 unmodified linesrms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much largerthan the `peak_clip` one to avoid further clipping.loudness_headroom_db (float): Target loudness for loudness normalization.log_clipping (bool): If True, basic logging on stderr when clipping stilloccurs despite strategy (only for 'rms').sample_rate (int): Sample rate for the audio data (required for loudness).17 unmodified lines_clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name)elif strategy == 'loudness':assert sample_rate is not None, "Loudness normalization requires sample rate."wav = normalize_loudness(wav, sample_rate, loudness_headroom_db)_clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name)else:assert wav.abs().max() < 153 unmodified lines54555657585960611 unmodified line636465666768697 unmodified lines777879808182838411 unmodified lines969798991001011021039 unmodified lines11311411511611711811917 unmodified lines13713813914014114214353 unmodified linesreturn wavdef normalize_loudness(wav: torch.Tensor, sample_rate: int, loudness_headroom_db: float = 14,loudness_compressor: bool = False, energy_floor: float = 2e-3):"""Normalize an input signal to a user loudness in dB LKFS.Audio loudness is defined according to the ITU-R BS.1770-4 recommendation.1 unmodified linewav (torch.Tensor): Input multichannel audio data.sample_rate (int): Sample rate.loudness_headroom_db (float): Target loudness of the output in dB LUFS.loudness_compressor (bool): Uses tanh for soft clipping.energy_floor (float): anything below that RMS level will not be rescaled.Returns:output (torch.Tensor): Loudness normalized output data.7 unmodified linesdelta_loudness = -loudness_headroom_db - input_loudness_dbgain = 10.0 ** (delta_loudness / 20.0)output = gain * wavif loudness_compressor:output = torch.tanh(output)assert output.isfinite().all(), (input_loudness_db, wav.pow(2).mean().sqrt())return output11 unmodified linesdef normalize_audio(wav: torch.Tensor, normalize: bool = True,strategy: str = 'peak', peak_clip_headroom_db: float = 1,rms_headroom_db: float = 18, loudness_headroom_db: float = 14,loudness_compressor: bool = False, log_clipping: bool = False,sample_rate: tp.Optional[int] = None,stem_name: tp.Optional[str] = None) -> torch.Tensor:"""Normalize the audio according to the prescribed strategy (see after).9 unmodified linesrms_headroom_db (float): Headroom in dB when doing 'rms' strategy. This must be much largerthan the `peak_clip` one to avoid further clipping.loudness_headroom_db (float): Target loudness for loudness normalization.loudness_compressor (bool): If True, uses tanh based soft clipping.log_clipping (bool): If True, basic logging on stderr when clipping stilloccurs despite strategy (only for 'rms').sample_rate (int): Sample rate for the audio data (required for loudness).17 unmodified lines_clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name)elif strategy == 'loudness':assert sample_rate is not None, "Loudness normalization requires sample rate."wav = normalize_loudness(wav, sample_rate, loudness_headroom_db, loudness_compressor)_clip_wav(wav, log_clipping=log_clipping, stem_name=stem_name)else:assert wav.abs().max() < 1
87 unmodified lines88899091929387 unmodified linescache_dir = os.environ.get('MUSICGEN_ROOT', None)compression_model = load_compression_model(name, device=device, cache_dir=cache_dir)lm = load_lm_model(name, device=device, cache_dir=cache_dir)return MusicGen(name, compression_model, lm)87 unmodified lines888990919293949587 unmodified linescache_dir = os.environ.get('MUSICGEN_ROOT', None)compression_model = load_compression_model(name, device=device, cache_dir=cache_dir)lm = load_lm_model(name, device=device, cache_dir=cache_dir)if name == 'melody':lm.condition_provider.conditioners['self_wav'].match_len_on_eval = Truereturn MusicGen(name, compression_model, lm)
8 unmodified lines91011121314469 unmodified lines48448548648748848949044 unmodified lines5355365375385395405418 unmodified linesfrom dataclasses import dataclass, fieldfrom itertools import chainimport loggingimport randomimport reimport typing as tp469 unmodified lines**kwargs: Additional parameters for the chroma extractor."""def __init__(self, output_dim: int, sample_rate: int, n_chroma: int, radix2_exp: int,duration: float, match_len_on_eval: bool = False, eval_wavs: tp.Optional[str] = None,n_eval_wavs: int = 0, device: tp.Union[torch.device, str] = "cpu", **kwargs):from demucs import pretrainedsuper().__init__(dim=n_chroma, output_dim=output_dim, device=device)44 unmodified lineschroma = chroma[:, :self.chroma_len]logger.debug(f'chroma was truncated! ({t} -> {chroma.shape[1]})')elif t < self.chroma_len:chroma = F.pad(chroma, (0, 0, 0, self.chroma_len - t))logger.debug(f'chroma was zero-padded! ({t} -> {chroma.shape[1]})')return chroma8 unmodified lines9101112131415469 unmodified lines48548648748848949049144 unmodified lines5365375385395405415425435445458 unmodified linesfrom dataclasses import dataclass, fieldfrom itertools import chainimport loggingimport mathimport randomimport reimport typing as tp469 unmodified lines**kwargs: Additional parameters for the chroma extractor."""def __init__(self, output_dim: int, sample_rate: int, n_chroma: int, radix2_exp: int,duration: float, match_len_on_eval: bool = True, eval_wavs: tp.Optional[str] = None,n_eval_wavs: int = 0, device: tp.Union[torch.device, str] = "cpu", **kwargs):from demucs import pretrainedsuper().__init__(dim=n_chroma, output_dim=output_dim, device=device)44 unmodified lineschroma = chroma[:, :self.chroma_len]logger.debug(f'chroma was truncated! ({t} -> {chroma.shape[1]})')elif t < self.chroma_len:# chroma = F.pad(chroma, (0, 0, 0, self.chroma_len - t))n_repeat = int(math.ceil(self.chroma_len / t))chroma = chroma.repeat(1, n_repeat, 1)chroma = chroma[:, :self.chroma_len]logger.debug(f'chroma was zero-padded! ({t} -> {chroma.shape[1]})')return chroma
16 unmodified lines17181916 unmodified linesxformersdemucslibrosa16 unmodified lines1718192016 unmodified linesxformersdemucslibrosagradio
CHANGELOG.md+11-2
MODEL_CARD.md+2-2
README.md+17-5
app.py+151-85
app_batched.py+3-1
audiocraft/__init__.py+1-1
audiocraft/data/audio.py+3-1
audiocraft/data/audio_utils.py+9-4
audiocraft/models/musicgen.py+2
audiocraft/modules/conditioners.py+6-2
requirements.txt+1