MySafeCode commited on
Commit
b5797c5
·
verified ·
1 Parent(s): ef6b9af

Create app2.py

Browse files
Files changed (1) hide show
  1. app2.py +241 -0
app2.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import os
4
+ import time
5
+ import json
6
+ from bs4 import BeautifulSoup
7
+
8
+ # Suno API key
9
+ SUNO_KEY = os.environ.get("SunoKey", "")
10
+ if not SUNO_KEY:
11
+ print("⚠️ SunoKey not set!")
12
+
13
+ # Function to fetch statistics from 1hit.no/log.php
14
+ def fetch_statistics():
15
+ """Fetch statistics from 1hit.no/log.php"""
16
+ try:
17
+ # Fetch the log.php page
18
+ response = requests.get('https://1hit.no/log.php', timeout=10)
19
+ response.raise_for_status()
20
+
21
+ # Parse HTML
22
+ soup = BeautifulSoup(response.text, 'html.parser')
23
+
24
+ # Find all stat-number elements
25
+ stat_numbers = soup.find_all('span', class_='stat-number')
26
+
27
+ # Find all stat-label elements
28
+ stat_labels = soup.find_all('span', class_='stat-label')
29
+
30
+ # Take first 3 of each (or as many as available)
31
+ stats = []
32
+ for i in range(min(3, len(stat_numbers), len(stat_labels))):
33
+ number = stat_numbers[i].text.strip()
34
+ label = stat_labels[i].text.strip()
35
+ stats.append((number, label))
36
+
37
+ return stats
38
+
39
+ except Exception as e:
40
+ print(f"Error fetching statistics: {e}")
41
+ # Return default/fallback stats
42
+ return [
43
+ ("N/A", "Lyrics Files"),
44
+ ("N/A", "Total Lines"),
45
+ ("N/A", "Unique Words")
46
+ ]
47
+
48
+ def generate_lyrics(prompt):
49
+ """Final working lyrics generator"""
50
+ if not SUNO_KEY:
51
+ yield "❌ Error: SunoKey not configured in environment variables"
52
+ return
53
+
54
+ if not prompt.strip():
55
+ yield "❌ Error: Please enter a prompt"
56
+ return
57
+
58
+ # Submit task
59
+ try:
60
+ resp = requests.post(
61
+ "https://api.sunoapi.org/api/v1/lyrics",
62
+ json={
63
+ "prompt": prompt,
64
+ "callBackUrl": "https://1hit.no/txtcallback.php" # Required but not used
65
+ },
66
+ headers={
67
+ "Authorization": f"Bearer {SUNO_KEY}",
68
+ "Content-Type": "application/json"
69
+ },
70
+ timeout=30
71
+ )
72
+
73
+ if resp.status_code != 200:
74
+ yield f"❌ Submission failed: HTTP {resp.status_code}"
75
+ return
76
+
77
+ data = resp.json()
78
+ if data.get("code") != 200:
79
+ yield f"❌ API error: {data.get('msg', 'Unknown')}"
80
+ return
81
+
82
+ task_id = data["data"]["taskId"]
83
+ yield f"✅ **Submitted!**\nTask ID: `{task_id}`\n\n⏳ Waiting for lyrics...\n"
84
+
85
+ # Poll for results
86
+ for attempt in range(30): # 30 attempts * 5 seconds = 150 seconds max
87
+ time.sleep(5)
88
+
89
+ try:
90
+ check = requests.get(
91
+ "https://api.sunoapi.org/api/v1/lyrics/record-info",
92
+ headers={"Authorization": f"Bearer {SUNO_KEY}"},
93
+ params={"taskId": task_id},
94
+ timeout=30
95
+ )
96
+
97
+ if check.status_code == 200:
98
+ check_data = check.json()
99
+ status = check_data["data"].get("status", "PENDING")
100
+
101
+ if status == "SUCCESS":
102
+ # Success! Extract lyrics
103
+ response_data = check_data["data"].get("response", {})
104
+
105
+ if isinstance(response_data, str):
106
+ # Sometimes response is a JSON string
107
+ try:
108
+ response_data = json.loads(response_data.replace('null', 'None'))
109
+ except:
110
+ response_data = {"data": []}
111
+
112
+ lyrics_list = response_data.get("data", [])
113
+
114
+ if lyrics_list:
115
+ output = "🎵 **Lyrics Generated Successfully!**\n\n"
116
+
117
+ for i, lyric in enumerate(lyrics_list, 1):
118
+ title = lyric.get('title', f'Variant {i}')
119
+ text = lyric.get('text', 'No lyrics')
120
+
121
+ output += f"## Variant {i}: {title}\n"
122
+ output += "```\n"
123
+ output += text
124
+ output += "\n```\n"
125
+ output += "---\n\n"
126
+
127
+ output += f"⏱️ Generated in about {(attempt + 1) * 5} seconds"
128
+ yield output
129
+ else:
130
+ yield "✅ Completed but no lyrics found in response"
131
+ return
132
+
133
+ elif status == "FAILED":
134
+ error = check_data["data"].get("errorMessage", "Unknown error")
135
+ yield f"❌ Task failed: {error}"
136
+ return
137
+
138
+ else:
139
+ # PENDING or PROCESSING
140
+ yield (f"⏳ Status: {status}\n"
141
+ f"Attempt: {attempt + 1}/30\n"
142
+ f"Task ID: `{task_id}`\n\n"
143
+ f"Still processing... (Usually takes 30-90 seconds)")
144
+ else:
145
+ yield f"⚠️ Check error: HTTP {check.status_code}"
146
+
147
+ except Exception as e:
148
+ yield f"⚠️ Error checking status: {str(e)}"
149
+
150
+ yield "⏰ Timeout after 150 seconds. Try checking again later."
151
+
152
+ except Exception as e:
153
+ yield f"❌ Error: {str(e)}"
154
+
155
+ # Create the app
156
+ with gr.Blocks(title="Suno Lyrics Generator", theme="soft") as app:
157
+ # Fetch statistics
158
+ stats = fetch_statistics()
159
+
160
+ gr.Markdown("# 🎵 Suno Lyrics Generator")
161
+ gr.Markdown("Generate song lyrics using Suno AI")
162
+
163
+ # Statistics display at the top
164
+ gr.Markdown("## 📊 Live Statistics")
165
+
166
+ # Create a row for stats
167
+ with gr.Row():
168
+ for i, (number, label) in enumerate(stats):
169
+ with gr.Column():
170
+ gr.Markdown(f"""
171
+ <div style="
172
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
173
+ padding: 20px;
174
+ border-radius: 10px;
175
+ text-align: center;
176
+ color: white;
177
+ margin: 10px;
178
+ box-shadow: 0 4px 6px rgba(0,0,0,0.1);
179
+ ">
180
+ <div style="font-size: 2.5em; font-weight: bold; margin-bottom: 10px;">
181
+ {number}
182
+ </div>
183
+ <div style="font-size: 1.2em;">
184
+ {label}
185
+ </div>
186
+ </div>
187
+ """)
188
+
189
+ gr.Markdown("---")
190
+
191
+ gr.Markdown("All songs are logged and public on 1hit.no (from 27th December 2025) and Suno AI")
192
+ gr.Markdown("""<a href="https://1hit.no/log.php" target="_blank" style="color: #667eea; text-decoration: none; font-weight: bold;">📊 View Detailed Song Log</a>""")
193
+
194
+ with gr.Row():
195
+ with gr.Column(scale=1):
196
+ prompt = gr.Textbox(
197
+ label="Lyrics Prompt",
198
+ placeholder="Example: A happy song about sunshine and rainbows",
199
+ lines=3
200
+ )
201
+ btn = gr.Button("🎵 Generate Lyrics", variant="primary", scale=1)
202
+
203
+ gr.Markdown("""
204
+ **How it works:**
205
+ 1. Enter your lyrics idea
206
+ 2. Click Generate
207
+ 3. Wait 30-90 seconds
208
+ 4. Get 2 lyric variants
209
+
210
+ **Status messages:**
211
+ - ✅ Submitted = Task accepted
212
+ - ⏳ PENDING/PROCESSING = Generating
213
+ - 🎵 Success = Lyrics ready!
214
+ """)
215
+
216
+ with gr.Column(scale=2):
217
+ output = gr.Markdown(
218
+ label="Results",
219
+ value="Your generated lyrics will appear here..."
220
+ )
221
+
222
+ gr.Markdown("---")
223
+ gr.Markdown(
224
+ """
225
+ <div style="text-align: center; padding: 20px;">
226
+ <p>Powered by <a href="https://suno.com/invite/@espenvh" target="_blank">Suno AI</a> •
227
+ <a href="https://sunoapi.org" target="_blank">Suno API Docs</a> •
228
+ <a href="https://github.com" target="_blank">GitHub</a></p>
229
+ <p><small>This app uses the Suno API to generate AI-powered lyrics.</small></p>
230
+ </div>
231
+ """,
232
+ elem_id="footer"
233
+ )
234
+
235
+ btn.click(generate_lyrics, prompt, output)
236
+
237
+ if __name__ == "__main__":
238
+ print("🚀 Starting Suno Lyrics Generator")
239
+ print(f"🔑 SunoKey: {'✅ Set' if SUNO_KEY else '❌ Not set'}")
240
+ print("📊 Fetching statistics from 1hit.no/log.php...")
241
+ app.launch(server_name="0.0.0.0", server_port=7860, share=False)