Spaces:
Paused
Paused
Update app.py
Browse files100 unmodified lines1011021031041051061071081091101111123 unmodified lines1161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671683 unmodified lines172173174175176177178179180181182183184185186117 unmodified lines304305306307308309100 unmodified linestask_id = data["data"]["taskId"]yield f"✅ **Request submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for song generation...\n"# Poll for results - FIXED ENDPOINTfor attempt in range(60): # 60 attempts * 5 seconds = 300 seconds max (5 minutes)time.sleep(5)try:# FIX: Use the correct endpoint from the API docscheck = requests.get(f"https://api.sunoapi.org/api/v1/generate/record-info?taskId={task_id}",headers={"Authorization": f"Bearer {SUNO_KEY}"},3 unmodified linesif check.status_code == 200:check_data = check.json()# Check if the response structure is validif check_data.get("code") != 200:yield f"⚠️ API returned error: {check_data.get('msg', 'Unknown')}"continuedata_info = check_data.get("data", {})status = data_info.get("status", "PENDING")if status == "COMPLETE":# Success! Extract song URLsresponse_data = data_info.get("response", {})# Try to parse response if it's a stringif isinstance(response_data, str):try:response_data = json.loads(response_data)except:response_data = {}songs = response_data.get("data", [])if songs:output = "🎶 **Song Generation Complete!**\n\n"for i, song in enumerate(songs, 1):song_title = song.get('title', f'Song {i}')stream_url = song.get('streamUrl', 'No URL')download_url = song.get('downloadUrl', 'No URL')output += f"## Song {i}: {song_title}\n"output += f"**Stream URL:** {stream_url}\n\n"output += f"**Download URL:** {download_url}\n\n"output += f"**Listen Now:** [Click to Stream]({stream_url})\n\n"# Add audio player for streamingif stream_url and stream_url != 'No URL':output += f"""<audio controls style="width: 100%; margin: 10px 0;"><source src="{stream_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>\n\n"""output += "---\n\n"output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds\n\n"output += "⚠️ **Note:** Files are retained for 15 days"yield outputelse:yield "✅ Completed but no songs found in response"returnelif status == "FAILED":3 unmodified lineselse:# Still processing (PENDING or PROCESSING)if attempt % 6 == 0: # Update every 30 secondsyield f"⏳ Status: {status}\nAttempt: {attempt + 1}/60\nTask ID: `{task_id}`\n\nStill processing... (Usually takes 30-180 seconds)\n\nTypical timing:\n- 30-40s: Stream URL ready\n- 2-3 min: Download URL ready"else:yield f"⚠️ Check error: HTTP {check.status_code}"except Exception as e:yield f"⚠️ Error checking status: {str(e)}"yield "⏰ Timeout after 300 seconds. Try checking again later."except Exception as e:yield f"❌ Error: {str(e)}"117 unmodified lines**Generation time:**- 30-40s: Stream URL ready- 2-3 min: Download URL ready""")with gr.Column(scale=2):100 unmodified lines1011021031041051061071081091101111121133 unmodified lines1171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112123 unmodified lines216217218219220221222223224225226227228229230231232233234235236237117 unmodified lines355356357358359360361100 unmodified linestask_id = data["data"]["taskId"]yield f"✅ **Request submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for song generation...\n"# Poll for resultsmax_attempts = 90 # 90 attempts * 10 seconds = 900 seconds (15 minutes)for attempt in range(max_attempts):time.sleep(10) # Check every 10 secondstry:# Check task statuscheck = requests.get(f"https://api.sunoapi.org/api/v1/generate/record-info?taskId={task_id}",headers={"Authorization": f"Bearer {SUNO_KEY}"},3 unmodified linesif check.status_code == 200:check_data = check.json()if check_data.get("code") != 200:# If we get an error, check if task might still be processingif attempt < max_attempts - 1:continueelse:yield f"⚠️ API returned error: {check_data.get('msg', 'Unknown')}"continuedata_info = check_data.get("data", {})status = data_info.get("status", "PENDING")if status == "COMPLETE":# Try to get the response dataresponse_data = data_info.get("response", {})# The response might be a JSON string or already parsedif isinstance(response_data, str):try:response_data = json.loads(response_data)except:# Try to extract URLs directly if it's not JSONyield f"🎵 **Generation Complete!**\n\n"yield f"Task ID: `{task_id}`\nStatus: {status}\n\n"yield "However, we couldn't parse the song URLs from the response.\n\n"yield "**Try this:**\n"yield "1. Go to https://sunoapi.org\n"yield "2. Log in to your account\n"yield f"3. Check your generation history for task ID: {task_id}\n"yield "4. You should find your songs there with download links\n"return# Extract songs from responsesongs = response_data.get("data", [])if not songs:# Try alternative structuresongs = response_data.get("songs", [])if songs:output = "🎶 **Song Generation Complete!**\n\n"output += f"Generated {len(songs)} song(s)\n\n"for i, song in enumerate(songs, 1):song_title = song.get('title', f'Song {i}')stream_url = song.get('streamUrl') or song.get('stream_url')download_url = song.get('downloadUrl') or song.get('download_url')output += f"## Song {i}: {song_title}\n"if stream_url:output += f"**Stream URL:** {stream_url}\n\n"output += f"**Listen Now:** [Click to Stream]({stream_url})\n\n"# Add audio player for streamingoutput += f"""<audio controls style="width: 100%; margin: 10px 0;"><source src="{stream_url}" type="audio/mpeg">Your browser does not support the audio element.</audio>\n\n"""else:output += "⚠️ Stream URL not available yet\n\n"if download_url:output += f"**Download URL:** {download_url}\n\n"output += f"**Download:** [Click to Download]({download_url})\n\n"else:output += "⚠️ Download URL not available yet (check back in 2-3 minutes)\n\n"output += "---\n\n"output += f"⏱️ Generated in about {(attempt + 1) * 10} seconds\n\n"output += "**Tips:**\n"output += "- Stream URLs work immediately\n"output += "- Download URLs may take 2-3 minutes to become available\n"output += "- Files are retained for 15 days\n\n"output += "**If URLs don't work:**\n"output += f"1. Visit https://sunoapi.org\n"output += f"2. Log in and check your generation history\n"output += f"3. Look for task ID: `{task_id}`\n"yield outputelse:# No songs found in responseyield f"🎵 **Generation Complete!**\n\n"yield f"Task ID: `{task_id}`\nStatus: {status}\n\n"yield "**To access your songs:**\n"yield "1. Go to https://sunoapi.org\n"yield "2. Log in to your account\n"yield "3. Check your generation history\n"yield f"4. Look for task ID: `{task_id}`\n"yield "\nThe songs should be available there with download links."returnelif status == "FAILED":3 unmodified lineselse:# Still processing (PENDING or PROCESSING)if attempt % 3 == 0: # Update every 30 secondsyield f"⏳ Status: {status}\n"yield f"Attempt: {attempt + 1}/{max_attempts}\n"yield f"Task ID: `{task_id}`\n\n"yield "Still processing...\n\n"yield "**Typical timing:**\n"yield "- 30-40 seconds: Stream URL ready\n"yield "- 2-3 minutes: Download URL ready\n"yield "- Up to 5 minutes for longer songs\n"else:yield f"⚠️ Check error: HTTP {check.status_code} - Task might still be processing"except Exception as e:yield f"⚠️ Error checking status: {str(e)} - Will try again..."yield "⏰ Timeout after 15 minutes. Try checking your Suno API dashboard for results."except Exception as e:yield f"❌ Error: {str(e)}"117 unmodified lines**Generation time:**- 30-40s: Stream URL ready- 2-3 min: Download URL ready- Up to 5 min for longer songs""")with gr.Column(scale=2):
app.py+77-25