Spaces:
Paused
Paused
Upload app.py
Browse files12 unmodified lines131415161718192021222324252627282930313233343536373839404142433 unmodified lines474849505152535455565758596061626364656667686970719 unmodified lines8182838485861 unmodified line888990919293942 unmodified lines9798991001011021031041051061071081096 unmodified lines1161171181191201211225 unmodified lines1281291301311321331342 unmodified lines1371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681 unmodified line1701711721731741751761771781791801811821831841851861871881 unmodified line1901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192 unmodified lines22222322422522622722822923023123223323423523623723825 unmodified lines2642652662672682692701 unmodified line2722732742752762778 unmodified lines28628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831912 unmodified lines3323333343353363373384 unmodified lines34334434534634734834935035135235335428 unmodified lines3833843853863873883899 unmodified lines39940040140240340440540612 unmodified lines41942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754812 unmodified linesif not SUNO_KEY:print("⚠️ Warning: SunoKey environment variable not set!")# Task storage with auto-pollingtasks_db = {}polling_threads = {}def poll_task_status(task_id: str, max_attempts=60, interval=2):"""Background thread to automatically poll task status"""if task_id not in tasks_db:returntask = tasks_db[task_id]api_task_id = task["api_task_id"]for attempt in range(max_attempts):try:# Poll the APIurl = 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)data = response.json()if response.status_code == 200 and data.get("code") == 200:task_data = data["data"]status = task_data.get("status", "unknown")# Update task statustasks_db[task_id]["status"] = statustasks_db[task_id]["last_checked"] = datetime.now().isoformat()3 unmodified lineslyrics_data = task_data["data"]tasks_db[task_id]["result"] = lyrics_datatasks_db[task_id]["completed_at"] = datetime.now().isoformat()print(f"✅ Task {task_id} completed via auto-polling")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()print(f"❌ Task {task_id} failed: {error_msg}")break# Update attemptstasks_db[task_id]["poll_attempts"] = attempt + 1except Exception as e:print(f"⚠️ Polling error for task {task_id}: {str(e)}")# Wait before next polltime.sleep(interval)# Clean up polling threadif task_id in polling_threads:del polling_threads[task_id]9 unmodified lines# Generate task IDtask_id = str(uuid.uuid4())[:8]# Prepare API requesturl = "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 onedummy_callback = "https://dummy.callback.url/not-used"payload = {2 unmodified lines}try:# Submit taskresponse = requests.post(url, headers=headers, json=payload, timeout=30)data = response.json()if response.status_code == 200 and data.get("code") == 200:api_task_id = data["data"]["taskId"]# Store task informationtasks_db[task_id] = {"id": task_id,6 unmodified lines"last_checked": None,"poll_attempts": 0,"completed_at": None,"auto_poll": auto_poll}# Start auto-polling if enabled5 unmodified lines)polling_threads[task_id] = poll_threadpoll_thread.start()print(f"🚀 Started auto-polling 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'}⏳ **Estimated time:** 10-30 seconds💡 **Tip:** Save your Task ID: `{task_id}`"""else:error_msg = data.get("msg", f"HTTP {response.status_code}")return f"""❌ **Submission Failed****Error:** {error_msg}💡 **Possible solutions:**• Check if your SunoKey is valid• Try a different prompt• Wait a few minutes and retry"""except requests.exceptions.Timeout:return "❌ Error: Request timeout - Suno API is not responding"except requests.exceptions.ConnectionError:return "❌ Error: Connection failed - Check your internet connection"except Exception as e:return f"❌ Error: {str(e)}"def check_task_status(task_id: str, auto_refresh: bool = False) -> str:"""Check the status of a task"""if not task_id or not task_id.strip():return "❌ Please enter a Task ID"1 unmodified linereturn f"❌ Task ID `{task_id}` not found. Please submit a task first."task = tasks_db[task_id]# If auto_refresh is True, force an immediate API checkif auto_refresh:try:url = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={task['api_task_id']}"headers = {"Authorization": f"Bearer {SUNO_KEY}"}response = requests.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")tasks_db[task_id]["status"] = statustasks_db[task_id]["last_checked"] = datetime.now().isoformat()1 unmodified linelyrics_data = task_data["data"]tasks_db[task_id]["result"] = lyrics_datatasks_db[task_id]["completed_at"] = datetime.now().isoformat()except Exception:pass # Keep existing status if API check failsstatus = task.get("status", "unknown")created_time = datetime.fromisoformat(task["created_at"])elapsed = int((datetime.now() - created_time).total_seconds())if status == "completed" and task.get("result"):# Format completed lyricsreturn format_lyrics_output(task["result"], task_id, elapsed)elif status == "failed":error_msg = task.get("error", "Unknown error")return f"""❌ **Task Failed****Task ID:** `{task_id}`**Error:** {error_msg}**Elapsed time:** {elapsed} seconds💡 Please try generating again with a different prompt."""else:# Still processingattempts = task.get("poll_attempts", 0)last_checked = task.get("last_checked")last_checked_str = ""2 unmodified lineslast_time = datetime.fromisoformat(last_checked)last_checked_str = f"\n**Last checked:** {last_time.strftime('%H:%M:%S')}"return f"""⏳ **Task Processing...****Task ID:** `{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'}{'✅ Results will appear automatically when ready!' if task.get('auto_poll') else '📊 Click "Check Status" again to refresh'}"""def format_lyrics_output(lyrics_data, task_id, elapsed_time):"""Format the lyrics for display"""25 unmodified linesreturn "\n".join(output_lines)def list_all_tasks():"""List all submitted tasks"""if not tasks_db:return "📭 No tasks found. Generate some lyrics first!"1 unmodified linefor task_id, task in sorted(tasks_db.items(), key=lambda x: x[1]["created_at"], reverse=True):status = task.get("status", "unknown")prompt_preview = task.get("prompt", "")[:50]created = task.get("created_at", "")[:19]8 unmodified linesicon = "⏳"color = "orange"output_lines.append(f"<span style='color:{color}'>{icon} **{task_id}** - {status}</span>")output_lines.append(f" Prompt: {prompt_preview}...")output_lines.append(f" Created: {created}")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 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"])total = len(tasks_db)output_lines.append(f"**Summary:** {completed} completed, {processing} processing, {total} total")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"result = check_task_status(task_id, auto_refresh=True)return task_id, result# Create the Gradio interfacewith gr.Blocks(title="Suno Lyrics Generator", theme=gr.themes.Soft()) as app:12 unmodified linesprompt_input = gr.Textbox(label="Lyrics Prompt",placeholder="Example: A romantic ballad about stargazing on a summer night...",lines=4)auto_poll_checkbox = gr.Checkbox(4 unmodified linessubmit_btn = gr.Button("🚀 Generate Lyrics", variant="primary", size="lg")gr.Markdown("### 📝 Tips:")gr.Markdown("""• Be descriptive in your prompt• Include genre, mood, or theme• Typical processing time: 10-30 seconds• Auto-polling will show results automatically""")with gr.Column(scale=3):28 unmodified linesgr.Markdown("### Enter your Task ID")task_id_input = gr.Textbox(label="Task ID",placeholder="Paste your Task ID here (e.g., 7d3b63c4)",scale=1)9 unmodified lineswith gr.Row():check_btn = gr.Button("🔍 Check Status", variant="primary")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 linesoutputs=status_output)# Auto-refresh functiondef 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 statesreturn task_id, "🔄 Starting auto-refresh...", gr.update(visible=True), gr.update(visible=False)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:breakresult = check_task_status(task_id, auto_refresh=True)results.append(result)# If completed, stop earlytask = tasks_db.get(task_id, {})if task.get("status") in ["completed", "failed"]:break# Wait between refreshesif i < iterations - 1:time.sleep(3)return task_id, results[-1] if results else "Auto-refresh stopped"# Connect auto-refresh buttonauto_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),inputs=None,outputs=None).then(fn=do_auto_refresh,inputs=task_id_input,outputs=[task_id_input, status_output])# Stop buttonstop_refresh_btn.click(fn=lambda: ("", "⏹️ Auto-refresh stopped", gr.update(visible=False), gr.update(visible=True)),inputs=None,outputs=[task_id_input, status_output, stop_refresh_btn, auto_refresh_btn])# List all tasksrefresh_all_btn.click(fn=list_all_tasks,inputs=None,outputs=tasks_list)# Tab 3: Help & Infowith gr.TabItem("ℹ️ Help"):gr.Markdown("# Help & Information")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("""1. **Generate Tab:**- Enter lyrics prompt- Enable auto-polling (recommended)- Click Generate- Save your Task ID2. **Check Status Tab:**- Paste your Task ID- Click "Check Status" for manual check- Click "Auto-refresh" for automatic updates- Results appear automatically with auto-polling3. **Results:**- Appear automatically if auto-polling enabled- Can take 10-30 seconds- Multiple lyric variants provided""")with gr.Column():gr.Markdown("### 🔧 Features")gr.Markdown("""**Auto-polling:**- Background thread checks status every 2 seconds- Results appear automatically- Stops after completion or 2 minutes**Manual checking:**- Check specific Task ID status- Auto-refresh button for continuous updates- List all submitted tasks**Task management:**- All tasks stored in memory- Status tracking- Error handling""")gr.Markdown("### ⚠️ Troubleshooting")gr.Markdown("""**If tasks aren't completing:**1. Check your SunoKey has available credits2. Try simpler prompts3. Wait 30+ seconds for processing4. 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...")app.launch(server_name="0.0.0.0",12 unmodified lines13141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273743 unmodified lines787980818283848586878889909192939495969798991001011021031041051061071081091101111121139 unmodified lines1231241251261271281291301 unmodified line1321331341351361371382 unmodified lines1411421431441451461471481491501511521531541551561571581596 unmodified lines1661671681691701711721735 unmodified lines1791801811821831841852 unmodified lines1881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282291 unmodified line2312322332342352362372382392402412422432442452462472482492502512522532542551 unmodified line2572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952 unmodified lines29829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033125 unmodified lines3573583593603613623631 unmodified line3653663673683693703718 unmodified lines38038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945012 unmodified lines4634644654664674684694 unmodified lines47447547647747847948048148248348448548648748848928 unmodified lines5185195205215225235249 unmodified lines53453553653753853954054112 unmodified lines55455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169212 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 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()3 unmodified lineslyrics_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]9 unmodified lines# 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 = {1 unmodified line"Content-Type": "application/json"}# Suno requires a callback URLdummy_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 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,6 unmodified lines"last_checked": None,"poll_attempts": 0,"completed_at": None,"auto_poll": auto_poll,"raw_response": data # Store for debugging}# Start auto-polling if enabled5 unmodified lines)polling_threads[task_id] = poll_threadpoll_thread.start()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!⏳ **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"1 unmodified linereturn 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()1 unmodified linelyrics_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 = ""2 unmodified lineslast_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"""25 unmodified linesreturn "\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!"1 unmodified linefor 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 linesicon = "⏳"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:12 unmodified linesprompt_input = gr.Textbox(label="Lyrics Prompt",placeholder="Example: A romantic ballad about stargazing on a summer night...",lines=3)auto_poll_checkbox = gr.Checkbox(4 unmodified linessubmit_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):28 unmodified linesgr.Markdown("### Enter your Task ID")task_id_input = gr.Textbox(label="Task ID",placeholder="Paste your Task ID here (e.g., 0f015fcb)",scale=1)9 unmodified lineswith 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")12 unmodified linesoutputs=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",
app.py+284-140