haraberget commited on
Commit
adf84ee
Β·
verified Β·
1 Parent(s): a1f04b8

Update a.py

Browse files
Files changed (1) hide show
  1. a.py +588 -585
a.py CHANGED
@@ -1,586 +1,589 @@
1
- import gradio as gr
2
- import requests
3
- import os
4
- import time
5
- import json
6
- from urllib.parse import urlparse, parse_qs
7
-
8
- # Suno API key
9
- SUNO_KEY = os.environ.get("SunoKey", "")
10
- if not SUNO_KEY:
11
- print("⚠️ SunoKey not set!")
12
-
13
- def get_task_info(task_id):
14
- """Manually check any Suno task status"""
15
- if not task_id:
16
- return "❌ Please enter a Task ID"
17
-
18
- try:
19
- resp = requests.get(
20
- "https://api.sunoapi.org/api/v1/generate/record-info",
21
- headers={"Authorization": f"Bearer {SUNO_KEY}"},
22
- params={"taskId": task_id},
23
- timeout=30
24
- )
25
-
26
- if resp.status_code != 200:
27
- return f"❌ HTTP Error {resp.status_code}\n\n{resp.text}"
28
-
29
- data = resp.json()
30
-
31
- # Format the response for display
32
- output = f"## πŸ” Task Status: `{task_id}`\n\n"
33
-
34
- if data.get("code") == 200:
35
- task_data = data.get("data", {})
36
- status = task_data.get("status", "UNKNOWN")
37
-
38
- output += f"**Status:** {status}\n"
39
- output += f"**Task ID:** `{task_data.get('taskId', 'N/A')}`\n"
40
- output += f"**Music ID:** `{task_data.get('musicId', 'N/A')}`\n"
41
- output += f"**Created:** {task_data.get('createTime', 'N/A')}\n"
42
-
43
- if status == "SUCCESS":
44
- response_data = task_data.get("response", {})
45
-
46
- # Try to parse response (could be string or dict)
47
- if isinstance(response_data, str):
48
- try:
49
- response_data = json.loads(response_data)
50
- except:
51
- output += f"\n**Raw Response:**\n```\n{response_data}\n```\n"
52
- response_data = {}
53
-
54
- # Check for song data
55
- songs = []
56
- if isinstance(response_data, dict):
57
- songs = response_data.get("sunoData", [])
58
- if not songs:
59
- songs = response_data.get("data", [])
60
- elif isinstance(response_data, list):
61
- songs = response_data
62
-
63
- if songs:
64
- output += f"\n## 🎡 Generated Songs ({len(songs)})\n\n"
65
-
66
- for i, song in enumerate(songs, 1):
67
- if isinstance(song, dict):
68
- output += f"### Song {i}\n"
69
- output += f"**Title:** {song.get('title', 'Untitled')}\n"
70
- output += f"**ID:** `{song.get('id', 'N/A')}`\n"
71
-
72
- # Audio URLs
73
- audio_url = song.get('audioUrl') or song.get('audio_url')
74
- stream_url = song.get('streamUrl') or song.get('stream_url')
75
- download_url = song.get('downloadUrl') or song.get('download_url')
76
-
77
- if audio_url:
78
- output += f"**Audio:** [Play]({audio_url}) | [Download]({audio_url})\n"
79
- elif stream_url:
80
- output += f"**Stream:** [Play]({stream_url})\n"
81
-
82
- if download_url:
83
- output += f"**Download:** [MP3]({download_url})\n"
84
-
85
- # Audio player
86
- play_url = audio_url or stream_url
87
- if play_url:
88
- output += f"""\n<audio controls style="width: 100%; margin: 10px 0;">
89
- <source src="{play_url}" type="audio/mpeg">
90
- Your browser does not support audio.
91
- </audio>\n"""
92
-
93
- output += f"**Prompt:** {song.get('prompt', 'N/A')[:100]}...\n"
94
- output += f"**Duration:** {song.get('duration', 'N/A')}s\n"
95
- output += f"**Created:** {song.get('createTime', 'N/A')}\n\n"
96
- output += "---\n\n"
97
- else:
98
- output += "\n**No song data found in response.**\n"
99
-
100
- elif status == "FAILED":
101
- error_msg = task_data.get("errorMessage", "Unknown error")
102
- output += f"\n**Error:** {error_msg}\n"
103
-
104
- elif status in ["PENDING", "PROCESSING", "RUNNING"]:
105
- output += f"\n**Task is still processing...**\n"
106
- output += f"Check again in 30 seconds.\n"
107
-
108
- else:
109
- output += f"\n**Unknown status:** {status}\n"
110
-
111
- else:
112
- output += f"**API Error:** {data.get('msg', 'Unknown')}\n"
113
-
114
- # Show raw JSON for debugging
115
- output += "\n## πŸ“‹ Raw Response\n"
116
- output += f"```json\n{json.dumps(data, indent=2)}\n```"
117
-
118
- return output
119
-
120
- except Exception as e:
121
- return f"❌ Error checking task: {str(e)}"
122
-
123
- def generate_song_from_text(lyrics_text, style, title, instrumental, model):
124
- """Generate a song from lyrics text"""
125
- if not SUNO_KEY:
126
- yield "❌ Error: SunoKey not configured in environment variables"
127
- return
128
-
129
- if not lyrics_text.strip() and not instrumental:
130
- yield "❌ Error: Please provide lyrics or select instrumental"
131
- return
132
-
133
- if not style.strip():
134
- yield "❌ Error: Please provide a music style"
135
- return
136
-
137
- if not title.strip():
138
- yield "❌ Error: Please provide a song title"
139
- return
140
-
141
- try:
142
- # Prepare request data
143
- request_data = {
144
- "customMode": True,
145
- "instrumental": instrumental,
146
- "model": model,
147
- "callBackUrl": "https://1hit.no/gen/cb.php",
148
- "style": style,
149
- "title": title,
150
- }
151
-
152
- if not instrumental:
153
- # Apply character limits
154
- if model == "V4" and len(lyrics_text) > 3000:
155
- lyrics_text = lyrics_text[:3000]
156
- yield f"⚠️ Lyrics truncated to 3000 characters for V4 model\n\n"
157
- elif model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"] and len(lyrics_text) > 5000:
158
- lyrics_text = lyrics_text[:5000]
159
- yield f"⚠️ Lyrics truncated to 5000 characters for {model} model\n\n"
160
-
161
- request_data["prompt"] = lyrics_text
162
- else:
163
- request_data["prompt"] = ""
164
-
165
- # Apply style length limits
166
- if model == "V4" and len(style) > 200:
167
- style = style[:200]
168
- yield f"⚠️ Style truncated to 200 characters for V4 model\n\n"
169
- elif model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"] and len(style) > 1000:
170
- style = style[:1000]
171
- yield f"⚠️ Style truncated to 1000 characters for {model} model\n\n"
172
-
173
- # Apply title length limits
174
- if model in ["V4", "V4_5ALL"] and len(title) > 80:
175
- title = title[:80]
176
- yield f"⚠️ Title truncated to 80 characters for {model} model\n\n"
177
- elif model in ["V4_5", "V4_5PLUS", "V5"] and len(title) > 100:
178
- title = title[:100]
179
- yield f"⚠️ Title truncated to 100 characters for {model} model\n\n"
180
-
181
- request_data["style"] = style
182
- request_data["title"] = title
183
-
184
- yield f"## πŸš€ Submitting Song Request\n\n"
185
- yield f"**Title:** {title}\n"
186
- yield f"**Style:** {style}\n"
187
- yield f"**Model:** {model}\n"
188
- yield f"**Instrumental:** {'Yes' if instrumental else 'No'}\n"
189
- if not instrumental:
190
- yield f"**Lyrics length:** {len(lyrics_text)} characters\n\n"
191
- yield f"**Callback URL:** https://1hit.no/callback.php\n\n"
192
-
193
- # Submit generation request
194
- try:
195
- resp = requests.post(
196
- "https://api.sunoapi.org/api/v1/generate",
197
- json=request_data,
198
- headers={
199
- "Authorization": f"Bearer {SUNO_KEY}",
200
- "Content-Type": "application/json"
201
- },
202
- timeout=30
203
- )
204
-
205
- if resp.status_code != 200:
206
- yield f"❌ Submission failed: HTTP {resp.status_code}"
207
- yield f"\n**Response:**\n```\n{resp.text}\n```"
208
- return
209
-
210
- data = resp.json()
211
- print(f"Submission response: {json.dumps(data, indent=2)}")
212
-
213
- if data.get("code") != 200:
214
- yield f"❌ API error: {data.get('msg', 'Unknown')}"
215
- return
216
-
217
- # Extract task ID from response
218
- task_id = None
219
- if "taskId" in data:
220
- task_id = data["taskId"]
221
- elif "data" in data and "taskId" in data["data"]:
222
- task_id = data["data"]["taskId"]
223
- elif data.get("data") and "taskId" in data.get("data", {}):
224
- task_id = data["data"]["taskId"]
225
-
226
- if not task_id:
227
- yield f"❌ Could not extract Task ID from response"
228
- yield f"\n**Raw Response:**\n```json\n{json.dumps(data, indent=2)}\n```"
229
- return
230
-
231
- yield f"## βœ… Request Submitted Successfully!\n\n"
232
- yield f"**🎯 Task ID:** `{task_id}`\n\n"
233
- yield f"**⏳ Status:** Generation started\n"
234
- yield f"**πŸ“ž Callback:** https://1hit.no/callback.php\n\n"
235
- yield "**What happens now:**\n"
236
- yield "1. Suno AI generates your song (1-3 minutes)\n"
237
- yield "2. You'll get a callback notification\n"
238
- yield "3. Use the Task ID above to check status manually\n\n"
239
- yield "---\n\n"
240
- yield f"## πŸ” Check Status Manually\n\n"
241
- yield f"Use this Task ID: `{task_id}`\n\n"
242
- yield "**To check status:**\n"
243
- yield "1. Copy the Task ID above\n"
244
- yield "2. Go to 'Check Any Task' tab\n"
245
- yield "3. Paste and click 'Check Status'\n"
246
- yield "4. Or wait for callback notification\n\n"
247
- yield "**Generation time:**\n"
248
- yield "- 30-60 seconds for stream URL\n"
249
- yield "- 2-3 minutes for download URL\n"
250
-
251
- # Simple one-time check after 30 seconds
252
- yield "\n**⏰ Will check once in 30 seconds...**\n"
253
- time.sleep(30)
254
-
255
- # Single status check
256
- status_result = get_task_info(task_id)
257
- yield "\n## πŸ“Š Status Check (30s)\n\n"
258
- yield status_result
259
-
260
- except Exception as e:
261
- yield f"❌ Error submitting request: {str(e)}"
262
- return
263
-
264
- except Exception as e:
265
- yield f"❌ **Unexpected Error:** {str(e)}"
266
-
267
- # Function to handle URL parameters
268
- def parse_url_params(request: gr.Request):
269
- """Parse taskid from URL parameters"""
270
- task_id = None
271
- if request:
272
- try:
273
- query_params = parse_qs(urlparse(request.request.url).query)
274
- if 'taskid' in query_params:
275
- task_id = query_params['taskid'][0]
276
- # Remove any whitespace
277
- task_id = task_id.strip()
278
- except Exception as e:
279
- print(f"Error parsing URL params: {e}")
280
-
281
- return task_id
282
-
283
- # Create the app
284
- with gr.Blocks() as app:
285
- gr.Markdown("# 🎡 Suno Song Generator")
286
- gr.Markdown("Create songs from lyrics and style using Suno AI")
287
-
288
- # We'll use a hidden component to track initial load
289
- initial_load_done = gr.State(value=False)
290
-
291
- with gr.TabItem("Audio Link"):
292
- gr.HTML("""
293
- <p>12 mar 2026 - I tried putting up 45 minutes of music on twitch. :)</p>
294
- <a href=" https://www.twitch.tv/videos/2724809128" target="_blank">1hit.no Suno - music on twitch created here.</a>
295
-
296
- <p>12 mar 2026 - I tried putting up 45 minutes of music on youtube via twitch. :)</p>
297
- <a href=" https://1hit.no/youtube/?v=BLjpwZwfKWY" target="_blank">1hit.no Suno - music on youtube created here.</a>
298
-
299
- <p>20 feb 2026 - WOW! We are features on two mockup radio stations. :)</p>
300
- <p>(: -------------- :)</p>
301
- <a href="https://1hit.no/1radio.m3u" target="_blank">1hit radio - Chat GPT is host</a>
302
- <a href="https://1hit.no/onlineradio.m3u" target="_blank">1hit radio - Deepseek is host</a>
303
- <p>(: -------------- :)</p>
304
-
305
- <p>Hey gangster kids, plis clean up the site for me, you are making a mess!</p>
306
- <a href=" https://1hit.no/gen/audio/images/patchfix.php" target="_blank">Open 1hit Image Cleanup</a>
307
-
308
- <p>Click below to open the audio page:</p>
309
- <a href="https://1hit.no/gen/audio/mp3/" target="_blank">Open 1hit Audio</a>
310
- <p>11 feb 2026 - New feature - Minimal m3u file download.</p>
311
- <a href="https://1hit.no/gen/xm3u.php" target="_blank">Get complete m3u.file of music lib - with titles and duration</a>
312
- <p>11 feb 2026 - New feature - Minimal m3u file download, better version comes up later?</p>
313
- <a href="https://1hit.no/gen/sm3u.php" target="_blank">Get complete m3u.file of music lib - with taskid</a>
314
- <p>Tested with VLC</p>
315
- <a href=" https://www.videolan.org/vlc/" target="_blank">Download VLC media player</a>
316
- <p>13 feb 2026 - Making a backup of dataset available, but made to many commits. :)</p>
317
- <a href="https://huggingface.co/datasets/MySafeCode/1hit.no-Music-Images/" target="_blank">https://huggingface.co/datasets/MySafeCode/1hit.no-Music-Images/</a>
318
-
319
- """)
320
-
321
-
322
- with gr.Tab("🎢 Generate Song", id="generate_tab") as tab_generate:
323
- with gr.Row():
324
- with gr.Column(scale=1):
325
- # Lyrics Input
326
- gr.Markdown("### Step 1: Enter Lyrics")
327
-
328
- lyrics_text = gr.Textbox(
329
- label="Lyrics",
330
- placeholder="Paste your lyrics here...\n\nExample:\n(Verse 1)\nSun is shining, sky is blue\nBirds are singing, just for you...",
331
- lines=10,
332
- interactive=True
333
- )
334
-
335
- # Song Settings
336
- gr.Markdown("### Step 2: Song Settings")
337
-
338
- style = gr.Textbox(
339
- label="Music Style",
340
- placeholder="Example: Pop, Rock, Jazz, Classical, Electronic, Hip Hop, Country",
341
- value="Folk soul flamenco glam rock goa trance fusion",
342
- interactive=True
343
- )
344
-
345
- title = gr.Textbox(
346
- label="Song Title",
347
- placeholder="My Awesome Song",
348
- value="Generated Song",
349
- interactive=True
350
- )
351
-
352
- with gr.Row():
353
- instrumental = gr.Checkbox(
354
- label="Instrumental (No Vocals)",
355
- value=False,
356
- interactive=True
357
- )
358
- model = gr.Dropdown(
359
- label="Model",
360
- choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"],
361
- value="V4_5ALL",
362
- interactive=True
363
- )
364
-
365
- # Action Buttons
366
- generate_btn = gr.Button("πŸš€ Generate Song", variant="primary")
367
- clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
368
-
369
- # Instructions
370
- gr.Markdown("""
371
- **How to use:**
372
- 1. Paste lyrics (or leave empty for instrumental)
373
- 2. Set music style
374
- 3. Enter song title
375
- 4. Choose model
376
- 5. Click Generate!
377
-
378
- **Tips:**
379
- - V4_5ALL: Best overall quality
380
- - V5: Latest model
381
- - Instrumental: No vocals, just music
382
- """)
383
-
384
- with gr.Column(scale=2):
385
- # Output Area
386
- output = gr.Markdown(
387
- value="### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'"
388
- )
389
-
390
- with gr.Tab("πŸ” Check Any Task", id="check_tab") as tab_check:
391
- with gr.Row():
392
- with gr.Column(scale=1):
393
- gr.Markdown("### Check Task Status")
394
- gr.Markdown("Enter any Suno Task ID to check its status")
395
-
396
- check_task_id = gr.Textbox(
397
- label="Task ID",
398
- placeholder="Enter Task ID from generation or separation",
399
- info="From Song Generator or Vocal Separator"
400
- )
401
-
402
- check_btn = gr.Button("πŸ” Check Status", variant="primary")
403
- check_clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
404
-
405
- # URL parameter info
406
- gr.Markdown("""
407
- **Quick access via URL:**
408
- Add `?taskid=YOUR_TASK_ID` to the URL
409
-
410
- Example:
411
- `https://1hit.no/gen/view.php?task_id=fa3529d5cbaa93427ee4451976ed5c4b`
412
- """)
413
-
414
- with gr.Column(scale=2):
415
- check_output = gr.Markdown(
416
- value="### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results."
417
- )
418
-
419
- with gr.Tab("πŸ“š Instructions", id="instructions_tab"):
420
- gr.Markdown("""
421
- ## πŸ“– How to Use This App
422
-
423
- ### 🎢 Generate Song Tab
424
- 1. **Enter Lyrics** (or leave empty for instrumental)
425
- 2. **Set Music Style** (e.g., "Pop", "Rock", "Jazz")
426
- 3. **Enter Song Title**
427
- 4. **Choose Model** (V4_5ALL recommended)
428
- 5. **Click "Generate Song"**
429
-
430
- ### πŸ” Check Any Task Tab
431
- 1. **Paste any Suno Task ID**
432
- 2. **Click "Check Status"**
433
- 3. **View results and download links**
434
-
435
- **Quick URL Access:**
436
- - Visit with `?taskid=YOUR_TASK_ID` in the URL
437
- - Automatically switches to Check tab
438
- - Shows task status immediately
439
-
440
- Example:
441
- ```
442
- https://1hit.no/gen/view.php?task_id=fa3529d5cbaa93427ee4451976ed5c4b
443
- ```
444
-
445
- ### ⏱️ What to Expect
446
-
447
- **After generating:**
448
- - You'll get a **Task ID** immediately
449
- - Generation takes **1-3 minutes**
450
- - **Callback** sent to https://1hit.no/gen/cb.php
451
- - Use Task ID to **check status manually**
452
-
453
- **Task IDs come from:**
454
- - Song Generator (this app)
455
- - Vocal Separator (other app)
456
- - Any Suno API request
457
-
458
- ### 🎡 Getting Your Songs
459
-
460
- 1. **Stream URL:** Ready in 30-60 seconds
461
- 2. **Download URL:** Ready in 2-3 minutes
462
- 3. **Both appear in status check**
463
- 4. **Audio player** included for streaming
464
-
465
- ### πŸ”§ Troubleshooting
466
-
467
- **Task not found?**
468
- - Wait a few minutes
469
- - Check callback logs at https://1hit.no/gen/view.php
470
- - Ensure Task ID is correct
471
-
472
- **No audio links?**
473
- - Wait 2-3 minutes
474
- - Check status again
475
- - Generation may have failed
476
- """)
477
-
478
- with gr.Tab("πŸ“š Less Instructions", id="less_instructions_tab"):
479
- gr.Markdown("""
480
- ## πŸ“– How to Use This App
481
-
482
- ### 🎢 Generate Song Tab
483
- 1. **Enter Lyrics** (or leave empty for instrumental)
484
- 2. **Set Music Style** (e.g., "Pop", "Rock", "Jazz")
485
- 3. **Enter Song Title**
486
- 4. **Choose Model** (V4_5ALL recommended)
487
- 5. **Click "Generate Song"**
488
-
489
- ### πŸ” Check Any Task via URL
490
- Add `?taskid=YOUR_TASK_ID` to the URL
491
-
492
- Example:
493
- ```
494
- https://1hit.no/gen/view.php?task_id=fa3529d5cbaa93427ee4451976ed5c4b
495
- ```
496
-
497
- ### πŸ“ž Callback Status
498
- https://1hit.no/gen/view.php
499
-
500
- **No audio links?**
501
- - Wait 2-3 minutes
502
- - Check status again
503
- - Generation may have failed
504
- """)
505
-
506
- gr.Markdown("---")
507
- gr.Markdown(
508
- """
509
- <div style="text-align: center; padding: 20px;">
510
- <p>Powered by <a href="https://suno.ai" target="_blank">Suno AI</a> β€’
511
- <a href="https://sunoapi.org" target="_blank">Suno API Docs</a></p>
512
- <p><small>Create custom songs by providing lyrics and music style</small></p>
513
- </div>
514
- """,
515
- elem_id="footer"
516
- )
517
-
518
- # Event handlers for Generate Song tab
519
- def clear_all():
520
- return "", "Pop", "Generated Song", False, "V4_5ALL", "### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'"
521
-
522
- clear_btn.click(
523
- clear_all,
524
- outputs=[lyrics_text, style, title, instrumental, model, output]
525
- )
526
-
527
- generate_btn.click(
528
- generate_song_from_text,
529
- inputs=[lyrics_text, style, title, instrumental, model],
530
- outputs=output
531
- )
532
-
533
- # Event handlers for Check Any Task tab
534
- def clear_check():
535
- return "", "### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results."
536
-
537
- check_clear_btn.click(
538
- clear_check,
539
- outputs=[check_task_id, check_output]
540
- )
541
-
542
- check_btn.click(
543
- get_task_info,
544
- inputs=[check_task_id],
545
- outputs=check_output
546
- )
547
-
548
- # Function to handle URL parameter on load
549
- def on_page_load(request: gr.Request):
550
- """Handle URL parameters when page loads"""
551
- task_id = parse_url_params(request)
552
-
553
- if task_id:
554
- # We have a task ID from URL, return it and fetch results
555
- task_result = get_task_info(task_id)
556
- return (
557
- task_id, # For check_task_id
558
- task_result, # For check_output
559
- gr.Tabs(selected="check_tab"), # Switch to check tab
560
- True # Mark as loaded
561
- )
562
- else:
563
- # No task ID in URL, stay on first tab
564
- return (
565
- "", # Empty check_task_id
566
- "### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results.", # Default message
567
- gr.Tabs(selected="generate_tab"), # Stay on generate tab
568
- True # Mark as loaded
569
- )
570
-
571
- # Load URL parameters when the app starts
572
- app.load(
573
- fn=on_page_load,
574
- inputs=[],
575
- outputs=[check_task_id, check_output, gr.Tabs(), initial_load_done],
576
- queue=False
577
- )
578
-
579
- # Launch the app
580
- if __name__ == "__main__":
581
- print("πŸš€ Starting Suno Song Generator")
582
- print(f"πŸ”‘ SunoKey: {'βœ… Set' if SUNO_KEY else '❌ Not set'}")
583
- print("🌐 Open your browser to: http://localhost:7860")
584
- print("πŸ”— Use URL parameter: http://localhost:7860?taskid=YOUR_TASK_ID")
585
-
 
 
 
