File size: 2,944 Bytes
b3ae416
 
18fba22
 
 
78ce901
52fbd36
 
 
1e057f2
b3ae416
52fbd36
dcec006
78ce901
dcec006
78ce901
 
52fbd36
 
 
 
 
ad31a8a
7607a06
ad31a8a
b3ae416
914bb77
7607a06
ad31a8a
 
78ce901
b3ae416
78ce901
e58f1ac
78ce901
 
bb1fff1
78ce901
bb1fff1
1e057f2
b3ae416
bb1fff1
 
78ce901
41a8b3e
78ce901
e58f1ac
bb1fff1
ff963d3
 
 
ad31a8a
52fbd36
7607a06
78ce901
41a8b3e
52fbd36
 
 
 
914bb77
dcec006
914bb77
 
803188d
1e057f2
 
 
ff963d3
 
78ce901
52fbd36
78ce901
914bb77
 
 
 
 
41a8b3e
914bb77
dcec006
52fbd36
e58f1ac
52fbd36
 
ff963d3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
import eventlet
eventlet.monkey_patch()

import os
import requests
from flask import Flask, render_template, request, session, send_from_directory, jsonify
from flask_socketio import SocketIO, emit

app = Flask(__name__)
app.config['SECRET_KEY'] = 'docker_suno_final_v2'
socketio = SocketIO(app, cors_allowed_origins="*", async_mode='eventlet')

MUSIC_FOLDER = os.path.join(os.getcwd(), 'saved_music')
if not os.path.exists(MUSIC_FOLDER):
    os.makedirs(MUSIC_FOLDER, exist_ok=True)

task_to_sid = {}

@app.route('/')
def index():
    return render_template('index.html')

@app.route('/callback', methods=['POST'])
def callback():
    data = request.json
    if not data: return jsonify({"status": "no_data"}), 400
    
    task_id = data.get('taskId') or data.get('task_id')
    audio_url = data.get('audio_url')

    if audio_url and task_id:
        filepath = os.path.join(MUSIC_FOLDER, f"{task_id}.mp3")
        try:
            r = requests.get(audio_url, timeout=30)
            with open(filepath, 'wb') as f:
                f.write(r.content)
            
            if task_id in task_to_sid:
                socketio.emit('status', {
                    'msg': 'βœ… Saved to Server!',
                    'file_name': f"{task_id}.mp3",
                    'done': True
                }, room=task_to_sid[task_id])
        except Exception as e:
            print(f"Download Error: {e}")

    return jsonify({"status": "ok"}), 200

@app.route('/get_music/<filename>')
def get_music(filename):
    return send_from_directory(MUSIC_FOLDER, filename, as_attachment=True)

@socketio.on('save_token')
def save_token(data):
    session['api_token'] = data.get('token')
    emit('status', {'msg': 'πŸ”‘ Token Linked.'})

@socketio.on('start_gen')
def handle_gen(payload):
    token = session.get('api_token')
    if not token:
        emit('status', {'msg': '❌ Error: Link token first.'})
        return

    headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
    
    # DOCKER FIX: Use the 'origin' header if available to set callback
    # If on HF, request.host_url works, but we provide a fallback
    callback_base = request.host_url.replace("0.0.0.0", "direct-url-here") 
    payload['callBackUrl'] = "https://zenjoul80-suno-api.hf.space/" + "callback"
    
    try:
        res = requests.post("https://api.sunoapi.org/api/v1/generate/upload-cover", json=payload, headers=headers)
        res_json = res.json()
        api_data = res_json.get('data')
        if api_data:
            task_id = api_data.get('taskId')
            task_to_sid[task_id] = request.sid
            emit('status', {'msg': f'πŸš€ Task {task_id} started...'})
        else:
            emit('status', {'msg': f"❌ API Error: {res_json.get('msg')}"})
    except Exception as e:
        emit('status', {'msg': f'❌ Connection Error: {str(e)}'})

if __name__ == '__main__':
    socketio.run(app, host="0.0.0.0", port=7860)