Spaces:
Paused
Paused
Update app.py
Browse files2 unmodified lines3456678910111314121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231 unmodified line12512612722231281291301311325 unmodified lines138139140351411421431441454014614714814930 unmodified lines18018118277183184185186187188189841901911921939 unmodified lines2032042052062072082092102112122132142151071081091101111121131141151162162172182192202212222232241181191201211221231241251261272252262272282291291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772302312322332342352362372382392402412422432442452462472482492792802812822832502512522532852862872882892902912922932942952962972982993002542552562572582592602612622632642653053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353362663382672682692703423433443453463472712722732742752762772782793512802812823543553563573583593603613623633643652832842852863662872882892903713722912923743752932942952962973803812982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323843853863873883333343353363373903913923933943383393403413423433443453463473483493503513523533973983994004014024034044054064074084094104114124134144154164174184194204214224234243543553563573583593603613624264274284294304314324334343633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084097 unmodified lines4174184194484494504514524534544554564574584594604614624634644654664674684204214224234704244254264274284764294304314324334344354364374384394404414424434444454464474484494504514524534864874544554562 unmodified linesimport osimport timeimport jsonimport tempfile
# Suno API keySUNO_KEY = os.environ.get("SunoKey", "")if not SUNO_KEY: print("⚠️ SunoKey not set!")
# Get the current Space URL for callbacksSPACE_URL = os.environ.get("SPACE_URL", "https://mysafecode-suno-api-v5.hf.space")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"""1 unmodified line yield "❌ Error: SunoKey not configured in environment variables" return if not lyrics_text.strip(): yield "❌ Error: Please provide lyrics" if not lyrics_text.strip() and not instrumental: yield "❌ Error: Please provide lyrics or select instrumental" return if not style.strip():5 unmodified lines return try: # Always use custom mode for full control # Prepare request data request_data = { "customMode": True, "instrumental": instrumental, "model": model, "callBackUrl": "https://1hit.no/callback.php", # Use the Space URL for callbacks "callBackUrl": "https://1hit.no/callback.php", "style": style, "title": title, }30 unmodified lines request_data["style"] = style request_data["title"] = title yield f"✅ **Submitting song request...**\n\n" 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:** {request_data['callBackUrl']}\n\n" yield f"**Callback URL:** https://1hit.no/callback.php\n\n" # Submit generation request try:9 unmodified lines if resp.status_code != 200: yield f"❌ Submission failed: HTTP {resp.status_code}" yield f"\n**Response:**\n```\n{resp.text}\n```" return data = resp.json() print(f"Submission response: {json.dumps(data, indent=2)}") if data.get("code") != 200: yield f"❌ API error: {data.get('msg', 'Unknown')}" return task_id = data["data"]["taskId"] yield f"✅ **Request submitted successfully!**\n" yield f"**Task ID:** `{task_id}`\n\n" yield f"⏳ Song generation started...\n\n" yield "**What's happening now:**\n" yield "1. Suno AI is generating your song (1-3 minutes)\n" yield "2. We'll poll the API every 10 seconds for updates\n" yield "3. When complete, you'll get direct links to your song\n" yield "4. Suno will also send a callback to our server\n\n" yield "**Keep this window open while we monitor progress...**\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"] except Exception as e: yield f"❌ Error submitting request: {str(e)}" return # Poll for completion - with better error handling max_attempts = 60 # 60 attempts * 10 seconds = 10 minutes last_status = "" for attempt in range(max_attempts): time.sleep(10) 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 try: # Check task status check_resp = requests.get( f"https://api.sunoapi.org/api/v1/generate/record-info?taskId={task_id}", headers={"Authorization": f"Bearer {SUNO_KEY}"}, timeout=30 ) if check_resp.status_code == 200: check_data = check_resp.json() if check_data.get("code") == 200: data_info = check_data.get("data", {}) current_status = data_info.get("status", "UNKNOWN") # Only show status update if it changed if current_status != last_status: last_status = current_status if current_status == "COMPLETE": # Try to parse the response response_data = data_info.get("response", {}) # Response might be a JSON string if isinstance(response_data, str): try: response_data = json.loads(response_data) except json.JSONDecodeError: # If it's not JSON, it might be a simple string yield f"✅ **Generation Complete!**\n\n" yield f"**Status:** {current_status}\n" yield f"**Task ID:** `{task_id}`\n\n" yield "**To access your song:**\n" yield "1. Visit https://sunoapi.org\n" yield "2. Log in to your account\n" yield "3. Go to 'Generation History'\n" yield "4. Find your song by Task ID\n" yield f"\n**Callback URL used:** {request_data['callBackUrl']}\n" return # Look for songs in different possible locations songs = [] # Try different possible structures if isinstance(response_data, dict): songs = response_data.get("data", []) if not songs: songs = response_data.get("songs", []) elif isinstance(response_data, list): songs = response_data if songs: yield "🎶 **SONG GENERATION COMPLETE!** 🎶\n\n" yield f"Generated {len(songs)} song(s)\n\n" for i, song in enumerate(songs, 1): if isinstance(song, dict): song_title = song.get('title', f'Song {i}') stream_url = song.get('streamUrl') or song.get('stream_url') download_url = song.get('downloadUrl') or song.get('download_url') yield f"## 🎵 Song {i}: {song_title}\n" if stream_url: yield f"**Stream URL:** {stream_url}\n" yield f"**Listen Now:** [Click to Stream]({stream_url})\n\n" # Audio player yield f"""<audio controls style="width: 100%; margin: 10px 0; padding: 10px; background: #f0f0f0; border-radius: 5px;"> <source src="{stream_url}" type="audio/mpeg"> Your browser does not support audio playback. </audio>\n\n""" else: yield "⏳ Stream URL not ready yet (check back in 30 seconds)\n\n" if download_url: yield f"**Download URL:** {download_url}\n" yield f"**Download:** [Click to Download]({download_url})\n\n" else: yield "⏳ Download URL not ready yet (usually takes 2-3 minutes)\n\n" yield "---\n\n" yield f"⏱️ Total generation time: {(attempt + 1) * 10} seconds\n\n" yield "**Important:**\n" yield "- Stream links work immediately\n" yield "- Download links may take 2-3 minutes\n" yield "- Files are kept for 15 days\n" yield f"- Task ID: `{task_id}` (save this for reference)\n" yield f"- Callback URL: {request_data['callBackUrl']}\n" return else: # No songs found in response yield f"✅ **Generation Complete!**\n\n" yield f"**Status:** {current_status}\n" yield f"**Task ID:** `{task_id}`\n\n" yield "**Response received but no song data found.**\n\n" yield "**To access your song:**\n" yield "1. Visit https://sunoapi.org\n" yield "2. Log in to your account\n" yield "3. Check 'Generation History'\n" yield "4. Look for this Task ID\n" yield f"\n**Callback URL used:** {request_data['callBackUrl']}\n" return elif current_status == "FAILED": error_msg = data_info.get("errorMessage", "Unknown error") yield f"❌ **Generation Failed**\n\n" yield f"**Status:** {current_status}\n" yield f"**Error:** {error_msg}\n" yield f"**Task ID:** `{task_id}`\n\n" yield f"**Callback URL:** {request_data['callBackUrl']}\n" yield "\nPlease try again with different parameters." return elif current_status in ["PENDING", "PROCESSING"]: yield f"⏳ **Status Update**\n\n" yield f"**Current Status:** {current_status}\n" yield f"**Task ID:** `{task_id}`\n" yield f"**Check:** {attempt + 1}/{max_attempts}\n" yield f"**Callback URL:** {request_data['callBackUrl']}\n\n" yield "**Estimated time remaining:**\n" yield "- Stream URL: 30-60 seconds\n" yield "- Download URL: 2-3 minutes\n" yield "\nWe'll check again in 10 seconds...\n" else: yield f"📊 **Status:** {current_status}\n" yield f"**Task ID:** `{task_id}`\n" yield f"**Check:** {attempt + 1}/{max_attempts}\n" yield f"**Callback URL:** {request_data['callBackUrl']}\n\n" yield "Still processing...\n" else: # API returned error code error_msg = check_data.get("msg", "Unknown error") yield f"⚠️ **API Error**\n\n" yield f"**Code:** {check_data.get('code')}\n" yield f"**Message:** {error_msg}\n" yield f"**Task ID:** `{task_id}`\n" yield f"**Callback URL:** {request_data['callBackUrl']}\n\n" yield "Will continue checking...\n" else: yield f"⚠️ **HTTP Error {check_resp.status_code}**\n\n" yield f"Failed to check status. Will retry in 10 seconds...\n" yield f"Check: {attempt + 1}/{max_attempts}\n" yield f"Task ID: `{task_id}`\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" except requests.exceptions.Timeout: yield f"⏱️ **Timeout checking status**\n\n" yield "The status check timed out. Will try again in 10 seconds...\n" yield f"Check: {attempt + 1}/{max_attempts}\n" yield f"Task ID: `{task_id}`\n" # Simple one-time check after 30 seconds yield "\n**⏰ Will check once in 30 seconds...**\n" time.sleep(30) except Exception as e: yield f"⚠️ **Error checking status:** {str(e)}\n\n" yield "Will retry in 10 seconds...\n" yield f"Check: {attempt + 1}/{max_attempts}\n" yield f"Task ID: `{task_id}`\n" # If we get here, we timed out yield "⏰ **Timeout after 10 minutes**\n\n" yield f"**Task ID:** `{task_id}`\n" yield f"**Callback URL:** {request_data['callBackUrl']}\n\n" yield "**What to do:**\n" yield "1. The song may still be processing\n" yield "2. Visit https://sunoapi.org\n" yield "3. Log in and check 'Generation History'\n" yield "4. Look for this Task ID\n" yield "\nSongs can sometimes take longer than expected, especially for longer tracks." # Single status check status_result = get_task_info(task_id) yield "\n## 📊 Status Check (30s)\n\n" yield status_result except Exception as e: yield f"❌ Error submitting request: {str(e)}" return except Exception as e: yield f"❌ **Unexpected 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, encoding='utf-8') 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)}"
def clear_all(): """Clear all input fields""" return "", "", "Generated Song", False, "V4_5ALL", "### Ready to generate!\n\n1. Enter lyrics\n2. Set style and title\n3. Click 'Generate Song'"
# Create the appwith gr.Blocks(title="Suno Song Generator", theme="soft") as app:with gr.Blocks() 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 Input gr.Markdown("### Step 1: Enter Lyrics") with gr.Tab("Paste Lyrics"): with gr.Tab("🎶 Generate Song"): with gr.Row(): with gr.Column(scale=1): # Lyrics Input gr.Markdown("### Step 1: Enter 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, lines=10, 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 Settings gr.Markdown("### Step 2: Song Settings") # Song Settings gr.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 interactive=True ) with gr.Row(): title = gr.Textbox( label="Song Title", placeholder="My Awesome Song", value="Generated Song", interactive=True, scale=2 interactive=True ) 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 Buttons generate_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 """) with gr.Row(): instrumental = gr.Checkbox( label="Instrumental (No Vocals)", value=False, interactive=True with gr.Column(scale=2): # Output Area output = gr.Markdown( value="### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'" ) model = gr.Dropdown( label="Model", choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"], value="V4_5ALL", interactive=True with gr.Tab("🔍 Check Any Task"): with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Check Task Status") gr.Markdown("Enter any Suno Task ID to check its status") check_task_id = gr.Textbox( label="Task ID", placeholder="Enter Task ID from generation or separation", info="From Song Generator or Vocal Separator" ) check_btn = gr.Button("🔍 Check Status", variant="primary") check_clear_btn = gr.Button("🗑️ Clear", variant="secondary") # 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) with gr.Row(): download_btn = gr.Button("💾 Download Lyrics", variant="secondary") # Instructions gr.Markdown(""" **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! **Features:** - Real callback URL for notifications - Automatic polling for status updates - Direct streaming and download links - File upload/download support **Generation time:** - 30-60s: Stream URL ready - 2-3 min: Download URL ready - Up to 5 min for longer songs """) with gr.Column(scale=2): check_output = gr.Markdown( value="### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results." ) with gr.Tab("📚 Instructions"): gr.Markdown(""" ## 📖 How to Use This App with gr.Column(scale=2): # Output Area output = gr.Markdown( label="Generation Status", value="### Ready to generate!\n\n1. Enter lyrics\n2. Set style and title\n3. Click 'Generate Song'" ) # Hidden download component file_output = gr.File(label="Download Lyrics", visible=False) ### 🎶 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** **Task IDs come from:** - Song Generator (this app) - Vocal Separator (other app) - Any Suno API request ### 🎵 Getting Your Songs 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 ### 🔧 Troubleshooting **Task not found?** - Wait a few minutes - Check callback logs at https://1hit.no/viewer.php - Ensure Task ID is correct **No audio links?** - Wait 2-3 minutes - Check status again - Generation may have failed """) gr.Markdown("---") gr.Markdown(7 unmodified lines elem_id="footer" ) # Event handlers # Upload text from file upload_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 lyrics download_btn.click( download_text_file, inputs=lyrics_text, outputs=file_output ).then( lambda: "💾 **Lyrics ready for download!**\n\nCheck the download button below.", outputs=output ) # 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'" # Clear all clear_btn.click( clear_all, outputs=[lyrics_text, style, title, instrumental, model, output] ) # Generate song generate_btn.click( generate_song_from_text, inputs=[lyrics_text, style, title, instrumental, model], outputs=output ) # 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_btn.click( get_task_info, inputs=[check_task_id], outputs=check_output )
# Launch the appif __name__ == "__main__": print("🚀 Starting Suno Song Generator") print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}") print(f"🌐 Space URL: {SPACE_URL}") print(f"📞 Callback URL: {SPACE_URL}/callback") print("🌐 Open your browser to: http://localhost:7860") app.launch(server_name="0.0.0.0", server_port=7860, share=False)app.py+298-330