Spaces:
Paused
Paused
Update app.py
Browse files9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771787 unmodified lines18618718818919019119219319419519619719825 unmodified lines22422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627716 unmodified lines2942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104111 unmodified line4134144154164174184194204211 unmodified line4234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754769 unmodified linesif not SUNO_KEY:print("⚠️ SunoKey not set!")def generate_lyrics(prompt):"""Final working lyrics generator - UNCHANGED"""if not SUNO_KEY:yield "❌ Error: SunoKey not configured in environment variables"returnif not prompt.strip():yield "❌ Error: Please enter a prompt"return# Submit tasktry:resp = requests.post("https://api.sunoapi.org/api/v1/lyrics",json={"prompt": prompt,"callBackUrl": "http://dummy.com/callback" # Required but not used},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"✅ **Submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for lyrics...\n"# Poll for resultsfor attempt in range(30): # 30 attempts * 5 seconds = 150 seconds maxtime.sleep(5)try:check = requests.get("https://api.sunoapi.org/api/v1/lyrics/record-info",headers={"Authorization": f"Bearer {SUNO_KEY}"},params={"taskId": task_id},timeout=30)if check.status_code == 200:check_data = check.json()status = check_data["data"].get("status", "PENDING")if status == "SUCCESS":# Success! Extract lyricsresponse_data = check_data["data"].get("response", {})if isinstance(response_data, str):# Sometimes response is a JSON stringtry:response_data = json.loads(response_data.replace('null', 'None'))except:response_data = {"data": []}lyrics_list = response_data.get("data", [])if lyrics_list:output = "🎵 **Lyrics Generated Successfully!**\n\n"for i, lyric in enumerate(lyrics_list, 1):title = lyric.get('title', f'Variant {i}')text = lyric.get('text', 'No lyrics')output += f"## Variant {i}: {title}\n"output += "```\n"output += textoutput += "\n```\n"output += "---\n\n"output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds"# NEW: Store lyrics for later uselyrics_data = {"variants": lyrics_list,"original_prompt": prompt}# NEW: Prepare variant choices for dropdownvariant_choices = [f"{i+1}: {lyric.get('title', f'Variant {i+1}')}"for i, lyric in enumerate(lyrics_list)]# NEW: Get first variant textfirst_text = lyrics_list[0].get('text', '') if lyrics_list else ""yield output, lyrics_data, variant_choices, first_textelse:yield "✅ Completed but no lyrics found in response", None, [], ""returnelif status == "FAILED":error = check_data["data"].get("errorMessage", "Unknown error")yield f"❌ Task failed: {error}", None, [], ""returnelse:# PENDING or PROCESSINGyield (f"⏳ Status: {status}\n"f"Attempt: {attempt + 1}/30\n"f"Task ID: `{task_id}`\n\n"f"Still processing... (Usually takes 30-90 seconds)"), None, [], ""else:yield f"⚠️ Check error: HTTP {check.status_code}", None, [], ""except Exception as e:yield f"⚠️ Error checking status: {str(e)}", None, [], ""yield "⏰ Timeout after 150 seconds. Try checking again later.", None, [], ""except Exception as e:yield f"❌ Error: {str(e)}", None, [], ""def generate_song_from_text(lyrics_text, style, title, instrumental, model, custom_mode):"""NEW: Generate a song from lyrics text"""if not SUNO_KEY:return "❌ Error: SunoKey not configured in environment variables"if not lyrics_text.strip():return "❌ Error: Please provide lyrics text"try:# Prepare request data based on custom moderequest_data = {"customMode": custom_mode,"instrumental": instrumental,"model": model,"callBackUrl": "http://dummy.com/callback", # Required but not used}if custom_mode:# Custom mode requires style and titleif not style.strip():return "❌ Error: Style is required in Custom Mode"if not title.strip():return "❌ Error: Title is required in Custom Mode"request_data["style"] = stylerequest_data["title"] = titleif not instrumental:# Non-instrumental requires lyrics as promptif len(lyrics_text) > 5000 and model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"]:lyrics_text = lyrics_text[:5000]elif len(lyrics_text) > 3000 and model == "V4":lyrics_text = lyrics_text[:3000]request_data["prompt"] = lyrics_textelse:# Non-custom mode only requires prompt (max 500 chars)if len(lyrics_text) > 500:lyrics_text = lyrics_text[:497] + "..."request_data["prompt"] = lyrics_text# Clear other fields for non-custom moderequest_data["style"] = ""request_data["title"] = ""# Submit generation requestresp = requests.post(7 unmodified lines)if resp.status_code != 200:return f"❌ Submission failed: HTTP {resp.status_code}"data = resp.json()if data.get("code") != 200:return f"❌ API error: {data.get('msg', 'Unknown')}"task_id = data["data"]["taskId"]# Poll for resultsfor attempt in range(60): # 60 attempts * 5 seconds = 300 seconds max (5 minutes)25 unmodified linesoutput += 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"output += "---\n\n"output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds\n\n"output += "⚠️ **Note:** Files are retained for 15 days"return outputelse:return "✅ Completed but no songs found in response"elif status == "FAILED":error = check_data["data"].get("errorMessage", "Unknown error")return f"❌ Task failed: {error}"else:# Still processingif 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)"else:yield f"⚠️ Check error: HTTP {check.status_code}"except Exception as e:yield f"⚠️ Error checking status: {str(e)}"return "⏰ Timeout after 300 seconds. Try checking again later."except Exception as e:return f"❌ Error: {str(e)}"# NEW: Helper functions for text handlingdef update_text_from_variant(lyrics_data, variant_choice):"""Update text area when variant is selected"""if lyrics_data and lyrics_data.get("variants") and variant_choice:try:variant_idx = int(variant_choice.split(":")[0].strip()) - 1variants = lyrics_data["variants"]if 0 <= variant_idx < len(variants):text = variants[variant_idx].get('text', '')return textexcept:passreturn ""def download_text_file(text):"""Create downloadable text file"""if not text.strip():return Nonewith tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:f.write(text)temp_path = f.name16 unmodified linesexcept Exception as e:return f"❌ Error reading file: {str(e)}"# Create the appwith gr.Blocks(title="Suno Lyrics Generator", theme="soft") as app:gr.Markdown("# 🎵 Suno Lyrics Generator")gr.Markdown("Generate song lyrics and turn them into full songs using Suno AI")# Store lyrics datalyrics_state = gr.State()with gr.Row():with gr.Column(scale=1):# Step 1: Generate Lyrics (original layout preserved)gr.Markdown("### Step 1: Generate Lyrics")prompt = gr.Textbox(label="Lyrics Prompt",placeholder="Example: A happy song about sunshine and rainbows",lines=3)lyrics_btn = gr.Button("🎵 Generate Lyrics", variant="primary")# NEW: Text Management Sectiongr.Markdown("### Text Management")with gr.Tab("Upload Text"):file_upload = gr.File(label="Upload Text File (.txt)",file_types=[".txt"],type="filepath")upload_btn = gr.Button("📁 Load Text", variant="secondary")with gr.Tab("Select from Generated"):variant_choice = gr.Dropdown(label="Select Generated Variant",choices=[],interactive=True)# Step 2: Edit Lyricsgr.Markdown("### Step 2: Edit Lyrics (Optional)")lyrics_text = gr.Textbox(label="Lyrics Text",placeholder="Your lyrics will appear here. You can edit them or paste your own.",lines=15,interactive=True)with gr.Row():download_btn = gr.Button("💾 Download Text", variant="secondary")clear_btn = gr.Button("🗑️ Clear", variant="secondary")# Step 3: Generate Song (NEW)gr.Markdown("### Step 3: Generate Song")with gr.Row():custom_mode = gr.Checkbox(label="Custom Mode",value=False,info="Enable for advanced settings")instrumental = gr.Checkbox(label="Instrumental",value=False,info="No vocals")with gr.Row():style = gr.Textbox(label="Music Style",placeholder="Pop, Rock, Jazz",value="Pop",interactive=True)title = gr.Textbox(label="Song Title",placeholder="My Song",value="Generated Song",interactive=True)model = gr.Dropdown(label="Model Version",choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"],value="V4_5ALL",interactive=True)song_btn = gr.Button("🎶 Generate Song", variant="primary")# Instructionsgr.Markdown("""**How it works:**1. Generate lyrics or upload your own2. Edit the text if needed3. Set song parameters4. Generate music!**Song Generation:**- Custom Mode: Requires style & title- Non-custom: Simple mode with prompt only- Instrumental: Music only, no singing""")with gr.Column(scale=2):# Main output (unchanged)output = gr.Markdown(label="Results",value="Your generated lyrics and songs will appear here...")# NEW: Hidden download componentfile_output = gr.File(label="Download Lyrics", visible=False)gr.Markdown("---")1 unmodified line"""<div style="text-align: center; padding: 20px;"><p>Powered by <a href="https://suno.ai" target="_blank">Suno AI</a> •<a href="https://sunoapi.org" target="_blank">Suno API Docs</a> •<a href="https://github.com" target="_blank">GitHub</a></p><p><small>This app uses the Suno API to generate AI-powered lyrics and music.</small></p></div>""",elem_id="footer"1 unmodified line# Event handlers# Original lyrics generation (unchanged except outputs)lyrics_btn.click(generate_lyrics,inputs=prompt,outputs=[output, lyrics_state, variant_choice, lyrics_text])# NEW: Upload textupload_btn.click(upload_text_file,inputs=file_upload,outputs=lyrics_text).then(lambda: "📁 **Text loaded from file!**\n\nYou can now edit the text and generate a song.",outputs=output)# NEW: Update text when variant selectedvariant_choice.change(update_text_from_variant,inputs=[lyrics_state, variant_choice],outputs=lyrics_text)# NEW: Download textdownload_btn.click(download_text_file,inputs=lyrics_text,outputs=file_output).then(lambda: "💾 **Text ready for download!**",outputs=output)# NEW: Clear textclear_btn.click(lambda: ("", "Text cleared."),outputs=[lyrics_text, output])# NEW: Generate songsong_btn.click(generate_song_from_text,inputs=[lyrics_text, style, title, instrumental, model, custom_mode],outputs=output)if __name__ == "__main__":print("🚀 Starting Suno Lyrics Generator")print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}")app.launch(server_name="0.0.0.0", server_port=7860, share=False)9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980817 unmodified lines899091929394959697989910010110210310425 unmodified lines13013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717816 unmodified lines1951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003011 unmodified line3033043053063073083093101 unmodified line3123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503519 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:return "❌ Error: SunoKey not configured in environment variables"if 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"] = titleyield f"✅ **Submitting song request...**\n\n"yield f"**Title:** {title}\n"yield f"**Style:** {style}\n"yield f"**Model:** {model}\n"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 requestresp = requests.post(7 unmodified lines)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 resultsfor attempt in range(60): # 60 attempts * 5 seconds = 300 seconds max (5 minutes)25 unmodified linesoutput += 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":error = check_data["data"].get("errorMessage", "Unknown error")yield f"❌ Task failed: {error}"returnelse:# Still processingif 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)}"def download_text_file(text):"""Create downloadable text file"""if not text.strip():return Nonewith tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f:f.write(text)temp_path = f.name16 unmodified linesexcept Exception as e:return f"❌ Error reading file: {str(e)}"def clear_all():"""Clear all input fields"""return "", "", "Generated Song", False, "V4_5ALL", ""# Create the appwith gr.Blocks(title="Suno Song Generator", theme="soft") as app:gr.Markdown("# 🎵 Suno Song Generator")gr.Markdown("Create songs from lyrics and style using Suno AI")with gr.Row():with gr.Column(scale=1):# Lyrics Inputgr.Markdown("### Step 1: Enter Lyrics")with gr.Tab("Paste Lyrics"):lyrics_text = gr.Textbox(label="Lyrics",placeholder="Paste your lyrics here...\n\nExample:\n(Verse 1)\nSun is shining, sky is blue\nBirds are singing, just for you...",lines=15,interactive=True)with gr.Tab("Upload Lyrics"):file_upload = gr.File(label="Upload Text File (.txt)",file_types=[".txt"],type="filepath")upload_btn = gr.Button("📁 Load from File", variant="secondary")# Song Settingsgr.Markdown("### Step 2: Song Settings")with gr.Row():style = gr.Textbox(label="Music Style",placeholder="Example: Pop, Rock, Jazz, Classical, Electronic, Hip Hop, Country",value="Pop",interactive=True,scale=2)with gr.Row():title = gr.Textbox(label="Song Title",placeholder="My Awesome Song",value="Generated Song",interactive=True,scale=2)with gr.Row():instrumental = gr.Checkbox(label="Instrumental (No Vocals)",value=False,interactive=True)model = gr.Dropdown(label="Model",choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"],value="V4_5ALL",interactive=True)# Action Buttonswith gr.Row():generate_btn = gr.Button("🎶 Generate Song", variant="primary", scale=2)clear_btn = gr.Button("🗑️ Clear All", variant="secondary", scale=1)with gr.Row():download_btn = gr.Button("💾 Download Lyrics", variant="secondary")# Instructionsgr.Markdown("""**How to use:**1. Paste lyrics or upload a .txt file2. Set music style (genre)3. Enter song title4. Choose model (V4_5ALL recommended)5. 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""")with gr.Column(scale=2):# Output Areaoutput = gr.Markdown(label="Generation Status",value="### Ready to generate!\n\n1. Enter lyrics\n2. Set style and title\n3. Click 'Generate Song'")# Hidden download componentfile_output = gr.File(label="Download Lyrics", visible=False)gr.Markdown("---")1 unmodified line"""<div style="text-align: center; padding: 20px;"><p>Powered by <a href="https://suno.ai" target="_blank">Suno AI</a> •<a href="https://sunoapi.org" target="_blank">Suno API Docs</a></p><p><small>Create custom songs by providing lyrics and music style</small></p></div>""",elem_id="footer"1 unmodified line# Event handlers# Upload text from fileupload_btn.click(upload_text_file,inputs=file_upload,outputs=lyrics_text).then(lambda: "📁 **Lyrics loaded from file!**\n\nReady to generate song.",outputs=output)# Download lyricsdownload_btn.click(download_text_file,inputs=lyrics_text,outputs=file_output).then(lambda: "💾 **Lyrics ready for download!**",outputs=output)# Clear allclear_btn.click(clear_all,outputs=[lyrics_text, style, title, instrumental, model, output])# Generate songgenerate_btn.click(generate_song_from_text,inputs=[lyrics_text, style, title, instrumental, model],outputs=output)if __name__ == "__main__":print("🚀 Starting Suno Song Generator")print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}")app.launch(server_name="0.0.0.0", server_port=7860, share=False)
app.py+154-279