File size: 2,269 Bytes
123dfcc
 
b112484
123dfcc
 
 
 
04c82a5
123dfcc
 
 
4611685
123dfcc
 
 
7b2527c
123dfcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import gradio as gr
import requests
# from IPython.display import Audio
import tempfile
import os

def generate_music(prompt, duration=10):
    API_URL = "https://api-inference.huggingface.co/models/facebook/musicgen-small"
    headers = {"Authorization": f"Bearer {os.getenv('HF_API_KEY')}"}
    
    payload = {
        "inputs": prompt
    }
    
    try:
        response = requests.post(API_URL, headers=headers, json=payload, timeout=300)
        if response.status_code != 200:
            return None, f"Error: API returned status code {response.status_code}"
            
        # Save the audio bytes to a temporary file
        with tempfile.NamedTemporaryFile(delete=False, suffix='.wav') as tmp_file:
            tmp_file.write(response.content)
            tmp_file_path = tmp_file.name
            
        return tmp_file_path, "Music generated successfully!"
    except Exception as e:
        return None, f"Error: {str(e)}"

# Create the Gradio interface
def gradio_interface(prompt, duration=10):
    audio_path, message = generate_music(prompt, duration)
    if audio_path:
        return audio_path, message
    else:
        raise gr.Error(message)

# Create the Gradio app
with gr.Blocks() as demo:
    gr.Markdown("""
    # MusicGen Audio Generator
    Generate music from text descriptions using Meta's MusicGen model.
    """)
    
    with gr.Row():
        with gr.Column():
            prompt_input = gr.Textbox(
                label="Enter your music description",
                placeholder="e.g., liquid drum and bass, atmospheric synths, airy sounds",
                lines=3
            )
            duration_slider = gr.Slider(
                minimum=5,
                maximum=30,
                value=10,
                step=5,
                label="Duration (seconds)"
            )
            generate_button = gr.Button("Generate Music")
        
        with gr.Column():
            audio_output = gr.Audio(label="Generated Music")
            message_output = gr.Textbox(label="Status")
    
    generate_button.click(
        fn=gradio_interface,
        inputs=[prompt_input, duration_slider],
        outputs=[audio_output, message_output]
    )

# Launch the app
if __name__ == "__main__":
    demo.launch()