Spaces:
Paused
Paused
Update app.py
Browse files123445671 unmodified line91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556121314585960611516176318196520212267682324252627707128293031323334747535363738397980404142434445464748495051828384855253545556575859606162636465666768697071727374757677787980818283848586878889878889909192939495969798991001011021039192931041051061071089596979899100101109110111112113114115116117118119120121122123124103104105106107108109110111112113114115116117118119120125126127128122123124125126127128129130131132129130131132133134135136137138139140141142143144145146135136137138139140147148149150151152153154155156157158159142160161144145146162163164165166167168169170171148172173150151152153154155156174175import gradio as grimport requestsimport osimport jsonimport timefrom 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 payload post_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)# Simple task storagetasks = {}
def test_correct_workflow(): """Test what SHOULD be the correct workflow based on your code""" results = ["# 🎯 Testing Correct Workflow", ""] def generate_lyrics_simple(prompt): """Simple lyrics generation using correct endpoints""" if not SUNO_KEY: return "❌ No SunoKey configured" return "❌ Error: SunoKey not configured" headers = {"Authorization": f"Bearer {SUNO_KEY}"} if not prompt.strip(): return "❌ Please enter a prompt" # Step 1: Submit lyrics (as per your original working code) results.append("## 1️⃣ Submit Lyrics") # Generate simple task ID for our tracking task_id = str(int(time.time()))[-6:] # Submit to Suno API submit_url = "https://api.sunoapi.org/api/v1/lyrics" submit_headers = headers.copy() submit_headers["Content-Type"] = "application/json" headers = { "Authorization": f"Bearer {SUNO_KEY}", "Content-Type": "application/json" } # Use a dummy callback URL (required by API) payload = { "prompt": "Correct workflow test song", "callBackUrl": "http://correct-test.com/callback" "prompt": prompt, "callBackUrl": "http://dummy.callback/not-used" } try: response = requests.post(submit_url, json=payload, headers=submit_headers, timeout=30) results.append(f"**Status:** {response.status_code}") # Step 1: Submit the task print(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')}" if response.status_code == 200: data = response.json() results.append(f"**Code:** {data.get('code')}") results.append(f"**Message:** {data.get('msg', 'No message')}") # Get Suno's task ID suno_task_id = data["data"]["taskId"] print(f"✅ Submitted! Suno Task ID: {suno_task_id}") # Store task tasks[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 endpoint time.sleep(2) # Give it a moment # Step 3: Poll using the CORRECT endpoint return 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-info poll_url = f"https://api.sunoapi.org/api/v1/lyrics/record-info" for attempt in range(max_attempts): try: # Try different parameter names params_list = [ {"taskId": suno_task_id}, {"id": suno_task_id}, {"record_id": suno_task_id}, ] if data.get("code") == 200 and "data" in data: task_id = data["data"]["taskId"] results.append(f"**Task ID:** `{task_id}`") response_data = None for 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: break except: continue if response_data and response_data.get("code") == 200: task_info = response_data["data"] # 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" # Update status (might be in different field names) status = task_info.get("status") or task_info.get("state") or "unknown" tasks[task_id]["status"] = status tasks[task_id]["checks"] = attempt + 1 # Try different query parameters test_params = [ {"taskId": task_id}, {"id": task_id}, {"record_id": task_id}, {}, # No params ] # Check if completed if status == "completed": # Try to get lyrics from different possible field names lyrics = ( task_info.get("lyrics") or task_info.get("data") or task_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" 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)}") elif status == "failed": error = task_info.get("error", "Unknown error") return f"❌ Task failed: {error}" # Step 3: Also try details endpoint for comparison results.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)}") elif status == "processing": # Still processing elapsed = int((datetime.now() - tasks[task_id]["start_time"]).total_seconds()) if attempt < max_attempts - 1: time.sleep(5) # Wait 5 seconds before next check continue else: return f"⏳ Still processing after {elapsed} seconds. Try checking again later." else: # submitted or unknown elapsed = int((datetime.now() - tasks[task_id]["start_time"]).total_seconds()) if attempt < max_attempts - 1: time.sleep(5) continue else: return f"📥 Still submitted after {elapsed} seconds. Suno API might be slow." 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)}") # If we can't get status, show what we got if 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) continue else: return f"⚠️ Error checking status: {str(e)}" return "\n".join(results) return "⏰ Timeout after multiple attempts"
def check_api_documentation(): """Show what we know about Suno API""" return """# 📚 Suno API Documentationdef format_success(lyrics_data, task_id, elapsed_time): """Format successful lyrics""" # Handle different data structures if isinstance(lyrics_data, dict): # If it's a dict, try to extract lyrics lyrics_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})
## 🔍 What We Know:**Generated in:** {elapsed_time} seconds
### **Endpoints Found:**1. `POST /api/v1/lyrics` - Submit lyrics generation ```json { "prompt": "song about...", "callBackUrl": "https://your-webhook.com/callback" }```text{lyrics_text}app.py+143-124