Spaces:
Build error
Build error
Alexandre Défossez commited on
Improve demo (#51)
Browse files* allowing sharing directly, changelog, reduce volume.
* activate
* plop
Files changed (9)
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.
79 unmodified lines8081828384858679 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")```79 unmodified lines8081828384858679 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)```
12 unmodified lines1314151617181936 unmodified lines565758596061623 unmodified lines6667686970717256 unmodified lines12913013113213313413513613713813914014114214314414514614720 unmodified lines16816917017117217317432 unmodified lines20720820921012 unmodified linesfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_writeMODEL = None36 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_video3 unmodified linesgr.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/>56 unmodified linesgr.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.20 unmodified linesif share:launch_kwargs['share'] = shareinterface.launch(**launch_kwargs)if __name__ == "__main__":# torch.cuda.set_per_process_memory_fraction(0.48)32 unmodified linesserver_port=args.server_port,share=args.share,listen=args.listen)12 unmodified lines13141516171836 unmodified lines5556575859606162633 unmodified lines6768697071727356 unmodified lines13013113213313413513613713813914014114214314414514614714820 unmodified lines16917017117217317417517632 unmodified lines20921021121212 unmodified linesfrom audiocraft.models import MusicGenfrom audiocraft.data.audio import audio_writeMODEL = None36 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_video3 unmodified linesgr.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/>56 unmodified linesgr.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.20 unmodified linesif share:launch_kwargs['share'] = shareinterface.queue().launch(**launch_kwargs, max_threads=1)if __name__ == "__main__":# torch.cuda.set_per_process_memory_fraction(0.48)32 unmodified linesserver_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' and True: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
CHANGELOG.md+11-2
README.md+1-1
app.py+11-9
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