MySafeCode commited on
Commit
f2cdd25
·
verified ·
1 Parent(s): 1df9cee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +191 -106
app.py CHANGED
@@ -3,6 +3,7 @@ import requests
3
  import os
4
  import time
5
  import json
 
6
 
7
  # Suno API key
8
  SUNO_KEY = os.environ.get("SunoKey", "")
@@ -88,20 +89,33 @@ def generate_lyrics(prompt):
88
  output += "\n```\n"
89
  output += "---\n\n"
90
 
91
- output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds"
92
- # Store lyrics for potential song generation
93
- lyrics_info = {
94
- "lyrics_list": lyrics_list,
 
 
 
 
 
95
  "original_prompt": prompt
96
  }
97
- yield output, lyrics_info
 
 
 
 
 
 
 
 
98
  else:
99
- yield "✅ Completed but no lyrics found in response", None
100
  return
101
 
102
  elif status == "FAILED":
103
  error = check_data["data"].get("errorMessage", "Unknown error")
104
- yield f"❌ Task failed: {error}", None
105
  return
106
 
107
  else:
@@ -109,44 +123,27 @@ def generate_lyrics(prompt):
109
  yield (f"⏳ Status: {status}\n"
110
  f"Attempt: {attempt + 1}/30\n"
111
  f"Task ID: `{task_id}`\n\n"
112
- f"Still processing... (Usually takes 30-90 seconds)"), None
113
  else:
114
- yield f"⚠️ Check error: HTTP {check.status_code}", None
115
 
116
  except Exception as e:
117
- yield f"⚠️ Error checking status: {str(e)}", None
118
 
119
- yield "⏰ Timeout after 150 seconds. Try checking again later.", None
120
 
121
  except Exception as e:
122
- yield f"❌ Error: {str(e)}", None
123
 
124
- def generate_song(lyrics_info, variant_choice, style, title, instrumental, model, custom_mode):
125
- """Generate a song from lyrics"""
126
  if not SUNO_KEY:
127
  return "❌ Error: SunoKey not configured in environment variables"
128
 
129
- if lyrics_info is None:
130
- return "❌ Error: No lyrics available. Please generate lyrics first."
131
-
132
- if not lyrics_info.get("lyrics_list"):
133
- return "❌ Error: No lyrics found in the provided data."
134
 
135
  try:
136
- # Get selected lyrics variant
137
- variant_idx = int(variant_choice.split(":")[0]) - 1 # Convert "1: Title" to 0-index
138
- lyrics_list = lyrics_info["lyrics_list"]
139
-
140
- if variant_idx >= len(lyrics_list):
141
- return f"❌ Error: Invalid variant selection. Only {len(lyrics_list)} variants available."
142
-
143
- selected_lyric = lyrics_list[variant_idx]
144
- lyrics_text = selected_lyric.get('text', '')
145
- lyrics_title = selected_lyric.get('title', f'Variant {variant_idx + 1}')
146
-
147
- if not lyrics_text.strip():
148
- return "❌ Error: Selected lyrics variant has no text content."
149
-
150
  # Prepare request data based on custom mode
