zenjoul80 commited on
Commit
41a8b3e
Β·
verified Β·
1 Parent(s): b8a61f8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +14 -21
app.py CHANGED
@@ -1,20 +1,20 @@
1
- import eventlet
2
- eventlet.monkey_patch() # This MUST be the first line
3
-
4
  import os, time, requests, threading, io
5
  from flask import Flask, render_template, request, session, send_from_directory, jsonify
6
  from flask_socketio import SocketIO, emit
7
 
 
 
 
 
8
  app = Flask(__name__)
9
- app.config['SECRET_KEY'] = 'suno_final_2026'
10
- # 'eventlet' is the key to fixing the "Invalid Session" error
11
- socketio = SocketIO(app, cors_allowed_origins="*", async_mode='eventlet')
12
 
13
  MUSIC_FOLDER = 'saved_music'
14
  if not os.path.exists(MUSIC_FOLDER):
15
  os.makedirs(MUSIC_FOLDER)
16
 
17
- # This dictionary remembers which browser tab belongs to which song task
18
  task_to_sid = {}
19
 
20
  @app.route('/')
@@ -33,12 +33,10 @@ def callback():
33
  filename = f"{task_id}.mp3"
34
  filepath = os.path.join(MUSIC_FOLDER, filename)
35
  try:
36
- # Download from Suno to your server
37
  r = requests.get(audio_url, timeout=30)
38
  with open(filepath, 'wb') as f:
39
  f.write(r.content)
40
 
41
- # Send the download link to the user
42
  if task_id in task_to_sid:
43
  socketio.emit('status', {
44
  'msg': '✨ Success! Music saved to server.',
@@ -46,7 +44,7 @@ def callback():
46
  'done': True
47
  }, room=task_to_sid[task_id])
48
  except Exception as e:
49
- print(f"Callback Download Error: {e}")
50
 
51
  return jsonify({"status": "ok"}), 200
52
 
@@ -57,37 +55,32 @@ def get_music(filename):
57
  @socketio.on('save_token')
58
  def save_token(data):
59
  session['api_token'] = data.get('token')
60
- emit('status', {'msg': 'πŸ”‘ Token Linked and Secured.'})
61
 
62
  @socketio.on('start_gen')
63
  def handle_gen(payload):
64
  token = session.get('api_token')
65
  if not token:
66
- emit('status', {'msg': '❌ Error: Please connect your token first.'})
67
  return
68
 
69
  headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
70
 
71
- # Fix the "Instrumental cannot be null" error
72
- if payload.get('instrumental') is None:
73
- payload['instrumental'] = False
74
-
75
- # Tell Suno where to send the finished song
76
  payload['callBackUrl'] = request.host_url + "callback"
77
 
78
  try:
79
  res = requests.post("https://api.sunoapi.org/api/v1/generate/upload-cover", json=payload, headers=headers)
80
  res_json = res.json()
81
 
82
- # Safe check to prevent NoneType error
83
  api_data = res_json.get('data')
84
  if api_data:
85
  task_id = api_data.get('taskId')
86
- # Link this song to the current browser session
87
  task_to_sid[task_id] = request.sid
88
- emit('status', {'msg': f'πŸš€ Task {task_id} started. Don\'t close this tab!'})
89
  else:
90
- msg = res_json.get('msg') or "Unknown API error"
91
  emit('status', {'msg': f'❌ Suno Error: {msg}'})
92
 
93
  except Exception as e:
 
 
 
 
1
  import os, time, requests, threading, io
2
  from flask import Flask, render_template, request, session, send_from_directory, jsonify
3
  from flask_socketio import SocketIO, emit
4
 
5
+ # We are switching to gevent for better stability in 2026
6
+ from gevent import monkey
7
+ monkey.patch_all()
8
+
9
  app = Flask(__name__)
10
+ app.config['SECRET_KEY'] = 'suno_modern_2026'
11
+ # Using gevent as the engine
12
+ socketio = SocketIO(app, cors_allowed_origins="*", async_mode='gevent')
13
 
14
  MUSIC_FOLDER = 'saved_music'
15
  if not os.path.exists(MUSIC_FOLDER):
16
  os.makedirs(MUSIC_FOLDER)
17
 
 
18
  task_to_sid = {}
19
 
20
  @app.route('/')
 
33
  filename = f"{task_id}.mp3"
34
  filepath = os.path.join(MUSIC_FOLDER, filename)
35
  try:
 
36
  r = requests.get(audio_url, timeout=30)
37
  with open(filepath, 'wb') as f:
38
  f.write(r.content)
39
 
 
40
  if task_id in task_to_sid:
41
  socketio.emit('status', {
42
  'msg': '✨ Success! Music saved to server.',
 
44
  'done': True
45
  }, room=task_to_sid[task_id])
46
  except Exception as e:
47
+ print(f"Download Error: {e}")
48
 
49
  return jsonify({"status": "ok"}), 200
50
 
 
55
  @socketio.on('save_token')
56
  def save_token(data):
57
  session['api_token'] = data.get('token')
58
+ emit('status', {'msg': 'πŸ”‘ Token Linked.'})
59
 
60
  @socketio.on('start_gen')
61
  def handle_gen(payload):
62
  token = session.get('api_token')
63
  if not token:
64
+ emit('status', {'msg': '❌ Error: Connect token first.'})
65
  return
66
 
67
  headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
68
 
69
+ # Fix potential nulls
70
+ payload['instrumental'] = bool(payload.get('instrumental'))
 
 
 
71
  payload['callBackUrl'] = request.host_url + "callback"
72
 
73
  try:
74
  res = requests.post("https://api.sunoapi.org/api/v1/generate/upload-cover", json=payload, headers=headers)
75
  res_json = res.json()
76
 
 
77
  api_data = res_json.get('data')
78
  if api_data:
79
  task_id = api_data.get('taskId')
 
80
  task_to_sid[task_id] = request.sid
81
+ emit('status', {'msg': f'πŸš€ Task {task_id} started...'})
82
  else:
83
+ msg = res_json.get('msg') or "API Error"
84
  emit('status', {'msg': f'❌ Suno Error: {msg}'})
85
 
86
  except Exception as e: