Spaces:
Paused
Paused
Upload app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966971 unmodified lineimport requestsimport osimport jsonimport uuidimport timeimport threadingfrom datetime import datetimefrom typing import Dict, Optional# Load Suno API keySUNO_KEY = os.environ.get("SunoKey", "")if not SUNO_KEY:print("⚠️ Warning: SunoKey environment variable not set!")# Debug modeDEBUG = True# Task storage with auto-pollingtasks_db = {}polling_threads = {}def debug_log(message):"""Debug logging"""if DEBUG:timestamp = datetime.now().strftime("%H:%M:%S")print(f"[{timestamp}] {message}")def make_api_request(method, url, **kwargs):"""Make API request with detailed error logging"""try:debug_log(f"Making {method} request to {url}")response = requests.request(method, url, **kwargs)debug_log(f"Response status: {response.status_code}")if DEBUG and len(response.content) < 10000: # Don't log huge responsesdebug_log(f"Response: {response.text[:500]}")return responseexcept Exception as e:debug_log(f"API request error: {str(e)}")raisedef poll_task_status(task_id: str, max_attempts=120, interval=3):"""Background thread to automatically poll task status"""if task_id not in tasks_db:debug_log(f"Task {task_id} not found in DB")returntask = tasks_db[task_id]api_task_id = task["api_task_id"]debug_log(f"Starting auto-polling for task {task_id} (API ID: {api_task_id})")for attempt in range(max_attempts):try:debug_log(f"Poll attempt {attempt + 1} for task {task_id}")# Poll the APIurl = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={api_task_id}"headers = {"Authorization": f"Bearer {SUNO_KEY}"}response = make_api_request("GET", url, headers=headers, timeout=30)data = response.json()if response.status_code == 200 and data.get("code") == 200:task_data = data["data"]status = task_data.get("status", "unknown")debug_log(f"Task {task_id} status: {status}")# Update task statustasks_db[task_id]["status"] = statustasks_db[task_id]["last_checked"] = datetime.now().isoformat()if status == "completed" and "data" in task_data:# Task completed successfullylyrics_data = task_data["data"]tasks_db[task_id]["result"] = lyrics_datatasks_db[task_id]["completed_at"] = datetime.now().isoformat()debug_log(f"✅ Task {task_id} completed successfully!")breakelif status == "failed":error_msg = task_data.get("error", "Unknown error")tasks_db[task_id]["error"] = error_msgtasks_db[task_id]["completed_at"] = datetime.now().isoformat()debug_log(f"❌ Task {task_id} failed: {error_msg}")breakelif status == "processing":debug_log(f"🔄 Task {task_id} is processing...")else:debug_log(f"📊 Task {task_id} has unknown status: {status}")else:error_code = data.get("code", "unknown")error_msg = data.get("msg", "No error message")debug_log(f"❌ API error for task {task_id}: Code {error_code}, {error_msg}")# Update attemptstasks_db[task_id]["poll_attempts"] = attempt + 1except Exception as e:debug_log(f"⚠️ Polling error for task {task_id}: {str(e)}")# Wait before next polltime.sleep(interval)debug_log(f"Finished polling for task {task_id} after {max_attempts} attempts")# Clean up polling threadif task_id in polling_threads:del polling_threads[task_id]def generate_lyrics(prompt: str, auto_poll: bool = True) -> str:"""Submit lyrics generation task to Suno API"""if not SUNO_KEY:return "❌ Error: SunoKey environment variable not set. Please add it in Space Settings."if not prompt or not prompt.strip():return "❌ Please enter a lyrics prompt"# Generate task IDtask_id = str(uuid.uuid4())[:8]debug_log(f"Starting generation for task {task_id} with prompt: {prompt[:50]}...")# Prepare API requesturl = "https://api.sunoapi.org/api/v1/lyrics"headers = {"Authorization": f"Bearer {SUNO_KEY}","Content-Type": "application/json"}# Suno requires a callback URLdummy_callback = "https://dummy.callback.url/not-used"payload = {"prompt": prompt,"callBackUrl": dummy_callback}try:debug_log(f"Submitting to Suno API: {json.dumps(payload, indent=2)}")# Submit taskresponse = make_api_request("POST", url, headers=headers, json=payload, timeout=30)data = response.json()debug_log(f"Submission response: {json.dumps(data, indent=2)[:500]}...")if response.status_code == 200 and data.get("code") == 200:api_task_id = data["data"]["taskId"]debug_log(f"✅ Submission successful! Task ID: {task_id}, API Task ID: {api_task_id}")# Store task informationtasks_db[task_id] = {"id": task_id,"api_task_id": api_task_id,"prompt": prompt,"status": "submitted","result": None,"error": None,"created_at": datetime.now().isoformat(),"last_checked": None,"poll_attempts": 0,"completed_at": None,"auto_poll": auto_poll,"raw_response": data # Store for debugging}# Start auto-polling if enabledif auto_poll:poll_thread = threading.Thread(target=poll_task_status,args=(task_id,),daemon=True)polling_threads[task_id] = poll_threadpoll_thread.start()debug_log(f"🚀 Started auto-polling thread for task {task_id}")return f"""✅ **Task Submitted Successfully!****Your Task ID:** `{task_id}`**API Task ID:** `{api_task_id}`📝 **Prompt:** {prompt[:100]}{'...' if len(prompt) > 100 else ''}🔄 **Auto-polling enabled** - Results will appear automatically!⏳ **Estimated time:** Usually 10-60 seconds📊 **Check Status tab** to monitor progress💡 **Save your Task ID:** `{task_id}`"""else:error_msg = data.get("msg", f"HTTP {response.status_code}")debug_log(f"❌ Submission failed: {error_msg}")return f"""❌ **Submission Failed****Error:** {error_msg}**Response:** {json.dumps(data, indent=2)[:500]}💡 **Possible solutions:**• Check if your SunoKey is valid• Ensure API has available credits• Try a different prompt• Wait a few minutes and retry"""except requests.exceptions.Timeout:debug_log("❌ Request timeout")return "❌ Error: Request timeout - Suno API is not responding"except requests.exceptions.ConnectionError:debug_log("❌ Connection error")return "❌ Error: Connection failed - Check your internet connection"except Exception as e:debug_log(f"❌ Unexpected error: {str(e)}")return f"❌ Error: {str(e)}"def check_task_status(task_id: str, force_check: bool = False) -> str:"""Check the status of a task with detailed debugging"""if not task_id or not task_id.strip():return "❌ Please enter a Task ID"if task_id not in tasks_db:return f"❌ Task ID `{task_id}` not found. Please submit a task first."task = tasks_db[task_id]api_task_id = task.get("api_task_id", "unknown")debug_log(f"Checking status for task {task_id} (API: {api_task_id})")# Force an immediate API check if requestedif force_check:try:debug_log(f"Forcing API check for task {task_id}")url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={api_task_id}"headers = {"Authorization": f"Bearer {SUNO_KEY}"}response = make_api_request("GET", url, headers=headers, timeout=30)data = response.json()if response.status_code == 200 and data.get("code") == 200:task_data = data["data"]status = task_data.get("status", "unknown")debug_log(f"Forced check result: {status}")tasks_db[task_id]["status"] = statustasks_db[task_id]["last_checked"] = datetime.now().isoformat()if status == "completed" and "data" in task_data:lyrics_data = task_data["data"]tasks_db[task_id]["result"] = lyrics_datatasks_db[task_id]["completed_at"] = datetime.now().isoformat()elif status == "failed":error_msg = task_data.get("error", "Unknown error")tasks_db[task_id]["error"] = error_msgtasks_db[task_id]["completed_at"] = datetime.now().isoformat()except Exception as e:debug_log(f"Force check error: {str(e)}")status = task.get("status", "unknown")created_time = datetime.fromisoformat(task["created_at"])elapsed = int((datetime.now() - created_time).total_seconds())debug_log(f"Task {task_id} - Status: {status}, Elapsed: {elapsed}s")# Display based on statusif status == "completed" and task.get("result"):debug_log(f"Task {task_id} has completed results")return format_lyrics_output(task["result"], task_id, elapsed)elif status == "failed":error_msg = task.get("error", "Unknown error")debug_log(f"Task {task_id} failed: {error_msg}")return f"""❌ **Task Failed****Task ID:** `{task_id}`**API Task ID:** `{api_task_id}`**Error:** {error_msg}**Elapsed time:** {elapsed} seconds💡 Please try generating again with a different prompt."""else:# Still processing or unknown statusattempts = task.get("poll_attempts", 0)last_checked = task.get("last_checked")last_checked_str = ""if last_checked:last_time = datetime.fromisoformat(last_checked)last_checked_str = f"\n**Last checked:** {last_time.strftime('%H:%M:%S')}"debug_info = ""if DEBUG and "raw_response" in task:debug_info = f"\n\n**Debug Info:**\n```json\n{json.dumps(task.get('raw_response', {}), indent=2)[:300]}...\n```"return f"""⏳ **Task Processing...****Task ID:** `{task_id}`**API Task ID:** `{api_task_id}`**Status:** {status}**Elapsed:** {elapsed} seconds**Poll attempts:** {attempts}{last_checked_str}⏰ **Status Guide:**- **submitted:** Task accepted by API- **processing:** AI is generating lyrics- **completed:** Ready! Check auto-refresh- **failed:** Error occurred🔄 **Auto-polling:** {'✅ Active' if task.get('auto_poll') else '❌ Disabled'}💡 **What to do:**1. Wait 30-60 seconds for processing2. Click "Force Check" for immediate update3. Results appear automatically when ready{debug_info}"""def force_check_task(task_id: str):"""Force an immediate API check"""return check_task_status(task_id, force_check=True)def format_lyrics_output(lyrics_data, task_id, elapsed_time):"""Format the lyrics for display"""if not lyrics_data:return "✅ Task completed but no lyrics data received"output_lines = [f"# 🎵 Generated Lyrics (Task: {task_id})","",f"**Generated in:** {elapsed_time} seconds",f"**Completed at:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",""]for i, item in enumerate(lyrics_data, 1):title = item.get('title', f'Variant {i}')lyrics = item.get('text', 'No lyrics generated')output_lines.append(f"## Variant {i}: {title}")output_lines.append("```")output_lines.append(lyrics)output_lines.append("```")output_lines.append("---")output_lines.append("")output_lines.append("### 🎉 All done!")output_lines.append("You can generate more lyrics or try different prompts.")return "\n".join(output_lines)def list_all_tasks():"""List all submitted tasks with detailed info"""if not tasks_db:return "📭 No tasks found. Generate some lyrics first!"output_lines = ["# 📋 All Submitted Tasks", ""]for task_id, task in sorted(tasks_db.items(), key=lambda x: x[1]["created_at"], reverse=True):status = task.get("status", "unknown")api_task_id = task.get("api_task_id", "unknown")prompt_preview = task.get("prompt", "")[:50]created = task.get("created_at", "")[:19]# Status icon and colorif status == "completed":icon = "✅"color = "green"elif status in ["failed", "error"]:icon = "❌"color = "red"else:icon = "⏳"color = "orange"# Age calculationcreated_time = datetime.fromisoformat(task["created_at"])age_seconds = int((datetime.now() - created_time).total_seconds())output_lines.append(f"<span style='color:{color}'>{icon} **{task_id}** - {status} ({age_seconds}s)</span>")output_lines.append(f" API ID: `{api_task_id}`")output_lines.append(f" Prompt: {prompt_preview}...")output_lines.append(f" Created: {created}")output_lines.append(f" Poll attempts: {task.get('poll_attempts', 0)}")if task.get("last_checked"):last_checked = task["last_checked"][:19]output_lines.append(f" Last checked: {last_checked}")if task.get("completed_at"):completed = task["completed_at"][:19]output_lines.append(f" Completed: {completed}")output_lines.append("")# Add summarycompleted = sum(1 for t in tasks_db.values() if t.get("status") == "completed")processing = sum(1 for t in tasks_db.values() if t.get("status") not in ["completed", "failed", "error"])failed = sum(1 for t in tasks_db.values() if t.get("status") in ["failed", "error"])total = len(tasks_db)output_lines.append(f"**Summary:** {completed} ✅, {processing} ⏳, {failed} ❌, {total} total")output_lines.append(f"**Active poll threads:** {len(polling_threads)}")return "\n".join(output_lines)def get_diagnostic_info():"""Get diagnostic information about the system"""info_lines = ["# 🩺 Diagnostic Information", ""]# API Key statusapi_status = "✅ Configured" if SUNO_KEY else "❌ NOT SET"api_preview = SUNO_KEY[:10] + "..." if SUNO_KEY and len(SUNO_KEY) > 10 else SUNO_KEY or "None"info_lines.append(f"**SunoKey:** {api_status} ({api_preview})")# Tasks summaryinfo_lines.append(f"\n**Tasks in memory:** {len(tasks_db)}")info_lines.append(f"**Active poll threads:** {len(polling_threads)}")# Recent tasksif tasks_db:info_lines.append("\n**Recent Tasks:**")for task_id, task in sorted(tasks_db.items(), key=lambda x: x[1]["created_at"], reverse=True)[:5]:status = task.get("status", "unknown")age = int((datetime.now() - datetime.fromisoformat(task["created_at"])).total_seconds())info_lines.append(f"- `{task_id}`: {status} ({age}s ago)")# Test API connectioninfo_lines.append("\n**API Connection Test:**")try:test_response = requests.get("https://api.sunoapi.org", timeout=5)info_lines.append(f"✅ Suno API reachable (HTTP {test_response.status_code})")except Exception as e:info_lines.append(f"❌ Cannot reach Suno API: {str(e)}")# Debug infoinfo_lines.append(f"\n**Debug Mode:** {'✅ Enabled' if DEBUG else '❌ Disabled'}")info_lines.append(f"**Current Time:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")return "\n".join(info_lines)# Create the Gradio interfacewith gr.Blocks(title="Suno Lyrics Generator", theme=gr.themes.Soft()) as app:gr.Markdown("# 🎵 Suno AI Lyrics Generator")gr.Markdown("Generate song lyrics using Suno's AI API")# Store the current task ID in a hidden statecurrent_task_id = gr.State("")with gr.Tabs():# Tab 1: Generate Lyricswith gr.TabItem("✨ Generate"):with gr.Row():with gr.Column(scale=2):gr.Markdown("### Enter your lyrics idea")prompt_input = gr.Textbox(label="Lyrics Prompt",placeholder="Example: A romantic ballad about stargazing on a summer night...",lines=3)auto_poll_checkbox = gr.Checkbox(label="🔁 Enable auto-polling",value=True,info="Automatically check for results (recommended)")submit_btn = gr.Button("🚀 Generate Lyrics", variant="primary", size="lg")gr.Markdown("### ⚠️ Current Issue:")gr.Markdown("""Tasks are getting stuck in "submitted" status.This version includes **debugging tools** to diagnose the issue.**What to try:**1. Submit a simple prompt2. Check "Diagnostic" tab3. Use "Force Check" button4. Monitor debug logs""")with gr.Column(scale=3):output_area = gr.Markdown(label="Result",value="Your task submission result will appear here...")def handle_generation(prompt, auto_poll):result = generate_lyrics(prompt, auto_poll)# Extract task ID from resulttask_id = ""if "Task ID:" in result:for line in result.split('\n'):if 'Task ID:' in line:parts = line.split('`')if len(parts) > 1:task_id = parts[1]breakreturn result, task_idsubmit_btn.click(fn=handle_generation,inputs=[prompt_input, auto_poll_checkbox],outputs=[output_area, current_task_id])# Tab 2: Check Statuswith gr.TabItem("🔍 Check Status"):with gr.Row():with gr.Column():gr.Markdown("### Enter your Task ID")task_id_input = gr.Textbox(label="Task ID",placeholder="Paste your Task ID here (e.g., 0f015fcb)",scale=1)# Auto-populate if we have a current task IDdef update_task_id_input(current_id):return current_id if current_id else ""current_task_id.change(fn=update_task_id_input,inputs=current_task_id,outputs=task_id_input)with gr.Row():check_btn = gr.Button("🔍 Check Status", variant="primary")force_check_btn = gr.Button("⚡ Force Check", variant="secondary")auto_refresh_btn = gr.Button("🔄 Auto-refresh", variant="secondary")gr.Markdown("---")refresh_all_btn = gr.Button("📋 List All Tasks")tasks_list = gr.Markdown(label="All Tasks")with gr.Column():status_output = gr.Markdown(label="Status",value="Enter a Task ID above and click Check Status")# Regular checkcheck_btn.click(fn=check_task_status,inputs=task_id_input,outputs=status_output)# Force check (immediate API call)force_check_btn.click(fn=force_check_task,inputs=task_id_input,outputs=status_output)# List all tasksrefresh_all_btn.click(fn=list_all_tasks,inputs=None,outputs=tasks_list)# Tab 3: Diagnosticwith gr.TabItem("🩺 Diagnostic"):gr.Markdown("# System Diagnostics")gr.Markdown("Use this tab to diagnose why tasks are getting stuck")with gr.Row():with gr.Column():diagnostic_btn = gr.Button("🔄 Refresh Diagnostics", variant="primary")diagnostic_output = gr.Markdown(label="Diagnostic Info")with gr.Column():gr.Markdown("### 🚨 Common Issues:")gr.Markdown("""**1. API Key Issues:**- Invalid or expired SunoKey- No API credits remaining- Incorrect environment variable name**2. API Response Issues:**- Suno API returning errors- Tasks stuck in queue- Rate limiting**3. Network Issues:**- Cannot reach api.sunoapi.org- Timeout errors- Connection refused**4. Task Processing:**- Suno AI taking longer than expected- Tasks stuck in "submitted" state- Server-side delays""")diagnostic_btn.click(fn=get_diagnostic_info,inputs=None,outputs=diagnostic_output)# Auto-refresh diagnostics every 10 secondsdiagnostic_btn.click(fn=lambda: time.sleep(10),inputs=None,outputs=None).then(fn=get_diagnostic_info,inputs=None,outputs=diagnostic_output)# Tab 4: Helpwith gr.TabItem("ℹ️ Help"):gr.Markdown("# Help & Troubleshooting")with gr.Row():with gr.Column():gr.Markdown("### 🐛 Debugging Stuck Tasks")gr.Markdown("""**If tasks are stuck in "submitted":**1. **Check Diagnostic Tab:**- Verify API key is set- Test API connection- View recent task status2. **Use Force Check:**- Makes immediate API call- Bypasses cached status- Shows raw API response3. **Monitor Debug Logs:**- Check Space logs (bottom of page)- Look for API errors- Note timeout messages4. **Try Simple Test:**- Use a very simple prompt- Disable auto-polling- Check after 60 seconds""")with gr.Column():gr.Markdown("### 📞 Support")gr.Markdown("""**If issues persist:**1. **Check SunoKey:**- Ensure it's valid- Check credit balance- Try in Suno's own interface2. **API Status:**- Suno API may be down- Check Suno status page- Wait and try later3. **Contact Support:**- Suno API support- Provide your Task IDs- Share debug logs4. **Alternative:**- Try a different prompt- Wait 5 minutes- Restart the Space""")# Launch the appif __name__ == "__main__":print("=" * 60)print("🚀 Starting Suno Lyrics Generator - DEBUG MODE")print("=" * 60)print(f"🔑 SunoKey: {'✅ Configured' if SUNO_KEY else '❌ NOT SET'}")if SUNO_KEY:print(f"🔑 Preview: {SUNO_KEY[:10]}...")print(f"🐛 Debug Mode: {'✅ Enabled' if DEBUG else '❌ Disabled'}")print(f"📊 Pre-existing tasks: {len(tasks_db)}")print("=" * 60)app.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=False,show_error=True)1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561 unmodified lineimport requestsimport osimport jsonfrom datetime import datetime# Load Suno API keySUNO_KEY = os.environ.get("SunoKey", "")if 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"}
app.py+118-659