MySafeCode commited on
Commit
d93a4dd
·
verified ·
1 Parent(s): 03644c8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +392 -191
app.py CHANGED
@@ -2,7 +2,10 @@ import streamlit as st
2
  import json
3
  import requests
4
  import time
 
5
  from datetime import datetime
 
 
6
 
7
  # Polling function
8
  def poll_status(task_id, single_poll=False):
@@ -18,14 +21,15 @@ def poll_status(task_id, single_poll=False):
18
 
19
  try:
20
  with st.spinner(f"Checking status for task: {task_id}..."):
21
- # Two possible endpoints - let's try both formats
22
- endpoints =[
 
23
  f"https://api.sunoapi.org/api/v1/wav/record-info/{task_id}",
24
- f"https://api.sunoapi.org/api/v1/wav/record-info?taskId={task_id}"
25
  ]
26
 
27
  response = None
28
- for endpoint in endpoints:
29
  try:
30
  response = requests.get(
31
  endpoint,
@@ -38,12 +42,23 @@ def poll_status(task_id, single_poll=False):
38
  continue
39
 
40
  if not response:
41
- st.error("❌ Failed to connect to polling endpoint")
42
  return False
43
 
44
  if response.status_code == 200:
45
  result = response.json()
46
 
 
 
 
 
 
 
 
 
 
 
 
47
  # Display result
48
  if result.get("code") == 200:
49
  data = result.get("data", {})
@@ -120,6 +135,54 @@ def poll_status(task_id, single_poll=False):
120
  except Exception as e:
121
  st.error(f"⚠️ Polling error: {str(e)}")
122
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
123
  # Page configuration
124
  st.set_page_config(
125
  page_title="Suno API Generator",
@@ -142,219 +205,340 @@ if 'auto_poll' not in st.session_state:
142
  st.session_state.auto_poll = False
143
  if 'suno_api_key' not in st.session_state:
144
  st.session_state.suno_api_key = SUNO_API_KEY
 
 
145
 
146
- # Title and info
147
  st.title("🎵 Suno API Audio Generator")
148
 
149
- with st.expander("📋 How it works", expanded=True):
150
- st.markdown("""
151
- ### Workflow:
152
- 1. **Step 1**: Submit task to Suno API → Get `taskId` from response
153
- 2. **Step 2**: Suno processes audio (async)
154
- 3. **Step 3**: Suno sends callback to: `https://1hit.no/wav/cb.php`
155
- 4. **Step 4**: You can view callbacks at: `https://1hit.no/wav/view.php`
156
- 5. **Step 5**: OR use Poll button to check status via `/api/v1/record-info` endpoint
157
- ### Polling Endpoint:
158
- ```javascript
159
- fetch('https://api.sunoapi.org/api/v1/wav/record-info', {
160
- method: 'GET',
161
- headers: {
162
- 'Authorization': 'Bearer YOUR_TOKEN'
163
- }
164
- })
165
- ```
166
-
167
- ### Error Handling:
168
- - **400**: Task ID cannot be empty
169
- - Make sure to include task ID in polling request
170
- """)
171
 
172
- # Main layout
173
- col1, col2 = st.columns([2, 1])
 
 
 
 
 
 
 
 
174
 
175
- with col1:
176
- st.header("🚀 Step 1: Submit to Suno API")
177
-
178
- # Form inputs
179
- task_id = st.text_input("Task ID", value="5c79****be8e", help="Enter your Suno task ID", key="input_task_id")
180
- audio_id = st.text_input("Audio ID", value="e231****-****-****-****-****8cadc7dc", help="Enter your Suno audio ID", key="input_audio_id")
181
-
182
- if st.button("🎵 Generate Audio", type="primary", use_container_width=True, key="generate_btn"):
183
- if not SUNO_API_KEY:
184
- st.error("❌ SunoKey not configured in Hugging Face secrets")
185
- st.info("Add `SunoKey` secret in Hugging Face Space settings")
186
- st.stop()
 
 
 
187
 
188
- if not task_id or not audio_id:
189
- st.error(" Please enter both Task ID and Audio ID")
190
- st.stop()
191
 
192
- with st.spinner("Sending request to Suno API..."):
193
- headers = {
194
- "Authorization": f"Bearer {SUNO_API_KEY}",
195
- "Content-Type": "application/json"
196
- }
197
 
198
- # Test sending to correct endpoint
199
- endpoint_url = "https://api.sunoapi.org/api/v1/wav/generate"
200
- st.info(f"Making request to: {endpoint_url}")
201
 
202
- payload = {
203
- "taskId": task_id,
204
- "audioId": audio_id,
205
- "callBackUrl": CALLBACK_URL
206
- }
207
-
208
- st.json(payload)
209
-
210
- try:
211
- response = requests.post(
212
- endpoint_url,
213
- headers=headers,
214
- json=payload,
215
- timeout=30
216
- )
217
 
218
- if response.status_code == 200:
219
- result = response.json()
220
-
221
- # Display response
222
- with st.expander("📋 API Response", expanded=True):
223
- st.json(result)
 
 
 
 
 
 
 
224
 
225
- if result.get("code") == 200 and "data" in result and "taskId" in result["data"]:
226
- st.session_state.task_id = result["data"]["taskId"]
227
- st.success(f"✅ Task submitted successfully!")
228
- st.info(f"**Task ID:** `{st.session_state.task_id}`")
229
 
230
- # Auto-fill poll input
231
- st.session_state.poll_task_input = st.session_state.task_id
 
232
 
233
- st.markdown("---")
234
- st.markdown("### 🔄 Next Steps:")
235
- st.markdown("""
236
- 1. **Automatic Callback**: Suno will send result to your callback URL
237
- 2. **Manual Poll**: Use the Poll button to check status
238
- 3. **View Logs**: Check [Callback Viewer](https://1hit.no/wav/view.php)
239
- """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
240
  else:
241
- st.error("❌ Unexpected response format")
242
-
243
- # Debug info
244
- st.markdown("**Debug Response:**")
245
- st.code(str(result))
246
- else:
247
- st.error(f"❌ API Error: {response.status_code}")
248
- try:
249
- error_data = response.json()
250
- st.json(error_data)
251
- except:
252
- st.text(f"Response: {response.text}")
253
-
254
- except requests.exceptions.Timeout:
255
- st.error("⏰ Request timed out after 30 seconds")
256
- except requests.exceptions.ConnectionError:
257
- st.error("🔌 Connection error - check your internet connection")
258
- except requests.exceptions.RequestException as e:
259
- st.error(f"⚠️ Request failed: {str(e)}")
260
 
261
- with col2:
262
- st.header("🔍 Step 2: Poll Status")
263
-
264
- # Manual task ID input for polling
265
- poll_task_id = st.text_input(
266
- "Task ID to Poll",
267
- value=st.session_state.get('poll_task_input', st.session_state.task_id or ""),
268
- help="Enter task ID to check status",
269
- key="poll_task_input_field"
270
- )
271
-
272
- col2a, col2b = st.columns(2)
273
-
274
- with col2a:
275
- poll_once_btn = st.button("🔄 Poll Once", type="secondary", use_container_width=True, key="poll_once_btn")
276
-
277
- with col2b:
278
- auto_poll_btn = st.button("🔁 Auto Poll (10s)", type="secondary", use_container_width=True, key="auto_poll_btn")
279
 
280
- # Handle poll button clicks
281
- if poll_once_btn:
282
- if not poll_task_id:
283
- st.error("❌ Please enter a Task ID")
284
- elif not SUNO_API_KEY:
285
- st.error("❌ SunoKey not configured")
286
- else:
287
- poll_status(poll_task_id, single_poll=True)
288
 
289
- if auto_poll_btn:
290
- if not poll_task_id:
291
- st.error("❌ Please enter a Task ID")
292
- elif not SUNO_API_KEY:
293
- st.error("❌ SunoKey not configured")
294
- else:
295
- st.session_state.auto_poll = True
296
- st.session_state.auto_poll_task_id = poll_task_id
297
- st.rerun()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
298
 
299
- # Display poll results if any
300
- if st.session_state.poll_results:
301
- st.markdown("---")
302
- st.header("📊 Polling History")
303
 
304
- # Show last 5 results
305
- recent_results = list(reversed(st.session_state.poll_results[-5:]))
 
 
306
 
307
- for i, result in enumerate(recent_results):
308
- with st.expander(f"Poll {i+1} - {result['timestamp']} - Task: {result['task_id'][:12]}...", expanded=(i == len(recent_results)-1)):
309
- response_data = result["response"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
310
 
311
- if response_data.get("code") == 200:
312
- data = response_data.get("data", {})
313
- status = data.get("successFlag", "UNKNOWN")
314
-
315
- # Status badge
316
- if status == "SUCCESS":
317
- st.success(f"✅ {status}")
318
- elif status == "PROCESSING":
319
- st.info(f"⏳ {status}")
320
- elif status == "FAILED":
321
- st.error(f"❌ {status}")
322
- else:
323
- st.warning(f"⚠️ {status}")
324
-
325
- # Display key info
326
- cols = st.columns(3)
327
- with cols[0]:
328
- st.metric("Task ID", data.get("taskId", "N/A")[:12] + "...")
329
- with cols[1]:
330
- st.metric("Music ID", data.get("musicId", "N/A")[:12] + "...")
331
- with cols[2]:
332
- st.metric("Status", status)
333
-
334
- # Show audio if available
335
- audio_url = data.get("response", {}).get("audioWavUrl")
336
- if audio_url:
337
- st.audio(audio_url, format="audio/wav")
338
- st.markdown(f"**Audio URL:** `{audio_url}`")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
339
 
340
- # Show full response
341
- with st.expander("📋 Full Response JSON"):
342
- st.json(response_data)
 
 
 
 
 
 
 
 
 
 
 
 
 
343
  else:
344
- st.error(f" Error: {response_data.get('msg', 'Unknown error')}")
345
- st.json(response_data)
 
 
 
346
 
347
  # Quick links and info
348
- st.markdown("---")
349
- st.markdown("### 📝 Quick Links")
350
- st.markdown("""
351
- - 🔗 [View Suno Callbacks](https://1hit.no/wav/view.php) - See all callback logs
352
- - 📚 [Suno API Documentation](https://docs.sunoapi.org/) - Official API docs
353
- - 🔄 **Poll Endpoint**: `GET https://api.sunoapi.org/api/v1/wav/record-info`
354
  """)
355
 
356
  # Secret status
357
- with st.expander("🔐 Secret Status", expanded=False):
358
  if SUNO_API_KEY:
359
  masked_key = f"{SUNO_API_KEY[:8]}...{SUNO_API_KEY[-8:]}" if len(SUNO_API_KEY) > 16 else "••••••••"
360
  st.success(f"✅ SunoKey loaded ({len(SUNO_API_KEY)} chars)")
@@ -362,4 +546,21 @@ with st.expander("🔐 Secret Status", expanded=False):
362
  else:
363
  st.error("❌ SunoKey not found")
364
 
365
- st.info(f"**Callback URL:** `{CALLBACK_URL}`")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import json
3
  import requests
4
  import time
5
+ import pandas as pd
6
  from datetime import datetime
7
+ from urllib.parse import urlparse
8
+ import os
9
 
10
  # Polling function
11
  def poll_status(task_id, single_poll=False):
 
21
 
22
  try:
23
  with st.spinner(f"Checking status for task: {task_id}..."):
24
+ # Try different endpoint formats
25
+ endpoints_to_try = [
26
+ f"https://api.sunoapi.org/api/v1/wav/record-info?taskId={task_id}",
27
  f"https://api.sunoapi.org/api/v1/wav/record-info/{task_id}",
28
+ f"https://api.sunoapi.org/api/v1/wav/record-info?id={task_id}"
29
  ]
30
 
31
  response = None
32
+ for endpoint in endpoints_to_try:
33
  try:
34
  response = requests.get(
35
  endpoint,
 
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
+ # Store in session state
52
+ if 'poll_results' not in st.session_state:
53
+ st.session_state.poll_results = []
54
+
55
+ poll_entry = {
56
+ "timestamp": datetime.now().strftime("%H:%M:%S"),
57
+ "task_id": task_id,
58
+ "response": result
59
+ }
60
+ st.session_state.poll_results.append(poll_entry)
61
+
62
  # Display result
63
  if result.get("code") == 200:
64
  data = result.get("data", {})
 
135
  except Exception as e:
136
  st.error(f"⚠️ Polling error: {str(e)}")
137
 
138
+ def load_callback_logs():
139
+ """Load and parse callback_log.json from remote URL"""
140
+ try:
141
+ # Try to fetch from your callback URL
142
+ log_url = "https://1hit.no/wav/callback_log.json"
143
+ response = requests.get(log_url, timeout=10)
144
+
145
+ if response.status_code == 200:
146
+ logs = response.json()
147
+ return logs
148
+ else:
149
+ st.warning(f"Could not fetch logs from {log_url}. Status: {response.status_code}")
150
+ return []
151
+ except Exception as e:
152
+ st.warning(f"Could not load callback logs: {str(e)}")
153
+ return []
154
+
155
+ def parse_callback_logs(logs):
156
+ """Parse callback logs into a structured format"""
157
+ parsed_logs = []
158
+
159
+ for log in logs:
160
+ # Handle both old and new format
161
+ callback_data = log.get('callback_data') or log.get('data_received') or {}
162
+
163
+ # Extract data with fallbacks for different formats
164
+ code = callback_data.get('code', 0)
165
+ msg = callback_data.get('msg', '')
166
+ data = callback_data.get('data', {})
167
+
168
+ # Get audio URL (handle both formats)
169
+ audio_url = data.get('audio_wav_url') or data.get('audioWavUrl') or ''
170
+ task_id = data.get('task_id') or data.get('taskId') or ''
171
+
172
+ # Get timestamp
173
+ timestamp = log.get('timestamp', 'Unknown')
174
+
175
+ parsed_logs.append({
176
+ 'timestamp': timestamp,
177
+ 'code': code,
178
+ 'message': msg,
179
+ 'task_id': task_id,
180
+ 'audio_url': audio_url,
181
+ 'raw_data': callback_data
182
+ })
183
+
184
+ return parsed_logs
185
+
186
  # Page configuration
187
  st.set_page_config(
188
  page_title="Suno API Generator",
 
205
  st.session_state.auto_poll = False
206
  if 'suno_api_key' not in st.session_state:
207
  st.session_state.suno_api_key = SUNO_API_KEY
208
+ if 'selected_audio' not in st.session_state:
209
+ st.session_state.selected_audio = None
210
 
211
+ # Title
212
  st.title("🎵 Suno API Audio Generator")
213
 
214
+ # Create tabs
215
+ tab1, tab2 = st.tabs(["🚀 Generate & Poll", "📊 Callback Logs"])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
216
 
217
+ with tab1:
218
+ # Info section
219
+ with st.expander("📋 How it works", expanded=True):
220
+ st.markdown("""
221
+ ### Workflow:
222
+ 1. **Step 1**: Submit task to Suno API → Get `taskId` from response
223
+ 2. **Step 2**: Suno processes audio (async)
224
+ 3. **Step 3**: Suno sends callback to: `https://1hit.no/wav/cb.php`
225
+ 4. **Step 4**: Check callback logs in the 📊 Callback Logs tab
226
+ 5. **Step 5**: OR use Poll button to check status via API
227
 
228
+ ### Polling Endpoint:
229
+ ```javascript
230
+ fetch('https://api.sunoapi.org/api/v1/wav/record-info', {
231
+ method: 'GET',
232
+ headers: {
233
+ 'Authorization': 'Bearer YOUR_TOKEN'
234
+ }
235
+ })
236
+ ```
237
+ """)
238
+
239
+ col1, col2 = st.columns([2, 1])
240
+
241
+ with col1:
242
+ st.header("🚀 Step 1: Submit to Suno API")
243
 
244
+ # Form inputs
245
+ task_id = st.text_input("Task ID", value="5c79****be8e", help="Enter your Suno task ID", key="input_task_id")
246
+ audio_id = st.text_input("Audio ID", value="e231****-****-****-****-****8cadc7dc", help="Enter your Suno audio ID", key="input_audio_id")
247
 
248
+ if st.button("🎵 Generate Audio", type="primary", use_container_width=True, key="generate_btn"):
249
+ if not SUNO_API_KEY:
250
+ st.error(" SunoKey not configured in Hugging Face secrets")
251
+ st.info("Add `SunoKey` secret in Hugging Face Space settings")
252
+ st.stop()
253
 
254
+ if not task_id or not audio_id:
255
+ st.error("❌ Please enter both Task ID and Audio ID")
256
+ st.stop()
257
 
258
+ with st.spinner("Sending request to Suno API..."):
259
+ headers = {
260
+ "Authorization": f"Bearer {SUNO_API_KEY}",
261
+ "Content-Type": "application/json"
262
+ }
 
 
 
 
 
 
 
 
 
 
263
 
264
+ payload = {
265
+ "taskId": task_id,
266
+ "audioId": audio_id,
267
+ "callBackUrl": CALLBACK_URL
268
+ }
269
+
270
+ try:
271
+ response = requests.post(
272
+ "https://api.sunoapi.org/api/v1/wav/generate",
273
+ headers=headers,
274
+ json=payload,
275
+ timeout=30
276
+ )
277
 
278
+ if response.status_code == 200:
279
+ result = response.json()
 
 
280
 
281
+ # Display response
282
+ with st.expander("📋 API Response", expanded=True):
283
+ st.json(result)
284
 
285
+ if result.get("code") == 200 and "data" in result and "taskId" in result["data"]:
286
+ st.session_state.task_id = result["data"]["taskId"]
287
+ st.success(f"✅ Task submitted successfully!")
288
+ st.info(f"**Task ID:** `{st.session_state.task_id}`")
289
+
290
+ # Auto-fill poll input
291
+ st.session_state.poll_task_input = st.session_state.task_id
292
+
293
+ st.markdown("---")
294
+ st.markdown("### 🔄 Next Steps:")
295
+ st.markdown("""
296
+ 1. **Automatic Callback**: Suno will send result to your callback URL
297
+ 2. **Manual Poll**: Use the Poll button to check status
298
+ 3. **View Logs**: Check the 📊 Callback Logs tab
299
+ """)
300
+ else:
301
+ st.error("❌ Unexpected response format")
302
+
303
+ # Debug info
304
+ st.markdown("**Debug Response:**")
305
+ st.code(str(result))
306
  else:
307
+ st.error(f"❌ API Error: {response.status_code}")
308
+ try:
309
+ error_data = response.json()
310
+ st.json(error_data)
311
+ except:
312
+ st.text(f"Response: {response.text}")
313
+
314
+ except requests.exceptions.Timeout:
315
+ st.error("⏰ Request timed out after 30 seconds")
316
+ except requests.exceptions.ConnectionError:
317
+ st.error("🔌 Connection error - check your internet connection")
318
+ except requests.exceptions.RequestException as e:
319
+ st.error(f"⚠️ Request failed: {str(e)}")
 
 
 
 
 
 
320
 
321
+ with col2:
322
+ st.header("🔍 Step 2: Poll Status")
323
+
324
+ # Manual task ID input for polling
325
+ poll_task_id = st.text_input(
326
+ "Task ID to Poll",
327
+ value=st.session_state.get('poll_task_input', st.session_state.task_id or ""),
328
+ help="Enter task ID to check status",
329
+ key="poll_task_input_field"
330
+ )
331
+
332
+ col2a, col2b = st.columns(2)
333
+
334
+ with col2a:
335
+ poll_once_btn = st.button("🔄 Poll Once", type="secondary", use_container_width=True, key="poll_once_btn")
336
+
337
+ with col2b:
338
+ auto_poll_btn = st.button("🔁 Auto Poll (10s)", type="secondary", use_container_width=True, key="auto_poll_btn")
339
 
340
+ # Handle poll button clicks
341
+ if poll_once_btn:
342
+ if not poll_task_id:
343
+ st.error("❌ Please enter a Task ID")
344
+ elif not SUNO_API_KEY:
345
+ st.error("❌ SunoKey not configured")
346
+ else:
347
+ poll_status(poll_task_id, single_poll=True)
348
 
349
+ if auto_poll_btn:
350
+ if not poll_task_id:
351
+ st.error("❌ Please enter a Task ID")
352
+ elif not SUNO_API_KEY:
353
+ st.error("❌ SunoKey not configured")
354
+ else:
355
+ st.session_state.auto_poll = True
356
+ st.session_state.auto_poll_task_id = poll_task_id
357
+ st.rerun()
358
+
359
+ # Display poll results if any
360
+ if st.session_state.poll_results:
361
+ st.markdown("---")
362
+ st.header("📊 Polling History")
363
+
364
+ # Show last 5 results
365
+ recent_results = list(reversed(st.session_state.poll_results[-5:]))
366
+
367
+ for i, result in enumerate(recent_results):
368
+ with st.expander(f"Poll {i+1} - {result['timestamp']} - Task: {result['task_id'][:12]}...", expanded=(i == len(recent_results)-1)):
369
+ response_data = result["response"]
370
+
371
+ if response_data.get("code") == 200:
372
+ data = response_data.get("data", {})
373
+ status = data.get("successFlag", "UNKNOWN")
374
+
375
+ # Status badge
376
+ if status == "SUCCESS":
377
+ st.success(f"✅ {status}")
378
+ elif status == "PROCESSING":
379
+ st.info(f"⏳ {status}")
380
+ elif status == "FAILED":
381
+ st.error(f"❌ {status}")
382
+ else:
383
+ st.warning(f"⚠️ {status}")
384
+
385
+ # Display key info
386
+ cols = st.columns(3)
387
+ with cols[0]:
388
+ st.metric("Task ID", data.get("taskId", "N/A")[:12] + "...")
389
+ with cols[1]:
390
+ st.metric("Music ID", data.get("musicId", "N/A")[:12] + "...")
391
+ with cols[2]:
392
+ st.metric("Status", status)
393
+
394
+ # Show audio if available
395
+ audio_url = data.get("response", {}).get("audioWavUrl")
396
+ if audio_url:
397
+ st.audio(audio_url, format="audio/wav")
398
+ st.markdown(f"**Audio URL:** `{audio_url}`")
399
+
400
+ # Show full response
401
+ with st.expander("📋 Full Response JSON"):
402
+ st.json(response_data)
403
+ else:
404
+ st.error(f"❌ Error: {response_data.get('msg', 'Unknown error')}")
405
+ st.json(response_data)
406
 
407
+ with tab2:
408
+ st.header("📊 Callback Log Viewer")
409
+ st.markdown("View and manage audio files from callback logs")
 
410
 
411
+ # Load callback logs
412
+ with st.spinner("Loading callback logs..."):
413
+ logs = load_callback_logs()
414
+ parsed_logs = parse_callback_logs(logs)
415
 
416
+ if not parsed_logs:
417
+ st.info("📭 No callback logs found. Callbacks will appear here when Suno API sends them.")
418
+ st.markdown(f"**Callback URL:** `{CALLBACK_URL}`")
419
+ else:
420
+ # Display statistics
421
+ total_logs = len(parsed_logs)
422
+ successful_logs = len([log for log in parsed_logs if log['code'] == 200])
423
+ audio_logs = len([log for log in parsed_logs if log['audio_url']])
424
+
425
+ col_stats1, col_stats2, col_stats3 = st.columns(3)
426
+ with col_stats1:
427
+ st.metric("📊 Total Callbacks", total_logs)
428
+ with col_stats2:
429
+ st.metric("✅ Successful", successful_logs)
430
+ with col_stats3:
431
+ st.metric("🎵 Audio Files", audio_logs)
432
+
433
+ # Create a DataFrame for display
434
+ df_data = []
435
+ for log in parsed_logs:
436
+ df_data.append({
437
+ 'Timestamp': log['timestamp'],
438
+ 'Status': '✅ Success' if log['code'] == 200 else '❌ Error',
439
+ 'Task ID': log['task_id'][:12] + '...' if log['task_id'] else 'N/A',
440
+ 'Audio URL': log['audio_url'][:50] + '...' if log['audio_url'] else 'No audio',
441
+ 'Message': log['message'][:50] + '...' if log['message'] else '',
442
+ 'Full Data': log
443
+ })
444
+
445
+ if df_data:
446
+ df = pd.DataFrame(df_data)
447
 
448
+ # Search and filter
449
+ st.markdown("### 🔍 Search & Filter")
450
+ search_term = st.text_input("Search by Task ID or Message:", placeholder="Enter search term...")
451
+
452
+ if search_term:
453
+ filtered_df = df[df.apply(lambda row: search_term.lower() in str(row['Task ID']).lower() or
454
+ search_term.lower() in str(row['Message']).lower(), axis=1)]
455
+ else:
456
+ filtered_df = df
457
+
458
+ # Display table
459
+ st.markdown("### 📋 Callback Logs")
460
+ for idx, row in filtered_df.iterrows():
461
+ with st.expander(f"{row['Timestamp']} - {row['Status']} - Task: {row['Task ID']}", expanded=False):
462
+ col1, col2 = st.columns(2)
463
+
464
+ with col1:
465
+ st.markdown(f"**Task ID:** `{row['Full Data']['task_id']}`")
466
+ st.markdown(f"**Status Code:** {row['Full Data']['code']}")
467
+ st.markdown(f"**Message:** {row['Full Data']['message']}")
468
+
469
+ with col2:
470
+ if row['Full Data']['audio_url']:
471
+ st.markdown("**Audio URL:**")
472
+ st.code(row['Full Data']['audio_url'])
473
+
474
+ # Audio player
475
+ st.audio(row['Full Data']['audio_url'], format="audio/wav")
476
+
477
+ # Download button
478
+ audio_filename = row['Full Data']['audio_url'].split('/')[-1] if '/' in row['Full Data']['audio_url'] else f"audio_{row['Full Data']['task_id']}.wav"
479
+ st.download_button(
480
+ label="⬇ Download WAV",
481
+ data=requests.get(row['Full Data']['audio_url']).content if row['Full Data']['audio_url'].startswith("http") else b"",
482
+ file_name=audio_filename,
483
+ mime="audio/wav",
484
+ key=f"download_callback_{idx}"
485
+ )
486
+ else:
487
+ st.info("No audio URL available")
488
+
489
+ # Show full JSON data
490
+ with st.expander("📋 View Full JSON"):
491
+ st.json(row['Full Data']['raw_data'])
492
+
493
+ # Audio player for selected file
494
+ st.markdown("---")
495
+ st.markdown("### 🔊 Audio Player")
496
+
497
+ # Create a dropdown of available audio files
498
+ audio_files = [log for log in parsed_logs if log['audio_url']]
499
+
500
+ if audio_files:
501
+ audio_options = [f"{log['timestamp']} - {log['task_id'][:12]}..." for log in audio_files]
502
+ selected_index = st.selectbox(
503
+ "Select audio to play:",
504
+ range(len(audio_options)),
505
+ format_func=lambda x: audio_options[x]
506
+ )
507
 
508
+ if selected_index is not None:
509
+ selected_audio = audio_files[selected_index]
510
+ st.session_state.selected_audio = selected_audio
511
+
512
+ st.markdown(f"**Selected:** {selected_audio['timestamp']} - Task: `{selected_audio['task_id']}`")
513
+ st.audio(selected_audio['audio_url'], format="audio/wav")
514
+
515
+ # Download button for selected audio
516
+ audio_filename = selected_audio['audio_url'].split('/')[-1] if '/' in selected_audio['audio_url'] else f"audio_{selected_audio['task_id']}.wav"
517
+ st.download_button(
518
+ label=f"⬇ Download {audio_filename}",
519
+ data=requests.get(selected_audio['audio_url']).content if selected_audio['audio_url'].startswith("http") else b"",
520
+ file_name=audio_filename,
521
+ mime="audio/wav",
522
+ key="download_selected_audio"
523
+ )
524
  else:
525
+ st.info("No audio files available in callback logs")
526
+
527
+ # Refresh button
528
+ if st.button("🔄 Refresh Logs", key="refresh_logs"):
529
+ st.rerun()
530
 
531
  # Quick links and info
532
+ st.sidebar.markdown("---")
533
+ st.sidebar.markdown("### 📝 Quick Links")
534
+ st.sidebar.markdown(f"""
535
+ - 🔗 [Callback Logs]({CALLBACK_URL.replace('cb.php', 'view.php')})
536
+ - 📚 [Suno API Docs](https://docs.sunoapi.org/)
537
+ - 🔄 **Poll Endpoint**: `GET /api/v1/wav/record-info`
538
  """)
539
 
540
  # Secret status
541
+ with st.sidebar.expander("🔐 Secret Status", expanded=False):
542
  if SUNO_API_KEY:
543
  masked_key = f"{SUNO_API_KEY[:8]}...{SUNO_API_KEY[-8:]}" if len(SUNO_API_KEY) > 16 else "••••••••"
544
  st.success(f"✅ SunoKey loaded ({len(SUNO_API_KEY)} chars)")
 
546
  else:
547
  st.error("❌ SunoKey not found")
548
 
549
+ st.info(f"**Callback URL:** `{CALLBACK_URL}`")
550
+
551
+ # Auto-polling logic
552
+ if st.session_state.get('auto_poll') and st.session_state.get('auto_poll_task_id'):
553
+ task_id = st.session_state.auto_poll_task_id
554
+
555
+ # Create a placeholder for auto-poll status
556
+ poll_placeholder = st.empty()
557
+
558
+ with poll_placeholder.container():
559
+ st.info(f"🔁 Auto-polling task: `{task_id[:12]}...` (every 10 seconds)")
560
+
561
+ # Poll once
562
+ poll_status(task_id, single_poll=True)
563
+
564
+ # Schedule next poll
565
+ time.sleep(10)
566
+ st.rerun()