MySafeCode commited on
Commit
5fc6da1
·
verified ·
1 Parent(s): f474f86

Create napp.py

Browse files
Files changed (1) hide show
  1. napp.py +565 -0
napp.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
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):
12
+ """Poll Suno API for task status including task ID"""
13
+ if not task_id:
14
+ st.error("❌ Task ID cannot be empty")
15
+ return False
16
+
17
+ headers = {
18
+ "Authorization": f"Bearer {st.session_state.suno_api_key}",
19
+ "Content-Type": "application/json"
20
+ }
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,
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
+ # 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", {})
65
+
66
+ if data.get("successFlag") == "SUCCESS":
67
+ # Audio is ready!
68
+ audio_url = data.get("response", {}).get("audioWavUrl")
69
+ if audio_url:
70
+ st.success("✅ Audio ready!")
71
+ st.balloons()
72
+
73
+ # Display audio info
74
+ st.markdown("### 🎵 Audio Information")
75
+ cols = st.columns(2)
76
+ with cols[0]:
77
+ st.metric("Task ID", data.get("taskId", "N/A")[:12] + "...")
78
+ st.metric("Music ID", data.get("musicId", "N/A")[:12] + "...")
79
+ with cols[1]:
80
+ st.metric("Status", data.get("successFlag", "N/A"))
81
+ st.metric("Created", data.get("createTime", "N/A"))
82
+
83
+ # Audio player
84
+ st.markdown("### 🔊 Listen")
85
+ st.audio(audio_url, format="audio/wav")
86
+
87
+ # Download section
88
+ st.markdown("### 📥 Download")
89
+ st.code(audio_url)
90
+
91
+ col_dl1, col_dl2 = st.columns(2)
92
+ with col_dl1:
93
+ st.download_button(
94
+ label="⬇ Download WAV",
95
+ data=requests.get(audio_url).content if audio_url.startswith("http") else b"",
96
+ file_name=f"audio_{data.get('taskId', 'unknown')[:8]}.wav",
97
+ mime="audio/wav",
98
+ key=f"download_{task_id}"
99
+ )
100
+ with col_dl2:
101
+ if st.button("📋 Copy URL", key=f"copy_{task_id}"):
102
+ st.code(audio_url)
103
+ st.success("URL copied to clipboard!")
104
+
105
+ # Stop auto-polling if active
106
+ if st.session_state.get('auto_poll'):
107
+ st.session_state.auto_poll = False
108
+ st.success("✅ Auto-polling stopped (audio ready)")
109
+ else:
110
+ st.info("⏳ Audio still processing...")
111
+ st.json(data)
112
+ else:
113
+ # Still processing or error
114
+ status = data.get("successFlag", "UNKNOWN")
115
+ if status == "PROCESSING":
116
+ st.info(f"⏳ Processing... ({status})")
117
+ elif status == "FAILED":
118
+ st.error(f"❌ Processing failed: {data.get('errorMessage', 'Unknown error')}")
119
+ else:
120
+ st.info(f"ℹ️ Status: {status}")
121
+
122
+ # Show progress info
123
+ st.json(data)
124
+ else:
125
+ st.error(f"❌ API Error: {result.get('msg', 'Unknown error')}")
126
+ st.json(result)
127
+ else:
128
+ st.error(f"❌ Status check failed: {response.status_code}")
129
+ try:
130
+ error_data = response.json()
131
+ st.json(error_data)
132
+ except:
133
+ st.text(f"Response: {response.text}")
134
+
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",
189
+ page_icon="🎵",
190
+ layout="wide"
191
+ )
192
+
193
+ # Load YOUR secret names
194
+ SUNO_API_KEY = st.secrets.get("SunoKey", "")
195
+ CALLBACK_URL = "https://1hit.no/wav/cb.php"
196
+
197
+ # Initialize session state
198
+ if 'task_id' not in st.session_state:
199
+ st.session_state.task_id = None
200
+ if 'polling' not in st.session_state:
201
+ st.session_state.polling = False
202
+ if 'poll_results' not in st.session_state:
203
+ st.session_state.poll_results = []
204
+ if 'auto_poll' not in st.session_state:
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)")
544
+ st.code(f"SunoKey: {masked_key}")
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()