Spaces:
Paused
Paused
Update app.py
Browse files9 unmodified lines1011121313141516171819202021222323242526272628293031323331343536343738394041424041424344454344454647484950515251535455555657565758596061626362636464656667686970687172734 unmodified lines78798079818283828384858687888990919293949596979884858687888990919293949596979899100101102103104105106107108109110111112113114115116101102117118119120104105121107122123124125111126127128129130131117118119120121122123124125126127128129132133134131132133134135136137138139140141142143144145146147148149135136137138151152153154155156157158159160139140141142162163164165143144145146167147148149150151152153154155156157158159160161162169170171172173174175176177178179163164165181182183184185166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210187211212213214215216217218219220221222223224225226227228229230231232189190191192193194195196197233234235236237238239240241199200201202203204205206207208209210211212213214215242243244245246247248249250251252253254255256257258218219220221222223224225226227259260261262263264265266267229268269270271272273274275276277232278279280281234282283284285286287288289290291292237293294295296105 unmodified lines4024034043493504054064074083534094104113564124134144159 unmodified linesif not SUNO_KEY: print("⚠️ SunoKey not set!")
def generate_song_from_text(lyrics_text, style, title, instrumental, model, custom_mode=True):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" return if not lyrics_text.strip(): return "❌ Error: Please provide lyrics" yield "❌ Error: Please provide lyrics" return if not style.strip(): return "❌ Error: Please provide a music style" yield "❌ Error: Please provide a music style" return if not title.strip(): return "❌ Error: Please provide a song title" yield "❌ Error: Please provide a song title" return try: # Always use custom mode for full control request_data = { "customMode": True, # Always True for our use case "customMode": True, "instrumental": instrumental, "model": model, "callBackUrl": "http://dummy.com/callback", "callBackUrl": "", # Empty callback URL - we'll poll instead "style": style, "title": title, } if not instrumental: # Non-instrumental requires lyrics as prompt # Apply character limits based on model if 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": # Apply character limits if 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_text else: # For instrumental, clear the prompt request_data["prompt"] = "" # Apply style length limits if len(style) > 1000 and model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"]: style = style[:1000] elif len(style) > 200 and model == "V4": if 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 limits if len(title) > 100 and model in ["V4_5", "V4_5PLUS", "V5"]: title = title[:100] elif len(title) > 80 and model in ["V4", "V4_5ALL"]: if 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" # Update with possibly truncated values request_data["style"] = style request_data["title"] = title 4 unmodified lines yield 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 request try: 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}" return data = resp.json() if data.get("code") != 200: yield f"❌ API error: {data.get('msg', 'Unknown')}" 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}" return data = resp.json() if data.get("code") != 200: yield f"❌ API error: {data.get('msg', 'Unknown')}" return task_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 task_id = data["data"]["taskId"] yield f"✅ **Request submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for song generation...\n" # Poll for completion - with better error handling max_attempts = 60 # 60 attempts * 10 seconds = 10 minutes last_status = "" # Poll for results max_attempts = 90 # 90 attempts * 10 seconds = 900 seconds (15 minutes) for attempt in range(max_attempts): time.sleep(10) # Check every 10 seconds time.sleep(10) try: # Check task status check = requests.get( check_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.status_code == 200: check_data = check.json() if check_data.get("code") != 200: # If we get an error, check if task might still be processing if attempt < max_attempts - 1: continue else: yield f"⚠️ API returned error: {check_data.get('msg', 'Unknown')}" continue data_info = check_data.get("data", {}) status = data_info.get("status", "PENDING") if check_resp.status_code == 200: check_data = check_resp.json() if status == "COMPLETE": # Try to get the response data response_data = data_info.get("response", {}) # The response might be a JSON string or already parsed if isinstance(response_data, str): try: response_data = json.loads(response_data) except: # Try to extract URLs directly if it's not JSON yield 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 if check_data.get("code") == 200: data_info = check_data.get("data", {}) current_status = data_info.get("status", "UNKNOWN") # Extract songs from response songs = response_data.get("data", []) if not songs: # Try alternative structure songs = response_data.get("songs", []) if songs: output = "🎶 **Song Generation Complete!**\n\n" output += f"Generated {len(songs)} song(s)\n\n" # Only show status update if it changed if current_status != last_status: last_status = current_status 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') if current_status == "COMPLETE": # Try to parse the response response_data = data_info.get("response", {}) output += f"## Song {i}: {song_title}\n" # Response might be a JSON string if isinstance(response_data, str): try: response_data = json.loads(response_data) except json.JSONDecodeError: # If it's not JSON, it might be a simple string yield 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 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 streaming 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""" else: output += "⚠️ Stream URL not available yet\n\n" # Look for songs in different possible locations songs = [] 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" # Try different possible structures if 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 list if 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_data if 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 player yield 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" output += "---\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" return else: # No songs found in response yield 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" return 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" elif 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." return yield output else: # No songs found in response yield 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." return elif status == "FAILED": error = data_info.get("errorMessage", "Unknown error") yield f"❌ Task failed: {error}" return elif 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: # Still processing (PENDING or PROCESSING) if attempt % 3 == 0: # Update every 30 seconds yield 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" # API returned error code error_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"⚠️ Check error: HTTP {check.status_code} - Task might still be processing" 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)} - Will try again..." yield f"⚠️ **Error checking status:** {str(e)}\n\n" yield "Will retry in 10 seconds...\n" yield f"Check: {attempt + 1}/{max_attempts}\n" yield "⏰ Timeout after 15 minutes. Try checking your Suno API dashboard for results." # If we get here, we timed out yield "⏰ **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"❌ Error: {str(e)}" yield f"❌ **Unexpected Error:** {str(e)}"
def download_text_file(text): """Create downloadable text file"""105 unmodified lines 5. Click Generate Song! **Tips:** - For best results, use structured lyrics with verses/chorus - Style examples: "Pop", "Rock guitar solo", "Jazz piano", "Electronic dance" - 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 - Instrumental: Check for music only (no vocals) **Generation time:** - 30-40s: Stream URL ready - 30-60s: Stream URL ready - 2-3 min: Download URL ready - Up to 5 min for longer songs """)app.py+208-152