Sure! Let's create a Gradio app step by step that uses the provided API to generate a song based on a user prompt and allows the user to play the generated track.
Step 1: Understand the API
We'll use the /api/generate endpoint from the API documentation you provided. This endpoint generates music based on a prompt. By setting wait_audio to true, the API will wait until the audio is generated (maximum of 100 seconds) and return the audio link directly, simplifying our process.
Step 2: Set Up the Environment
First, ensure you have Python installed on your system. Then, install the necessary libraries:
pip install gradio requests
Step 3: Import Necessary Libraries
We'll need the following libraries:
requests for making HTTP requests to the API.
gradio for creating the web interface.
tempfile for handling temporary files.
import requests
import gradio as gr
import tempfile
Step 4: Define the Function to Generate the Song
We'll create a function that:
- Takes the user's prompt as input.
- Sends a POST request to the
/api/generate endpoint with wait_audio set to true.
- Receives the response and extracts the
audio_url.
- Downloads the audio file from the
audio_url.
- Saves the audio to a temporary file.
- Returns the path to the temporary audio file for playback.
API_URL = 'https://suno-api-ivory-chi.vercel.app/api/generate'
def generate_song(prompt):
payload = {
'prompt': prompt,
'make_instrumental': False,
'model': 'chirp-v3-5', # You can also use 'chirp-v3-0' if desired
'wait_audio': True
}
headers = {'Content-Type': 'application/json'}
# Send POST request to the API
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
data = response.json()
# Check if data is a list and has content
if data and isinstance(data, list):
song_info = data[0] # The first element contains our song info
first_song = song_info.get('0') # Accessing the song data
if first_song:
audio_url = first_song.get('audio_url')
if audio_url:
# Download the audio file from the audio_url
audio_response = requests.get(audio_url)
if audio_response.status_code == 200:
# Save the audio content to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
temp_file.write(audio_response.content)
temp_file.close()
# Return the path to the temporary audio file
return temp_file.name
else:
return "Error fetching audio from audio_url."
else:
return "No audio_url found in the response."
else:
return "Song information not found in the response."
else:
return "Invalid response data."
else:
return f"Error generating song. Status code: {response.status_code} - {response.text}"
Step 5: Create the Gradio Interface
Now, we'll define the Gradio app interface. We'll set up:
- An input textbox for the user to enter the song prompt.
- An audio output component to play the generated track.
iface = gr.Interface(
fn=generate_song,
inputs=gr.Textbox(lines=2, placeholder="Enter song prompt here..."),
outputs=gr.Audio(type='filepath'),
title="AI Song Generator",
description="Enter a prompt to generate a song using the Suno API."
)
Step 6: Launch the App
Finally, we'll launch the Gradio app so that it runs locally and provides a web interface.
iface.launch()
Step 7: Full Code Implementation
Putting it all together, here's the complete script:
import requests
import gradio as gr
import tempfile
API_URL = 'https://suno-api-ivory-chi.vercel.app/api/generate'
def generate_song(prompt):
payload = {
'prompt': prompt,
'make_instrumental': False,
'model': 'chirp-v3-5', # You can use 'chirp-v3-0' as an alternative
'wait_audio': True
}
headers = {'Content-Type': 'application/json'}
# Send POST request to the API
response = requests.post(API_URL, json=payload, headers=headers)
if response.status_code == 200:
data = response.json()
# Check if data is a list and has content
if data and isinstance(data, list):
song_info = data[0] # The first element contains our song info
first_song = song_info.get('0') # Accessing the song data
if first_song:
audio_url = first_song.get('audio_url')
if audio_url:
# Download the audio file from the audio_url
audio_response = requests.get(audio_url)
if audio_response.status_code == 200:
# Save the audio content to a temporary file
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
temp_file.write(audio_response.content)
temp_file.close()
# Return the path to the temporary audio file
return temp_file.name
else:
return "Error fetching audio from audio_url."
else:
return "No audio_url found in the response."
else:
return "Song information not found in the response."
else:
return "Invalid response data."
else:
return f"Error generating song. Status code: {response.status_code} - {response.text}"
iface = gr.Interface(
fn=generate_song,
inputs=gr.Textbox(lines=2, placeholder="Enter song prompt here..."),
outputs=gr.Audio(type='filepath'),
title="AI Song Generator",
description="Enter a prompt to generate a song using the Suno API."
)
iface.launch()
Step 8: Run the App
Save your script with a filename like song_generator.py, and then run it from your terminal or command prompt:
python song_generator.py
This will launch the Gradio app and provide you with a local URL (e.g., http://127.0.0.1:7860/) to access it in your web browser.
Step 9: Test the App
In your browser:
- Open the Gradio app using the URL provided.
- Enter a song prompt in the textbox. For example:
A calm acoustic folk song about a journey through the mountains, sung by a soothing male voice.
- Click the "Submit" button.
- Wait for the song to be generated. This can take up to 100 seconds.
- Once the song is ready, an audio player will appear below the input box.
- Click the play button to listen to your generated song.
Additional Customizations
Adding More Input Options
If you want to provide more options to the user, such as making the song instrumental or selecting the model, you can update your Gradio interface and function accordingly.
Updated Function with Additional Parameters:
def generate_song(prompt, make_instrumental, model):
payload = {
'prompt': prompt,
'make_instrumental': make_instrumental,
'model': model,
'wait_audio': True
}
# Rest of the function remains the same...
Updated Interface:
iface = gr.Interface(
fn=generate_song,
inputs=[
gr.Textbox(lines=2, placeholder="Enter song prompt here..."),
gr.Checkbox(label="Make Instrumental", default=False),
gr.Dropdown(choices=['chirp-v3-5', 'chirp-v3-0'], label="Model", value='chirp-v3-5')
],
outputs=gr.Audio(type='filepath'),
title="AI Song Generator",
description="Enter a prompt to generate a song using the Suno API."
)
Allowing Custom Lyrics with /api/custom_generate
If you prefer to allow users to input custom lyrics, you can use the /api/custom_generate endpoint.
Function for Custom Lyrics:
def generate_custom_song(lyrics, tags, title, make_instrumental, model):
API_URL = 'https://suno-api-ivory-chi.vercel.app/api/custom_generate'
payload = {
'prompt': lyrics,
'tags': tags,
'title': title,
'make_instrumental': make_instrumental,
'model': model,
'wait_audio': True
}
# Rest of the function remains the same...
Interface for Custom Lyrics:
iface = gr.Interface(
fn=generate_custom_song,
inputs=[
gr.Textbox(lines=10, placeholder="Enter custom lyrics here...", label="Lyrics"),
gr.Textbox(placeholder="Enter tags (e.g., pop, rock, energetic)", label="Tags"),
gr.Textbox(placeholder="Enter song title", label="Title"),
gr.Checkbox(label="Make Instrumental", default=False),
gr.Dropdown(choices=['chirp-v3-5', 'chirp-v3-0'], label="Model", value='chirp-v3-5')
],
outputs=gr.Audio(type='filepath'),
title="AI Custom Song Generator",
description="Generate a song using your own lyrics with the Suno API."
)
Notes and Considerations
-
API Limits: Be mindful of any rate limits or usage quotas imposed by the API. The documentation mentions that this is a demo bound to a test account. Avoid excessive use to prevent reaching the quota.
-
Error Handling: The provided code includes basic error handling. You might want to enhance it by adding more detailed exceptions and user feedback.
-
Temporary Files: The audio files are saved to temporary files that are not automatically deleted. For a production environment, consider managing these files properly to avoid storage issues.
-
Concurrency: If multiple users will use the app simultaneously, ensure that the temporary file handling is thread-safe and consider potential race conditions.
-
Security: Since the app makes external API calls and handles file downloads, ensure that you handle any potential security issues, especially if deploying the app publicly.
Conclusion
You've now created a Gradio app that:
- Takes a user's prompt.
- Uses the provided API to generate a song.
- Allows the user to play the generated track directly within the app.
Feel free to customize and expand upon this basic framework to suit your needs. You can add more features, improve the UI, or integrate additional functionality from the API's capabilities.
Let me know if you need further assistance!