Spaces:
Paused
Paused
Update app.py
Browse files3 unmodified lines456778910111112131415161718191213211415161718192021222324252623242728293031323326272829343536373839404142434445464748495031323334353637383940414251525354555657585944454647484950606152626364656654555657585960616768697071727374757664773 unmodified linesimport gradio as grSUNO_KEY = os.environ.get("SunoKey")if not SUNO_KEY: raise ValueError("API key not found! Please set SunoKey in the Space secrets.") raise ValueError("Suno API key not found! Please set the secret 'SunoKey'.")
API_BASE = "https://api.sunoapi.org/api/v1"
def generate_lyrics(prompt): """Submit lyrics generation task and poll for results.""" # Step 1: Submit task submit_url = f"{API_BASE}/lyrics" headers = { "Authorization": f"Bearer {SUNO_KEY}", "Content-Type": "application/json" } data = {"prompt": prompt} """Generate lyrics from Suno API with full error feedback.""" try: submit_resp = requests.post(submit_url, json=data, headers=headers) # Submit the lyrics generation task submit_resp = requests.post( f"{API_BASE}/lyrics", headers={ "Authorization": f"Bearer {SUNO_KEY}", "Content-Type": "application/json" }, json={ "prompt": prompt, "callBackUrl": "" # empty if we want to poll instead } ) submit_resp.raise_for_status() except requests.exceptions.HTTPError as e: return f"Submit failed: {submit_resp.status_code}\nResponse: {submit_resp.text}\nError: {e}" submit_data = submit_resp.json() if submit_data.get("code") != 200 or "taskId" not in submit_data.get("data", {}): return f"Failed to submit task: {submit_data}" task_id = submit_data["data"]["taskId"] print(f"Submitted task. Task ID: {task_id}")
submit_json = submit_resp.json() task_id = submit_json.get("data", {}).get("taskId") if not task_id: return f"Failed to get taskId. Response:\n{submit_json}" # Polling for status max_attempts = 30 for attempt in range(max_attempts): time.sleep(2) # 2 seconds between polls status_resp = requests.get( f"{API_BASE}/lyrics/details?taskId={task_id}", headers={"Authorization": f"Bearer {SUNO_KEY}"} ) if status_resp.status_code == 404: # Task not ready yet continue try: status_resp.raise_for_status() except requests.exceptions.HTTPError as e: # Full feedback on HTTP error return f"HTTP Error during polling: {e}\nResponse body: {status_resp.text}"
# Step 2: Poll for lyrics details_url = f"{API_BASE}/lyrics/details?taskId={task_id}" for i in range(30): # ~1 minute polling time.sleep(2) try: details_resp = requests.get(details_url, headers=headers) except Exception as e: return f"Error polling lyrics: {e}" if details_resp.status_code != 200: print(f"Polling attempt {i+1} failed: {details_resp.status_code} - {details_resp.text}") continue status_data = status_resp.json() if status_data.get("code") != 200: return f"API returned error during polling: {status_data}"
lyrics_items = status_data.get("data", {}).get("data", []) if lyrics_items: # Return all variants return "\n\n".join([f"Title: {item['title']}\nLyrics:\n{item['text']}" for item in lyrics_items])
details_json = details_resp.json() lyrics_data = details_json.get("data", {}).get("data") if lyrics_data: results = [] for idx, variant in enumerate(lyrics_data): results.append(f"Variant {idx+1} ({variant.get('title','')}):\n{variant.get('text','')}") return "\n\n".join(results) return "Task timed out: lyrics not ready after polling."
return "Lyrics generation timed out. Try again." except requests.exceptions.RequestException as e: return f"Request Exception: {e}" except Exception as e: return f"Unexpected Exception: {e}"
# Gradio UIwith gr.Blocks() as demo: gr.Markdown("## Suno API Lyrics Generator 🎵") prompt_input = gr.Textbox(label="Enter your song prompt", placeholder="A song about a peaceful night in the city") output_box = gr.Textbox(label="Generated Lyrics") generate_button = gr.Button("Generate Lyrics") generate_button.click(fn=generate_lyrics, inputs=prompt_input, outputs=output_box)# Gradio interfaceiface = gr.Interface( fn=generate_lyrics, inputs=gr.Textbox(label="Enter Lyrics Prompt", placeholder="Write your song idea here..."), outputs=gr.Textbox(label="Generated Lyrics"), title="Suno AI Lyrics Generator", description="Generate lyrics using Suno API with full error feedback.")
if __name__ == "__main__": demo.launch() iface.launch()app.py+59-46