Spaces:
Paused
Paused
Update app.py
Browse files12345671 unmodified line9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156import gradio as grimport requestsimport osimport jsonfrom datetime import datetime# Load Suno API key1 unmodified lineif not SUNO_KEY:print("⚠️ Warning: SunoKey environment variable not set!")def test_all_endpoints():"""Test all possible Suno API endpoints to find the right one"""results = ["# 🔍 Testing All Suno API Endpoints", ""]headers = {"Authorization": f"Bearer {SUNO_KEY}"}endpoints = [("GET", "https://api.sunoapi.org/api/v1/lyrics", "Base lyrics endpoint"),("GET", "https://api.sunoapi.org/api/v1/lyrics/record-info", "Record info endpoint"),("GET", "https://api.sunoapi.org/api/v1/lyrics/details", "Details endpoint"),("POST", "https://api.sunoapi.org/api/v1/lyrics", "Submit lyrics"),]for method, url, description in endpoints:results.append(f"\n## 🔗 {method} {url.split('/')[-1]}")results.append(f"**Description:** {description}")try:if method == "GET":response = requests.get(url, headers=headers, timeout=10)else: # POST# Try POST with minimal payloadpost_headers = headers.copy()post_headers["Content-Type"] = "application/json"payload = {"prompt": "Test endpoint","callBackUrl": "http://test.com/callback"}response = requests.post(url, json=payload, headers=post_headers, timeout=10)results.append(f"**HTTP Status:** {response.status_code}")if response.status_code == 200:try:data = response.json()results.append(f"**Response:** ```json\n{json.dumps(data, indent=2)[:500]}...\n```")except:results.append(f"**Response:** {response.text[:200]}...")else:results.append(f"**Error:** {response.text[:200]}...")except Exception as e:results.append(f"**Exception:** {str(e)}")return "\n".join(results)def test_correct_workflow():"""Test what SHOULD be the correct workflow based on your code"""results = ["# 🎯 Testing Correct Workflow", ""]if not SUNO_KEY:return "❌ No SunoKey configured"headers = {"Authorization": f"Bearer {SUNO_KEY}"}# Step 1: Submit lyrics (as per your original working code)results.append("## 1️⃣ Submit Lyrics")submit_url = "https://api.sunoapi.org/api/v1/lyrics"submit_headers = headers.copy()submit_headers["Content-Type"] = "application/json"payload = {"prompt": "Correct workflow test song","callBackUrl": "http://correct-test.com/callback"}try:response = requests.post(submit_url, json=payload, headers=submit_headers, timeout=30)results.append(f"**Status:** {response.status_code}")if response.status_code == 200:data = response.json()results.append(f"**Code:** {data.get('code')}")results.append(f"**Message:** {data.get('msg', 'No message')}")if data.get("code") == 200 and "data" in data:task_id = data["data"]["taskId"]results.append(f"**Task ID:** `{task_id}`")# Step 2: Check using record-info endpoint (from your example)results.append("\n## 2️⃣ Check with /record-info")record_url = "https://api.sunoapi.org/api/v1/lyrics/record-info"# Try different query parameterstest_params = [{"taskId": task_id},{"id": task_id},{"record_id": task_id},{}, # No params]for params in test_params:results.append(f"\n**Trying params:** {params}")try:record_response = requests.get(record_url,headers=headers,params=params,timeout=30)results.append(f"Status: {record_response.status_code}")if record_response.status_code == 200:record_data = record_response.json()results.append(f"Response: ```json\n{json.dumps(record_data, indent=2)[:300]}...\n```")else:results.append(f"Error: {record_response.text[:100]}")except Exception as e:results.append(f"Exception: {str(e)}")# Step 3: Also try details endpoint for comparisonresults.append("\n## 3️⃣ Check with /details (for comparison)")details_url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={task_id}"try:details_response = requests.get(details_url, headers=headers, timeout=30)results.append(f"Status: {details_response.status_code}")if details_response.status_code == 200:details_data = details_response.json()results.append(f"Response: ```json\n{json.dumps(details_data, indent=2)[:300]}...\n```")except Exception as e:results.append(f"Exception: {str(e)}")else:results.append("❌ No task ID in response")else:results.append(f"❌ Submission failed: {response.text[:200]}")except Exception as e:results.append(f"❌ Exception: {str(e)}")return "\n".join(results)def check_api_documentation():"""Show what we know about Suno API"""return """# 📚 Suno API Documentation## 🔍 What We Know:### **Endpoints Found:**1. `POST /api/v1/lyrics` - Submit lyrics generation```json{"prompt": "song about...","callBackUrl": "https://your-webhook.com/callback"}12345671 unmodified line9101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175import gradio as grimport requestsimport osimport timefrom datetime import datetime# Load Suno API key1 unmodified lineif not SUNO_KEY:print("⚠️ Warning: SunoKey environment variable not set!")# Simple task storagetasks = {}def generate_lyrics_simple(prompt):"""Simple lyrics generation using correct endpoints"""if not SUNO_KEY:return "❌ Error: SunoKey not configured"if not prompt.strip():return "❌ Please enter a prompt"# Generate simple task ID for our trackingtask_id = str(int(time.time()))[-6:]# Submit to Suno APIsubmit_url = "https://api.sunoapi.org/api/v1/lyrics"headers = {"Authorization": f"Bearer {SUNO_KEY}","Content-Type": "application/json"}# Use a dummy callback URL (required by API)payload = {"prompt": prompt,"callBackUrl": "http://dummy.callback/not-used"}try:# Step 1: Submit the taskprint(f"📤 Submitting: {prompt[:50]}...")response = requests.post(submit_url, json=payload, headers=headers, timeout=30)if response.status_code != 200:return f"❌ Submission failed: HTTP {response.status_code}"data = response.json()if data.get("code") != 200:return f"❌ API error: {data.get('msg', 'Unknown error')}"# Get Suno's task IDsuno_task_id = data["data"]["taskId"]print(f"✅ Submitted! Suno Task ID: {suno_task_id}")# Store tasktasks[task_id] = {"suno_id": suno_task_id,"prompt": prompt,"status": "submitted","start_time": datetime.now(),"checks": 0}# Step 2: Wait a bit then check using /record-info endpointtime.sleep(2) # Give it a moment# Step 3: Poll using the CORRECT endpointreturn poll_for_results(task_id, suno_task_id)except Exception as e:return f"❌ Error: {str(e)}"def poll_for_results(task_id, suno_task_id, max_attempts=12):"""Poll for results using /record-info endpoint"""headers = {"Authorization": f"Bearer {SUNO_KEY}"}# Use the CORRECT endpoint: /record-infopoll_url = f"https://api.sunoapi.org/api/v1/lyrics/record-info"for attempt in range(max_attempts):try:# Try different parameter namesparams_list = [{"taskId": suno_task_id},{"id": suno_task_id},{"record_id": suno_task_id},]response_data = Nonefor params in params_list:try:response = requests.get(poll_url, headers=headers, params=params, timeout=30)if response.status_code == 200:response_data = response.json()if response_data.get("code") == 200:breakexcept:continueif response_data and response_data.get("code") == 200:task_info = response_data["data"]# Update status (might be in different field names)status = task_info.get("status") or task_info.get("state") or "unknown"tasks[task_id]["status"] = statustasks[task_id]["checks"] = attempt + 1# Check if completedif status == "completed":# Try to get lyrics from different possible field nameslyrics = (task_info.get("lyrics") ortask_info.get("data") ortask_info.get("result") or[])if lyrics:elapsed = int((datetime.now() - tasks[task_id]["start_time"]).total_seconds())return format_success(lyrics, task_id, elapsed)else:return "✅ Completed but no lyrics data found"elif status == "failed":error = task_info.get("error", "Unknown error")return f"❌ Task failed: {error}"elif status == "processing":# Still processingelapsed = int((datetime.now() - tasks[task_id]["start_time"]).total_seconds())if attempt < max_attempts - 1:time.sleep(5) # Wait 5 seconds before next checkcontinueelse:return f"⏳ Still processing after {elapsed} seconds. Try checking again later."else: # submitted or unknownelapsed = int((datetime.now() - tasks[task_id]["start_time"]).total_seconds())if attempt < max_attempts - 1:time.sleep(5)continueelse:return f"📥 Still submitted after {elapsed} seconds. Suno API might be slow."else:# If we can't get status, show what we gotif response_data:return f"⚠️ Status check error: {response_data.get('msg', 'Unknown')}"else:return "⚠️ Could not check status - no response from API"except Exception as e:if attempt < max_attempts - 1:time.sleep(5)continueelse:return f"⚠️ Error checking status: {str(e)}"return "⏰ Timeout after multiple attempts"def format_success(lyrics_data, task_id, elapsed_time):"""Format successful lyrics"""# Handle different data structuresif isinstance(lyrics_data, dict):# If it's a dict, try to extract lyricslyrics_text = lyrics_data.get('text') or lyrics_data.get('lyrics') or str(lyrics_data)title = lyrics_data.get('title', 'Generated Lyrics')output = f"""# 🎵 {title} (Task: {task_id})**Generated in:** {elapsed_time} seconds```text{lyrics_text}
app.py+143-124