from audiocraft.models import MusicGen import streamlit as st import torch import torchaudio import io import base64 @st.cache_resource def load_model(): model = MusicGen.get_pretrained('facebook/musicgen-small') return model def generate_music_tensors(description, duration: int): st.write(f"Generating music for: '{description}' (Duration: {duration}s)") model = load_model() model.set_generation_params(use_sampling=True, top_k=250, duration=duration) output = model.generate(descriptions=[description], progress=True) return output[0] def create_audio_buffer(samples: torch.Tensor): """Generate an in-memory audio buffer.""" sample_rate = 32000 samples = samples.detach().cpu() if samples.dim() == 2: samples = samples[None, ...] # Create an in-memory buffer to store the audio buffer = io.BytesIO() torchaudio.save(buffer, samples[0], sample_rate, format="wav") buffer.seek(0) return buffer def generate_download_link(buffer, file_label="Download Music"): """Create a download link for the generated audio.""" data = buffer.read() b64 = base64.b64encode(data).decode() href = f'{file_label}' return href # Apply CSS for improved UI styling st.markdown( """ """, unsafe_allow_html=True ) # Set Streamlit page configuration def main(): st.markdown('

Theaimart: Music Generator 🎵

', unsafe_allow_html=True) st.write("Generate music based on your text input using Meta's Audiocraft library!") description = st.text_area("Enter a description:") duration = st.slider("Select duration (seconds)", 1, 20, 10) if description and duration: music_tensors = generate_music_tensors(description, duration) audio_buffer = create_audio_buffer(music_tensors) st.audio(audio_buffer, format="audio/wav") st.markdown(generate_download_link(audio_buffer), unsafe_allow_html=True) # Add footer message st.markdown('', unsafe_allow_html=True) if __name__ == "__main__": main()