Spaces:
Paused
Paused
Update app.py
Browse files12344561 unmodified line8910121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231112131251261415161291301718191331342021221371382324252610 unmodified lines373839155404115842434445461641651661671681691704748495051525354555657172173174175176177178585960180181616218318418518618718818919063646519219319419519619719819920020120220320420520620766676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135209210136137138139140212213214141142216217218219220221222223143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188225226227228189190191192193194195230231232233234235236237238239240241242243244245246247248196197198199200250251252201202203204254255256257205206207208259260261262209210211212213214215216217218219220264221222223224225269226227228229230231232274275276233234278279280281235236237238239284285286240241289242291243244245246247296297298248249250251302303304305306252253308254255311256257258314315259316260318261320321322323324325326327328329330262263264265266267268269270334335336271272273274275339276277278342343279280281345282283347348284285286287351352288289290291292293294295296297298299355356300301302303304305306307308309359310311361362363364365366367368369370371372373374375376377378379380381312313383384385386314315316317318319388320321322323324325390391392393326327328329330331332395333334335336337338397398399400339340341342343344402403404405345346347348349408409410411412413414415416417418419420421422350351352353424425426354355356357358359429430360361362363364365366367368369432370371372435436437438439440441442373374375376377378445446447379380381382383450384385386387455388import gradio as grimport requestsimport osimport timeimport json
# Suno API key1 unmodified lineif not SUNO_KEY: print("⚠️ SunoKey not set!")
def get_task_info(task_id): """Manually check any Suno task status""" if not task_id: return "❌ Please enter a Task ID" try: resp = requests.get( "https://api.sunoapi.org/api/v1/generate/record-info", headers={"Authorization": f"Bearer {SUNO_KEY}"}, params={"taskId": task_id}, timeout=30 ) if resp.status_code != 200: return f"❌ HTTP Error {resp.status_code}\n\n{resp.text}" data = resp.json() # Format the response for display output = f"## 🔍 Task Status: `{task_id}`\n\n" if data.get("code") == 200: task_data = data.get("data", {}) status = task_data.get("status", "UNKNOWN") output += f"**Status:** {status}\n" output += f"**Task ID:** `{task_data.get('taskId', 'N/A')}`\n" output += f"**Music ID:** `{task_data.get('musicId', 'N/A')}`\n" output += f"**Created:** {task_data.get('createTime', 'N/A')}\n" if status == "SUCCESS": response_data = task_data.get("response", {}) # Try to parse response (could be string or dict) if isinstance(response_data, str): try: response_data = json.loads(response_data) except: output += f"\n**Raw Response:**\n```\n{response_data}\n```\n" response_data = {} # Check for song data songs = [] if isinstance(response_data, dict): songs = response_data.get("sunoData", []) if not songs: songs = response_data.get("data", []) elif isinstance(response_data, list): songs = response_data if songs: output += f"\n## 🎵 Generated Songs ({len(songs)})\n\n" for i, song in enumerate(songs, 1): if isinstance(song, dict): output += f"### Song {i}\n" output += f"**Title:** {song.get('title', 'Untitled')}\n" output += f"**ID:** `{song.get('id', 'N/A')}`\n" # Audio URLs audio_url = song.get('audioUrl') or song.get('audio_url') stream_url = song.get('streamUrl') or song.get('stream_url') download_url = song.get('downloadUrl') or song.get('download_url') if audio_url: output += f"**Audio:** [Play]({audio_url}) | [Download]({audio_url})\n" elif stream_url: output += f"**Stream:** [Play]({stream_url})\n" if download_url: output += f"**Download:** [MP3]({download_url})\n" # Audio player play_url = audio_url or stream_url if play_url: output += f"""\n<audio controls style="width: 100%; margin: 10px 0;"> <source src="{play_url}" type="audio/mpeg"> Your browser does not support audio. </audio>\n""" output += f"**Prompt:** {song.get('prompt', 'N/A')[:100]}...\n" output += f"**Duration:** {song.get('duration', 'N/A')}s\n" output += f"**Created:** {song.get('createTime', 'N/A')}\n\n" output += "---\n\n" else: output += "\n**No song data found in response.**\n" elif status == "FAILED": error_msg = task_data.get("errorMessage", "Unknown error") output += f"\n**Error:** {error_msg}\n" elif status in ["PENDING", "PROCESSING", "RUNNING"]: output += f"\n**Task is still processing...**\n" output += f"Check again in 30 seconds.\n" else: output += f"\n**Unknown status:** {status}\n" else: output += f"**API Error:** {data.get('msg', 'Unknown')}\n" # Show raw JSON for debugging output += "\n## 📋 Raw Response\n" output += f"```json\n{json.dumps(data, indent=2)}\n```" return output except Exception as e: return f"❌ Error checking task: {str(e)}"
def generate_song_from_text(lyrics_text, style, title, instrumental, model): """Generate a song from lyrics text"""def submit_song_generation(lyrics_text, style, title, instrumental, model): """Submit song generation request - IMMEDIATE RESPONSE WITH TASK ID""" if not SUNO_KEY: yield "❌ Error: SunoKey not configured in environment variables" return return "❌ Error: SunoKey not configured", "" if not lyrics_text.strip() and not instrumental: yield "❌ Error: Please provide lyrics or select instrumental" return return "❌ Error: Please provide lyrics or select instrumental", "" if not style.strip(): yield "❌ Error: Please provide a music style" return return "❌ Error: Please provide a music style", "" if not title.strip(): yield "❌ Error: Please provide a song title" return return "❌ Error: Please provide a song title", "" try: # Prepare request data10 unmodified lines # 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: request_data["prompt"] = "" # Apply style length limits 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" # Submit generation request 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 ) # Apply title length limits 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" if resp.status_code != 200: return f"❌ Submission failed: HTTP {resp.status_code}\n\n{resp.text}", "" request_data["style"] = style request_data["title"] = title data = resp.json() 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"**Callback URL:** https://1hit.no/callback.php\n\n" # Extract task ID - IMMEDIATELY task_id = None # 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}" yield f"\n**Response:**\n```\n{resp.text}\n```" return # Try different response formats if "taskId" in data: task_id = data["taskId"] elif "data" in data and "taskId" in data["data"]: task_id = data["data"]["taskId"] elif data.get("data") and "taskId" in data.get("data", {}): task_id = data["data"]["taskId"] if not task_id: return f"❌ Could not extract Task ID\n\n**Raw:**\n```json\n{json.dumps(data, indent=2)}\n```", "" # RETURN TASK ID IMMEDIATELY output = f"## ✅ TASK SUBMITTED!\n\n" output += f"**🎯 YOUR TASK ID:** `{task_id}`\n\n" output += f"**📋 Details:**\n" output += f"- **Title:** {title}\n" output += f"- **Style:** {style}\n" output += f"- **Model:** {model}\n" output += f"- **Instrumental:** {'Yes' if instrumental else 'No'}\n\n" output += f"**🚀 Next Steps:**\n" output += f"1. **Copy this Task ID:** `{task_id}`\n" output += f"2. **Switch to 'Check Status' tab**\n" output += f"3. **Paste the Task ID**\n" output += f"4. **Click 'Check Status'** for results\n\n" output += f"**⏱️ Processing time:** 1-3 minutes\n" output += f"**📞 Callback URL:** https://1hit.no/callback.php\n" return output, task_id except Exception as e: return f"❌ Error: {str(e)}", ""
def check_song_status(task_id, show_raw=False): """Check song generation status - RETURNS DOWNLOAD LINKS""" if not task_id: return "❌ Please enter a Task ID", "" try: resp = requests.get( "https://api.sunoapi.org/api/v1/generate/record-info", headers={"Authorization": f"Bearer {SUNO_KEY}"}, params={"taskId": task_id}, timeout=30 ) if resp.status_code != 200: return f"❌ HTTP Error {resp.status_code}\n\n{resp.text}", "" data = resp.json() # RAW JSON for debugging (always stored, shown if requested) raw_json = f"```json\n{json.dumps(data, indent=2)}\n```" if data.get("code") != 200: return f"❌ API Error: {data.get('msg', 'Unknown')}", raw_json task_data = data.get("data", {}) status = task_data.get("status", "UNKNOWN") # Format main output output = f"## 🔍 Status Check: `{task_id}`\n\n" output += f"**Status:** {status}\n" if status == "TEXT_SUCCESS": # This is the key status! Songs are ready! response_data = task_data.get("response", {}) songs = response_data.get("sunoData", []) data = resp.json() print(f"Submission response: {json.dumps(data, indent=2)}") if not songs: output += f"\n**⚠️ Status TEXT_SUCCESS but no songs found**\n" output += f"Raw data available in dropdown below\n" return output, raw_json if data.get("code") != 200: yield f"❌ API error: {data.get('msg', 'Unknown')}" return output += f"## 🎵 SONGS READY! ({len(songs)} tracks)\n\n" # Extract task ID from response task_id = None if "taskId" in data: task_id = data["taskId"] elif "data" in data and "taskId" in data["data"]: task_id = data["data"]["taskId"] elif data.get("data") and "taskId" in data.get("data", {}): task_id = data["data"]["taskId"] for i, song in enumerate(songs, 1): output += f"### Track {i}\n" output += f"**Title:** {song.get('title', 'Untitled')}\n" # Get all possible URLs audio_url = song.get('audioUrl') stream_url = song.get('streamAudioUrl') or song.get('streamAudioURL') or song.get('stream_url') source_stream = song.get('sourceStreamAudioUrl') source_audio = song.get('sourceAudioUrl') # Image URL image_url = song.get('imageUrl') or song.get('sourceImageUrl') # Best URL for listening best_url = audio_url or stream_url or source_stream or source_audio if best_url: output += f"**🎧 Listen Now:** [Click to Play]({best_url})\n" # Audio player output += f"""<audio controls style="width: 100%; margin: 10px 0;"> <source src="{best_url}" type="audio/mpeg"> Your browser does not support audio. </audio>\n""" # Download button if audio_url: output += f"**💾 Download:** [MP3 File]({audio_url})\n" elif stream_url: output += f"**💾 Download:** [Stream MP3]({stream_url})\n" if image_url: output += f"**🖼️ Cover Art:** [View Image]({image_url})\n" output += f"**ID:** `{song.get('id', 'N/A')}`\n" output += f"**Model:** {song.get('modelName', 'N/A')}\n" output += f"**Tags:** {song.get('tags', 'N/A')}\n" if song.get('duration'): output += f"**Duration:** {song.get('duration')}s\n" # Show first 200 chars of prompt prompt = song.get('prompt', '') if prompt: output += f"**Preview:** {prompt[:200]}...\n" output += "\n---\n\n" if not task_id: yield f"❌ Could not extract Task ID from response" yield f"\n**Raw Response:**\n```json\n{json.dumps(data, indent=2)}\n```" return # Summary output += f"**✅ Generation complete!**\n\n" output += "**To save your songs:**\n" output += "1. Right-click 'Listen Now' links → 'Save link as...'\n" output += "2. Or use the download links above\n" output += "3. Note the Track IDs for reference\n" yield f"## ✅ Request Submitted Successfully!\n\n" yield f"**🎯 Task ID:** `{task_id}`\n\n" yield f"**⏳ Status:** Generation started\n" yield f"**📞 Callback:** https://1hit.no/callback.php\n\n" yield "**What happens now:**\n" yield "1. Suno AI generates your song (1-3 minutes)\n" yield "2. You'll get a callback notification\n" yield "3. Use the Task ID above to check status manually\n\n" yield "---\n\n" yield f"## 🔍 Check Status Manually\n\n" yield f"Use this Task ID: `{task_id}`\n\n" yield "**To check status:**\n" yield "1. Copy the Task ID above\n" yield "2. Go to 'Check Any Task' tab\n" yield "3. Paste and click 'Check Status'\n" yield "4. Or wait for callback notification\n\n" yield "**Generation time:**\n" yield "- 30-60 seconds for stream URL\n" yield "- 2-3 minutes for download URL\n" elif status in ["PENDING", "PROCESSING", "RUNNING"]: output += f"\n**⏳ Song is still being generated...**\n" output += "Check again in 30-60 seconds\n" output += f"This usually takes 1-3 minutes total\n" # Simple one-time check after 30 seconds yield "\n**⏰ Will check once in 30 seconds...**\n" time.sleep(30) elif status == "SUCCESS": output += f"\n**✅ Generation succeeded!**\n" output += "Check raw data below for song URLs\n" # Single status check status_result = get_task_info(task_id) yield "\n## 📊 Status Check (30s)\n\n" yield status_result elif status == "FAILED": error_msg = task_data.get("errorMessage", "Unknown error") output += f"\n**❌ Generation failed:** {error_msg}\n" except Exception as e: yield f"❌ Error submitting request: {str(e)}" return else: output += f"\n**⚠️ Unknown status:** {status}\n" output += "Check raw data below\n" # Always show premium info output += f"\n**💡 Tip:** Songs may take 2-3 minutes to fully process\n" output += f"**📞 Callback sent to:** https://1hit.no/callback.php\n" output += f"**🔗 Viewer:** [https://1hit.no/viewer.php?task_id={task_id}](https://1hit.no/viewer.php?task_id={task_id})\n" return output, raw_json except Exception as e: yield f"❌ **Unexpected Error:** {str(e)}" return f"❌ Error checking task: {str(e)}", ""
# Create the appwith gr.Blocks() as app: gr.Markdown("# 🎵 Suno Song Generator") gr.Markdown("Create songs from lyrics and style using Suno AI") # Store current task ID current_task_id = gr.State(value="") with gr.Tab("🎶 Generate Song"): with gr.Row(): with gr.Column(scale=1): # Lyrics Input gr.Markdown("### Step 1: Enter Lyrics") # Inputs 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=10, interactive=True label="Lyrics (leave empty for instrumental)", placeholder="[Verse 1]\nType your lyrics here...", lines=8 ) # Song Settings gr.Markdown("### Step 2: Song Settings") style = gr.Textbox( label="Music Style", placeholder="Example: Pop, Rock, Jazz, Classical, Electronic, Hip Hop, Country", value="Pop", interactive=True placeholder="e.g., Rock, Jazz, Electronic" ) title = gr.Textbox( label="Song Title", placeholder="My Awesome Song", value="Generated Song", interactive=True value="My Song" ) with gr.Row(): instrumental = gr.Checkbox( label="Instrumental (No Vocals)", value=False, interactive=True ) instrumental = gr.Checkbox(label="Instrumental Only") model = gr.Dropdown( label="Model", choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"], value="V4_5ALL", interactive=True label="Model" ) # Action Buttons generate_btn = gr.Button("🚀 Generate Song", variant="primary") submit_btn = gr.Button("🚀 Generate Song", variant="primary") clear_btn = gr.Button("🗑️ Clear All", variant="secondary") # Instructions gr.Markdown(""" **How to use:** 1. Paste lyrics (or leave empty for instrumental) 2. Set music style 3. Enter song title 4. Choose model 5. Click Generate! **Tips:** - V4_5ALL: Best overall quality - V5: Latest model - Instrumental: No vocals, just music **Instructions:** 1. Enter lyrics (or blank for instrumental) 2. Set style & title 3. Click Generate 4. **Copy the Task ID** 5. Check status in next tab """) with gr.Column(scale=2): # Output Area output = gr.Markdown( value="### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'" # Submission output submission_output = gr.Markdown( value="### Ready to generate!\n\nFill in the form and click 'Generate Song'" ) with gr.Tab("🔍 Check Any Task"): with gr.Tab("🔍 Check Status"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Check Task Status") gr.Markdown("Enter any Suno Task ID to check its status") gr.Markdown("### Check Song Status") # Task ID input (auto-fills from generation) check_task_id = gr.Textbox( status_task_id = gr.Textbox( label="Task ID", placeholder="Enter Task ID from generation or separation", info="From Song Generator or Vocal Separator" placeholder="Paste your Task ID here", info="Will auto-fill from generated task" ) check_btn = gr.Button("🔍 Check Status", variant="primary") check_clear_btn = gr.Button("🗑️ Clear", variant="secondary") check_btn = gr.Button("🔍 Check Status Now", variant="primary") auto_check = gr.Checkbox(label="Auto-check every 30s", value=False) gr.Markdown(""" **What to expect:** - **TEXT_SUCCESS**: Songs ready! Listen/download - **PENDING/PROCESSING**: Still generating - Check every 30s until ready """) with gr.Column(scale=2): # Status output check_output = gr.Markdown( value="### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results." status_output = gr.Markdown( value="### Enter a Task ID to check status" ) # Raw data in accordion with gr.Accordion("📊 Raw API Response (Debug)", open=False): raw_output = gr.Markdown( value="*Raw JSON will appear here when you check status*" ) with gr.Tab("📚 Instructions"): with gr.Tab("📋 Instructions"): gr.Markdown(""" ## 📖 How to Use This App ### 🎶 Generate Song Tab 1. **Enter Lyrics** (or leave empty for instrumental) 2. **Set Music Style** (e.g., "Pop", "Rock", "Jazz") 3. **Enter Song Title** 4. **Choose Model** (V4_5ALL recommended) 5. **Click "Generate Song"** ### 🔍 Check Any Task Tab 1. **Paste any Suno Task ID** 2. **Click "Check Status"** 3. **View results and download links** ### ⏱️ What to Expect **After generating:** - You'll get a **Task ID** immediately - Generation takes **1-3 minutes** - **Callback** sent to https://1hit.no/callback.php - Use Task ID to **check status manually** ## 🎵 Complete Workflow **Task IDs come from:** - Song Generator (this app) - Vocal Separator (other app) - Any Suno API request ### 1. Generate Song - Enter lyrics & settings - Click **Generate Song** - **IMMEDIATELY get a Task ID** - Copy the Task ID ### 🎵 Getting Your Songs ### 2. Check Status - Switch to **Check Status** tab - Task ID auto-fills - Click **Check Status Now** - Wait for **TEXT_SUCCESS** status 1. **Stream URL:** Ready in 30-60 seconds 2. **Download URL:** Ready in 2-3 minutes 3. **Both appear in status check** 4. **Audio player** included for streaming ### 3. Download Songs - When **TEXT_SUCCESS** appears: - **Listen Now** links with audio players - **Download** links for MP3 files - Cover art images - Track IDs for reference ### 🔧 Troubleshooting ### 4. Tips - Processing: **1-3 minutes** - Check every **30 seconds** - Use **Auto-check** for convenience - Raw data available for debugging **Task not found?** - Wait a few minutes - Check callback logs at https://1hit.no/viewer.php - Ensure Task ID is correct ### 5. Status Meanings - **TEXT_SUCCESS**: ✅ Songs ready! - **PENDING/PROCESSING**: ⏳ Still working - **SUCCESS**: Check raw data - **FAILED**: Try again **No audio links?** - Wait 2-3 minutes - Check status again - Generation may have failed ### 6. Callback System - Results also sent to: https://1hit.no/callback.php - View all results: https://1hit.no/viewer.php """) gr.Markdown("---") gr.Markdown( """ <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" ) # Event handlers for Generate Song tab def clear_all(): return "", "Pop", "Generated Song", False, "V4_5ALL", "### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'" # Auto-fill status tab with task ID def update_status_field(task_id): return task_id clear_btn.click( clear_all, outputs=[lyrics_text, style, title, instrumental, model, output] current_task_id.change( fn=update_status_field, inputs=[current_task_id], outputs=[status_task_id] ) generate_btn.click( generate_song_from_text, # Generate song def on_generate(lyrics, style, title, instrumental, model): output, task_id = submit_song_generation(lyrics, style, title, instrumental, model) if task_id: return output, task_id, task_id # Also updates status_task_id return output, "", "" # Clear if error submit_btn.click( fn=on_generate, inputs=[lyrics_text, style, title, instrumental, model], outputs=output outputs=[submission_output, current_task_id, status_task_id] ) # Event handlers for Check Any Task tab def clear_check(): return "", "### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results." check_clear_btn.click( clear_check, outputs=[check_task_id, check_output] ) # Check status def on_check(task_id, show_raw): output, raw = check_song_status(task_id, show_raw) return output, raw check_btn.click( get_task_info, inputs=[check_task_id], outputs=check_output fn=on_check, inputs=[status_task_id, gr.State(True)], # Always show raw outputs=[status_output, raw_output] )
# Launch the appif __name__ == "__main__": print("🚀 Starting Suno Song Generator") print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}") print("🌐 Open your browser to: http://localhost:7860") app.launch(server_name="0.0.0.0", server_port=7860, share=False)app.py+268-336