haraberget commited on
Commit
5621d80
·
verified ·
1 Parent(s): d3cdef9

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +148 -65
app.py CHANGED
@@ -1,77 +1,160 @@
 
 
1
  import os
2
  import time
3
- import requests
4
- import gradio as gr
5
- SUNO_KEY = os.environ.get("SunoKey")
6
- if not SUNO_KEY:
7
- raise ValueError("Suno API key not found! Please set the secret 'SunoKey'.")
8
 
9
- API_BASE = "https://api.sunoapi.org/api/v1"
10
-
11
- def generate_lyrics(prompt):
12
- """Generate lyrics from Suno API with full error feedback."""
13
- try:
14
- # Submit the lyrics generation task
15
- submit_resp = requests.post(
16
- f"{API_BASE}/lyrics",
17
- headers={
18
- "Authorization": f"Bearer {SUNO_KEY}",
19
- "Content-Type": "application/json"
20
- },
21
- json={
22
- "prompt": prompt,
23
- "callBackUrl": "" # empty if we want to poll instead
24
- }
25
- )
26
- submit_resp.raise_for_status()
27
- submit_data = submit_resp.json()
28
- if submit_data.get("code") != 200 or "taskId" not in submit_data.get("data", {}):
29
- return f"Failed to submit task: {submit_data}"
30
-
31
- task_id = submit_data["data"]["taskId"]
32
- print(f"Submitted task. Task ID: {task_id}")
33
-
34
- # Polling for status
35
- max_attempts = 30
36
- for attempt in range(max_attempts):
37
- time.sleep(2) # 2 seconds between polls
38
- status_resp = requests.get(
39
- f"{API_BASE}/lyrics/details?taskId={task_id}",
40
- headers={"Authorization": f"Bearer {SUNO_KEY}"}
41
- )
42
- if status_resp.status_code == 404:
43
- # Task not ready yet
44
- continue
45
- try:
46
- status_resp.raise_for_status()
47
- except requests.exceptions.HTTPError as e:
48
- # Full feedback on HTTP error
49
- return f"HTTP Error during polling: {e}\nResponse body: {status_resp.text}"
50
 
51
- status_data = status_resp.json()
52
- if status_data.get("code") != 200:
53
- return f"API returned error during polling: {status_data}"
54
 
55
- lyrics_items = status_data.get("data", {}).get("data", [])
56
- if lyrics_items:
57
- # Return all variants
58
- return "\n\n".join([f"Title: {item['title']}\nLyrics:\n{item['text']}" for item in lyrics_items])
59
 
60
- return "Task timed out: lyrics not ready after polling."
 
 
 
 
 
 
 
 
 
 
 
 
 
61
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  except requests.exceptions.RequestException as e:
63
- return f"Request Exception: {e}"
64
  except Exception as e:
65
- return f"Unexpected Exception: {e}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
 