151
  request_data = {
152
  "customMode": custom_mode,
@@ -258,89 +255,150 @@ def generate_song(lyrics_info, variant_choice, style, title, instrumental, model
258
  except Exception as e:
259
  return f"❌ Error: {str(e)}"
260
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  # Create the app
262
- with gr.Blocks(title="Suno Lyrics & Song Generator", theme="soft") as app:
263
- gr.Markdown("# 🎵 Suno Lyrics & Song Generator")
264
  gr.Markdown("Generate song lyrics and turn them into full songs using Suno AI")
265
 
266
- # Store lyrics between steps
267
  lyrics_state = gr.State()
268
 
269
  with gr.Row():
270
  with gr.Column(scale=1):
271
  # Lyrics Generation Section
272
- gr.Markdown("### Step 1: Generate Lyrics")
273
- prompt = gr.Textbox(
274
- label="Lyrics Prompt",
275
- placeholder="Example: A happy song about sunshine and rainbows",
276
- lines=3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
277
  )
278
- lyrics_btn = gr.Button("🎵 Generate Lyrics", variant="primary")
279
 
280
- # Song Generation Section (initially hidden)
281
- gr.Markdown("### Step 2: Create Song")
282
- with gr.Group():
283
- variant_choice = gr.Dropdown(
284
- label="Select Lyrics Variant",
285
- choices=[],
 
 
 
 
 
 
 
 
 
 
 
 
286
  interactive=True
287
  )
288
-
289
- with gr.Row():
290
- custom_mode = gr.Checkbox(
291
- label="Custom Mode (Advanced Settings)",
292
- value=False,
293
- interactive=True
294
- )
295
- instrumental = gr.Checkbox(
296
- label="Instrumental (No Vocals)",
297
- value=False,
298
- interactive=True
299
- )
300
-
301
- with gr.Row():
302
- style = gr.Textbox(
303
- label="Music Style (Required for Custom Mode)",
304
- placeholder="Example: Pop, Rock, Jazz, Classical",
305
- interactive=True
306
- )
307
- title = gr.Textbox(
308
- label="Song Title (Required for Custom Mode)",
309
- placeholder="Example: My Awesome Song",
310
- interactive=True
311
- )
312
-
313
- model = gr.Dropdown(
314
- label="Model Version",
315
- choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"],
316
- value="V4_5ALL",
317
  interactive=True
318
  )
319
-
320
- song_btn = gr.Button("🎶 Generate Song", variant="secondary")
321
 
322
- # Instructions
323
- gr.Markdown("""
324
- **How it works:**
325
- 1. Enter your lyrics idea and generate
326
- 2. Select a lyrics variant from results
327
- 3. Choose song settings (or use defaults)
328
- 4. Generate a full song with music!
 
 
 
 
 
 
329
 
330
- **Custom Mode:** Enable for advanced control
331
- **Instrumental:** Check for music only (no singing)
 
 
 
 
332
 
333
- **Status messages:**
334
- - ✅ Submitted = Task accepted
335
- - ⏳ PROCESSING = Generating
336
- - 🎶 Complete = Song ready!
337
- """)
338
 
339
  with gr.Column(scale=2):
340
  output = gr.Markdown(
341
  label="Results",
342
  value="Your generated lyrics and songs will appear here..."
343
  )
 
 
 
344
 
345
  gr.Markdown("---")
346
  gr.Markdown(
@@ -355,29 +413,56 @@ with gr.Blocks(title="Suno Lyrics & Song Generator", theme="soft") as app:
355
  elem_id="footer"
356
  )
357
 
358
- # Lyrics generation
 
 
359
  lyrics_btn.click(
360
  generate_lyrics,
361
  inputs=prompt,
362
- outputs=[output, lyrics_state]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
363
  ).then(
364
- lambda lyrics_info: gr.Dropdown(
365
- choices=[f"{i+1}: {lyric.get('title', f'Variant {i+1}')}"
366
- for i, lyric in enumerate(lyrics_info.get("lyrics_list", []))]
367
- if lyrics_info and lyrics_info.get("lyrics_list") else []
368
- ),
369
- inputs=lyrics_state,
370
- outputs=variant_choice
 
371
  )
372
 
373
- # Song generation
374
  song_btn.click(
375
- generate_song,
376
- inputs=[lyrics_state, variant_choice, style, title, instrumental, model, custom_mode],
377
  outputs=output
378
  )
379
 
380
  if __name__ == "__main__":
381
- print("🚀 Starting Suno Lyrics & Song Generator")
382
  print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}")
383
  app.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
3
  import os
4
  import time
5
  import json
6
+ import tempfile
7
 
8
  # Suno API key
9
  SUNO_KEY = os.environ.get("SunoKey", "")
 
89
  output += "\n```\n"
90
  output += "---\n\n"
91
 
92
+ output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds\n\n"
93
+ output += "📝 **Now you can:**\n"
94
+ output += "1. Select a variant below\n"
95
+ output += "2. Edit the text if needed\n"
96
+ output += "3. Generate a song!"
97
+
98
+ # Prepare data for state
99
+ lyrics_data = {
100
+ "variants": lyrics_list,
101
  "original_prompt": prompt
102
  }
103
+
104
+ # Update dropdown with variants
105
+ variant_choices = [f"{i+1}: {lyric.get('title', f'Variant {i+1}')}"
106
+ for i, lyric in enumerate(lyrics_list)]
107
+
108
+ # Get first variant text for editing
109
+ first_text = lyrics_list[0].get('text', '') if lyrics_list else ""
110
+
111
+ yield output, lyrics_data, variant_choices, first_text
112
  else:
113
+ yield "✅ Completed but no lyrics found in response", None, [], ""
114
  return
115
 
116
  elif status == "FAILED":
117
  error = check_data["data"].get("errorMessage", "Unknown error")
118
+ yield f"❌ Task failed: {error}", None, [], ""
119
  return
120
 
121
  else:
 
123
  yield (f"⏳ Status: {status}\n"
124
  f"Attempt: {attempt + 1}/30\n"
125
  f"Task ID: `{task_id}`\n\n"
126
+ f"Still processing... (Usually takes 30-90 seconds)"), None, [], ""
127
  else:
128
+ yield f"⚠️ Check error: HTTP {check.status_code}", None, [], ""
129
 
130
  except Exception as e:
131
+ yield f"⚠️ Error checking status: {str(e)}", None, [], ""
132
 
133
+ yield "⏰ Timeout after 150 seconds. Try checking again later.", None, [], ""
134
 
135
  except Exception as e:
136
+ yield f"❌ Error: {str(e)}", None, [], []
137
 
138
+ def generate_song_from_text(lyrics_text, style, title, instrumental, model, custom_mode):
139
+ """Generate a song from text"""
140
  if not SUNO_KEY:
141
  return "❌ Error: SunoKey not configured in environment variables"
142
 
143
+ if not lyrics_text.strip():
144
+ return "❌ Error: Please provide lyrics text"
 
 
 
145
 
146
  try:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  # Prepare request data based on custom mode
148
  request_data = {
149
  "customMode": custom_mode,
 
255
  except Exception as e:
256
  return f"❌ Error: {str(e)}"
257
 
258
+ def update_text_from_variant(lyrics_data, variant_choice):
259
+ """Update the text area when a variant is selected"""
260
+ if lyrics_data and lyrics_data.get("variants") and variant_choice:
261
+ try:
262
+ # Extract variant index from choice (e.g., "1: Title" -> 0)
263
+ variant_idx = int(variant_choice.split(":")[0].strip()) - 1
264
+ variants = lyrics_data["variants"]
265
+
266
+ if 0 <= variant_idx < len(variants):
267
+ text = variants[variant_idx].get('text', '')
268
+ return text
269
+ except:
270
+ pass
271
+ return ""
272
+
273
+ def download_text_file(text):
274
+ """Create a downloadable text file"""
275
+ if not text.strip():
276
+ return None
277
+
278
+ # Create a temporary file
279
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as f:
280
+ f.write(text)
281
+ temp_path = f.name
282
+
283
+ return temp_path
284
+
285
+ def upload_text_file(file):
286
+ """Read text from uploaded file"""
287
+ if file is None:
288
+ return ""
289
+
290
+ try:
291
+ with open(file.name, 'r', encoding='utf-8') as f:
292
+ content = f.read()
293
+ return content
294
+ except:
295
+ try:
296
+ with open(file.name, 'r', encoding='latin-1') as f:
297
+ content = f.read()
298
+ return content
299
+ except Exception as e:
300
+ return f"❌ Error reading file: {str(e)}"
301
+
302
  # Create the app
303
+ with gr.Blocks(title="Suno Lyrics Generator", theme="soft") as app:
304
+ gr.Markdown("# 🎵 Suno Lyrics Generator")
305
  gr.Markdown("Generate song lyrics and turn them into full songs using Suno AI")
306
 
307
+ # Store lyrics data between steps
308
  lyrics_state = gr.State()
309
 
310
  with gr.Row():
311
  with gr.Column(scale=1):
312
  # Lyrics Generation Section
313
+ gr.Markdown("### Step 1: Generate or Upload Lyrics")
314
+
315
+ with gr.Tab("Generate Lyrics"):
316
+ prompt = gr.Textbox(
317
+ label="Lyrics Prompt",
318
+ placeholder="Example: A happy song about sunshine and rainbows",
319
+ lines=3
320
+ )
321
+ lyrics_btn = gr.Button("🎵 Generate Lyrics", variant="primary")
322
+
323
+ with gr.Tab("Upload Lyrics"):
324
+ file_upload = gr.File(
325
+ label="Upload Text File",
326
+ file_types=[".txt"],
327
+ type="filepath"
328
+ )
329
+ upload_btn = gr.Button("📁 Load from File", variant="secondary")
330
+ upload_text = gr.Textbox(
331
+ label="Uploaded Text",
332
+ lines=10,
333
+ interactive=False
334
+ )
335
+
336
+ # Lyrics Selection & Editing Section
337
+ gr.Markdown("### Step 2: Select & Edit Lyrics")
338
+
339
+ variant_choice = gr.Dropdown(
340
+ label="Select Lyrics Variant",
341
+ choices=[],
342
+ interactive=True
343
  )
 
344
 
345
+ lyrics_text = gr.Textbox(
346
+ label="Lyrics Text (Editable)",
347
+ placeholder="Your lyrics will appear here...",
348
+ lines=15,
349
+ interactive=True
350
+ )
351
+
352
+ with gr.Row():
353
+ download_btn = gr.Button("💾 Download Text", variant="secondary")
354
+ clear_btn = gr.Button("🗑️ Clear", variant="secondary")
355
+
356
+ # Song Generation Section
357
+ gr.Markdown("### Step 3: Create Song")
358
+
359
+ with gr.Row():
360
+ custom_mode = gr.Checkbox(
361
+ label="Custom Mode",
362
+ value=False,
363
  interactive=True
364
  )
365
+ instrumental = gr.Checkbox(
366
+ label="Instrumental",
367
+ value=False,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
368
  interactive=True
369
  )
 
 
370
 
371
+ with gr.Row():
372
+ style = gr.Textbox(
373
+ label="Music Style",
374
+ placeholder="Pop, Rock, Jazz, Classical",
375
+ interactive=True,
376
+ value="Pop"
377
+ )
378
+ title = gr.Textbox(
379
+ label="Song Title",
380
+ placeholder="My Awesome Song",
381
+ interactive=True,
382
+ value="Generated Song"
383
+ )
384
 
385
+ model = gr.Dropdown(
386
+ label="Model Version",
387
+ choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"],
388
+ value="V4_5ALL",
389
+ interactive=True
390
+ )
391
 
392
+ song_btn = gr.Button("🎶 Generate Song", variant="primary")
 
 
 
 
393
 
394
  with gr.Column(scale=2):
395
  output = gr.Markdown(
396
  label="Results",
397
  value="Your generated lyrics and songs will appear here..."
398
  )
399
+
400
+ # Hidden file download component
401
+ file_output = gr.File(label="Download Lyrics", visible=False)
402
 
403
  gr.Markdown("---")
404
  gr.Markdown(
 
413
  elem_id="footer"
414
  )
415
 
416
+ # Event handlers
417
+
418
+ # Generate lyrics from prompt
419
  lyrics_btn.click(
420
  generate_lyrics,
421
  inputs=prompt,
422
+ outputs=[output, lyrics_state, variant_choice, lyrics_text]
423
+ )
424
+
425
+ # Upload text from file
426
+ upload_btn.click(
427
+ upload_text_file,
428
+ inputs=file_upload,
429
+ outputs=lyrics_text
430
+ ).then(
431
+ lambda: "📁 **Text loaded from file!**\n\nYou can now edit the text above and generate a song.",
432
+ outputs=output
433
+ )
434
+
435
+ # Update text when variant is selected
436
+ variant_choice.change(
437
+ update_text_from_variant,
438
+ inputs=[lyrics_state, variant_choice],
439
+ outputs=lyrics_text
440
+ )
441
+
442
+ # Download text as file
443
+ download_btn.click(
444
+ download_text_file,
445
+ inputs=lyrics_text,
446
+ outputs=file_output
447
  ).then(
448
+ lambda: "💾 **Text ready for download!**\n\nCheck the download button below.",
449
+ outputs=output
450
+ )
451
+
452
+ # Clear text
453
+ clear_btn.click(
454
+ lambda: ("", ""),
455
+ outputs=[lyrics_text, output]
456
  )
457
 
458
+ # Generate song from text
459
  song_btn.click(
460
+ generate_song_from_text,
461
+ inputs=[lyrics_text, style, title, instrumental, model, custom_mode],
462
  outputs=output
463
  )
464
 
465
  if __name__ == "__main__":
466
+ print("🚀 Starting Suno Lyrics Generator")
467
  print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}")
468
  app.launch(server_name="0.0.0.0", server_port=7860, share=False)