Spaces:
Paused
Paused
Update app.py
Browse files2 unmodified lines345678979 unmodified lines89909191929394929394959697989910010110297103104105106107108109110111112991131141151161171041181191201211 unmodified line123124125112126127114128129130117131132119133134135122136137124125138139140141142129130131132133143144145146136137138139140141142143144145146147148149147148149105 unmodified lines2552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013022622633033043053062663073083093103113123133142722732742752763153163173183193203213223233243253263273283293303313323333343353363373383393403413423432783442802812822832842853453463473483493503513523533543553563573583593603613623633642882892902912922932942952962973653663672982993003013023033043053063073083093103113123133143153163683693193203703223233243253263273283713723733743753763773783793803813823833843303313853863873883893903913333343353363373923933943953963973983994004014024034048 unmodified lines4134144153584164174184194204213624224234244254264274284294304314324334344354364374384394404414424434444454464473643653663673683693704484494504514524534544554564573734584593753764604614624634644653814664674682 unmodified linesimport osimport timeimport jsonimport tempfile
# Suno API keySUNO_KEY = os.environ.get("SunoKey", "")79 unmodified lines output += "\n```\n" output += "---\n\n" output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds" # Store lyrics for potential song generation lyrics_info = { "lyrics_list": lyrics_list, output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds\n\n" output += "📝 **Now you can:**\n" output += "1. Select a variant below\n" output += "2. Edit the text if needed\n" output += "3. Generate a song!" # Prepare data for state lyrics_data = { "variants": lyrics_list, "original_prompt": prompt } yield output, lyrics_info # Update dropdown with variants variant_choices = [f"{i+1}: {lyric.get('title', f'Variant {i+1}')}" for i, lyric in enumerate(lyrics_list)] # Get first variant text for editing 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 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 yield f"❌ Task failed: {error}", None, [], "" return else:1 unmodified line 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 f"Still processing... (Usually takes 30-90 seconds)"), None, [], "" else: yield f"⚠️ Check error: HTTP {check.status_code}", None yield f"⚠️ Check error: HTTP {check.status_code}", None, [], "" except Exception as e: yield f"⚠️ Error checking status: {str(e)}", None yield f"⚠️ Error checking status: {str(e)}", None, [], "" yield "⏰ Timeout after 150 seconds. Try checking again later.", None yield "⏰ Timeout after 150 seconds. Try checking again later.", None, [], "" except Exception as e: yield f"❌ Error: {str(e)}", None yield f"❌ Error: {str(e)}", None, [], []
def generate_song(lyrics_info, variant_choice, style, title, instrumental, model, custom_mode): """Generate a song from lyrics"""def generate_song_from_text(lyrics_text, style, title, instrumental, model, custom_mode): """Generate a song from text""" if not SUNO_KEY: return "❌ Error: SunoKey not configured in environment variables" if lyrics_info is None: return "❌ Error: No lyrics available. Please generate lyrics first." if not lyrics_info.get("lyrics_list"): return "❌ Error: No lyrics found in the provided data." if not lyrics_text.strip(): return "❌ Error: Please provide lyrics text" try: # Get selected lyrics variant variant_idx = int(variant_choice.split(":")[0]) - 1 # Convert "1: Title" to 0-index lyrics_list = lyrics_info["lyrics_list"] if variant_idx >= len(lyrics_list): return f"❌ Error: Invalid variant selection. Only {len(lyrics_list)} variants available." selected_lyric = lyrics_list[variant_idx] lyrics_text = selected_lyric.get('text', '') lyrics_title = selected_lyric.get('title', f'Variant {variant_idx + 1}') if not lyrics_text.strip(): return "❌ Error: Selected lyrics variant has no text content." # Prepare request data based on custom mode request_data = { "customMode": custom_mode,105 unmodified lines except Exception as e: return f"❌ Error: {str(e)}"
def update_text_from_variant(lyrics_data, variant_choice): """Update the text area when a variant is selected""" if lyrics_data and lyrics_data.get("variants") and variant_choice: try: # Extract variant index from choice (e.g., "1: Title" -> 0) 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 ""
def download_text_file(text): """Create a downloadable text file""" if not text.strip(): return None # Create a temporary file with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f: f.write(text) temp_path = f.name return temp_path
def upload_text_file(file): """Read text from uploaded file""" if file is None: return "" try: with open(file.name, 'r', encoding='utf-8') as f: content = f.read() return content except: try: with open(file.name, 'r', encoding='latin-1') as f: content = f.read() return content except Exception as e: return f"❌ Error reading file: {str(e)}"
# Create the appwith gr.Blocks(title="Suno Lyrics & Song Generator", theme="soft") as app: gr.Markdown("# 🎵 Suno Lyrics & Song Generator")with 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 between steps # Store lyrics data between steps lyrics_state = gr.State() with gr.Row(): with gr.Column(scale=1): # Lyrics Generation Section gr.Markdown("### Step 1: Generate or Upload Lyrics") gr.Markdown("### Step 1: Generate Lyrics") prompt = gr.Textbox( label="Lyrics Prompt", placeholder="Example: A happy song about sunshine and rainbows", lines=3 with gr.Tab("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") with gr.Tab("Upload Lyrics"): file_upload = gr.File( label="Upload Text File", file_types=[".txt"], type="filepath" ) upload_btn = gr.Button("📁 Load from File", variant="secondary") upload_text = gr.Textbox( label="Uploaded Text", lines=10, interactive=False ) # Lyrics Selection & Editing Section gr.Markdown("### Step 2: Select & Edit Lyrics") variant_choice = gr.Dropdown( label="Select Lyrics Variant", choices=[], interactive=True ) lyrics_btn = gr.Button("🎵 Generate Lyrics", variant="primary") # Song Generation Section (initially hidden) gr.Markdown("### Step 2: Create Song") with gr.Group(): variant_choice = gr.Dropdown( label="Select Lyrics Variant", choices=[], lyrics_text = gr.Textbox( label="Lyrics Text (Editable)", placeholder="Your lyrics will appear here...", lines=15, interactive=True ) with gr.Row(): download_btn = gr.Button("💾 Download Text", variant="secondary") clear_btn = gr.Button("🗑️ Clear", variant="secondary") # Song Generation Section gr.Markdown("### Step 3: Create Song") with gr.Row(): custom_mode = gr.Checkbox( label="Custom Mode", value=False, interactive=True ) with gr.Row(): custom_mode = gr.Checkbox( label="Custom Mode (Advanced Settings)", value=False, interactive=True ) instrumental = gr.Checkbox( label="Instrumental (No Vocals)", value=False, instrumental = gr.Checkbox( label="Instrumental", value=False, interactive=True ) with gr.Row(): style = gr.Textbox( label="Music Style (Required for Custom Mode)", placeholder="Example: Pop, Rock, Jazz, Classical", interactive=True ) title = gr.Textbox( label="Song Title (Required for Custom Mode)", placeholder="Example: My Awesome 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="secondary") # Instructions gr.Markdown(""" **How it works:** 1. Enter your lyrics idea and generate 2. Select a lyrics variant from results 3. Choose song settings (or use defaults) 4. Generate a full song with music! with gr.Row(): style = gr.Textbox( label="Music Style", placeholder="Pop, Rock, Jazz, Classical", interactive=True, value="Pop" ) title = gr.Textbox( label="Song Title", placeholder="My Awesome Song", interactive=True, value="Generated Song" ) **Custom Mode:** Enable for advanced control **Instrumental:** Check for music only (no singing) model = gr.Dropdown( label="Model Version", choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"], value="V4_5ALL", interactive=True ) **Status messages:** - ✅ Submitted = Task accepted - ⏳ PROCESSING = Generating - 🎶 Complete = Song ready! """) song_btn = gr.Button("🎶 Generate Song", variant="primary") with gr.Column(scale=2): output = gr.Markdown( label="Results", value="Your generated lyrics and songs will appear here..." ) # Hidden file download component file_output = gr.File(label="Download Lyrics", visible=False) gr.Markdown("---") gr.Markdown(8 unmodified lines elem_id="footer" ) # Lyrics generation # Event handlers # Generate lyrics from prompt lyrics_btn.click( generate_lyrics, inputs=prompt, outputs=[output, lyrics_state] outputs=[output, lyrics_state, variant_choice, lyrics_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 above and generate a song.", outputs=output ) # Update text when variant is selected variant_choice.change( update_text_from_variant, inputs=[lyrics_state, variant_choice], outputs=lyrics_text ) # Download text as file download_btn.click( download_text_file, inputs=lyrics_text, outputs=file_output ).then( lambda lyrics_info: gr.Dropdown( choices=[f"{i+1}: {lyric.get('title', f'Variant {i+1}')}" for i, lyric in enumerate(lyrics_info.get("lyrics_list", []))] if lyrics_info and lyrics_info.get("lyrics_list") else [] ), inputs=lyrics_state, outputs=variant_choice lambda: "💾 **Text ready for download!**\n\nCheck the download button below.", outputs=output ) # Clear text clear_btn.click( lambda: ("", ""), outputs=[lyrics_text, output] ) # Song generation # Generate song from text song_btn.click( generate_song, inputs=[lyrics_state, variant_choice, style, title, instrumental, model, custom_mode], generate_song_from_text, inputs=[lyrics_text, style, title, instrumental, model, custom_mode], outputs=output )
if __name__ == "__main__": print("🚀 Starting Suno Lyrics & Song Generator") 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)app.py+191-106