Spaces:
Paused
Paused
Update app.py
Browse files9 unmodified lines10111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970714 unmodified lines767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240105 unmodified lines3463473483493503513523533543553563573583599 unmodified linesif not SUNO_KEY:print("⚠️ SunoKey not set!")def generate_song_from_text(lyrics_text, style, title, instrumental, model, custom_mode=True):"""Generate a song from lyrics text"""if not SUNO_KEY:yield "❌ Error: SunoKey not configured in environment variables"returnif not lyrics_text.strip():return "❌ Error: Please provide lyrics"if not style.strip():return "❌ Error: Please provide a music style"if not title.strip():return "❌ Error: Please provide a song title"try:# Always use custom mode for full controlrequest_data = {"customMode": True, # Always True for our use case"instrumental": instrumental,"model": model,"callBackUrl": "http://dummy.com/callback","style": style,"title": title,}if not instrumental:# Non-instrumental requires lyrics as prompt# Apply character limits based on modelif len(lyrics_text) > 5000 and model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"]:lyrics_text = lyrics_text[:5000]yield f"⚠️ Lyrics truncated to 5000 characters for {model} model\n\n"elif len(lyrics_text) > 3000 and model == "V4":lyrics_text = lyrics_text[:3000]yield f"⚠️ Lyrics truncated to 3000 characters for V4 model\n\n"request_data["prompt"] = lyrics_textelse:# For instrumental, clear the promptrequest_data["prompt"] = ""# Apply style length limitsif len(style) > 1000 and model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"]:style = style[:1000]elif len(style) > 200 and model == "V4":style = style[:200]yield f"⚠️ Style truncated to 200 characters for V4 model\n\n"# Apply title length limitsif len(title) > 100 and model in ["V4_5", "V4_5PLUS", "V5"]:title = title[:100]elif len(title) > 80 and model in ["V4", "V4_5ALL"]:title = title[:80]yield f"⚠️ Title truncated to 80 characters for {model} model\n\n"# Update with possibly truncated valuesrequest_data["style"] = stylerequest_data["title"] = title4 unmodified linesyield f"**Instrumental:** {'Yes' if instrumental else 'No'}\n"if not instrumental:yield f"**Lyrics length:** {len(lyrics_text)} characters\n\n"yield f"⏳ Processing...\n"# Submit generation requestresp = requests.post("https://api.sunoapi.org/api/v1/generate",json=request_data,headers={"Authorization": f"Bearer {SUNO_KEY}","Content-Type": "application/json"},timeout=30)if resp.status_code != 200:yield f"❌ Submission failed: HTTP {resp.status_code}"returndata = resp.json()if data.get("code") != 200:yield f"❌ API error: {data.get('msg', 'Unknown')}"returntask_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}"},timeout=30)if 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":error = data_info.get("errorMessage", "Unknown error")yield f"❌ Task failed: {error}"returnelse:# 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)}"def download_text_file(text):"""Create downloadable text file"""105 unmodified lines5. Click Generate Song!**Tips:**- For best results, use structured lyrics with verses/chorus- Style examples: "Pop", "Rock guitar solo", "Jazz piano", "Electronic dance"- V5: Latest model, best quality- V4_5ALL: Good balance, up to 8 minutes- Instrumental: Check for music only**Generation time:**- 30-40s: Stream URL ready- 2-3 min: Download URL ready- Up to 5 min for longer songs""")9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172734 unmodified lines78798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296105 unmodified lines4024034044054064074084094104114124134144159 unmodified linesif not SUNO_KEY:print("⚠️ SunoKey not set!")def generate_song_from_text(lyrics_text, style, title, instrumental, model):"""Generate a song from lyrics text"""if not SUNO_KEY:yield "❌ Error: SunoKey not configured in environment variables"returnif not lyrics_text.strip():yield "❌ Error: Please provide lyrics"returnif not style.strip():yield "❌ Error: Please provide a music style"returnif not title.strip():yield "❌ Error: Please provide a song title"returntry:# Always use custom mode for full controlrequest_data = {"customMode": True,"instrumental": instrumental,"model": model,"callBackUrl": "", # Empty callback URL - we'll poll instead"style": style,"title": title,}if not instrumental:# Apply character limitsif model == "V4" and len(lyrics_text) > 3000:lyrics_text = lyrics_text[:3000]yield f"⚠️ Lyrics truncated to 3000 characters for V4 model\n\n"elif model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"] and len(lyrics_text) > 5000:lyrics_text = lyrics_text[:5000]yield f"⚠️ Lyrics truncated to 5000 characters for {model} model\n\n"request_data["prompt"] = lyrics_textelse:request_data["prompt"] = ""# Apply style length limitsif model == "V4" and len(style) > 200:style = style[:200]yield f"⚠️ Style truncated to 200 characters for V4 model\n\n"elif model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"] and len(style) > 1000:style = style[:1000]yield f"⚠️ Style truncated to 1000 characters for {model} model\n\n"# Apply title length limitsif model in ["V4", "V4_5ALL"] and len(title) > 80:title = title[:80]yield f"⚠️ Title truncated to 80 characters for {model} model\n\n"elif model in ["V4_5", "V4_5PLUS", "V5"] and len(title) > 100:title = title[:100]yield f"⚠️ Title truncated to 100 characters for {model} model\n\n"request_data["style"] = stylerequest_data["title"] = title4 unmodified linesyield f"**Instrumental:** {'Yes' if instrumental else 'No'}\n"if not instrumental:yield f"**Lyrics length:** {len(lyrics_text)} characters\n\n"# Submit generation requesttry:resp = requests.post("https://api.sunoapi.org/api/v1/generate",json=request_data,headers={"Authorization": f"Bearer {SUNO_KEY}","Content-Type": "application/json"},timeout=30)if resp.status_code != 200:yield f"❌ Submission failed: HTTP {resp.status_code}"returndata = resp.json()if data.get("code") != 200:yield f"❌ API error: {data.get('msg', 'Unknown')}"returntask_id = data["data"]["taskId"]yield f"✅ **Request submitted successfully!**\n"yield f"**Task ID:** `{task_id}`\n\n"yield f"⏳ Song generation started...\n\n"yield "**What to do next:**\n"yield "1. Keep this window open while the song generates\n"yield "2. We'll automatically check the status every 10 seconds\n"yield "3. Generation typically takes 1-3 minutes\n"yield "4. When complete, you'll get streaming and download links\n\n"except Exception as e:yield f"❌ Error submitting request: {str(e)}"return# Poll for completion - with better error handlingmax_attempts = 60 # 60 attempts * 10 seconds = 10 minuteslast_status = ""for attempt in range(max_attempts):time.sleep(10)try:# Check task statuscheck_resp = requests.get(f"https://api.sunoapi.org/api/v1/generate/record-info?taskId={task_id}",headers={"Authorization": f"Bearer {SUNO_KEY}"},timeout=30)if check_resp.status_code == 200:check_data = check_resp.json()if check_data.get("code") == 200:data_info = check_data.get("data", {})current_status = data_info.get("status", "UNKNOWN")# Only show status update if it changedif current_status != last_status:last_status = current_statusif current_status == "COMPLETE":# Try to parse the responseresponse_data = data_info.get("response", {})# Response might be a JSON stringif isinstance(response_data, str):try:response_data = json.loads(response_data)except json.JSONDecodeError:# If it's not JSON, it might be a simple stringyield f"✅ **Generation Complete!**\n\n"yield f"**Status:** {current_status}\n"yield f"**Task ID:** `{task_id}`\n\n"yield "**To access your song:**\n"yield "1. Visit https://sunoapi.org\n"yield "2. Log in to your account\n"yield "3. Go to 'Generation History'\n"yield "4. Find your song by Task ID\n"return# Look for songs in different possible locationssongs = []# Try different possible structuresif isinstance(response_data, dict):songs = response_data.get("data", [])if not songs:songs = response_data.get("songs", [])if not songs:# Check if response_data itself is a song listif isinstance(response_data.get("0"), dict):songs = [response_data.get("0")]if isinstance(response_data.get("1"), dict):songs.append(response_data.get("1"))elif isinstance(response_data, list):songs = response_dataif songs:yield "🎶 **SONG GENERATION COMPLETE!** 🎶\n\n"yield f"Generated {len(songs)} song(s)\n\n"for i, song in enumerate(songs, 1):if isinstance(song, dict):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')yield f"## 🎵 Song {i}: {song_title}\n"if stream_url:yield f"**Stream URL:** {stream_url}\n"yield f"**Listen Now:** [Click to Stream]({stream_url})\n\n"# Audio playeryield f"""<audio controls style="width: 100%; margin: 10px 0; padding: 10px; background: #f0f0f0; border-radius: 5px;"><source src="{stream_url}" type="audio/mpeg">Your browser does not support audio playback.</audio>\n\n"""else:yield "⏳ Stream URL not ready yet (check back in 30 seconds)\n\n"if download_url:yield f"**Download URL:** {download_url}\n"yield f"**Download:** [Click to Download]({download_url})\n\n"else:yield "⏳ Download URL not ready yet (usually takes 2-3 minutes)\n\n"yield "---\n\n"yield f"⏱️ Total generation time: {(attempt + 1) * 10} seconds\n\n"yield "**Important:**\n"yield "- Stream links work immediately\n"yield "- Download links may take 2-3 minutes\n"yield "- Files are kept for 15 days\n"yield f"- Task ID: `{task_id}` (save this for reference)\n"returnelse:# No songs found in responseyield f"✅ **Generation Complete!**\n\n"yield f"**Status:** {current_status}\n"yield f"**Task ID:** `{task_id}`\n\n"yield "**Response received but no song data found.**\n\n"yield "**To access your song:**\n"yield "1. Visit https://sunoapi.org\n"yield "2. Log in to your account\n"yield "3. Check 'Generation History'\n"yield "4. Look for this Task ID\n"returnelif current_status == "FAILED":error_msg = data_info.get("errorMessage", "Unknown error")yield f"❌ **Generation Failed**\n\n"yield f"**Status:** {current_status}\n"yield f"**Error:** {error_msg}\n"yield f"**Task ID:** `{task_id}`\n\n"yield "Please try again with different parameters."returnelif current_status in ["PENDING", "PROCESSING"]:yield f"⏳ **Status Update**\n\n"yield f"**Current Status:** {current_status}\n"yield f"**Task ID:** `{task_id}`\n"yield f"**Check:** {attempt + 1}/{max_attempts}\n\n"yield "**Estimated time remaining:**\n"yield "- Stream URL: 30-60 seconds\n"yield "- Download URL: 2-3 minutes\n"yield "\nWe'll check again in 10 seconds...\n"else:yield f"📊 **Status:** {current_status}\n"yield f"**Task ID:** `{task_id}`\n"yield f"**Check:** {attempt + 1}/{max_attempts}\n\n"yield "Still processing...\n"else:# API returned error codeerror_msg = check_data.get("msg", "Unknown error")yield f"⚠️ **API Error**\n\n"yield f"**Code:** {check_data.get('code')}\n"yield f"**Message:** {error_msg}\n"yield f"**Task ID:** `{task_id}`\n\n"yield "Will continue checking...\n"else:yield f"⚠️ **HTTP Error {check_resp.status_code}**\n\n"yield f"Failed to check status. Will retry in 10 seconds...\n"yield f"Check: {attempt + 1}/{max_attempts}\n"except requests.exceptions.Timeout:yield f"⏱️ **Timeout checking status**\n\n"yield "The status check timed out. Will try again in 10 seconds...\n"yield f"Check: {attempt + 1}/{max_attempts}\n"except Exception as e:yield f"⚠️ **Error checking status:** {str(e)}\n\n"yield "Will retry in 10 seconds...\n"yield f"Check: {attempt + 1}/{max_attempts}\n"# If we get here, we timed outyield "⏰ **Timeout after 10 minutes**\n\n"yield f"**Task ID:** `{task_id}`\n\n"yield "**What to do:**\n"yield "1. The song may still be processing\n"yield "2. Visit https://sunoapi.org\n"yield "3. Log in and check 'Generation History'\n"yield "4. Look for this Task ID\n"yield "\nSongs can sometimes take longer than expected, especially for longer tracks."except Exception as e:yield f"❌ **Unexpected Error:** {str(e)}"def download_text_file(text):"""Create downloadable text file"""105 unmodified lines5. Click Generate Song!**Tips:**- Use structured lyrics with verses/chorus for best results- Style examples: "Pop", "Rock guitar", "Jazz piano", "Electronic"- V5: Latest model, best quality- V4_5ALL: Good balance, up to 8 minutes- Instrumental: Check for music only (no vocals)**Generation time:**- 30-60s: Stream URL ready- 2-3 min: Download URL ready- Up to 5 min for longer songs""")
app.py+208-152