586
  app.launch(server_name="0.0.0.0", server_port=7860, share=False)
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ import time
5
+ import json
6
+ from urllib.parse import urlparse, parse_qs
7
+
8
+ # Suno API key
9
+ SUNO_KEY = os.environ.get("SunoKey", "")
10
+ if not SUNO_KEY:
11
+ print("⚠️ SunoKey not set!")
12
+
13
+ def get_task_info(task_id):
14
+ """Manually check any Suno task status"""
15
+ if not task_id:
16
+ return "❌ Please enter a Task ID"
17
+
18
+ try:
19
+ resp = requests.get(
20
+ "https://api.sunoapi.org/api/v1/generate/record-info",
21
+ headers={"Authorization": f"Bearer {SUNO_KEY}"},
22
+ params={"taskId": task_id},
23
+ timeout=30
24
+ )
25
+
26
+ if resp.status_code != 200:
27
+ return f"❌ HTTP Error {resp.status_code}\n\n{resp.text}"
28
+
29
+ data = resp.json()
30
+
31
+ # Format the response for display
32
+ output = f"## πŸ” Task Status: `{task_id}`\n\n"
33
+
34
+ if data.get("code") == 200:
35
+ task_data = data.get("data", {})
36
+ status = task_data.get("status", "UNKNOWN")
37
+
38
+ output += f"**Status:** {status}\n"
39
+ output += f"**Task ID:** `{task_data.get('taskId', 'N/A')}`\n"
40
+ output += f"**Music ID:** `{task_data.get('musicId', 'N/A')}`\n"
41
+ output += f"**Created:** {task_data.get('createTime', 'N/A')}\n"
42
+
43
+ if status == "SUCCESS":
44
+ response_data = task_data.get("response", {})
45
+
46
+ # Try to parse response (could be string or dict)
47
+ if isinstance(response_data, str):
48
+ try:
49
+ response_data = json.loads(response_data)
50
+ except:
51
+ output += f"\n**Raw Response:**\n```\n{response_data}\n```\n"
52
+ response_data = {}
53
+
54
+ # Check for song data
55
+ songs = []
56
+ if isinstance(response_data, dict):
57
+ songs = response_data.get("sunoData", [])
58
+ if not songs:
59
+ songs = response_data.get("data", [])
60
+ elif isinstance(response_data, list):
61
+ songs = response_data
62
+
63
+ if songs:
64
+ output += f"\n## 🎡 Generated Songs ({len(songs)})\n\n"
65
+
66
+ for i, song in enumerate(songs, 1):
67
+ if isinstance(song, dict):
68
+ output += f"### Song {i}\n"
69
+ output += f"**Title:** {song.get('title', 'Untitled')}\n"
70
+ output += f"**ID:** `{song.get('id', 'N/A')}`\n"
71
+
72
+ # Audio URLs
73
+ audio_url = song.get('audioUrl') or song.get('audio_url')
74
+ stream_url = song.get('streamUrl') or song.get('stream_url')
75
+ download_url = song.get('downloadUrl') or song.get('download_url')
76
+
77
+ if audio_url:
78
+ output += f"**Audio:** [Play]({audio_url}) | [Download]({audio_url})\n"
79
+ elif stream_url:
80
+ output += f"**Stream:** [Play]({stream_url})\n"
81
+
82
+ if download_url:
83
+ output += f"**Download:** [MP3]({download_url})\n"
84
+
85
+ # Audio player
86
+ play_url = audio_url or stream_url
87
+ if play_url:
88
+ output += f"""\n<audio controls style="width: 100%; margin: 10px 0;">
89
+ <source src="{play_url}" type="audio/mpeg">
90
+ Your browser does not support audio.
91
+ </audio>\n"""
92
+
93
+ output += f"**Prompt:** {song.get('prompt', 'N/A')[:100]}...\n"
94
+ output += f"**Duration:** {song.get('duration', 'N/A')}s\n"
95
+ output += f"**Created:** {song.get('createTime', 'N/A')}\n\n"
96
+ output += "---\n\n"
97
+ else:
98
+ output += "\n**No song data found in response.**\n"
99
+
100
+ elif status == "FAILED":
101
+ error_msg = task_data.get("errorMessage", "Unknown error")
102
+ output += f"\n**Error:** {error_msg}\n"
103
+
104
+ elif status in ["PENDING", "PROCESSING", "RUNNING"]:
105
+ output += f"\n**Task is still processing...**\n"
106
+ output += f"Check again in 30 seconds.\n"
107
+
108
+ else:
109
+ output += f"\n**Unknown status:** {status}\n"
110
+
111
+ else:
112
+ output += f"**API Error:** {data.get('msg', 'Unknown')}\n"
113
+
114
+ # Show raw JSON for debugging
115
+ output += "\n## πŸ“‹ Raw Response\n"
116
+ output += f"```json\n{json.dumps(data, indent=2)}\n```"
117
+
118
+ return output
119
+
120
+ except Exception as e:
121
+ return f"❌ Error checking task: {str(e)}"
122
+
123
+ def generate_song_from_text(lyrics_text, style, title, instrumental, model):
124
+ """Generate a song from lyrics text"""
125
+ if not SUNO_KEY:
126
+ yield "❌ Error: SunoKey not configured in environment variables"
127
+ return
128
+
129
+ if not lyrics_text.strip() and not instrumental:
130
+ yield "❌ Error: Please provide lyrics or select instrumental"
131
+ return
132
+
133
+ if not style.strip():
134
+ yield "❌ Error: Please provide a music style"
135
+ return
136
+
137
+ if not title.strip():
138
+ yield "❌ Error: Please provide a song title"
139
+ return
140
+
141
+ try:
142
+ # Prepare request data
143
+ request_data = {
144
+ "customMode": True,
145
+ "instrumental": instrumental,
146
+ "model": model,
147
+ "callBackUrl": "https://1hit.no/gen/cb.php",
148
+ "style": style,
149
+ "title": title,
150
+ }
151
+
152
+ if not instrumental:
153
+ # Apply character limits
154
+ if model == "V4" and len(lyrics_text) > 3000:
155
+ lyrics_text = lyrics_text[:3000]
156
+ yield f"⚠️ Lyrics truncated to 3000 characters for V4 model\n\n"
157
+ elif model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"] and len(lyrics_text) > 5000:
158
+ lyrics_text = lyrics_text[:5000]
159
+ yield f"⚠️ Lyrics truncated to 5000 characters for {model} model\n\n"
160
+
161
+ request_data["prompt"] = lyrics_text
162
+ else:
163
+ request_data["prompt"] = ""
164
+
165
+ # Apply style length limits
166
+ if model == "V4" and len(style) > 200:
167
+ style = style[:200]
168
+ yield f"⚠️ Style truncated to 200 characters for V4 model\n\n"
169
+ elif model in ["V4_5", "V4_5PLUS", "V4_5ALL", "V5"] and len(style) > 1000:
170
+ style = style[:1000]
171
+ yield f"⚠️ Style truncated to 1000 characters for {model} model\n\n"
172
+
173
+ # Apply title length limits
174
+ if model in ["V4", "V4_5ALL"] and len(title) > 80:
175
+ title = title[:80]
176
+ yield f"⚠️ Title truncated to 80 characters for {model} model\n\n"
177
+ elif model in ["V4_5", "V4_5PLUS", "V5"] and len(title) > 100:
178
+ title = title[:100]
179
+ yield f"⚠️ Title truncated to 100 characters for {model} model\n\n"
180
+
181
+ request_data["style"] = style
182
+ request_data["title"] = title
183
+
184
+ yield f"## πŸš€ Submitting Song Request\n\n"
185
+ yield f"**Title:** {title}\n"
186
+ yield f"**Style:** {style}\n"
187
+ yield f"**Model:** {model}\n"
188
+ yield f"**Instrumental:** {'Yes' if instrumental else 'No'}\n"
189
+ if not instrumental:
190
+ yield f"**Lyrics length:** {len(lyrics_text)} characters\n\n"
191
+ yield f"**Callback URL:** https://1hit.no/callback.php\n\n"
192
+
193
+ # Submit generation request
194
+ try:
195
+ resp = requests.post(
196
+ "https://api.sunoapi.org/api/v1/generate",
197
+ json=request_data,
198
+ headers={
199
+ "Authorization": f"Bearer {SUNO_KEY}",
200
+ "Content-Type": "application/json"
201
+ },
202
+ timeout=30
203
+ )
204
+
205
+ if resp.status_code != 200:
206
+ yield f"❌ Submission failed: HTTP {resp.status_code}"
207
+ yield f"\n**Response:**\n```\n{resp.text}\n```"
208
+ return
209
+
210
+ data = resp.json()
211
+ print(f"Submission response: {json.dumps(data, indent=2)}")
212
+
213
+ if data.get("code") != 200:
214
+ yield f"❌ API error: {data.get('msg', 'Unknown')}"
215
+ return
216
+
217
+ # Extract task ID from response
218
+ task_id = None
219
+ if "taskId" in data:
220
+ task_id = data["taskId"]
221
+ elif "data" in data and "taskId" in data["data"]:
222
+ task_id = data["data"]["taskId"]
223
+ elif data.get("data") and "taskId" in data.get("data", {}):
224
+ task_id = data["data"]["taskId"]
225
+
226
+ if not task_id:
227
+ yield f"❌ Could not extract Task ID from response"
228
+ yield f"\n**Raw Response:**\n```json\n{json.dumps(data, indent=2)}\n```"
229
+ return
230
+
231
+ yield f"## βœ… Request Submitted Successfully!\n\n"
232
+ yield f"**🎯 Task ID:** `{task_id}`\n\n"
233
+ yield f"**⏳ Status:** Generation started\n"
234
+ yield f"**πŸ“ž Callback:** https://1hit.no/callback.php\n\n"
235
+ yield "**What happens now:**\n"
236
+ yield "1. Suno AI generates your song (1-3 minutes)\n"
237
+ yield "2. You'll get a callback notification\n"
238
+ yield "3. Use the Task ID above to check status manually\n\n"
239
+ yield "---\n\n"
240
+ yield f"## πŸ” Check Status Manually\n\n"
241
+ yield f"Use this Task ID: `{task_id}`\n\n"
242
+ yield "**To check status:**\n"
243
+ yield "1. Copy the Task ID above\n"
244
+ yield "2. Go to 'Check Any Task' tab\n"
245
+ yield "3. Paste and click 'Check Status'\n"
246
+ yield "4. Or wait for callback notification\n\n"
247
+ yield "**Generation time:**\n"
248
+ yield "- 30-60 seconds for stream URL\n"
249
+ yield "- 2-3 minutes for download URL\n"
250
+
251
+ # Simple one-time check after 30 seconds
252
+ yield "\n**⏰ Will check once in 30 seconds...**\n"
253
+ time.sleep(30)
254
+
255
+ # Single status check
256
+ status_result = get_task_info(task_id)
257
+ yield "\n## πŸ“Š Status Check (30s)\n\n"
258
+ yield status_result
259
+
260
+ except Exception as e:
261
+ yield f"❌ Error submitting request: {str(e)}"
262
+ return
263
+
264
+ except Exception as e:
265
+ yield f"❌ **Unexpected Error:** {str(e)}"
266
+
267
+ # Function to handle URL parameters
268
+ def parse_url_params(request: gr.Request):
269
+ """Parse taskid from URL parameters"""
270
+ task_id = None
271
+ if request:
272
+ try:
273
+ query_params = parse_qs(urlparse(request.request.url).query)
274
+ if 'taskid' in query_params:
275
+ task_id = query_params['taskid'][0]
276
+ # Remove any whitespace
277
+ task_id = task_id.strip()
278
+ except Exception as e:
279
+ print(f"Error parsing URL params: {e}")
280
+
281
+ return task_id
282
+
283
+ # Create the app
284
+ with gr.Blocks() as app:
285
+ gr.Markdown("# 🎡 Suno Song Generator")
286
+ gr.Markdown("Create songs from lyrics and style using Suno AI")
287
+
288
+ # We'll use a hidden component to track initial load
289
+ initial_load_done = gr.State(value=False)
290
+
291
+ with gr.TabItem("Audio Link"):
292
+ gr.HTML("""
293
+ <p>27 mar 2026 - Made an example on how to include lib in games etc... :)</p>
294
+ <a href="https://1hit.no/demo/hola.html" target="_blank">1hit.no Suno - playlist demo.</a>
295
+
296
+ <p>12 mar 2026 - I tried putting up 45 minutes of music on twitch. :)</p>
297
+ <a href=" https://www.twitch.tv/videos/2724809128" target="_blank">1hit.no Suno - music on twitch created here.</a>
298
+
299
+ <p>12 mar 2026 - I tried putting up 45 minutes of music on youtube via twitch. :)</p>
300
+ <a href=" https://1hit.no/youtube/?v=BLjpwZwfKWY" target="_blank">1hit.no Suno - music on youtube created here.</a>
301
+
302
+ <p>20 feb 2026 - WOW! We are features on two mockup radio stations. :)</p>
303
+ <p>(: -------------- :)</p>
304
+ <a href="https://1hit.no/1radio.m3u" target="_blank">1hit radio - Chat GPT is host</a>
305
+ <a href="https://1hit.no/onlineradio.m3u" target="_blank">1hit radio - Deepseek is host</a>
306
+ <p>(: -------------- :)</p>
307
+
308
+ <p>Hey gangster kids, plis clean up the site for me, you are making a mess!</p>
309
+ <a href=" https://1hit.no/gen/audio/images/patchfix.php" target="_blank">Open 1hit Image Cleanup</a>
310
+
311
+ <p>Click below to open the audio page:</p>
312
+ <a href="https://1hit.no/gen/audio/mp3/" target="_blank">Open 1hit Audio</a>
313
+ <p>11 feb 2026 - New feature - Minimal m3u file download.</p>
314
+ <a href="https://1hit.no/gen/xm3u.php" target="_blank">Get complete m3u.file of music lib - with titles and duration</a>
315
+ <p>11 feb 2026 - New feature - Minimal m3u file download, better version comes up later?</p>
316
+ <a href="https://1hit.no/gen/sm3u.php" target="_blank">Get complete m3u.file of music lib - with taskid</a>
317
+ <p>Tested with VLC</p>
318
+ <a href=" https://www.videolan.org/vlc/" target="_blank">Download VLC media player</a>
319
+ <p>13 feb 2026 - Making a backup of dataset available, but made to many commits. :)</p>
320
+ <a href="https://huggingface.co/datasets/MySafeCode/1hit.no-Music-Images/" target="_blank">https://huggingface.co/datasets/MySafeCode/1hit.no-Music-Images/</a>
321
+
322
+ """)
323
+
324
+
325
+ with gr.Tab("🎢 Generate Song", id="generate_tab") as tab_generate:
326
+ with gr.Row():
327
+ with gr.Column(scale=1):
328
+ # Lyrics Input
329
+ gr.Markdown("### Step 1: Enter Lyrics")
330
+
331
+ lyrics_text = gr.Textbox(
332
+ label="Lyrics",
333
+ placeholder="Paste your lyrics here...\n\nExample:\n(Verse 1)\nSun is shining, sky is blue\nBirds are singing, just for you...",
334
+ lines=10,
335
+ interactive=True
336
+ )
337
+
338
+ # Song Settings
339
+ gr.Markdown("### Step 2: Song Settings")
340
+
341
+ style = gr.Textbox(
342
+ label="Music Style",
343
+ placeholder="Example: Pop, Rock, Jazz, Classical, Electronic, Hip Hop, Country",
344
+ value="Folk soul flamenco glam rock goa trance fusion",
345
+ interactive=True
346
+ )
347
+
348
+ title = gr.Textbox(
349
+ label="Song Title",
350
+ placeholder="My Awesome Song",
351
+ value="Generated Song",
352
+ interactive=True
353
+ )
354
+
355
+ with gr.Row():
356
+ instrumental = gr.Checkbox(
357
+ label="Instrumental (No Vocals)",
358
+ value=False,
359
+ interactive=True
360
+ )
361
+ model = gr.Dropdown(
362
+ label="Model",
363
+ choices=["V5", "V4_5PLUS", "V4_5ALL", "V4_5", "V4"],
364
+ value="V4_5ALL",
365
+ interactive=True
366
+ )
367
+
368
+ # Action Buttons
369
+ generate_btn = gr.Button("πŸš€ Generate Song", variant="primary")
370
+ clear_btn = gr.Button("πŸ—‘οΈ Clear All", variant="secondary")
371
+
372
+ # Instructions
373
+ gr.Markdown("""
374
+ **How to use:**
375
+ 1. Paste lyrics (or leave empty for instrumental)
376
+ 2. Set music style
377
+ 3. Enter song title
378
+ 4. Choose model
379
+ 5. Click Generate!
380
+
381
+ **Tips:**
382
+ - V4_5ALL: Best overall quality
383
+ - V5: Latest model
384
+ - Instrumental: No vocals, just music
385
+ """)
386
+
387
+ with gr.Column(scale=2):
388
+ # Output Area
389
+ output = gr.Markdown(
390
+ value="### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'"
391
+ )
392
+
393
+ with gr.Tab("πŸ” Check Any Task", id="check_tab") as tab_check:
394
+ with gr.Row():
395
+ with gr.Column(scale=1):
396
+ gr.Markdown("### Check Task Status")
397
+ gr.Markdown("Enter any Suno Task ID to check its status")
398
+
399
+ check_task_id = gr.Textbox(
400
+ label="Task ID",
401
+ placeholder="Enter Task ID from generation or separation",
402
+ info="From Song Generator or Vocal Separator"
403
+ )
404
+
405
+ check_btn = gr.Button("πŸ” Check Status", variant="primary")
406
+ check_clear_btn = gr.Button("πŸ—‘οΈ Clear", variant="secondary")
407
+
408
+ # URL parameter info
409
+ gr.Markdown("""
410
+ **Quick access via URL:**
411
+ Add `?taskid=YOUR_TASK_ID` to the URL
412
+
413
+ Example:
414
+ `https://1hit.no/gen/view.php?task_id=fa3529d5cbaa93427ee4451976ed5c4b`
415
+ """)
416
+
417
+ with gr.Column(scale=2):
418
+ check_output = gr.Markdown(
419
+ value="### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results."
420
+ )
421
+
422
+ with gr.Tab("πŸ“š Instructions", id="instructions_tab"):
423
+ gr.Markdown("""
424
+ ## πŸ“– How to Use This App
425
+
426
+ ### 🎢 Generate Song Tab
427
+ 1. **Enter Lyrics** (or leave empty for instrumental)
428
+ 2. **Set Music Style** (e.g., "Pop", "Rock", "Jazz")
429
+ 3. **Enter Song Title**
430
+ 4. **Choose Model** (V4_5ALL recommended)
431
+ 5. **Click "Generate Song"**
432
+
433
+ ### πŸ” Check Any Task Tab
434
+ 1. **Paste any Suno Task ID**
435
+ 2. **Click "Check Status"**
436
+ 3. **View results and download links**
437
+
438
+ **Quick URL Access:**
439
+ - Visit with `?taskid=YOUR_TASK_ID` in the URL
440
+ - Automatically switches to Check tab
441
+ - Shows task status immediately
442
+
443
+ Example:
444
+ ```
445
+ https://1hit.no/gen/view.php?task_id=fa3529d5cbaa93427ee4451976ed5c4b
446
+ ```
447
+
448
+ ### ⏱️ What to Expect
449
+
450
+ **After generating:**
451
+ - You'll get a **Task ID** immediately
452
+ - Generation takes **1-3 minutes**
453
+ - **Callback** sent to https://1hit.no/gen/cb.php
454
+ - Use Task ID to **check status manually**
455
+
456
+ **Task IDs come from:**
457
+ - Song Generator (this app)
458
+ - Vocal Separator (other app)
459
+ - Any Suno API request
460
+
461
+ ### 🎡 Getting Your Songs
462
+
463
+ 1. **Stream URL:** Ready in 30-60 seconds
464
+ 2. **Download URL:** Ready in 2-3 minutes
465
+ 3. **Both appear in status check**
466
+ 4. **Audio player** included for streaming
467
+
468
+ ### πŸ”§ Troubleshooting
469
+
470
+ **Task not found?**
471
+ - Wait a few minutes
472
+ - Check callback logs at https://1hit.no/gen/view.php
473
+ - Ensure Task ID is correct
474
+
475
+ **No audio links?**
476
+ - Wait 2-3 minutes
477
+ - Check status again
478
+ - Generation may have failed
479
+ """)
480
+
481
+ with gr.Tab("πŸ“š Less Instructions", id="less_instructions_tab"):
482
+ gr.Markdown("""
483
+ ## πŸ“– How to Use This App
484
+
485
+ ### 🎢 Generate Song Tab
486
+ 1. **Enter Lyrics** (or leave empty for instrumental)
487
+ 2. **Set Music Style** (e.g., "Pop", "Rock", "Jazz")
488
+ 3. **Enter Song Title**
489
+ 4. **Choose Model** (V4_5ALL recommended)
490
+ 5. **Click "Generate Song"**
491
+
492
+ ### πŸ” Check Any Task via URL
493
+ Add `?taskid=YOUR_TASK_ID` to the URL
494
+
495
+ Example:
496
+ ```
497
+ https://1hit.no/gen/view.php?task_id=fa3529d5cbaa93427ee4451976ed5c4b
498
+ ```
499
+
500
+ ### πŸ“ž Callback Status
501
+ https://1hit.no/gen/view.php
502
+
503
+ **No audio links?**
504
+ - Wait 2-3 minutes
505
+ - Check status again
506
+ - Generation may have failed
507
+ """)
508
+
509
+ gr.Markdown("---")
510
+ gr.Markdown(
511
+ """
512
+ <div style="text-align: center; padding: 20px;">
513
+ <p>Powered by <a href="https://suno.ai" target="_blank">Suno AI</a> β€’
514
+ <a href="https://sunoapi.org" target="_blank">Suno API Docs</a></p>
515
+ <p><small>Create custom songs by providing lyrics and music style</small></p>
516
+ </div>
517
+ """,
518
+ elem_id="footer"
519
+ )
520
+
521
+ # Event handlers for Generate Song tab
522
+ def clear_all():
523
+ return "", "Pop", "Generated Song", False, "V4_5ALL", "### Ready to generate!\n\nEnter lyrics and settings, then click 'Generate Song'"
524
+
525
+ clear_btn.click(
526
+ clear_all,
527
+ outputs=[lyrics_text, style, title, instrumental, model, output]
528
+ )
529
+
530
+ generate_btn.click(
531
+ generate_song_from_text,
532
+ inputs=[lyrics_text, style, title, instrumental, model],
533
+ outputs=output
534
+ )
535
+
536
+ # Event handlers for Check Any Task tab
537
+ def clear_check():
538
+ return "", "### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results."
539
+
540
+ check_clear_btn.click(
541
+ clear_check,
542
+ outputs=[check_task_id, check_output]
543
+ )
544
+
545
+ check_btn.click(
546
+ get_task_info,
547
+ inputs=[check_task_id],
548
+ outputs=check_output
549
+ )
550
+
551
+ # Function to handle URL parameter on load
552
+ def on_page_load(request: gr.Request):
553
+ """Handle URL parameters when page loads"""
554
+ task_id = parse_url_params(request)
555
+
556
+ if task_id:
557
+ # We have a task ID from URL, return it and fetch results
558
+ task_result = get_task_info(task_id)
559
+ return (
560
+ task_id, # For check_task_id
561
+ task_result, # For check_output
562
+ gr.Tabs(selected="check_tab"), # Switch to check tab
563
+ True # Mark as loaded
564
+ )
565
+ else:
566
+ # No task ID in URL, stay on first tab
567
+ return (
568
+ "", # Empty check_task_id
569
+ "### Enter a Task ID above\n\nPaste any Suno Task ID to check its current status and results.", # Default message
570
+ gr.Tabs(selected="generate_tab"), # Stay on generate tab
571
+ True # Mark as loaded
572
+ )
573
+
574
+ # Load URL parameters when the app starts
575
+ app.load(
576
+ fn=on_page_load,
577
+ inputs=[],
578
+ outputs=[check_task_id, check_output, gr.Tabs(), initial_load_done],
579
+ queue=False
580
+ )
581
+
582
+ # Launch the app
583
+ if __name__ == "__main__":
584
+ print("πŸš€ Starting Suno Song Generator")
585
+ print(f"πŸ”‘ SunoKey: {'βœ… Set' if SUNO_KEY else '❌ Not set'}")
586
+ print("🌐 Open your browser to: http://localhost:7860")
587
+ print("πŸ”— Use URL parameter: http://localhost:7860?taskid=YOUR_TASK_ID")
588
+
589
  app.launch(server_name="0.0.0.0", server_port=7860, share=False)