MySafeCode commited on
Commit
c37b0d6
·
verified ·
1 Parent(s): c053fbf

Update a.py

Browse files
Files changed (1) hide show
  1. a.py +85 -173
a.py CHANGED
@@ -1,177 +1,89 @@
1
- import streamlit as st
2
- import json
3
- import requests
4
- from datetime import datetime
5
-
6
- # Page configuration
7
- st.set_page_config(
8
- page_title="Suno API Generator",
9
- page_icon="🎵",
10
- layout="centered"
11
- )
12
-
13
- # Title
14
- st.title("🎵 Suno API Audio Generator")
15
-
16
- # Load secrets from Hugging Face Space - using YOUR exact secret names
17
- SUNO_API_KEY = st.secrets.get("SunoKey", "")
18
- CALLBACK_URL = st.secrets.get("CallbackURL", "")
19
-
20
- # Debug: Show what secrets were found
21
- st.write("### 🔍 Debug Info")
22
- st.write(f"Secrets found: {list(st.secrets.keys())}")
23
- st.write(f"SunoKey loaded: {'✅ Yes' if SUNO_API_KEY else '❌ No'}")
24
- st.write(f"CallbackURL loaded: {'✅ Yes' if CALLBACK_URL else '❌ No'}")
25
-
26
- # Show secret status
27
- if SUNO_API_KEY and CALLBACK_URL:
28
- st.success("✅ Secrets loaded successfully from Hugging Face!")
29
- st.info(f"Loaded **SunoKey** and **CallbackURL** secrets")
30
- else:
31
- st.error("❌ Secrets not loaded correctly")
32
- st.info("""
33
- **Make sure you've added these secrets in Hugging Face Space:**
34
- 1. Go to **Settings** → **Repository secrets**
35
- 2. Add:
36
- - **Key:** `SunoKey` (exact name)
37
- - **Value:** Your Suno API Bearer token
38
 
39
- 3. Add:
40
- - **Key:** `CallbackURL` (exact name)
41
- - **Value:** Your callback URL
42
- """)
43
-
44
- # API Form
45
- st.markdown("---")
46
- st.markdown("### 🎛️ API Parameters")
47
-
48
- task_id = st.text_input("Task ID", value="5c79****be8e")
49
- audio_id = st.text_input("Audio ID", value="e231****-****-****-****-****8cadc7dc")
50
-
51
- # Make API call button
52
- if st.button("🎵 Generate Audio", type="primary", use_container_width=True):
53
- if not SUNO_API_KEY or not CALLBACK_URL:
54
- st.error("❌ Please configure SunoKey and CallbackURL in Hugging Face Space settings")
55
- elif not task_id or not audio_id:
56
- st.error("❌ Please enter both Task ID and Audio ID")
57
- else:
58
- with st.spinner("Making API call to Suno..."):
59
- try:
60
- # Prepare the API call using YOUR secrets
61
- headers = {
62
- "Authorization": f"Bearer {SUNO_API_KEY}",
63
- "Content-Type": "application/json"
64
- }
65
-
66
- data = {
67
- "taskId": task_id,
68
- "audioId": audio_id,
69
- "callBackUrl": CALLBACK_URL
70
- }
71
-
72
- # Show what we're sending
73
- with st.expander("📡 Request Details", expanded=True):
74
- st.code(f"""
75
- POST https://api.sunoapi.org/api/v1/wav/generate
76
-
77
- Headers:
78
- {{
79
- "Authorization": "Bearer {SUNO_API_KEY[:10]}...{SUNO_API_KEY[-10:] if len(SUNO_API_KEY) > 20 else '***'}",
80
- "Content-Type": "application/json"
81
- }}
82
-
83
- Body:
84
- {json.dumps(data, indent=2)}
85
- """)
86
 
87
- # Make the actual API call
88
- response = requests.post(
89
- "https://api.sunoapi.org/api/v1/wav/generate",
90
- headers=headers,
91
- json=data,
92
- timeout=30
93
- )
94
 
95
- # Check response
96
- if response.status_code == 200:
97
- result = response.json()
98
- st.success(f"✅ Success! Status: {response.status_code}")
99
-
100
- # Display response
101
- st.markdown("### 📋 API Response")
102
- st.json(result)
103
 
