haraberget commited on
Commit
597c3bb
·
verified ·
1 Parent(s): e1c2b50

Update app.py

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