zenjoul80 commited on
Commit
e58f1ac
Β·
verified Β·
1 Parent(s): f0da78e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -26
app.py CHANGED
@@ -1,28 +1,30 @@
1
- import time, requests, threading, os, io
 
 
 
2
  from flask import Flask, render_template, request, session, send_from_directory, jsonify
3
  from flask_socketio import SocketIO, emit
4
 
5
  app = Flask(__name__)
6
- app.config['SECRET_KEY'] = 'suno_server_direct_2026'
7
- socketio = SocketIO(app, cors_allowed_origins="*")
 
8
 
9
- # Create folder for persistent storage
10
  MUSIC_FOLDER = 'saved_music'
11
  if not os.path.exists(MUSIC_FOLDER):
12
  os.makedirs(MUSIC_FOLDER)
13
 
14
- # Map taskId to the specific user's SID
15
  task_to_sid = {}
16
 
17
  @app.route('/')
18
  def index():
19
  return render_template('index.html')
20
 
21
- # --- WEBHOOK CALLBACK ---
22
  @app.route('/callback', methods=['POST'])
23
  def callback():
24
  data = request.json
25
- if not data: return jsonify({"status": "no_data"}), 400
26
 
27
  task_id = data.get('taskId') or data.get('task_id')
28
  audio_url = data.get('audio_url')
@@ -31,24 +33,23 @@ def callback():
31
  filename = f"{task_id}.mp3"
32
  filepath = os.path.join(MUSIC_FOLDER, filename)
33
  try:
34
- # Download file from Suno to our server
35
- r = requests.get(audio_url)
36
  with open(filepath, 'wb') as f:
37
  f.write(r.content)
38
 
39
- # Notify the specific browser tab via SocketIO
40
  if task_id in task_to_sid:
41
  socketio.emit('status', {
42
- 'msg': 'βœ… Success! Saved to server storage.',
43
  'file_name': filename,
44
  'done': True
45
  }, room=task_to_sid[task_id])
46
  except Exception as e:
47
- print(f"Callback error: {e}")
48
 
49
- return jsonify({"status": "received"}), 200
50
 
51
- # --- SERVE SAVED FILES ---
52
  @app.route('/get_music/<filename>')
53
  def get_music(filename):
54
  return send_from_directory(MUSIC_FOLDER, filename, as_attachment=True)
@@ -56,41 +57,41 @@ def get_music(filename):
56
  @socketio.on('save_token')
57
  def save_token(data):
58
  session['api_token'] = data.get('token')
59
- emit('status', {'msg': 'πŸ”‘ Token Linked.'})
60
 
61
  @socketio.on('start_gen')
62
  def handle_gen(payload):
63
  token = session.get('api_token')
64
  if not token:
65
- emit('status', {'msg': '❌ Error: Please set API Token.'})
66
  return
67
 
68
  headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
69
 
70
- # SAFETY FIX 1: Ensure instrumental is never null
71
- if 'instrumental' not in payload or payload['instrumental'] is None:
72
  payload['instrumental'] = False
73
 
74
- # Set dynamic callback
75
  payload['callBackUrl'] = request.host_url + "callback"
76
 
77
  try:
78
  res = requests.post("https://api.sunoapi.org/api/v1/generate/upload-cover", json=payload, headers=headers)
79
  res_json = res.json()
80
 
81
- # SAFETY FIX 2: Check 'data' before getting taskId
82
  api_data = res_json.get('data')
83
  if api_data:
84
  task_id = api_data.get('taskId')
 
85
  task_to_sid[task_id] = request.sid
86
- emit('status', {'msg': f'πŸš€ Task {task_id} started. Waiting for server download...'})
87
  else:
88
- error_msg = res_json.get('msg') or "API rejected request"
89
- emit('status', {'msg': f'❌ Suno API says: {error_msg}'})
90
 
91
  except Exception as e:
92
- emit('status', {'msg': f'❌ System Error: {str(e)}'})
93
 
94
  if __name__ == '__main__':
95
- # Use port 7860 for Hugging Face or 5000 for local/server
96
- socketio.run(app, host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
 
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('/')
21
  def index():
22
  return render_template('index.html')
23
 
 
24
  @app.route('/callback', methods=['POST'])
25
  def callback():
26
  data = request.json
27
+ if not data: return jsonify({"status": "error"}), 400
28
 
29
  task_id = data.get('taskId') or data.get('task_id')
30
  audio_url = data.get('audio_url')
 
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.',
45
  'file_name': filename,
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
 
 
53
  @app.route('/get_music/<filename>')
54
  def get_music(filename):
55
  return send_from_directory(MUSIC_FOLDER, filename, as_attachment=True)
 
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:
94
+ emit('status', {'msg': f'❌ Connection Error: {str(e)}'})
95
 
96
  if __name__ == '__main__':
97
+ socketio.run(app, host="0.0.0.0")