zenjoul80 commited on
Commit
bb1fff1
Β·
verified Β·
1 Parent(s): 914bb77

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -12
app.py CHANGED
@@ -3,25 +3,27 @@ from flask import Flask, render_template, request, session, send_from_directory,
3
  from flask_socketio import SocketIO, emit
4
 
5
  app = Flask(__name__)
6
- app.config['SECRET_KEY'] = 'server_direct_save_2026'
7
  socketio = SocketIO(app, cors_allowed_origins="*")
8
 
 
9
  MUSIC_FOLDER = 'saved_music'
10
  if not os.path.exists(MUSIC_FOLDER):
11
  os.makedirs(MUSIC_FOLDER)
12
 
 
13
  task_to_sid = {}
14
 
15
  @app.route('/')
16
  def index():
17
  return render_template('index.html')
18
 
 
19
  @app.route('/callback', methods=['POST'])
20
  def callback():
21
  data = request.json
22
- if not data: return jsonify({"status": "no data"}), 400
23
 
24
- # Extract taskId and audio_url carefully
25
  task_id = data.get('taskId') or data.get('task_id')
26
  audio_url = data.get('audio_url')
27
 
@@ -29,15 +31,24 @@ def callback():
29
  filename = f"{task_id}.mp3"
30
  filepath = os.path.join(MUSIC_FOLDER, filename)
31
  try:
 
32
  r = requests.get(audio_url)
33
  with open(filepath, 'wb') as f:
34
  f.write(r.content)
 
 
35
  if task_id in task_to_sid:
36
- socketio.emit('status', {'msg': 'βœ… Saved to Server!', 'file_name': filename, 'done': True}, room=task_to_sid[task_id])
 
 
 
 
37
  except Exception as e:
38
  print(f"Callback error: {e}")
39
- return jsonify({"status": "ok"}), 200
40
 
 
 
 
41
  @app.route('/get_music/<filename>')
42
  def get_music(filename):
43
  return send_from_directory(MUSIC_FOLDER, filename, as_attachment=True)
@@ -51,29 +62,35 @@ def save_token(data):
51
  def handle_gen(payload):
52
  token = session.get('api_token')
53
  if not token:
54
- emit('status', {'msg': '❌ Error: Set Token first.'})
55
  return
56
 
57
  headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
 
 
 
 
 
 
58
  payload['callBackUrl'] = request.host_url + "callback"
59
 
60
  try:
61
  res = requests.post("https://api.sunoapi.org/api/v1/generate/upload-cover", json=payload, headers=headers)
62
  res_json = res.json()
63
 
64
- # SAFETY CHECK: Verify 'data' exists before calling .get()
65
  api_data = res_json.get('data')
66
  if api_data:
67
  task_id = api_data.get('taskId')
68
  task_to_sid[task_id] = request.sid
69
- emit('status', {'msg': f'πŸš€ Task {task_id} started...'})
70
  else:
71
- # If 'data' is missing, show the actual error from Suno
72
- error_msg = res_json.get('msg') or "Unknown API Error"
73
  emit('status', {'msg': f'❌ Suno API says: {error_msg}'})
74
 
75
  except Exception as e:
76
- emit('status', {'msg': f'❌ Script Error: {str(e)}'})
77
 
78
  if __name__ == '__main__':
79
- socketio.run(app, host="0.0.0.0", port=5000)
 
 
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')
29
 
 
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)
 
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)))