File size: 2,814 Bytes
7155a3e
e1c2b50
 
597c3bb
4938901
597c3bb
d3cdef9
 
e1c2b50
d15c3c8
e1c2b50
d3cdef9
597c3bb
d3cdef9
 
 
 
 
 
 
 
 
 
 
 
597c3bb
d3cdef9
 
 
 
 
 
e1c2b50
d3cdef9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e1c2b50
d3cdef9
 
 
 
 
 
 
 
597c3bb
d3cdef9
e1c2b50
d3cdef9
 
 
 
e1c2b50
d3cdef9
 
 
 
 
 
 
 
e1c2b50
597c3bb
d3cdef9
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
74
75
76
77
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()