MySafeCode's picture
Rename app.py to a.py
3efa312 verified
raw
history blame
6.28 kB
import streamlit as st
import json
import requests
from datetime import datetime
# Page configuration
st.set_page_config(
page_title="Suno API Generator",
page_icon="🎵",
layout="centered"
)
# Title
st.title("🎵 Suno API Audio Generator")
# Load secrets from Hugging Face Space - using YOUR exact secret names
SUNO_API_KEY = st.secrets.get("SunoKey", "")
CALLBACK_URL = st.secrets.get("CallbackURL", "")
# Debug: Show what secrets were found
st.write("### 🔍 Debug Info")
st.write(f"Secrets found: {list(st.secrets.keys())}")
st.write(f"SunoKey loaded: {'✅ Yes' if SUNO_API_KEY else '❌ No'}")
st.write(f"CallbackURL loaded: {'✅ Yes' if CALLBACK_URL else '❌ No'}")
# Show secret status
if SUNO_API_KEY and CALLBACK_URL:
st.success("✅ Secrets loaded successfully from Hugging Face!")
st.info(f"Loaded **SunoKey** and **CallbackURL** secrets")
else:
st.error("❌ Secrets not loaded correctly")
st.info("""
**Make sure you've added these secrets in Hugging Face Space:**
1. Go to **Settings** → **Repository secrets**
2. Add:
- **Key:** `SunoKey` (exact name)
- **Value:** Your Suno API Bearer token
3. Add:
- **Key:** `CallbackURL` (exact name)
- **Value:** Your callback URL
""")
# API Form
st.markdown("---")
st.markdown("### 🎛️ API Parameters")
task_id = st.text_input("Task ID", value="5c79****be8e")
audio_id = st.text_input("Audio ID", value="e231****-****-****-****-****8cadc7dc")
# Make API call button
if st.button("🎵 Generate Audio", type="primary", use_container_width=True):
if not SUNO_API_KEY or not CALLBACK_URL:
st.error("❌ Please configure SunoKey and CallbackURL in Hugging Face Space settings")
elif not task_id or not audio_id:
st.error("❌ Please enter both Task ID and Audio ID")
else:
with st.spinner("Making API call to Suno..."):
try:
# Prepare the API call using YOUR secrets
headers = {
"Authorization": f"Bearer {SUNO_API_KEY}",
"Content-Type": "application/json"
}
data = {
"taskId": task_id,
"audioId": audio_id,
"callBackUrl": CALLBACK_URL
}
# Show what we're sending
with st.expander("📡 Request Details", expanded=True):
st.code(f"""
POST https://api.sunoapi.org/api/v1/wav/generate
Headers:
{{
"Authorization": "Bearer {SUNO_API_KEY[:10]}...{SUNO_API_KEY[-10:] if len(SUNO_API_KEY) > 20 else '***'}",
"Content-Type": "application/json"
}}
Body:
{json.dumps(data, indent=2)}
""")
# Make the actual API call
response = requests.post(
"https://api.sunoapi.org/api/v1/wav/generate",
headers=headers,
json=data,
timeout=30
)
# Check response
if response.status_code == 200:
result = response.json()
st.success(f"✅ Success! Status: {response.status_code}")
# Display response
st.markdown("### 📋 API Response")
st.json(result)
# Download button
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
st.download_button(
label="📥 Download JSON Response",
data=json.dumps(result, indent=2),
file_name=f"suno_response_{timestamp}.json",
mime="application/json"
)
# Show useful info
if "jobId" in result:
st.info(f"**Job ID:** `{result['jobId']}`")
if "message" in result:
st.info(f"**Message:** {result['message']}")
else:
st.error(f"❌ API Error: {response.status_code}")
try:
error_details = response.json()
st.json(error_details)
except:
st.text(f"Response: {response.text}")
except requests.exceptions.Timeout:
st.error("⏰ Request timed out after 30 seconds")
except requests.exceptions.ConnectionError:
st.error("🔌 Connection error - check your internet connection")
except requests.exceptions.RequestException as e:
st.error(f"⚠️ Request failed: {str(e)}")
except Exception as e:
st.error(f"❌ Unexpected error: {str(e)}")
# Secret info section
st.markdown("---")
with st.expander("🔐 Secret Information"):
if SUNO_API_KEY:
# Show masked key
key_length = len(SUNO_API_KEY)
if key_length > 20:
masked = f"{SUNO_API_KEY[:10]}...{SUNO_API_KEY[-10:]}"
elif key_length > 8:
masked = f"{SUNO_API_KEY[:4]}...{SUNO_API_KEY[-4:]}"
else:
masked = "••••••••"
st.write(f"**SunoKey (API Key):** `{masked}`")
st.write(f"**Key Length:** {key_length} characters")
else:
st.write("**SunoKey:** Not loaded")
if CALLBACK_URL:
st.write(f"**CallbackURL:** `{CALLBACK_URL}`")
else:
st.write("**CallbackURL:** Not loaded")
st.write("---")
st.write("**Note:** Secrets are securely loaded from Hugging Face Space settings.")
# Instructions
st.markdown("---")
st.markdown("### 📝 How to Use")
st.markdown("""
1. **Configure Secrets** in Hugging Face Space settings:
- Add `SunoKey` with your API Bearer token
- Add `CallbackURL` with your callback endpoint
2. **Enter API Parameters**:
- Task ID from your Suno account
- Audio ID from your Suno account
3. **Click "Generate Audio"** to make the API call
4. **View Response** and download the JSON result
""")