Spaces:
Paused
Paused
Update app.py
Browse files9 unmodified lines1011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351314151617181401920212223242526271432829145303132148333435363715115215315415515638394041424344454647158159160161162163164165166167168169170171481731741754950515253545556575859606162636465666768697071727374757677787980817 unmodified lines899091189929394959619397989910010110210310425 unmodified lines13013113213313413513613713813914014114214314423114514623314714814915015123715215315415515615724215815916016116216316424916516616725225325425525625725825926026126226326426526626716816917017117217317427417517617717816 unmodified lines1951961971981992002012022982993003013023032032042052062072083073082092102113103113123133143153163173182122132142152162172182193202202212222232242253263273283293303313323333343353362262273383393403413423433443453463473483493503513523533543553563573583593603613622282292302312322333672342353692362372382392402412423732432442452462472482492502512522532542552562572582592602613783793803813823832622632642652663852672682692702713893903913923932722732742752762772782792802812822832842853953963973982862872882892902914022922934044052942952962974082982993003011 unmodified line3033043054164174183063073083093101 unmodified line3123133144264274284294304314324333153163173183193204393213223233244434444454464474484494503253263273283293304563313323333344603353364624633373383393404664673413423434693443453463473484743493503519 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" return if not prompt.strip(): yield "❌ Error: Please enter a prompt" return # Submit task try: 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}" 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"✅ **Submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for lyrics...\n" # Poll for results for attempt in range(30): # 30 attempts * 5 seconds = 150 seconds max time.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 lyrics response_data = check_data["data"].get("response", {}) if isinstance(response_data, str): # Sometimes response is a JSON string try: 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 += text output += "\n```\n" output += "---\n\n" output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds" # NEW: Store lyrics for later use lyrics_data = { "variants": lyrics_list, "original_prompt": prompt } # NEW: Prepare variant choices for dropdown variant_choices = [f"{i+1}: {lyric.get('title', f'Variant {i+1}')}" for i, lyric in enumerate(lyrics_list)] # NEW: Get first variant text first_text = lyrics_list[0].get('text', '') if lyrics_list else "" yield output, lyrics_data, variant_choices, first_text else: yield "✅ Completed but no lyrics found in response", None, [], "" return elif status == "FAILED": error = check_data["data"].get("errorMessage", "Unknown error") yield f"❌ Task failed: {error}", None, [], "" return else: # PENDING or PROCESSING yield (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"""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 text" 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: # Prepare request data based on custom mode # Always use custom mode for full control request_data = { "customMode": custom_mode, "customMode": True, # Always True for our use case "instrumental": instrumental, "model": model, "callBackUrl": "http://dummy.com/callback", # Required but not used "callBackUrl": "http://dummy.com/callback", "style": style, "title": title, } if custom_mode: # Custom mode requires style and title if not style.strip(): return "❌ Error: Style is required in Custom Mode" if not title.strip(): return "❌ Error: Title is required in Custom Mode" 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": lyrics_text = lyrics_text[:3000] yield f"⚠️ Lyrics truncated to 3000 characters for V4 model\n\n" request_data["style"] = style request_data["title"] = title if not instrumental: # Non-instrumental requires lyrics as prompt if 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_text else: # 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 mode request_data["style"] = "" request_data["title"] = "" 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": style = style[:200] yield f"⚠️ Style truncated to 200 characters for V4 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"]: title = title[:80] yield f"⚠️ Title truncated to 80 characters for {model} model\n\n" # Update with possibly truncated values request_data["style"] = style request_data["title"] = title yield 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 request resp = requests.post(7 unmodified lines ) if resp.status_code != 200: return f"❌ Submission failed: HTTP {resp.status_code}" yield f"❌ Submission failed: HTTP {resp.status_code}" return data = resp.json() if data.get("code") != 200: return f"❌ API error: {data.get('msg', 'Unknown')}" yield f"❌ API error: {data.get('msg', 'Unknown')}" return task_id = data["data"]["taskId"] yield f"✅ **Request submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for song generation...\n" # Poll for results for attempt in range(60): # 60 attempts * 5 seconds = 300 seconds max (5 minutes)25 unmodified lines 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 streaming if 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" return output yield output else: return "✅ Completed but no songs found in response" yield "✅ Completed but no songs found in response" return elif status == "FAILED": error = check_data["data"].get("errorMessage", "Unknown error") return f"❌ Task failed: {error}" yield f"❌ Task failed: {error}" return else: # Still processing if attempt % 6 == 0: # Update every 30 seconds yield f"⏳ Status: {status}\nAttempt: {attempt + 1}/60\nTask ID: `{task_id}`\n\nStill processing... (Usually takes 30-180 seconds)" yield 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)}" return "⏰ Timeout after 300 seconds. Try checking again later." yield "⏰ 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()) - 1 variants = lyrics_data["variants"] if 0 <= variant_idx < len(variants): text = variants[variant_idx].get('text', '') return text except: pass return "" yield f"❌ Error: {str(e)}"
def download_text_file(text): """Create downloadable text file""" if not text.strip(): return None with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f: with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False, encoding='utf-8') as f: f.write(text) temp_path = f.name 16 unmodified lines except 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 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 data lyrics_state = gr.State()with 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): # Step 1: Generate Lyrics (original layout preserved) gr.Markdown("### Step 1: Generate Lyrics") # Lyrics Input gr.Markdown("### Step 1: Enter 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 Section gr.Markdown("### Text Management") 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 Text"): with gr.Tab("Upload Lyrics"): 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 Lyrics gr.Markdown("### Step 2: Edit Lyrics (Optional)") upload_btn = gr.Button("📁 Load from File", variant="secondary") 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" ) # Song Settings gr.Markdown("### Step 2: Song Settings") with gr.Row(): style = gr.Textbox( label="Music Style", placeholder="Pop, Rock, Jazz", placeholder="Example: Pop, Rock, Jazz, Classical, Electronic, Hip Hop, Country", value="Pop", interactive=True interactive=True, scale=2 ) with gr.Row(): title = gr.Textbox( label="Song Title", placeholder="My Song", 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 ) model = gr.Dropdown( label="Model Version", choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"], value="V4_5ALL", interactive=True ) # Action Buttons with gr.Row(): generate_btn = gr.Button("🎶 Generate Song", variant="primary", scale=2) clear_btn = gr.Button("🗑️ Clear All", variant="secondary", scale=1) song_btn = gr.Button("🎶 Generate Song", variant="primary") with gr.Row(): download_btn = gr.Button("💾 Download Lyrics", variant="secondary") # Instructions gr.Markdown(""" **How it works:** 1. Generate lyrics or upload your own 2. Edit the text if needed 3. Set song parameters 4. Generate music! **How to use:** 1. Paste lyrics or upload a .txt file 2. Set music style (genre) 3. Enter song title 4. 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 **Song Generation:** - Custom Mode: Requires style & title - Non-custom: Simple mode with prompt only - Instrumental: Music only, no singing **Generation time:** - 30-40s: Stream URL ready - 2-3 min: Download URL ready """) with gr.Column(scale=2): # Main output (unchanged) # Output Area output = gr.Markdown( label="Results", value="Your generated lyrics and songs will appear here..." label="Generation Status", value="### Ready to generate!\n\n1. Enter lyrics\n2. Set style and title\n3. Click 'Generate Song'" ) # NEW: Hidden download component # Hidden download component file_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> <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 # Original lyrics generation (unchanged except outputs) lyrics_btn.click( generate_lyrics, inputs=prompt, outputs=[output, lyrics_state, variant_choice, lyrics_text] ) # NEW: Upload text # Upload text from file upload_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.", lambda: "📁 **Lyrics loaded from file!**\n\nReady to generate song.", outputs=output ) # NEW: Update text when variant selected variant_choice.change( update_text_from_variant, inputs=[lyrics_state, variant_choice], outputs=lyrics_text ) # NEW: Download text # Download lyrics download_btn.click( download_text_file, inputs=lyrics_text, outputs=file_output ).then( lambda: "💾 **Text ready for download!**", lambda: "💾 **Lyrics ready for download!**", outputs=output ) # NEW: Clear text # Clear all clear_btn.click( lambda: ("", "Text cleared."), outputs=[lyrics_text, output] clear_all, outputs=[lyrics_text, style, title, instrumental, model, output] ) # NEW: Generate song song_btn.click( # Generate song generate_btn.click( generate_song_from_text, inputs=[lyrics_text, style, title, instrumental, model, custom_mode], inputs=[lyrics_text, style, title, instrumental, model], outputs=output )
if __name__ == "__main__": print("🚀 Starting Suno Lyrics Generator") 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