Spaces:
Paused
Paused
Update app.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866872 unmodified linesimport osimport jsonimport uuidimport threadingimport timefrom datetime import datetime, timedeltafrom typing import Dict, Optionalfrom fastapi import Request# Load Suno API key - using SunoKey as you specifiedSUNO_KEY = os.environ.get("SunoKey", "")if not SUNO_KEY:print("⚠️ Warning: SunoKey environment variable not set!")# ConfigurationPOLLING_INTERVAL = 5 # secondsMAX_POLLING_TIME = 300 # 5 minutes maxWEBHOOK_TIMEOUT = 30 # seconds to wait for webhook before starting polling# For Hugging Face Spaces - get the public URLSPACE_NAME = os.environ.get("SPACE_NAME", "")AUTHOR_NAME = os.environ.get("AUTHOR_NAME", "")if SPACE_NAME and AUTHOR_NAME:SPACE_URL = f"https://{AUTHOR_NAME}-{SPACE_NAME}.hf.space"elif os.environ.get("SYSTEM") == "spaces":# Try to construct from environmentSPACE_URL = f"https://{os.environ.get('SPACE_ID', '').replace('_', '-')}.hf.space"else:SPACE_URL = "http://localhost:7860"# Task storage with automatic cleanupclass TaskManager:def __init__(self):self.tasks: Dict[str, dict] = {}self._lock = threading.Lock()def create_task(self, prompt: str, callback_url: str = "") -> str:"""Create a new task and start background monitoring"""task_id = str(uuid.uuid4())[:8]with self._lock:self.tasks[task_id] = {"id": task_id,"prompt": prompt,"callback_url": callback_url,"api_task_id": None,"status": "created","result": None,"error": None,"created_at": datetime.now(),"last_checked": None,"method": None, # 'webhook' or 'polling'"webhook_received": False,"polling_started": False,"completed": False}return task_iddef update_task(self, task_id: str, **kwargs):"""Update task properties"""with self._lock:if task_id in self.tasks:self.tasks[task_id].update(kwargs)self.tasks[task_id]["last_checked"] = datetime.now()def get_task(self, task_id: str) -> Optional[dict]:"""Get task by ID"""with self._lock:return self.tasks.get(task_id)def get_all_tasks(self):"""Get all tasks"""with self._lock:return list(self.tasks.values())def cleanup_old_tasks(self, hours=24):"""Remove tasks older than specified hours"""cutoff = datetime.now() - timedelta(hours=hours)with self._lock:to_delete = [task_id for task_id, task in self.tasks.items()if task["created_at"] < cutoff]for task_id in to_delete:del self.tasks[task_id]return len(to_delete)task_manager = TaskManager()# Background polling threadclass PollingThread(threading.Thread):def __init__(self, task_id: str):super().__init__(daemon=True)self.task_id = task_idself.stop_event = threading.Event()def run(self):"""Poll Suno API for task completion"""task = task_manager.get_task(self.task_id)if not task or not task.get("api_task_id"):returnapi_task_id = task["api_task_id"]start_time = datetime.now()while not self.stop_event.is_set():# Check if we've been polling too longif (datetime.now() - start_time).seconds > MAX_POLLING_TIME:task_manager.update_task(self.task_id,status="timeout",error="Polling timeout - task took too long",completed=True)breaktry:# Poll the APIresult = _poll_suno_api(api_task_id)if result["status"] == "completed":task_manager.update_task(self.task_id,status="completed",result=result.get("data"),method="polling",completed=True)breakelif result["status"] == "failed":task_manager.update_task(self.task_id,status="failed",error=result.get("error", "Unknown error"),completed=True)breakelse:# Still processingtask_manager.update_task(self.task_id,status=result["status"])# Wait before next pollself.stop_event.wait(POLLING_INTERVAL)except Exception as e:task_manager.update_task(self.task_id,status="polling_error",error=f"Polling error: {str(e)}",last_checked=datetime.now())# Wait before retryself.stop_event.wait(POLLING_INTERVAL * 2)def stop(self):self.stop_event.set()def _poll_suno_api(api_task_id: str) -> dict:"""Internal function to poll Suno API"""if not SUNO_KEY:raise ValueError("SunoKey not configured")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.raise_for_status()data = response.json()if data.get("code") == 200 and "data" in data:task_data = data["data"]return {"status": task_data.get("status", "unknown"),"data": task_data.get("data"),"error": task_data.get("error")}else:raise Exception(data.get("msg", "API polling failed"))def submit_to_suno(prompt: str, task_id: str, callback_url: str = "") -> dict:"""Submit task to Suno API with error handling"""if not SUNO_KEY:raise ValueError("SunoKey environment variable not set")url = "https://api.sunoapi.org/api/v1/lyrics"headers = {"Authorization": f"Bearer {SUNO_KEY}","Content-Type": "application/json"}# If no callback_url provided, use a dummy one# Suno requires a URL, but we'll rely on pollingeffective_callback = callback_url or "https://dummy.webhook.url/not-used"payload = {"prompt": prompt,"callBackUrl": effective_callback}try:response = requests.post(url, headers=headers, json=payload, timeout=30)response.raise_for_status()data = response.json()if data.get("code") == 200 and "data" in data:api_task_id = data["data"]["taskId"]# Start background polling with delay (give webhook a chance)polling_thread = PollingThread(task_id)# Start polling after WEBHOOK_TIMEOUT secondsdef start_polling():time.sleep(WEBHOOK_TIMEOUT)task = task_manager.get_task(task_id)if task and not task.get("webhook_received") and not task.get("polling_started"):task_manager.update_task(task_id, polling_started=True)polling_thread.start()threading.Thread(target=start_polling, daemon=True).start()return {"success": True,"api_task_id": api_task_id,"message": "Task submitted successfully"}else:error_msg = data.get("msg", "Unknown API error")return {"success": False,"error": f"API Error: {error_msg}","code": data.get("code")}except requests.exceptions.Timeout:return {"success": False,"error": "Request timeout - Suno API is not responding"}except requests.exceptions.ConnectionError:return {"success": False,"error": "Connection error - Check your internet connection"}except requests.exceptions.HTTPError as e:return {"success": False,"error": f"HTTP Error: {e.response.status_code if e.response else 'Unknown'}"}except Exception as e:return {"success": False,"error": f"Unexpected error: {str(e)}"}def generate_lyrics(prompt: str, use_callback: bool = True):"""Main function to generate lyrics with hybrid approach"""if not prompt or not prompt.strip():return "❌ Please enter a prompt"if not SUNO_KEY:return "❌ Error: SunoKey environment variable not set. Please configure it in Settings."# Create taskcallback_url = f"{SPACE_URL}/callback" if use_callback else ""task_id = task_manager.create_task(prompt, callback_url)try:# Submit to Sunoresult = submit_to_suno(prompt, task_id, callback_url)if result["success"]:# Update task with API task IDtask_manager.update_task(task_id,api_task_id=result["api_task_id"],status="submitted",method="webhook" if use_callback else "polling")return f"""✅ **Task Submitted Successfully!****Your Task ID:** `{task_id}`**API Task ID:** `{result['api_task_id']}`**Method:** {'Webhook + Polling Fallback' if use_callback else 'Polling Only'}**Status:** Submitted - Processing...📝 **Prompt:** {prompt[:100]}{'...' if len(prompt) > 100 else ''}⏳ **What happens next:**1. Task submitted to Suno AI2. {'Webhook expected within 30 seconds' if use_callback else 'Polling started'}3. Results will appear automatically4. You can also check status manually🆔 **Save this Task ID:** {task_id}"""else:# Submission failedtask_manager.update_task(task_id,status="submission_failed",error=result["error"],completed=True)return f"""❌ **Submission Failed****Task ID:** `{task_id}`**Error:** {result['error']}💡 **Possible solutions:**• Check your SunoKey is valid• Try a different prompt• Wait a few minutes and try again"""except Exception as e:error_msg = str(e)task_manager.update_task(task_id,status="exception",error=error_msg,completed=True)return f"❌ Exception occurred: {error_msg}"def check_task_status(task_id: str):"""Check status of a specific task"""if not task_id or not task_id.strip():return "❌ Please enter a Task ID"task = task_manager.get_task(task_id)if not task:return f"❌ Task ID `{task_id}` not found. Please check and try again."status = task["status"]method = task.get("method", "unknown")elapsed = (datetime.now() - task["created_at"]).seconds# Format status displayif task["completed"]:if status == "completed" and task["result"]:return format_lyrics_result(task["result"], task_id, method)elif status == "failed" or status == "error":return f"""❌ **Task Failed****Task ID:** `{task_id}`**Status:** {status}**Error:** {task.get('error', 'Unknown error')}**Method:** {method}**Elapsed:** {elapsed} seconds💡 Please try generating again."""else:return f"📊 **Task Completed with status:** {status}"else:# Task still in progressstatus_icon = {"created": "🆕","submitted": "⏳","processing": "🔄","pending": "⏱️"}.get(status, "❓")return f"""{status_icon} **Task In Progress****Task ID:** `{task_id}`**Status:** {status}**Method:** {method}**Elapsed:** {elapsed} seconds**Last checked:** {task.get('last_checked', 'Never')}⏳ **Processing...** Please check back in a few seconds.🔁 **Auto-refreshing in 5 seconds...**"""def format_lyrics_result(lyrics_data, task_id, method):"""Format lyrics for display"""if not lyrics_data:return "✅ Task completed but no lyrics data received"output = [f"🎵 **Generated Lyrics (Task: {task_id})**", ""]for i, item in enumerate(lyrics_data, 1):title = item.get('title', f'Variant {i}')text = item.get('text', 'No lyrics generated')output.append(f"### Variant {i}: {title}")output.append("```")output.append(text)output.append("```")output.append("---")output.append(f"\n✅ **Completed via:** {method}")output.append(f"🕒 **Finished at:** {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")return "\n".join(output)def list_all_tasks():"""List all tasks with status"""tasks = task_manager.get_all_tasks()if not tasks:return "📭 No tasks found. Generate some lyrics first!"# Sort by creation time (newest first)tasks.sort(key=lambda x: x["created_at"], reverse=True)output = ["📋 **All Tasks**", ""]for task in tasks:# Status iconif task["completed"]:icon = "✅" if task["status"] == "completed" else "❌"else:icon = "⏳"elapsed = (datetime.now() - task["created_at"]).secondsmethod = task.get("method", "unknown")output.append(f"{icon} **{task['id']}** - {task['status']}")output.append(f" Prompt: {task['prompt'][:50]}...")output.append(f" Method: {method} | Age: {elapsed}s")if task.get("error"):output.append(f" Error: {task['error'][:50]}...")output.append("")# Cleanup old tasks periodicallycleaned = task_manager.cleanup_old_tasks(hours=1)if cleaned:output.append(f"🧹 Cleaned up {cleaned} old tasks")return "\n".join(output)# Webhook handler function for Gradio 6.0+async def webhook_handler(request: Request):"""Handle incoming webhook from Suno"""try:# Get the raw request bodybody = await request.body()print(f"📥 Webhook received: {request.method}")# Try to parse JSONtry:data = json.loads(body.decode('utf-8'))except:# Try form dataform_data = await request.form()data = dict(form_data) if form_data else {}print(f"📦 Webhook data received")# Extract task info (adjust based on Suno's actual format)if isinstance(data, dict):print(f"Data structure: {json.dumps(data, indent=2)[:500]}...")# Try different possible response formatsapi_data = Noneif "data" in data:api_data = data["data"]elif "task" in data:api_data = data["task"]elif "result" in data:api_data = data["result"]if api_data and isinstance(api_data, dict):api_task_id = api_data.get("taskId") or api_data.get("id")status = api_data.get("status", "unknown")if api_task_id:# Find task by API task IDfor task in task_manager.get_all_tasks():if task.get("api_task_id") == api_task_id:task_id = task["id"]if status == "completed":lyrics_data = api_data.get("data") or api_data.get("lyrics") or api_data.get("result")task_manager.update_task(task_id,status="completed",result=lyrics_data,webhook_received=True,method="webhook",completed=True)print(f"✅ Webhook completed task {task_id}")return {"status": "success", "task_id": task_id}elif status == "failed":error_msg = api_data.get("error", "Unknown error")task_manager.update_task(task_id,status="failed",error=error_msg,webhook_received=True,completed=True)return {"status": "error", "task_id": task_id, "error": error_msg}else:task_manager.update_task(task_id, status=status)return {"status": "updated", "task_id": task_id}return {"status": "no_match", "message": "Task not found in database"}except Exception as e:print(f"❌ Webhook error: {str(e)}")return {"status": "error", "message": str(e)}# Create Gradio appwith gr.Blocks() as app:gr.Markdown("# 🎵 Suno AI Lyrics Generator")gr.Markdown("Hybrid solution: Webhooks with automatic polling fallback")with gr.Tabs():with gr.TabItem("✨ Generate"):with gr.Row():with gr.Column(scale=2):prompt_input = gr.Textbox(label="Lyrics Prompt",placeholder="A jazz song about rainy nights in Tokyo...",lines=4)use_webhook = gr.Checkbox(label="Enable webhooks (recommended)",value=True,info="If webhook fails, automatic polling will start")submit_btn = gr.Button("🚀 Generate Lyrics", variant="primary", scale=1)gr.Markdown("### 📋 Instructions:")gr.Markdown("""1. Enter your lyrics idea2. Submit (webhooks enabled by default)3. Save your Task ID4. Check status in the "Status" tab5. Results arrive automatically**🔧 Behind the scenes:**- Webhook attempted first- If no response in 30s, polling starts- Polling continues until completion- Results available in both tabs""")with gr.Column(scale=3):output_result = gr.Markdown(label="Submission Result",value="Your results will appear here...")submit_btn.click(generate_lyrics,inputs=[prompt_input, use_webhook],outputs=output_result)with gr.TabItem("🔍 Check Status"):with gr.Row():with gr.Column():task_id_input = gr.Textbox(label="Task ID",placeholder="Enter your Task ID (e.g., a1b2c3d4)")with gr.Row():check_btn = gr.Button("🔎 Check Status", variant="primary")refresh_btn = gr.Button("🔄 Auto-refresh", variant="secondary")list_all_btn = gr.Button("📋 All Tasks")task_list_output = gr.Textbox(label="All Tasks",lines=10,interactive=False)with gr.Column():status_output = gr.Markdown(label="Task Status",value="Enter a Task ID and click Check Status")# Event handlerscheck_btn.click(check_task_status,inputs=task_id_input,outputs=status_output)refresh_btn.click(check_task_status,inputs=task_id_input,outputs=status_output)list_all_btn.click(list_all_tasks,inputs=None,outputs=task_list_output)with gr.TabItem("⚙️ Settings & Info"):gr.Markdown("### ⚙️ Configuration")with gr.Row():with gr.Column():gr.Markdown("**🔑 API Status:**")api_status = gr.Markdown(value=f"✅ SunoKey: {'Configured' if SUNO_KEY else '❌ NOT SET'}")gr.Markdown(f"**🌐 Space URL:** `{SPACE_URL}`")gr.Markdown("**🔄 Webhook Endpoint:**")webhook_info = gr.Textbox(value=f"{SPACE_URL}/callback",interactive=False)with gr.Column():gr.Markdown("**📊 Statistics:**")stats_text = gr.Textbox(value=f"Active tasks: {len(task_manager.get_all_tasks())}",interactive=False)cleanup_btn = gr.Button("🧹 Cleanup Old Tasks", variant="secondary")cleanup_output = gr.Textbox(label="Cleanup Result", interactive=False)gr.Markdown("### 📚 How It Works:")gr.Markdown(f"""**Hybrid Approach:**1. Submit with webhook URL (required by Suno API)2. Wait 30 seconds for webhook response3. If no webhook, start background polling4. Poll every 5 seconds until completion5. Return results via polling if webhook fails**Your Webhook URL:** `{SPACE_URL}/callback`**Error Recovery:**• Network issues → automatic retry• API errors → informative messages• Timeouts → fallback to polling• All errors → logged for debugging""")cleanup_btn.click(lambda: f"Cleaned {task_manager.cleanup_old_tasks(hours=1)} old tasks",inputs=None,outputs=cleanup_output)# Add the webhook route using the new Gradio 6.0 methodapp.add_api_route("/callback", webhook_handler, methods=["POST"])# For backward compatibility, also add a simple GET endpoint@app.get("/")def home():return {"status": "running", "app": "Suno Lyrics Generator"}# Launch the appif __name__ == "__main__":print("🚀 Starting Suno Lyrics Generator...")print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ NOT SET'}")print(f"🌐 Space URL: {SPACE_URL}")print(f"🌐 Webhook endpoint: {SPACE_URL}/callback")print(f"⏱️ Polling fallback: {WEBHOOK_TIMEOUT}s delay")app.launch(server_name="0.0.0.0",server_port=7860,share=False,show_error=True,debug=False,title="Suno Lyrics Generator",theme="soft")2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024032 unmodified linesimport osimport jsonimport uuidimport timefrom 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!")# Task storagetasks_db = {}def generate_lyrics(prompt: str) -> 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]# Prepare API requesturl = "https://api.sunoapi.org/api/v1/lyrics"headers = {"Authorization": f"Bearer {SUNO_KEY}","Content-Type": "application/json"}# Suno requires a callback URL, but we'll use a dummy one and rely on pollingdummy_callback = "https://dummy.callback.url/not-used"payload = {"prompt": prompt,"callBackUrl": dummy_callback}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,"api_task_id": api_task_id,"prompt": prompt,"status": "submitted","result": None,"error": None,"created_at": datetime.now().isoformat(),"last_checked": None}return f"""✅ **Task Submitted Successfully!****Your Task ID:** `{task_id}`**API Task ID:** `{api_task_id}`📝 **Prompt:** {prompt[:100]}{'...' if len(prompt) > 100 else ''}⏳ **Next Steps:**1. Task is now processing with Suno AI2. This usually takes 10-30 seconds3. Click **"Check Status"** tab to check progress4. Use your Task ID: `{task_id}`💡 **Tip:** Save your Task ID to check results later!"""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 requests.exceptions.HTTPError as e:return f"❌ Error: HTTP {e.response.status_code if e.response else 'Unknown'}"except Exception as e:return f"❌ Error: {str(e)}"def check_task_status(task_id: str) -> str:"""Check the status of a task using polling"""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["api_task_id"]# Poll the Suno APIurl = f"https://api.sunoapi.org/api/v1/lyrics/details?taskId={api_task_id}"headers = {"Authorization": f"Bearer {SUNO_KEY}"}try: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()if status == "completed" and "data" in task_data:# Task completed successfullylyrics_data = task_data["data"]tasks_db[task_id]["result"] = lyrics_data# Format the outputreturn format_lyrics_output(lyrics_data, task_id)elif status == "failed":error_msg = task_data.get("error", "Unknown error")tasks_db[task_id]["error"] = error_msgreturn f"""❌ **Task Failed****Task ID:** `{task_id}`**Error:** {error_msg}💡 Please try generating again with a different prompt."""else:# Still processingelapsed = time_since(task["created_at"])return f"""⏳ **Task Processing...****Task ID:** `{task_id}`**Status:** {status}**Elapsed:** {elapsed}⏰ **Estimated time:** 10-30 seconds🔄 **Auto-refresh recommended**💡 Check back in a few seconds!"""else:error_msg = data.get("msg", f"HTTP {response.status_code}")return f"❌ Error checking status: {error_msg}"except Exception as e:return f"❌ Error: {str(e)}"def format_lyrics_output(lyrics_data, task_id):"""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 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 time_since(iso_timestamp: str) -> str:"""Calculate time elapsed since timestamp"""try:created = datetime.fromisoformat(iso_timestamp)elapsed = datetime.now() - createdseconds = int(elapsed.total_seconds())if seconds < 60:return f"{seconds} seconds"elif seconds < 3600:minutes = seconds // 60return f"{minutes} minutes"else:hours = seconds // 3600return f"{hours} hours"except:return "Unknown"def list_all_tasks():"""List all submitted tasks"""if not tasks_db:return "📭 No tasks found. Generate some lyrics first!"output_lines = ["# 📋 All Submitted Tasks", ""]for task_id, task in tasks_db.items():status = task.get("status", "unknown")prompt_preview = task.get("prompt", "")[:50]created = task.get("created_at", "")[:19]# Status iconif status == "completed":icon = "✅"elif status in ["failed", "error"]:icon = "❌"else:icon = "⏳"output_lines.append(f"{icon} **{task_id}** - {status}")output_lines.append(f" Prompt: {prompt_preview}...")output_lines.append(f" Created: {created}")if task.get("last_checked"):last_checked = task["last_checked"][:19]output_lines.append(f" Last checked: {last_checked}")output_lines.append("")# Add summarycompleted = sum(1 for t in tasks_db.values() if t.get("status") == "completed")total = len(tasks_db)output_lines.append(f"**Summary:** {completed}/{total} tasks completed")return "\n".join(output_lines)def auto_refresh_status(task_id: str):"""Auto-refresh status with loading animation"""if not task_id or task_id not in tasks_db:return task_id, "❌ Invalid Task ID"result = check_task_status(task_id)return task_id, result# 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")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=4)submit_btn = gr.Button("🚀 Generate Lyrics", variant="primary", size="lg")gr.Markdown("### 📝 Tips:")gr.Markdown("""• Be descriptive in your prompt• Include genre, mood, or theme• Specify if you want verses, chorus, bridge• Typical processing time: 10-30 seconds""")with gr.Column(scale=3):output_area = gr.Markdown(label="Result",value="Your task submission result will appear here...")submit_btn.click(fn=generate_lyrics,inputs=prompt_input,outputs=output_area)# 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., a1b2c3d4)",scale=1)with gr.Row():check_btn = gr.Button("🔍 Check Status", variant="primary")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")# Connect buttons to functionscheck_btn.click(fn=check_task_status,inputs=task_id_input,outputs=status_output)auto_refresh_btn.click(fn=auto_refresh_status,inputs=task_id_input,outputs=[task_id_input, status_output]).then(fn=lambda: time.sleep(3),inputs=None,outputs=None).then(fn=auto_refresh_status,inputs=task_id_input,outputs=[task_id_input, status_output])refresh_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 a lyrics prompt and submit2. **Save your Task ID** from the result3. **Check Status Tab:** Paste your Task ID to check progress4. **Results:** Lyrics will appear when processing is complete""")with gr.Column():gr.Markdown("### 🚨 Troubleshooting")gr.Markdown("""**Common Issues:**• **"SunoKey not set":** Add your API key in Space Settings → Repository secrets• **"Task ID not found":** Submit a new task and save the ID• **Long processing time:** Suno API can take 10-30 seconds• **API errors:** Check if your API key is valid and has credits**For best results:**- Use descriptive prompts- Check status after 15-20 seconds- Save your Task IDs""")gr.Markdown("### 📞 Support")gr.Markdown("""If you continue to have issues:1. **Check your SunoKey** is correct and has available credits2. **Try a simpler prompt** to test the API3. **Wait a few minutes** if the API seems busy4. **Contact Suno API support** for API-specific issues""")# Launch the appif __name__ == "__main__":print(f"🔑 SunoKey status: {'Configured' if SUNO_KEY else 'NOT SET'}")print(f"📊 Tasks in memory: {len(tasks_db)}")print("🚀 Starting Suno Lyrics Generator...")app.launch(server_name="0.0.0.0",server_port=7860,share=False,debug=False,show_error=True)
app.py+243-527