Spaces:
Sleeping
Sleeping
| import os | |
| import time | |
| import requests | |
| import gradio as gr | |
| SUNO_KEY = os.environ.get("SunoKey") | |
| if not SUNO_KEY: | |
| raise ValueError("Suno API key not found! Please set the secret 'SunoKey'.") | |
| API_BASE = "https://api.sunoapi.org/api/v1" | |
| def generate_lyrics(prompt): | |
| """Generate lyrics from Suno API with full error feedback.""" | |
| try: | |
| # 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() | |
| 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}") | |
| # 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}" | |
| 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]) | |
| return "Task timed out: lyrics not ready after polling." | |
| except requests.exceptions.RequestException as e: | |
| return f"Request Exception: {e}" | |
| except Exception as e: | |
| return f"Unexpected Exception: {e}" | |
| # Gradio interface | |
| iface = 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__": | |
| iface.launch() |