Spaces:
Paused
Paused
Update app.py
Browse files2 unmodified lines34567879 unmodified lines8889909192939495969798991001011021031041051061071 unmodified line109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152105 unmodified lines2582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453468 unmodified lines3553563573583593603613623633643653663673683693703713723733743753763773783793803813823832 unmodified linesimport osimport timeimport json# Suno API keySUNO_KEY = os.environ.get("SunoKey", "")79 unmodified linesoutput += "\n```\n"output += "---\n\n"output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds"# Store lyrics for potential song generationlyrics_info = {"lyrics_list": lyrics_list,"original_prompt": prompt}yield output, lyrics_infoelse:yield "✅ Completed but no lyrics found in response", Nonereturnelif status == "FAILED":error = check_data["data"].get("errorMessage", "Unknown error")yield f"❌ Task failed: {error}", Nonereturnelse:1 unmodified lineyield (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)"), Noneelse:yield f"⚠️ Check error: HTTP {check.status_code}", Noneexcept Exception as e:yield f"⚠️ Error checking status: {str(e)}", Noneyield "⏰ Timeout after 150 seconds. Try checking again later.", Noneexcept Exception as e:yield f"❌ Error: {str(e)}", Nonedef generate_song(lyrics_info, variant_choice, style, title, instrumental, model, custom_mode):"""Generate a song from lyrics"""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."try:# Get selected lyrics variantvariant_idx = int(variant_choice.split(":")[0]) - 1 # Convert "1: Title" to 0-indexlyrics_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 moderequest_data = {"customMode": custom_mode,105 unmodified linesexcept Exception as e:return f"❌ Error: {str(e)}"# Create the appwith gr.Blocks(title="Suno Lyrics & Song Generator", theme="soft") as app:gr.Markdown("# 🎵 Suno Lyrics & Song Generator")gr.Markdown("Generate song lyrics and turn them into full songs using Suno AI")# Store lyrics between stepslyrics_state = gr.State()with gr.Row():with gr.Column(scale=1):# Lyrics Generation Sectiongr.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")# Song Generation Section (initially hidden)gr.Markdown("### Step 2: Create Song")with gr.Group():variant_choice = gr.Dropdown(label="Select Lyrics Variant",choices=[],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,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")# Instructionsgr.Markdown("""**How it works:**1. Enter your lyrics idea and generate2. Select a lyrics variant from results3. Choose song settings (or use defaults)4. Generate a full song with music!**Custom Mode:** Enable for advanced control**Instrumental:** Check for music only (no singing)**Status messages:**- ✅ Submitted = Task accepted- ⏳ PROCESSING = Generating- 🎶 Complete = Song ready!""")with gr.Column(scale=2):output = gr.Markdown(label="Results",value="Your generated lyrics and songs will appear here...")gr.Markdown("---")gr.Markdown(8 unmodified lineselem_id="footer")# Lyrics generationlyrics_btn.click(generate_lyrics,inputs=prompt,outputs=[output, lyrics_state]).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)# Song generationsong_btn.click(generate_song,inputs=[lyrics_state, variant_choice, style, title, instrumental, model, custom_mode],outputs=output)if __name__ == "__main__":print("🚀 Starting Suno Lyrics & 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)2 unmodified lines345678979 unmodified lines89909192939495969798991001011021031041051061071081091101111121131141151161171181191201211 unmodified line123124125126127128129130131132133134135136137138139140141142143144145146147148149105 unmodified lines2552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034048 unmodified lines4134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674682 unmodified linesimport osimport timeimport jsonimport tempfile# Suno API keySUNO_KEY = os.environ.get("SunoKey", "")79 unmodified linesoutput += "\n```\n"output += "---\n\n"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 statelyrics_data = {"variants": lyrics_list,"original_prompt": prompt}# Update dropdown with variantsvariant_choices = [f"{i+1}: {lyric.get('title', f'Variant {i+1}')}"for i, lyric in enumerate(lyrics_list)]# Get first variant text for editingfirst_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:1 unmodified lineyield (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):"""Generate a song from 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,105 unmodified linesexcept 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()) - 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 a downloadable text file"""if not text.strip():return None# Create a temporary filewith tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:f.write(text)temp_path = f.namereturn temp_pathdef 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 contentexcept:try:with open(file.name, 'r', encoding='latin-1') as f:content = f.read()return contentexcept 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 data between stepslyrics_state = gr.State()with gr.Row():with gr.Column(scale=1):# Lyrics Generation Sectiongr.Markdown("### Step 1: Generate or Upload Lyrics")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 Sectiongr.Markdown("### Step 2: Select & Edit Lyrics")variant_choice = gr.Dropdown(label="Select Lyrics Variant",choices=[],interactive=True)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 Sectiongr.Markdown("### Step 3: Create Song")with gr.Row():custom_mode = gr.Checkbox(label="Custom Mode",value=False,interactive=True)instrumental = gr.Checkbox(label="Instrumental",value=False,interactive=True)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")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")with gr.Column(scale=2):output = gr.Markdown(label="Results",value="Your generated lyrics and songs will appear here...")# Hidden file download componentfile_output = gr.File(label="Download Lyrics", visible=False)gr.Markdown("---")gr.Markdown(8 unmodified lineselem_id="footer")# Event handlers# Generate lyrics from promptlyrics_btn.click(generate_lyrics,inputs=prompt,outputs=[output, lyrics_state, variant_choice, lyrics_text])# Upload text from fileupload_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 selectedvariant_choice.change(update_text_from_variant,inputs=[lyrics_state, variant_choice],outputs=lyrics_text)# Download text as filedownload_btn.click(download_text_file,inputs=lyrics_text,outputs=file_output).then(lambda: "💾 **Text ready for download!**\n\nCheck the download button below.",outputs=output)# Clear textclear_btn.click(lambda: ("", ""),outputs=[lyrics_text, output])# Generate song from textsong_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)
app.py+191-106