67
- # Gradio interface
68
- iface = gr.Interface(
69
- fn=generate_lyrics,
70
- inputs=gr.Textbox(label="Enter Lyrics Prompt", placeholder="Write your song idea here..."),
71
- outputs=gr.Textbox(label="Generated Lyrics"),
72
- title="Suno AI Lyrics Generator",
73
- description="Generate lyrics using Suno API with full error feedback."
74
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
 
76
  if __name__ == "__main__":
77
- iface.launch()
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
  import os
4
  import time
 
 
 
 
 
5
 
6
+ # Load Suno API key from environment variable
7
+ SUNO_KEY = os.environ.get("SUNO_KEY") # Changed to match typical naming
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ # Check if API key exists
10
+ if not SUNO_KEY:
11
+ print("⚠️ Warning: SUNO_KEY environment variable not set!")
12
 
13
+ # Store tasks in a dictionary for multiple users (better than global)
14
+ user_tasks = {}
 
 
15
 
16
+ def generate_lyrics(prompt, username="default"):
17
+ """Submit lyrics generation task"""
18
+ if not SUNO_KEY:
19
+ return "Error: API key not configured. Please set SUNO_KEY environment variable."
20
+
21
+ url = "https://api.sunoapi.org/api/v1/lyrics"
22
+ headers = {
23
+ "Authorization": f"Bearer {SUNO_KEY}",
24
+ "Content-Type": "application/json"
25
+ }
26
+ payload = {
27
+ "prompt": prompt,
28
+ "callBackUrl": ""
29
+ }
30
 
31
+ try:
32
+ resp = requests.post(url, headers=headers, json=payload, timeout=30)
33
+ resp.raise_for_status()
34
+ data = resp.json()
35
+
36
+ if data.get("code") == 200 and "data" in data:
37
+ task_id = data["data"]["taskId"]
38
+ user_tasks[username] = task_id
39
+ return f"✅ Submitted!\nTask ID: {task_id}\nPrompt: {prompt[:50]}..."
40
+ else:
41
+ return f"❌ API Error: {data.get('message', 'Unknown error')}"
42
+
43
  except requests.exceptions.RequestException as e:
44
+ return f" Connection Error: {str(e)}"
45
  except Exception as e:
46
+ return f"Unexpected Error: {str(e)}"
47
+
48
+ def poll_task(username="default"):
49
+ """Poll the current user's task"""
50
+ if not SUNO_KEY:
51
+ return "Error: API key not configured."
52
+
53
+ task_id = user_tasks.get(username)
54
+ if not task_id:
55
+ return "No task submitted yet! Generate lyrics first."
56
+
57
+ url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={task_id}"
58
+ headers = {"Authorization": f"Bearer {SUNO_KEY}"}
59
+
60
+ try:
61
+ resp = requests.get(url, headers=headers, timeout=30)
62
+ resp.raise_for_status()
63
+ data = resp.json()
64
+
65
+ if data.get("code") == 200 and "data" in data:
66
+ task_data = data["data"]
67
+ status = task_data.get("status", "unknown")
68
+
69
+ if status == "completed" and "data" in task_data:
70
+ lyrics_data = task_data["data"]
71
+ output_lines = []
72
+
73
+ for i, item in enumerate(lyrics_data, 1):
74
+ output_lines.append(f"🎵 Variant {i}: {item.get('title', 'Untitled')}")
75
+ output_lines.append(f"{item.get('text', 'No lyrics')}")
76
+ output_lines.append("-" * 40)
77
+
78
+ return "\n".join(output_lines)
79
+ else:
80
+ return f"⏳ Status: {status}\nTask ID: {task_id}\n\nCheck back in a few seconds..."
81
+ else:
82
+ return f"❌ API Error: {data.get('message', 'Unknown error')}"
83
+
84
+ except requests.exceptions.RequestException as e:
85
+ return f"❌ Connection Error: {str(e)}"
86
+
87
+ def auto_poll_task(username="default"):
88
+ """Auto-poll with loading animation"""
89
+ if username not in user_tasks:
90
+ return "No task submitted yet!"
91
+
92
+ result = poll_task(username)
93
+
94
+ # If still processing, show animation
95
+ if "⏳ Status: processing" in result:
96
+ return f"🔄 Processing...\n{result}"
97
+
98
+ return result
99
 
100
+ # Enhanced Gradio interface
101
+ with gr.Blocks(theme=gr.themes.Soft(), title="Suno Lyrics Generator") as app:
102
+ gr.Markdown("# 🎵 Suno AI Lyrics Generator")
103
+ gr.Markdown("Generate song lyrics using Suno's AI API")
104
+
105
+ with gr.Row():
106
+ with gr.Column(scale=2):
107
+ prompt_input = gr.Textbox(
108
+ label="Lyrics Prompt",
109
+ placeholder="Enter your lyrics idea (e.g., 'A love song about Paris in spring')",
110
+ lines=3
111
+ )
112
+
113
+ with gr.Row():
114
+ submit_btn = gr.Button("✨ Generate Lyrics", variant="primary")
115
+ poll_btn = gr.Button("🔄 Check Status", variant="secondary")
116
+ auto_poll_btn = gr.Button("🔁 Auto Refresh", variant="secondary")
117
+
118
+ gr.Markdown("### How to use:")
119
+ gr.Markdown("""
120
+ 1. Enter your lyrics idea
121
+ 2. Click **Generate Lyrics** to submit
122
+ 3. Wait 10-30 seconds
123
+ 4. Click **Check Status** to see results
124
+ """)
125
+
126
+ with gr.Column(scale=3):
127
+ output_area = gr.Textbox(
128
+ label="Output",
129
+ lines=20,
130
+ placeholder="Your generated lyrics will appear here..."
131
+ )
132
+
133
+ # Event handlers
134
+ submit_btn.click(
135
+ generate_lyrics,
136
+ inputs=prompt_input,
137
+ outputs=output_area
138
+ )
139
+
140
+ poll_btn.click(
141
+ poll_task,
142
+ inputs=None,
143
+ outputs=output_area
144
+ )
145
+
146
+ auto_poll_btn.click(
147
+ auto_poll_task,
148
+ inputs=None,
149
+ outputs=output_area,
150
+ every=5 # Auto-refresh every 5 seconds while visible
151
+ )
152
 
153
+ # Launch with better configuration
154
  if __name__ == "__main__":
155
+ app.launch(
156
+ share=False, # Set to True for temporary public link
157
+ server_name="0.0.0.0",
158
+ server_port=7860,
159
+ show_error=True
160
+ )