Spaces:
Paused
Paused
Upload app.py
Browse files12 unmodified lines131415161718192021222324252627282930313233343536373839404142432044454647484950515253545556575859606162346364656667686970717273743 unmodified lines787980508182838485868757888990919293949596979899100101102103641041051061071081091101111121139 unmodified lines1231241251261271281291301 unmodified line132133134911351361371382 unmodified lines1411421431441451461011471481491501511521531541551561571581596 unmodified lines1661671681191691701711721735 unmodified lines1791801811311821831841852 unmodified lines1881891901401911921421931941441951961971981992002012022032042052062072082092102112122132142152162172182192202212222232241641652252262272282291 unmodified line2312322332342351741752362372382392402411772422432441802452462472482492502512522532542551 unmodified line2572582592602612622632641941952652662672682692702712722732742752022762772782792802812822832842852862872882892902912162922932942952 unmodified lines29829930030130230330430530630730830931031131223223331331431531631731831932023532132232332432532632732832933033125 unmodified lines3573583592673603613623631 unmodified line3653663673683693703718 unmodified lines38038138238338438538628938738838939039139239339439539639739839940029729829940140240340440540640740830640941041141241331031131231341441541641731531641841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945012 unmodified lines4634644653354664674684694 unmodified lines47447547634647747834834935035147948048148248348448548648748848928 unmodified lines5185195203865215225235249 unmodified lines53453553653753840353954054112 unmodified lines55455555642242342442542642742855755855956056156256343043143243343456456556656756856957057157257357457557657757857958058158258358458558658758843643758959059159259343944044144259459559659759844444544644744859960060160260360445045145245345445545660560660745845946046146260860961046546646761161261361446947047147247347461561661761847661962062147962262348162462562662748548648748848962862949149249349449563063163263363463563649749849950050163763863964064150350450550664264364464564664764864965065165265351065465551251351451565665765865966066166266366466566666751751851952066866967067167252252352452567367467567667752752852953053153253353453553653753853954067867968054454568168268368468568668768868969069169212 unmodified linesif 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 responses debug_log(f"Response: {response.text[:500]}") return response except Exception as e: debug_log(f"API request error: {str(e)}") raise
def poll_task_status(task_id: str, max_attempts=60, interval=2):def 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") return task = 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 API url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={api_task_id}" headers = {"Authorization": f"Bearer {SUNO_KEY}"} response = requests.get(url, headers=headers, timeout=30) 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 status tasks_db[task_id]["status"] = status tasks_db[task_id]["last_checked"] = datetime.now().isoformat()3 unmodified lines lyrics_data = task_data["data"] tasks_db[task_id]["result"] = lyrics_data tasks_db[task_id]["completed_at"] = datetime.now().isoformat() print(f"✅ Task {task_id} completed via auto-polling") debug_log(f"✅ Task {task_id} completed successfully!") break elif status == "failed": error_msg = task_data.get("error", "Unknown error") tasks_db[task_id]["error"] = error_msg tasks_db[task_id]["completed_at"] = datetime.now().isoformat() print(f"❌ Task {task_id} failed: {error_msg}") debug_log(f"❌ Task {task_id} failed: {error_msg}") break elif 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 attempts tasks_db[task_id]["poll_attempts"] = attempt + 1 except Exception as e: print(f"⚠️ Polling error for task {task_id}: {str(e)}") debug_log(f"⚠️ Polling error for task {task_id}: {str(e)}") # Wait before next poll time.sleep(interval) debug_log(f"Finished polling for task {task_id} after {max_attempts} attempts") # Clean up polling thread if task_id in polling_threads: del polling_threads[task_id]9 unmodified lines # Generate task ID task_id = str(uuid.uuid4())[:8] debug_log(f"Starting generation for task {task_id} with prompt: {prompt[:50]}...") # Prepare API request url = "https://api.sunoapi.org/api/v1/lyrics" headers = {1 unmodified line "Content-Type": "application/json" } # Suno requires a callback URL, but we'll use a dummy one # Suno requires a callback URL dummy_callback = "https://dummy.callback.url/not-used" payload = {2 unmodified lines } try: debug_log(f"Submitting to Suno API: {json.dumps(payload, indent=2)}") # Submit task response = requests.post(url, headers=headers, json=payload, timeout=30) response = 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 information tasks_db[task_id] = { "id": task_id,6 unmodified lines "last_checked": None, "poll_attempts": 0, "completed_at": None, "auto_poll": auto_poll "auto_poll": auto_poll, "raw_response": data # Store for debugging } # Start auto-polling if enabled5 unmodified lines ) polling_threads[task_id] = poll_thread poll_thread.start() print(f"🚀 Started auto-polling for task {task_id}") debug_log(f"🚀 Started auto-polling thread for task {task_id}") return f"""✅ **Task Submitted Successfully!**
2 unmodified lines
📝 **Prompt:** {prompt[:100]}{'...' if len(prompt) > 100 else ''}
{'🔄 **Auto-polling enabled** - Results will appear automatically!' if auto_poll else '📊 **Auto-polling disabled** - Check status manually'}🔄 **Auto-polling enabled** - Results will appear automatically!
⏳ **Estimated time:** 10-30 seconds⏳ **Estimated time:** Usually 10-60 seconds
💡 **Tip:** Save your Task ID: `{task_id}`"""📊 **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, auto_refresh: bool = False) -> str: """Check the status of a task"""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" 1 unmodified line 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") # If auto_refresh is True, force an immediate API check if auto_refresh: debug_log(f"Checking status for task {task_id} (API: {api_task_id})") # Force an immediate API check if requested if force_check: try: debug_log(f"Forcing API check for task {task_id}") url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={task['api_task_id']}" url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={api_task_id}" headers = {"Authorization": f"Bearer {SUNO_KEY}"} response = requests.get(url, headers=headers, timeout=30) 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"] = status tasks_db[task_id]["last_checked"] = datetime.now().isoformat() 1 unmodified line lyrics_data = task_data["data"] tasks_db[task_id]["result"] = lyrics_data tasks_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_msg tasks_db[task_id]["completed_at"] = datetime.now().isoformat() except Exception: pass # Keep existing status if API check fails 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 status if status == "completed" and task.get("result"): # Format completed lyrics 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 # Still processing or unknown status attempts = task.get("poll_attempts", 0) last_checked = task.get("last_checked") last_checked_str = ""2 unmodified lines 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}
⏰ **Estimated completion:** 10-30 seconds🔄 {'Auto-polling active' if task.get('auto_poll') else 'Auto-polling disabled'}⏰ **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'}
{'✅ Results will appear automatically when ready!' if task.get('auto_poll') else '📊 Click "Check Status" again to refresh'}"""💡 **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"""25 unmodified lines return "\n".join(output_lines)
def list_all_tasks(): """List all submitted tasks""" """List all submitted tasks with detailed info""" if not tasks_db: return "📭 No tasks found. Generate some lyrics first!" 1 unmodified line 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] 8 unmodified lines icon = "⏳" color = "orange" # Age calculation created_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}</span>") 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}") if task.get("auto_poll"): output_lines.append(f" Auto-polling: ✅ Enabled") output_lines.append("") # Add summary completed = 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} completed, {processing} processing, {total} total") 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 auto_refresh_display(task_id: str): """Auto-refresh the status display""" if not task_id or task_id not in tasks_db: return task_id, "❌ Invalid Task ID"def get_diagnostic_info(): """Get diagnostic information about the system""" info_lines = ["# 🩺 Diagnostic Information", ""] result = check_task_status(task_id, auto_refresh=True) return task_id, result # API Key status api_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 summary info_lines.append(f"\n**Tasks in memory:** {len(tasks_db)}") info_lines.append(f"**Active poll threads:** {len(polling_threads)}") # Recent tasks if 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 connection info_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 info info_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:12 unmodified lines prompt_input = gr.Textbox( label="Lyrics Prompt", placeholder="Example: A romantic ballad about stargazing on a summer night...", lines=4 lines=3 ) auto_poll_checkbox = gr.Checkbox(4 unmodified lines submit_btn = gr.Button("🚀 Generate Lyrics", variant="primary", size="lg") gr.Markdown("### 📝 Tips:") gr.Markdown("### ⚠️ Current Issue:") gr.Markdown(""" • Be descriptive in your prompt • Include genre, mood, or theme • Typical processing time: 10-30 seconds • Auto-polling will show results automatically Tasks are getting stuck in "submitted" status. This version includes **debugging tools** to diagnose the issue. **What to try:** 1. Submit a simple prompt 2. Check "Diagnostic" tab 3. Use "Force Check" button 4. Monitor debug logs """) with gr.Column(scale=3):28 unmodified lines gr.Markdown("### Enter your Task ID") task_id_input = gr.Textbox( label="Task ID", placeholder="Paste your Task ID here (e.g., 7d3b63c4)", placeholder="Paste your Task ID here (e.g., 0f015fcb)", scale=1 ) 9 unmodified lines 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") stop_refresh_btn = gr.Button("⏹️ Stop", variant="stop", visible=False) gr.Markdown("---") refresh_all_btn = gr.Button("📋 List All Tasks")12 unmodified lines outputs=status_output ) # Auto-refresh function def start_auto_refresh(task_id, stop_flag): if not task_id: return task_id, "❌ Please enter a Task ID first", gr.update(visible=False), gr.update(visible=True) # Update button states return task_id, "🔄 Starting auto-refresh...", gr.update(visible=True), gr.update(visible=False) # Force check (immediate API call) force_check_btn.click( fn=force_check_task, inputs=task_id_input, outputs=status_output ) def do_auto_refresh(task_id, iterations=10): results = [] for i in range(iterations): if not task_id or task_id not in tasks_db: break # List all tasks refresh_all_btn.click( fn=list_all_tasks, inputs=None, outputs=tasks_list ) # Tab 3: Diagnostic with 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 result = check_task_status(task_id, auto_refresh=True) results.append(result) **2. API Response Issues:** - Suno API returning errors - Tasks stuck in queue - Rate limiting # If completed, stop early task = tasks_db.get(task_id, {}) if task.get("status") in ["completed", "failed"]: break **3. Network Issues:** - Cannot reach api.sunoapi.org - Timeout errors - Connection refused # Wait between refreshes if i < iterations - 1: time.sleep(3) return task_id, results[-1] if results else "Auto-refresh stopped" **4. Task Processing:** - Suno AI taking longer than expected - Tasks stuck in "submitted" state - Server-side delays """) # Connect auto-refresh button auto_refresh_click = auto_refresh_btn.click( fn=start_auto_refresh, inputs=[task_id_input, gr.State(False)], outputs=[task_id_input, status_output, stop_refresh_btn, auto_refresh_btn] ).then( fn=lambda: time.sleep(1), diagnostic_btn.click( fn=get_diagnostic_info, inputs=None, outputs=None ).then( fn=do_auto_refresh, inputs=task_id_input, outputs=[task_id_input, status_output] outputs=diagnostic_output ) # Stop button stop_refresh_btn.click( fn=lambda: ("", "⏹️ Auto-refresh stopped", gr.update(visible=False), gr.update(visible=True)), # Auto-refresh diagnostics every 10 seconds diagnostic_btn.click( fn=lambda: time.sleep(10), inputs=None, outputs=[task_id_input, status_output, stop_refresh_btn, auto_refresh_btn] ) # List all tasks refresh_all_btn.click( fn=list_all_tasks, outputs=None ).then( fn=get_diagnostic_info, inputs=None, outputs=tasks_list outputs=diagnostic_output ) # Tab 3: Help & Info # Tab 4: Help with gr.TabItem("ℹ️ Help"): gr.Markdown("# Help & Information") gr.Markdown("# Help & Troubleshooting") with gr.Row(): with gr.Column(): gr.Markdown("### 🔑 API Status") api_status = "✅ Configured" if SUNO_KEY else "❌ Not configured" gr.Markdown(f"**SunoKey:** {api_status}") gr.Markdown("### 🚀 How to Use:") gr.Markdown("### 🐛 Debugging Stuck Tasks") gr.Markdown(""" 1. **Generate Tab:** - Enter lyrics prompt - Enable auto-polling (recommended) - Click Generate - Save your Task ID **If tasks are stuck in "submitted":** 1. **Check Diagnostic Tab:** - Verify API key is set - Test API connection - View recent task status 2. **Check Status Tab:** - Paste your Task ID - Click "Check Status" for manual check - Click "Auto-refresh" for automatic updates - Results appear automatically with auto-polling 2. **Use Force Check:** - Makes immediate API call - Bypasses cached status - Shows raw API response 3. **Results:** - Appear automatically if auto-polling enabled - Can take 10-30 seconds - Multiple lyric variants provided 3. **Monitor Debug Logs:** - Check Space logs (bottom of page) - Look for API errors - Note timeout messages 4. **Try Simple Test:** - Use a very simple prompt - Disable auto-polling - Check after 60 seconds """) with gr.Column(): gr.Markdown("### 🔧 Features") gr.Markdown("### 📞 Support") gr.Markdown(""" **Auto-polling:** - Background thread checks status every 2 seconds - Results appear automatically - Stops after completion or 2 minutes **If issues persist:** 1. **Check SunoKey:** - Ensure it's valid - Check credit balance - Try in Suno's own interface 2. **API Status:** - Suno API may be down - Check Suno status page - Wait and try later **Manual checking:** - Check specific Task ID status - Auto-refresh button for continuous updates - List all submitted tasks 3. **Contact Support:** - Suno API support - Provide your Task IDs - Share debug logs **Task management:** - All tasks stored in memory - Status tracking - Error handling 4. **Alternative:** - Try a different prompt - Wait 5 minutes - Restart the Space """) gr.Markdown("### ⚠️ Troubleshooting") gr.Markdown(""" **If tasks aren't completing:** 1. Check your SunoKey has available credits 2. Try simpler prompts 3. Wait 30+ seconds for processing 4. Use the "Auto-refresh" button **Common errors:** - "Task ID not found": Submit a new task - "SunoKey not set": Add API key in Space Settings - "Timeout": Suno API may be busy """)
# Launch the appif __name__ == "__main__": print(f"🔑 SunoKey status: {'Configured' if SUNO_KEY else 'NOT SET'}") print("🚀 Starting Suno Lyrics Generator with auto-polling...") 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",app.py+284-140