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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +59 -46
app.py CHANGED
@@ -4,61 +4,74 @@ import requests
4
  import gradio as gr
5
  SUNO_KEY = os.environ.get("SunoKey")
6
  if not SUNO_KEY:
7
- raise ValueError("API key not found! Please set SunoKey in the Space secrets.")
 
8
  API_BASE = "https://api.sunoapi.org/api/v1"
9
 
10
  def generate_lyrics(prompt):
11
- """Submit lyrics generation task and poll for results."""
12
- # Step 1: Submit task
13
- submit_url = f"{API_BASE}/lyrics"
14
- headers = {
15
- "Authorization": f"Bearer {SUNO_KEY}",
16
- "Content-Type": "application/json"
17
- }
18
- data = {"prompt": prompt}
19
-
20
  try:
21
- submit_resp = requests.post(submit_url, json=data, headers=headers)
 
 
 
 
 
 
 
 
 
 
 
22
  submit_resp.raise_for_status()
23
- except requests.exceptions.HTTPError as e:
24
- return f"Submit failed: {submit_resp.status_code}\nResponse: {submit_resp.text}\nError: {e}"
 
 
 
 
25
 
26
- submit_json = submit_resp.json()
27
- task_id = submit_json.get("data", {}).get("taskId")
28
- if not task_id:
29
- return f"Failed to get taskId. Response:\n{submit_json}"
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
- # Step 2: Poll for lyrics
32
- details_url = f"{API_BASE}/lyrics/details?taskId={task_id}"
33
- for i in range(30): # ~1 minute polling
34
- time.sleep(2)
35
- try:
36
- details_resp = requests.get(details_url, headers=headers)
37
- except Exception as e:
38
- return f"Error polling lyrics: {e}"
39
-
40
- if details_resp.status_code != 200:
41
- print(f"Polling attempt {i+1} failed: {details_resp.status_code} - {details_resp.text}")
42
- continue
43
 
44
- details_json = details_resp.json()
45
- lyrics_data = details_json.get("data", {}).get("data")
46
- if lyrics_data:
47
- results = []
48
- for idx, variant in enumerate(lyrics_data):
49
- results.append(f"Variant {idx+1} ({variant.get('title','')}):\n{variant.get('text','')}")
50
- return "\n\n".join(results)
51
 
52
- return "Lyrics generation timed out. Try again."
 
 
 
53
 
54
- # Gradio UI
55
- with gr.Blocks() as demo:
56
- gr.Markdown("## Suno API Lyrics Generator 🎵")
57
- prompt_input = gr.Textbox(label="Enter your song prompt", placeholder="A song about a peaceful night in the city")
58
- output_box = gr.Textbox(label="Generated Lyrics")
59
- generate_button = gr.Button("Generate Lyrics")
60
-
61
- generate_button.click(fn=generate_lyrics, inputs=prompt_input, outputs=output_box)
62
 
63
  if __name__ == "__main__":
64
- demo.launch()
 
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()