104
- # Download button
105
- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
106
- st.download_button(
107
- label="📥 Download JSON Response",
108
- data=json.dumps(result, indent=2),
109
- file_name=f"suno_response_{timestamp}.json",
110
- mime="application/json"
111
- )
112
-
113
- # Show useful info
114
- if "jobId" in result:
115
- st.info(f"**Job ID:** `{result['jobId']}`")
116
- if "message" in result:
117
- st.info(f"**Message:** {result['message']}")
118
-
119
- else:
120
- st.error(f"❌ API Error: {response.status_code}")
121
- try:
122
- error_details = response.json()
123
- st.json(error_details)
124
- except:
125
- st.text(f"Response: {response.text}")
126
-
127
- except requests.exceptions.Timeout:
128
- st.error("⏰ Request timed out after 30 seconds")
129
- except requests.exceptions.ConnectionError:
130
- st.error("🔌 Connection error - check your internet connection")
131
- except requests.exceptions.RequestException as e:
132
- st.error(f"⚠️ Request failed: {str(e)}")
133
- except Exception as e:
134
- st.error(f"❌ Unexpected error: {str(e)}")
135
-
136
- # Secret info section
137
- st.markdown("---")
138
- with st.expander("🔐 Secret Information"):
139
- if SUNO_API_KEY:
140
- # Show masked key
141
- key_length = len(SUNO_API_KEY)
142
- if key_length > 20:
143
- masked = f"{SUNO_API_KEY[:10]}...{SUNO_API_KEY[-10:]}"
144
- elif key_length > 8:
145
- masked = f"{SUNO_API_KEY[:4]}...{SUNO_API_KEY[-4:]}"
146
- else:
147
- masked = "••••••••"
148
-
149
- st.write(f"**SunoKey (API Key):** `{masked}`")
150
- st.write(f"**Key Length:** {key_length} characters")
151
- else:
152
- st.write("**SunoKey:** Not loaded")
153
-
154
- if CALLBACK_URL:
155
- st.write(f"**CallbackURL:** `{CALLBACK_URL}`")
156
- else:
157
- st.write("**CallbackURL:** Not loaded")
158
-
159
- st.write("---")
160
- st.write("**Note:** Secrets are securely loaded from Hugging Face Space settings.")
161
-
162
- # Instructions
163
- st.markdown("---")
164
- st.markdown("### 📝 How to Use")
165
- st.markdown("""
166
- 1. **Configure Secrets** in Hugging Face Space settings:
167
- - Add `SunoKey` with your API Bearer token
168
- - Add `CallbackURL` with your callback endpoint
169
-
170
- 2. **Enter API Parameters**:
171
- - Task ID from your Suno account
172
- - Audio ID from your Suno account
173
-
174
- 3. **Click "Generate Audio"** to make the API call
175
-
176
- 4. **View Response** and download the JSON result
177
- """)
 
1
+ # Updated polling function with correct endpoint
2
+ def poll_status(task_id, single_poll=False):
3
+ """Poll Suno API for task status"""
4
+ if not task_id:
5
+ st.error("❌ Task ID cannot be empty. The API returned: '任务id不能为空' (Task ID cannot be empty)")
6
+ return False
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ headers = {
9
+ "Authorization": f"Bearer {st.session_state.suno_api_key}",
10
+ "Content-Type": "application/json"
11
+ }
12
+
13
+ try:
14
+ with st.spinner(f"Checking status for task: {task_id}..."):
15
+ # Try different endpoint formats
16
+ endpoints_to_try = []
17
+
18
+ # Format 1: /api/v1/wav/record-info with task_id as query parameter
19
+ endpoints_to_try.append(f"https://api.sunoapi.org/api/v1/wav/record-info?taskId={task_id}")
20
+
21
+ # Format 2: Different endpoint pattern (possible other versions)
22
+ endpoints_to_try.append(f"https://api.sunoapi.org/api/v1/wav/record-info/{task_id}")
23
+ endpoints_to_try.append(f"https://api.sunoapi.org/api/v1/wav/record-info?id={task_id}")
24
+
25
+ # Format 3: JSON body
26
+ endpoints_to_try.append({
27
+ "url": "https://api.sunoapi.org/api/v1/wav/record-info",
28
+ "params": {"taskId": task_id}
29
+ })
30
+
31
+ response = None
32
+ for endpoint in endpoints_to_try:
33
+ try:
34
+ response = requests.get(
35
+ endpoint,
36
+ headers=headers,
37
+ timeout=30
38
+ )
39
+ if response.status_code == 200:
40
+ break
41
+ except:
42
+ continue
43
+
44
+ if not response:
45
+ st.error("❌ Could not connect to any polling endpoint")
46
+ return False
 
 
 
 
 
 
 
 
47
 
48
+ if response.status_code == 200:
49
+ result = response.json()
 
 
 
 
 
50
 
51
+ # Display result
52
+ if result.get("code") == 200:
53
+ data = result.get("data", {})
 
 
 
 
 
54
 
55
+ if data.get("successFlag") == "SUCCESS":
56
+ # Audio is ready!
57
+ audio_url = data.get("response", {}).get("audioWavUrl")
58
+ if audio_url:
59
+ st.success("✅ Audio ready!")
60
+ st.balloons()
61
+
62
+ # Display audio info
63
+ st.markdown("### 🎵 Audio Information")
64
+ cols = st.columns(2)
65
+ with cols[0]:
66
+ st.metric("Task ID", data.get("taskId", "N/A")[:12] + "...")
67
+ st.metric("Music ID", data.get("musicId", "N/A")[:12] + "...")
68
+ with cols[1]:
69
+ st.metric("Status", data.get("successFlag", "N/A"))
70
+ st.metric("Created", data.get("createTime", "N/A"))
71
+
72
+ # Audio player
73
+ st.markdown("### 🔊 Listen")
74
+ st.audio(audio_url, format="audio/wav")
75
+
76
+ # Download section
77
+ st.markdown("### 📥 Download")
78
+ st.code(audio_url)
79
+
80
+ col_dl1, col_dl2 = st.columns(2)
81
+ with col_dl1:
82
+ st.download_button(
83
+ label=" Download WAV",
84
+ data=requests.get(audio_url).content if audio_url.startswith("http") else b"",
85
+ file_name=f"audio_{data.get('taskId', 'unknown')[:8]}.wav",
86
+ mime="audio/wav",
87
+ key=f"download_{task_id}"
88
+ )
89
+ with col_dl