Spaces:
Running
Running
Upload 8 files
Browse files- .gitattributes +35 -35
- README.md +11 -12
- app.py +524 -0
- index.html +398 -0
- napp.py +565 -0
- requirements.txt +3 -0
- script.js +68 -0
- style.css +28 -0
.gitattributes
CHANGED
|
@@ -1,35 +1,35 @@
|
|
| 1 |
-
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
-
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
-
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
-
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
-
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
-
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
-
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
-
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
-
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
-
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
-
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
-
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
-
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
-
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
-
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
-
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
-
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
-
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
-
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
-
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
-
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
-
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
-
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
-
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
-
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
-
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
-
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
-
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
-
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
-
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
-
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
-
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
-
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
-
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
-
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
README.md
CHANGED
|
@@ -1,12 +1,11 @@
|
|
| 1 |
-
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo: red
|
| 6 |
-
sdk:
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Getwavefromsuno
|
| 3 |
+
emoji: 🏆
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: red
|
| 6 |
+
sdk: streamlit
|
| 7 |
+
pinned: true
|
| 8 |
+
sdk_version: 1.53.0
|
| 9 |
+
---
|
| 10 |
+
|
| 11 |
+
Check out the configuration reference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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 448 |
+
|
| 449 |
+
# Display table
|
| 450 |
+
|
| 451 |
+
# Audio player for selected file
|
| 452 |
+
st.markdown("---")
|
| 453 |
+
st.markdown("### 🔊 Audio Player")
|
| 454 |
+
|
| 455 |
+
# Create a dropdown of available audio files
|
| 456 |
+
audio_files = [log for log in parsed_logs if log['audio_url']]
|
| 457 |
+
|
| 458 |
+
if audio_files:
|
| 459 |
+
audio_options = [f"{log['timestamp']} - {log['task_id'][:12]}..." for log in audio_files]
|
| 460 |
+
selected_index = st.selectbox(
|
| 461 |
+
"Select audio to play:",
|
| 462 |
+
range(len(audio_options)),
|
| 463 |
+
format_func=lambda x: audio_options[x]
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
if selected_index is not None:
|
| 467 |
+
selected_audio = audio_files[selected_index]
|
| 468 |
+
st.session_state.selected_audio = selected_audio
|
| 469 |
+
|
| 470 |
+
st.markdown(f"**Selected:** {selected_audio['timestamp']} - Task: `{selected_audio['task_id']}`")
|
| 471 |
+
st.audio(selected_audio['audio_url'], format="audio/wav")
|
| 472 |
+
|
| 473 |
+
# Download button for selected audio
|
| 474 |
+
audio_filename = selected_audio['audio_url'].split('/')[-1] if '/' in selected_audio['audio_url'] else f"audio_{selected_audio['task_id']}.wav"
|
| 475 |
+
st.download_button(
|
| 476 |
+
label=f"⬇ Download {audio_filename}",
|
| 477 |
+
data=requests.get(selected_audio['audio_url']).content if selected_audio['audio_url'].startswith("http") else b"",
|
| 478 |
+
file_name=audio_filename,
|
| 479 |
+
mime="audio/wav",
|
| 480 |
+
key="download_selected_audio"
|
| 481 |
+
)
|
| 482 |
+
else:
|
| 483 |
+
st.info("No audio files available in callback logs")
|
| 484 |
+
|
| 485 |
+
# Refresh button
|
| 486 |
+
if st.button("🔄 Refresh Logs", key="refresh_logs"):
|
| 487 |
+
st.rerun()
|
| 488 |
+
|
| 489 |
+
# Quick links and info
|
| 490 |
+
st.sidebar.markdown("---")
|
| 491 |
+
st.sidebar.markdown("### 📝 Quick Links")
|
| 492 |
+
st.sidebar.markdown(f"""
|
| 493 |
+
- 🔗 [Callback Logs]({CALLBACK_URL.replace('cb.php', 'view.php')})
|
| 494 |
+
- 📚 [Suno API Docs](https://docs.sunoapi.org/)
|
| 495 |
+
- 🔄 **Poll Endpoint**: `GET /api/v1/wav/record-info`
|
| 496 |
+
""")
|
| 497 |
+
|
| 498 |
+
# Secret status
|
| 499 |
+
with st.sidebar.expander("🔐 Secret Status", expanded=False):
|
| 500 |
+
if SUNO_API_KEY:
|
| 501 |
+
masked_key = f"{SUNO_API_KEY[:8]}...{SUNO_API_KEY[-8:]}" if len(SUNO_API_KEY) > 16 else "••••••••"
|
| 502 |
+
st.success(f"✅ SunoKey loaded ({len(SUNO_API_KEY)} chars)")
|
| 503 |
+
st.code(f"SunoKey: {masked_key}")
|
| 504 |
+
else:
|
| 505 |
+
st.error("❌ SunoKey not found")
|
| 506 |
+
|
| 507 |
+
st.info(f"**Callback URL:** `{CALLBACK_URL}`")
|
| 508 |
+
|
| 509 |
+
# Auto-polling logic
|
| 510 |
+
if st.session_state.get('auto_poll') and st.session_state.get('auto_poll_task_id'):
|
| 511 |
+
task_id = st.session_state.auto_poll_task_id
|
| 512 |
+
|
| 513 |
+
# Create a placeholder for auto-poll status
|
| 514 |
+
poll_placeholder = st.empty()
|
| 515 |
+
|
| 516 |
+
with poll_placeholder.container():
|
| 517 |
+
st.info(f"🔁 Auto-polling task: `{task_id[:12]}...` (every 10 seconds)")
|
| 518 |
+
|
| 519 |
+
# Poll once
|
| 520 |
+
poll_status(task_id, single_poll=True)
|
| 521 |
+
|
| 522 |
+
# Schedule next poll
|
| 523 |
+
time.sleep(10)
|
| 524 |
+
st.rerun()
|
index.html
ADDED
|
@@ -0,0 +1,398 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
<meta charset="UTF-8">
|
| 6 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 7 |
+
<meta name="description" content="Suno API Audio Generator with Hugging Face Secrets">
|
| 8 |
+
<title>🎵 Suno AI Audio Generator</title>
|
| 9 |
+
|
| 10 |
+
<!-- Tailwind CSS for styling -->
|
| 11 |
+
<script src="https://cdn.tailwindcss.com"></script>
|
| 12 |
+
|
| 13 |
+
<style>
|
| 14 |
+
body {
|
| 15 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 16 |
+
min-height: 100vh;
|
| 17 |
+
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
.gradient-bg {
|
| 21 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
.card {
|
| 25 |
+
background: rgba(255, 255, 255, 0.95);
|
| 26 |
+
backdrop-filter: blur(10px);
|
| 27 |
+
border: 1px solid rgba(255, 255, 255, 0.2);
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
.input-field {
|
| 31 |
+
transition: all 0.3s ease;
|
| 32 |
+
border: 2px solid #e5e7eb;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
.input-field:focus {
|
| 36 |
+
border-color: #667eea;
|
| 37 |
+
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
.btn-primary {
|
| 41 |
+
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
|
| 42 |
+
transition: all 0.3s ease;
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
.btn-primary:hover {
|
| 46 |
+
transform: translateY(-2px);
|
| 47 |
+
box-shadow: 0 10px 25px rgba(102, 126, 234, 0.4);
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
.btn-primary:disabled {
|
| 51 |
+
opacity: 0.6;
|
| 52 |
+
cursor: not-allowed;
|
| 53 |
+
transform: none;
|
| 54 |
+
box-shadow: none;
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
.spinner {
|
| 58 |
+
border: 3px solid #f3f3f3;
|
| 59 |
+
border-top: 3px solid #667eea;
|
| 60 |
+
border-radius: 50%;
|
| 61 |
+
width: 24px;
|
| 62 |
+
height: 24px;
|
| 63 |
+
animation: spin 1s linear infinite;
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
@keyframes spin {
|
| 67 |
+
0% { transform: rotate(0deg); }
|
| 68 |
+
100% { transform: rotate(360deg); }
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
.copy-btn {
|
| 72 |
+
transition: all 0.2s ease;
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
.copy-btn:hover {
|
| 76 |
+
background-color: #f3f4f6;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
.copy-btn.copied {
|
| 80 |
+
background-color: #10b981 !important;
|
| 81 |
+
color: white;
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
pre {
|
| 85 |
+
white-space: pre-wrap;
|
| 86 |
+
word-wrap: break-word;
|
| 87 |
+
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
| 88 |
+
font-size: 14px;
|
| 89 |
+
}
|
| 90 |
+
</style>
|
| 91 |
+
</head>
|
| 92 |
+
<body class="flex items-center justify-center min-h-screen p-4">
|
| 93 |
+
<div class="card rounded-2xl shadow-2xl w-full max-w-2xl p-8">
|
| 94 |
+
<!-- Header -->
|
| 95 |
+
<div class="text-center mb-8">
|
| 96 |
+
<h1 class="text-3xl font-bold bg-gradient-to-r from-purple-600 to-blue-600 bg-clip-text text-transparent mb-2">
|
| 97 |
+
🎵 Suno AI Audio Generator
|
| 98 |
+
</h1>
|
| 99 |
+
<p class="text-gray-600">
|
| 100 |
+
Generate audio using Suno API with secure secret management
|
| 101 |
+
</p>
|
| 102 |
+
<div class="mt-2">
|
| 103 |
+
<span id="configStatus" class="inline-flex items-center px-3 py-1 rounded-full text-xs font-medium">
|
| 104 |
+
<span class="w-2 h-2 rounded-full bg-yellow-500 mr-2"></span>
|
| 105 |
+
Loading configuration...
|
| 106 |
+
</span>
|
| 107 |
+
</div>
|
| 108 |
+
</div>
|
| 109 |
+
|
| 110 |
+
<!-- Configuration Section -->
|
| 111 |
+
<div id="configSection" class="mb-6 p-4 bg-blue-50 rounded-lg border border-blue-200 hidden">
|
| 112 |
+
<h3 class="font-semibold text-blue-800 mb-2">🔒 Configuration Status</h3>
|
| 113 |
+
<div class="space-y-2">
|
| 114 |
+
<div class="flex items-center">
|
| 115 |
+
<span id="apiKeyStatus" class="text-sm">API Key: <span class="font-mono">Loading...</span></span>
|
| 116 |
+
<button onclick="copyToClipboard('apiKey')"
|
| 117 |
+
class="copy-btn ml-2 px-2 py-1 text-xs bg-gray-100 rounded hover:bg-gray-200">
|
| 118 |
+
Copy
|
| 119 |
+
</button>
|
| 120 |
+
</div>
|
| 121 |
+
<div class="flex items-center">
|
| 122 |
+
<span id="callbackStatus" class="text-sm">Callback URL: <span class="font-mono">Loading...</span></span>
|
| 123 |
+
<button onclick="copyToClipboard('callbackUrl')"
|
| 124 |
+
class="copy-btn ml-2 px-2 py-1 text-xs bg-gray-100 rounded hover:bg-gray-200">
|
| 125 |
+
Copy
|
| 126 |
+
</button>
|
| 127 |
+
</div>
|
| 128 |
+
</div>
|
| 129 |
+
</div>
|
| 130 |
+
|
| 131 |
+
<!-- Form Section -->
|
| 132 |
+
<div class="space-y-6">
|
| 133 |
+
<div>
|
| 134 |
+
<label for="taskId" class="block text-sm font-medium text-gray-700 mb-2">
|
| 135 |
+
Task ID
|
| 136 |
+
</label>
|
| 137 |
+
<input type="text"
|
| 138 |
+
id="taskId"
|
| 139 |
+
placeholder="5c79****be8e"
|
| 140 |
+
value="5c79****be8e"
|
| 141 |
+
class="input-field w-full px-4 py-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
|
| 142 |
+
<p class="text-xs text-gray-500 mt-1">Enter your Suno API task ID</p>
|
| 143 |
+
</div>
|
| 144 |
+
|
| 145 |
+
<div>
|
| 146 |
+
<label for="audioId" class="block text-sm font-medium text-gray-700 mb-2">
|
| 147 |
+
Audio ID
|
| 148 |
+
</label>
|
| 149 |
+
<input type="text"
|
| 150 |
+
id="audioId"
|
| 151 |
+
placeholder="e231****-****-****-****-****8cadc7dc"
|
| 152 |
+
value="e231****-****-****-****-****8cadc7dc"
|
| 153 |
+
class="input-field w-full px-4 py-3 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
|
| 154 |
+
<p class="text-xs text-gray-500 mt-1">Enter your Suno API audio ID</p>
|
| 155 |
+
</div>
|
| 156 |
+
|
| 157 |
+
<!-- Generate Button -->
|
| 158 |
+
<button id="generateBtn"
|
| 159 |
+
onclick="generateAudio()"
|
| 160 |
+
class="btn-primary w-full py-3 rounded-lg text-white font-semibold flex items-center justify-center">
|
| 161 |
+
<span>🎵 Generate Audio</span>
|
| 162 |
+
</button>
|
| 163 |
+
|
| 164 |
+
<!-- Loading Indicator -->
|
| 165 |
+
<div id="loading" class="hidden flex-col items-center justify-center p-4">
|
| 166 |
+
<div class="spinner mb-3"></div>
|
| 167 |
+
<p class="text-gray-600">Generating audio... Please wait</p>
|
| 168 |
+
</div>
|
| 169 |
+
|
| 170 |
+
<!-- Status Messages -->
|
| 171 |
+
<div id="status" class="hidden p-4 rounded-lg"></div>
|
| 172 |
+
|
| 173 |
+
<!-- Result Section -->
|
| 174 |
+
<div id="result" class="hidden">
|
| 175 |
+
<h3 class="font-semibold text-gray-700 mb-3">📋 Response:</h3>
|
| 176 |
+
<div class="bg-gray-50 p-4 rounded-lg border border-gray-200">
|
| 177 |
+
<pre id="response" class="text-gray-800"></pre>
|
| 178 |
+
</div>
|
| 179 |
+
<div class="mt-4 flex justify-end">
|
| 180 |
+
<button onclick="copyToClipboard('response')"
|
| 181 |
+
class="copy-btn px-4 py-2 bg-gray-100 rounded-lg hover:bg-gray-200">
|
| 182 |
+
📋 Copy Response
|
| 183 |
+
</button>
|
| 184 |
+
</div>
|
| 185 |
+
</div>
|
| 186 |
+
</div>
|
| 187 |
+
|
| 188 |
+
<!-- Footer -->
|
| 189 |
+
<div class="mt-8 pt-6 border-t border-gray-200">
|
| 190 |
+
<p class="text-xs text-gray-500 text-center">
|
| 191 |
+
🔒 Secrets are loaded securely from Hugging Face Space environment variables
|
| 192 |
+
<br>
|
| 193 |
+
<span id="envInfo" class="font-mono text-gray-600"></span>
|
| 194 |
+
</p>
|
| 195 |
+
</div>
|
| 196 |
+
</div>
|
| 197 |
+
|
| 198 |
+
<!-- Inline JavaScript for configuration -->
|
| 199 |
+
<script>
|
| 200 |
+
// Configuration object - will be populated from environment
|
| 201 |
+
window.config = {
|
| 202 |
+
apiKey: '',
|
| 203 |
+
callbackUrl: '',
|
| 204 |
+
isConfigured: false,
|
| 205 |
+
envSource: 'Unknown',
|
| 206 |
+
timestamp: new Date().toISOString()
|
| 207 |
+
};
|
| 208 |
+
|
| 209 |
+
// Function to load configuration from multiple sources
|
| 210 |
+
function loadConfiguration() {
|
| 211 |
+
console.log('🔧 Loading configuration...');
|
| 212 |
+
|
| 213 |
+
// Method 1: Try to get from Hugging Face Space environment
|
| 214 |
+
// Note: In Hugging Face Spaces, environment variables might not be directly accessible in browser
|
| 215 |
+
// So we need to use fetch to a backend endpoint or URL parameters
|
| 216 |
+
|
| 217 |
+
// For this example, we'll use URL parameters which can be set in Hugging Face Space settings
|
| 218 |
+
const urlParams = new URLSearchParams(window.location.search);
|
| 219 |
+
|
| 220 |
+
// Method 2: Try URL parameters (set in Hugging Face Space as query string)
|
| 221 |
+
const apiKeyFromUrl = urlParams.get('api_key');
|
| 222 |
+
const callbackUrlFromUrl = urlParams.get('callback_url');
|
| 223 |
+
|
| 224 |
+
// Method 3: Try localStorage (for development/testing)
|
| 225 |
+
const apiKeyFromStorage = localStorage.getItem('suno_api_key');
|
| 226 |
+
const callbackUrlFromStorage = localStorage.getItem('suno_callback_url');
|
| 227 |
+
|
| 228 |
+
// Priority: URL params > localStorage > empty
|
| 229 |
+
if (apiKeyFromUrl && callbackUrlFromUrl) {
|
| 230 |
+
window.config.apiKey = apiKeyFromUrl;
|
| 231 |
+
window.config.callbackUrl = callbackUrlFromUrl;
|
| 232 |
+
window.config.envSource = 'URL Parameters';
|
| 233 |
+
window.config.isConfigured = true;
|
| 234 |
+
} else if (apiKeyFromStorage && callbackUrlFromStorage) {
|
| 235 |
+
window.config.apiKey = apiKeyFromStorage;
|
| 236 |
+
window.config.callbackUrl = callbackUrlFromStorage;
|
| 237 |
+
window.config.envSource = 'Local Storage (Dev Mode)';
|
| 238 |
+
window.config.isConfigured = true;
|
| 239 |
+
} else {
|
| 240 |
+
// Method 4: Try to fetch from a backend endpoint
|
| 241 |
+
fetch('/api/config')
|
| 242 |
+
.then(response => {
|
| 243 |
+
if (response.ok) return response.json();
|
| 244 |
+
throw new Error('No config endpoint');
|
| 245 |
+
})
|
| 246 |
+
.then(data => {
|
| 247 |
+
window.config.apiKey = data.apiKey || '';
|
| 248 |
+
window.config.callbackUrl = data.callbackUrl || '';
|
| 249 |
+
window.config.envSource = 'Backend API';
|
| 250 |
+
window.config.isConfigured = !!window.config.apiKey;
|
| 251 |
+
updateUI();
|
| 252 |
+
})
|
| 253 |
+
.catch(error => {
|
| 254 |
+
console.log('No backend config available');
|
| 255 |
+
// Show configuration form
|
| 256 |
+
showConfigForm();
|
| 257 |
+
});
|
| 258 |
+
}
|
| 259 |
+
|
| 260 |
+
updateUI();
|
| 261 |
+
console.log('Configuration loaded:', window.config);
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// Update UI based on configuration status
|
| 265 |
+
function updateUI() {
|
| 266 |
+
const configStatus = document.getElementById('configStatus');
|
| 267 |
+
const configSection = document.getElementById('configSection');
|
| 268 |
+
const apiKeyStatus = document.getElementById('apiKeyStatus');
|
| 269 |
+
const callbackStatus = document.getElementById('callbackStatus');
|
| 270 |
+
const envInfo = document.getElementById('envInfo');
|
| 271 |
+
|
| 272 |
+
if (window.config.isConfigured) {
|
| 273 |
+
// Show success status
|
| 274 |
+
configStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-green-500 mr-2"></span> Configured';
|
| 275 |
+
configStatus.className = 'inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-green-100 text-green-800';
|
| 276 |
+
|
| 277 |
+
// Update config display
|
| 278 |
+
apiKeyStatus.innerHTML = `API Key: <span class="font-mono">${maskString(window.config.apiKey, 8)}</span>`;
|
| 279 |
+
callbackStatus.innerHTML = `Callback URL: <span class="font-mono">${window.config.callbackUrl}</span>`;
|
| 280 |
+
envInfo.textContent = `Source: ${window.config.envSource}`;
|
| 281 |
+
|
| 282 |
+
// Show config section
|
| 283 |
+
configSection.classList.remove('hidden');
|
| 284 |
+
} else {
|
| 285 |
+
// Show warning status
|
| 286 |
+
configStatus.innerHTML = '<span class="w-2 h-2 rounded-full bg-red-500 mr-2"></span> Not Configured';
|
| 287 |
+
configStatus.className = 'inline-flex items-center px-3 py-1 rounded-full text-xs font-medium bg-red-100 text-red-800';
|
| 288 |
+
envInfo.textContent = 'Please configure secrets in Hugging Face Space settings';
|
| 289 |
+
}
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
// Helper function to mask sensitive strings
|
| 293 |
+
function maskString(str, visibleChars = 4) {
|
| 294 |
+
if (!str || str.length <= visibleChars * 2) return '••••••••';
|
| 295 |
+
const first = str.substring(0, visibleChars);
|
| 296 |
+
const last = str.substring(str.length - visibleChars);
|
| 297 |
+
return `${first}••••${last}`;
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
// Copy to clipboard helper
|
| 301 |
+
function copyToClipboard(elementId) {
|
| 302 |
+
let text = '';
|
| 303 |
+
|
| 304 |
+
if (elementId === 'apiKey') {
|
| 305 |
+
text = window.config.apiKey;
|
| 306 |
+
} else if (elementId === 'callbackUrl') {
|
| 307 |
+
text = window.config.callbackUrl;
|
| 308 |
+
} else if (elementId === 'response') {
|
| 309 |
+
text = document.getElementById('response').textContent;
|
| 310 |
+
}
|
| 311 |
+
|
| 312 |
+
navigator.clipboard.writeText(text).then(() => {
|
| 313 |
+
const btn = event.target;
|
| 314 |
+
const originalText = btn.innerHTML;
|
| 315 |
+
btn.innerHTML = '✅ Copied!';
|
| 316 |
+
btn.classList.add('copied');
|
| 317 |
+
setTimeout(() => {
|
| 318 |
+
btn.innerHTML = originalText;
|
| 319 |
+
btn.classList.remove('copied');
|
| 320 |
+
}, 2000);
|
| 321 |
+
});
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
// Show configuration form (for manual setup)
|
| 325 |
+
function showConfigForm() {
|
| 326 |
+
// Create a modal for manual configuration
|
| 327 |
+
const modal = document.createElement('div');
|
| 328 |
+
modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50';
|
| 329 |
+
modal.innerHTML = `
|
| 330 |
+
<div class="bg-white rounded-xl p-6 max-w-md w-full">
|
| 331 |
+
<h3 class="text-lg font-semibold text-gray-800 mb-4">⚙️ Manual Configuration</h3>
|
| 332 |
+
<p class="text-sm text-gray-600 mb-4">Enter your Suno API credentials:</p>
|
| 333 |
+
|
| 334 |
+
<div class="space-y-4">
|
| 335 |
+
<div>
|
| 336 |
+
<label class="block text-sm font-medium text-gray-700 mb-1">API Key</label>
|
| 337 |
+
<input type="password"
|
| 338 |
+
id="manualApiKey"
|
| 339 |
+
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
| 340 |
+
placeholder="Bearer token...">
|
| 341 |
+
</div>
|
| 342 |
+
<div>
|
| 343 |
+
<label class="block text-sm font-medium text-gray-700 mb-1">Callback URL</label>
|
| 344 |
+
<input type="text"
|
| 345 |
+
id="manualCallbackUrl"
|
| 346 |
+
class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
|
| 347 |
+
placeholder="https://api.example.com/callback">
|
| 348 |
+
</div>
|
| 349 |
+
</div>
|
| 350 |
+
|
| 351 |
+
<div class="flex gap-2 mt-6">
|
| 352 |
+
<button onclick="saveManualConfig()" class="flex-1 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
| 353 |
+
Save
|
| 354 |
+
</button>
|
| 355 |
+
<button onclick="closeModal(this)" class="flex-1 py-2 bg-gray-200 text-gray-800 rounded-lg hover:bg-gray-300">
|
| 356 |
+
Cancel
|
| 357 |
+
</button>
|
| 358 |
+
</div>
|
| 359 |
+
</div>
|
| 360 |
+
`;
|
| 361 |
+
document.body.appendChild(modal);
|
| 362 |
+
}
|
| 363 |
+
|
| 364 |
+
function saveManualConfig() {
|
| 365 |
+
const apiKey = document.getElementById('manualApiKey').value;
|
| 366 |
+
const callbackUrl = document.getElementById('manualCallbackUrl').value;
|
| 367 |
+
|
| 368 |
+
if (apiKey && callbackUrl) {
|
| 369 |
+
// Save to localStorage for development
|
| 370 |
+
localStorage.setItem('suno_api_key', apiKey);
|
| 371 |
+
localStorage.setItem('suno_callback_url', callbackUrl);
|
| 372 |
+
|
| 373 |
+
// Update global config
|
| 374 |
+
window.config.apiKey = apiKey;
|
| 375 |
+
window.config.callbackUrl = callbackUrl;
|
| 376 |
+
window.config.envSource = 'Manual Setup';
|
| 377 |
+
window.config.isConfigured = true;
|
| 378 |
+
|
| 379 |
+
updateUI();
|
| 380 |
+
closeModal();
|
| 381 |
+
} else {
|
| 382 |
+
alert('Please fill in both fields');
|
| 383 |
+
}
|
| 384 |
+
}
|
| 385 |
+
|
| 386 |
+
function closeModal(btn) {
|
| 387 |
+
const modal = btn.closest('.fixed');
|
| 388 |
+
if (modal) modal.remove();
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
// Initialize configuration when page loads
|
| 392 |
+
document.addEventListener('DOMContentLoaded', loadConfiguration);
|
| 393 |
+
</script>
|
| 394 |
+
|
| 395 |
+
<!-- External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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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()
|
requirements.txt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit==1.53.0
|
| 2 |
+
requests>=2.32.0
|
| 3 |
+
python-dotenv>=1.0.0
|
script.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Main function to generate audio
|
| 2 |
+
async function generateAudio() {
|
| 3 |
+
const taskId = document.getElementById('taskId').value.trim();
|
| 4 |
+
const audioId = document.getElementById('audioId').value.trim();
|
| 5 |
+
const generateBtn = document.getElementById('generateBtn');
|
| 6 |
+
const loading = document.getElementById('loading');
|
| 7 |
+
const status = document.getElementById('status');
|
| 8 |
+
const result = document.getElementById('result');
|
| 9 |
+
const response = document.getElementById('response');
|
| 10 |
+
|
| 11 |
+
// Validate inputs
|
| 12 |
+
if (!taskId || !audioId) {
|
| 13 |
+
showStatus('Please fill in both Task ID and Audio ID', 'error');
|
| 14 |
+
return;
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
// Validate API key
|
| 18 |
+
if (!window.config.apiKey || window.config.apiKey === '') {
|
| 19 |
+
showStatus('API Key is not configured. Please set SUNO_API_KEY in Space secrets.', 'error');
|
| 20 |
+
return;
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
// Validate callback URL
|
| 24 |
+
if (!window.config.callbackUrl || window.config.callbackUrl === '') {
|
| 25 |
+
showStatus('Callback URL is not configured. Please set CALLBACK_URL in Space secrets.', 'error');
|
| 26 |
+
return;
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
// Prepare request
|
| 30 |
+
const requestData = {
|
| 31 |
+
taskId: taskId,
|
| 32 |
+
audioId: audioId,
|
| 33 |
+
callBackUrl: window.config.callbackUrl
|
| 34 |
+
};
|
| 35 |
+
|
| 36 |
+
const options = {
|
| 37 |
+
method: 'POST',
|
| 38 |
+
headers: {
|
| 39 |
+
'Authorization': `Bearer ${window.config.apiKey}`,
|
| 40 |
+
'Content-Type': 'application/json'
|
| 41 |
+
},
|
| 42 |
+
body: JSON.stringify(requestData)
|
| 43 |
+
};
|
| 44 |
+
|
| 45 |
+
// Show loading state
|
| 46 |
+
generateBtn.disabled = true;
|
| 47 |
+
loading.classList.add('show');
|
| 48 |
+
status.classList.remove('show', 'success', 'error');
|
| 49 |
+
result.classList.remove('show');
|
| 50 |
+
|
| 51 |
+
try {
|
| 52 |
+
// Make API call
|
| 53 |
+
const apiResponse = await fetch('https://api.sunoapi.org/api/v1/wav/generate', options);
|
| 54 |
+
const data = await apiResponse.json();
|
| 55 |
+
|
| 56 |
+
// Display response
|
| 57 |
+
response.textContent = JSON.stringify(data, null, 2);
|
| 58 |
+
result.classList.add('show');
|
| 59 |
+
|
| 60 |
+
// Show success status
|
| 61 |
+
if (apiResponse.ok) {
|
| 62 |
+
showStatus('✅ Audio generation request sent successfully!', 'success');
|
| 63 |
+
} else {
|
| 64 |
+
showStatus(`❌ Error: ${data.message || 'Unknown error'}`, 'error');
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
} catch (error) {
|
| 68 |
+
// Handle errors
|
style.css
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
body {
|
| 2 |
+
padding: 2rem;
|
| 3 |
+
font-family: -apple-system, BlinkMacSystemFont, "Arial", sans-serif;
|
| 4 |
+
}
|
| 5 |
+
|
| 6 |
+
h1 {
|
| 7 |
+
font-size: 16px;
|
| 8 |
+
margin-top: 0;
|
| 9 |
+
}
|
| 10 |
+
|
| 11 |
+
p {
|
| 12 |
+
color: rgb(107, 114, 128);
|
| 13 |
+
font-size: 15px;
|
| 14 |
+
margin-bottom: 10px;
|
| 15 |
+
margin-top: 5px;
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
.card {
|
| 19 |
+
max-width: 620px;
|
| 20 |
+
margin: 0 auto;
|
| 21 |
+
padding: 16px;
|
| 22 |
+
border: 1px solid lightgray;
|
| 23 |
+
border-radius: 16px;
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
.card p:last-child {
|
| 27 |
+
margin-bottom: 0;
|
| 28 |
+
}
|