I want my gradio app to show both songs not just one, so give me the updated code to paste
if audio_info[0]["status"] != 'streaming':
return "Audio generation timed out."
code
audio_url = audio_info[0].get('audio_url')
if not audio_url:
return "Error fetching 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."
import requests
import gradio as gr
import tempfile
import time
# Generate audio by prompt
data = generate_audio_by_prompt(payload)
if not data or 'error' in data:
return "Error generating song."
ids = f"{data[0]['id']},{data[1]['id']}"
# Polling to wait for audio to be ready
for _ in range(60): # Polling for 60 times
audio_info = get_audio_information(ids)
if audio_info[0]["status"] == 'streaming':
break
time.sleep(5) # Wait for 5 seconds before the next poll
if audio_info[0]["status"] != 'streaming':
return "Audio generation timed out."
audio_url = audio_info[0].get('audio_url')
if not audio_url:
return "Error fetching 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."
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."
)
if name == 'main':
iface.launch(share=True)
given the below integration
API Integration Code Example
Python
import time
import requests
if name == 'main':
data = generate_audio_by_prompt({
"prompt": "A popular heavy metal song about war, sung by a deep-voiced male singer, slowly and melodiously. The lyrics depict the sorrow of people after the war.",
"make_instrumental": False,
"wait_audio": False
})
code
ids = f"{data[0]['id']},{data[1]['id']}"
print(f"ids: {ids}")
for _ in range(60):
data = get_audio_information(ids)
if data[0]["status"] == 'streaming':
print(f"{data[0]['id']} ==> {data[0]['audio_url']}")
print(f"{data[1]['id']} ==> {data[1]['audio_url']}")
break
# sleep 5s
time.sleep(5)
To modify your Gradio app to display both generated songs instead of just one, you'll need to update both the generate_song function and the Gradio interface configuration. Here's the updated code with detailed comments to help you understand the changes:
python
import time
import requests
import gradio as gr
import tempfile
# Replace with your actual Vercel domain
BASE_URL = 'https://suno-api-ivory-chi.vercel.app'
def generate_audio_by_prompt(payload):
"""
Sends a request to generate audio based on the provided prompt.
"""
url = f"{BASE_URL}/api/generate"
response = requests.post(url, json=payload, headers={'Content-Type': 'application/json'})
if response.status_code != 200:
return None
return response.json()
def get_audio_information(audio_ids):
"""
Retrieves the status and URL of the generated audio files using their IDs.
"""
url = f"{BASE_URL}/api/get?ids={audio_ids}"
response = requests.get(url)
if response.status_code != 200:
return None
return response.json()
def download_audio(audio_url):
"""
Downloads the audio file from the provided URL and saves it to a temporary file.
"""
audio_response = requests.get(audio_url)
if audio_response.status_code == 200:
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix='.mp3')
temp_file.write(audio_response.content)
temp_file.close()
return temp_file.name
else:
return None
def generate_song(prompt):
"""
Generates two songs based on the input prompt and returns their file paths.
"""
payload = {
"prompt": prompt,
"make_instrumental": False,
"wait_audio": False
}
# Generate audio by prompt
data = generate_audio_by_prompt(payload)
if not data or 'error' in data:
return "Error generating songs.", "Error generating songs."
# Extract the IDs of both audio files
ids = f"{data[0]['id']},{data[1]['id']}"
# Polling to wait for both audios to be ready
for _ in range(60): # Polling for up to 5 minutes (60 * 5 seconds)
audio_info = get_audio_information(ids)
if not audio_info or 'error' in audio_info:
return "Error fetching audio information.", "Error fetching audio information."
# Check if both audio files are ready
status_0 = audio_info[0].get("status")
status_1 = audio_info[1].get("status")
if status_0 == 'streaming' and status_1 == 'streaming':
break
time.sleep(5) # Wait for 5 seconds before the next poll
else:
return "Audio generation timed out.", "Audio generation timed out."
# Get audio URLs
audio_url_0 = audio_info[0].get('audio_url')
audio_url_1 = audio_info[1].get('audio_url')
if not audio_url_0 or not audio_url_1:
return "Error fetching audio URLs.", "Error fetching audio URLs."
# Download both audio files
audio_file_0 = download_audio(audio_url_0)
audio_file_1 = download_audio(audio_url_1)
if not audio_file_0 or not audio_file_1:
return "Error downloading one or both audio files.", "Error downloading one or both audio files."
# Return paths to both audio files
return audio_file_0, audio_file_1
# Define the Gradio interface with two audio outputs
iface = gr.Interface(
fn=generate_song,
inputs=gr.Textbox(lines=2, placeholder="Enter song prompt here..."),
outputs=[
gr.Audio(label="Song 1", type='filepath'),
gr.Audio(label="Song 2", type='filepath')
],
title="AI Song Generator",
description="Enter a prompt to generate two songs using the Suno API."
)
if __name__ == '__main__':
iface.launch(share=True)
Changes and Enhancements:
Handling Two Audio Files:
The generate_song function now returns two file paths corresponding to the two generated songs.
Both audio IDs (data[0]['id'] and data[1]['id']) are fetched and used to retrieve their respective statuses and URLs.
Polling for Both Audios:
The polling loop now checks the status of both audio files (audio_info[0] and audio_info[1]) to ensure both are ready before proceeding.
If either of the audio files fails to generate within the polling limit, an appropriate timeout message is returned for both outputs.
Downloading Both Audios:
A helper function download_audio is created to handle downloading the audio files, reducing code redundancy.
Both audio files are downloaded separately, and their paths are returned.
Gradio Interface Updates:
The outputs parameter in the Gradio interface is updated to include two gr.Audio components, each labeled appropriately ("Song 1" and "Song 2").
This allows the interface to display two separate audio players for the generated songs.
Error Handling:
Enhanced error handling ensures that if any step fails (e.g., fetching audio information, downloading files), meaningful error messages are returned for both audio outputs.
Comments and Documentation:
Added comprehensive comments to explain each part of the code for better readability and maintainability.
Usage:
Run the Script:
Ensure all required libraries (requests, gradio) are installed.
Run the script using Python. For example:
bash
python your_script_name.py
Access the Gradio Interface:
Once the script is running, it will provide a local URL (and a shareable URL if share=True) where you can access the Gradio interface.
Generate Songs:
Enter your desired song prompt in the textbox and submit.
After a short wait (due to polling), two audio players will appear, allowing you to play both generated songs.
Notes:
Temporary Files:
The audio files are saved as temporary files with a .mp3 extension. Depending on your deployment environment, you might want to manage these files to avoid excessive storage usage.
API Limits:
Be mindful of any rate limits or quotas associated with the Suno API to prevent unexpected errors or service interruptions.
Customization:
You can further customize the interface, such as adding progress indicators or allowing users to download the generated songs.
This updated code should enable your Gradio app to display both generated songs seamlessly. Let me know if you encounter any issues or need further assistance!