MySafeCode commited on
Commit
a7a2def
·
verified ·
1 Parent(s): 6994f95

Update app.py

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