teszenofficial commited on
Commit
f104d0e
·
verified ·
1 Parent(s): fa5f9ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +213 -126
app.py CHANGED
@@ -1,127 +1,214 @@
1
- # =====================================================
2
- # Segue AI — Apple Music style (HF SAFE)
3
- # =====================================================
4
-
5
- import librosa
6
- import numpy as np
7
- import soundfile as sf
8
- import gradio as gr
9
- import time
10
-
11
- SR = 22050
12
- MIX_TIME = 20 # segundos TOTALES
13
-
14
- # =====================================================
15
- # UTILS
16
- # =====================================================
 
 
 
17
  def load_audio(path):
18
- y, _ = librosa.load(path, sr=SR, mono=True)
19
- return y
20
-
21
- def safe_bpm(y):
22
- try:
23
- bpm, _ = librosa.beat.beat_track(y=y, sr=SR)
24
- if bpm <= 0 or np.isnan(bpm):
25
- return 120.0
26
- return float(bpm)
27
- except:
28
- return 120.0
29
-
30
- def safe_stretch(y, rate):
31
- rate = float(np.clip(rate, 0.85, 1.15))
32
- if len(y) < SR: # audio demasiado corto
33
- return y
34
- return librosa.effects.time_stretch(y, rate)
35
-
36
- # =====================================================
37
- # CORE MIX (ERROR-PROOF)
38
- # =====================================================
39
- def apple_style_mix(a, b):
40
- bpm_a = safe_bpm(a)
41
- bpm_b = safe_bpm(b)
42
-
43
- mix_len = MIX_TIME * SR
44
-
45
- # puntos exactos
46
- sa = max(0, len(a) - mix_len)
47
-
48
- # si B es muy corta
49
- if len(b) < mix_len:
50
- mix_len = len(b)
51
-
52
- # segmentos
53
- a_mix = a[sa:sa + mix_len]
54
- b_intro = b[:mix_len]
55
- b_rest = b[mix_len:]
56
-
57
- # sincronizar BPM SOLO en intro
58
- rate = bpm_a / bpm_b
59
- b_intro_sync = safe_stretch(b_intro, rate)
60
-
61
- # ⚠️ CLAVE: igualar longitudes SÍ o SÍ
62
- min_len = min(len(a_mix), len(b_intro_sync))
63
- a_mix = a_mix[:min_len]
64
- b_mix = b_intro_sync[:min_len]
65
-
66
- # curvas Apple-style
67
- t = np.linspace(0, 1, min_len)
68
- vol_a = np.cos(t * np.pi / 2)
69
- vol_b = np.sin(t * np.pi / 2)
70
-
71
- mix = a_mix * vol_a + b_mix * vol_b
72
-
73
- return np.concatenate([
74
- a[:sa],
75
- mix,
76
- b_rest
77
- ])
78
-
79
- # =====================================================
80
- # PIPELINE HF
81
- # =====================================================
82
- def automix(file1, file2, progress=gr.Progress()):
83
- try:
84
- progress(0.1, desc="Loading tracks…")
85
- a = load_audio(file1)
86
- b = load_audio(file2)
87
-
88
- progress(0.6, desc="Mixing seamlessly…")
89
- output = apple_style_mix(a, b)
90
-
91
- progress(0.9, desc="Finalizing…")
92
- out = "segue_ai_mix.wav"
93
- sf.write(out, output, SR)
94
- time.sleep(0.3)
95
-
96
- return out
97
-
98
- except Exception as e:
99
- # fallback ultra seguro (HF nunca debe romper)
100
- out = "segue_ai_fallback.wav"
101
- min_len = min(len(a), len(b))
102
- sf.write(out, a[:min_len] * 0.7 + b[:min_len] * 0.3, SR)
103
- return out
104
-
105
- # =====================================================
106
- # UI
107
- # =====================================================
108
- with gr.Blocks() as demo:
109
- gr.Markdown("""
110
- # 🎧 Segue AI
111
- **Apple Music–style Automix**
112
-
113
- • Total mix duration: **20 seconds**
114
- • Starts 20s before Track A ends
115
- • Ends at 20s into Track B
116
- """)
117
-
118
- with gr.Row():
119
- song1 = gr.Audio(type="filepath", label="Track A")
120
- song2 = gr.Audio(type="filepath", label="Track B")
121
-
122
- output = gr.Audio(label="Generated Mix")
123
-
124
- btn = gr.Button("Generate Segue")
125
- btn.click(automix, [song1, song2], output)
126
-
127
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File
2
+ from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
3
+ from pydub import AudioSegment
4
+ import os
5
+ import uuid
6
+
7
+ app = FastAPI()
8
+
9
+ UPLOAD_DIR = "uploads"
10
+ OUTPUT_DIR = "outputs"
11
+ CROSSFADE_MS = 20_000 # 20 segundos reales
12
+
13
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
14
+ os.makedirs(OUTPUT_DIR, exist_ok=True)
15
+
16
+ # ---------------------------
17
+ # Audio logic
18
+ # ---------------------------
19
+
20
  def load_audio(path):
21
+ return AudioSegment.from_file(path)
22
+
23
+ def smart_crossfade(track_a, track_b):
24
+ return track_a.append(track_b, crossfade=CROSSFADE_MS)
25
+
26
+ def build_playlist(track_paths):
27
+ current = load_audio(track_paths[0])
28
+
29
+ for next_path in track_paths[1:]:
30
+ next_track = load_audio(next_path)
31
+ current = smart_crossfade(current, next_track)
32
+
33
+ output_name = f"{uuid.uuid4().hex}.wav"
34
+ output_path = os.path.join(OUTPUT_DIR, output_name)
35
+ current.export(output_path, format="wav")
36
+ return output_name
37
+
38
+ # ---------------------------
39
+ # Web UI
40
+ # ---------------------------
41
+
42
+ @app.get("/", response_class=HTMLResponse)
43
+ def index():
44
+ return """
45
+ <!DOCTYPE html>
46
+ <html lang="es">
47
+ <head>
48
+ <meta charset="UTF-8">
49
+ <title>Lunna Mix AI</title>
50
+
51
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
52
+
53
+ <style>
54
+ body {
55
+ background: linear-gradient(135deg, #0f2027, #203a43, #2c5364);
56
+ font-family: Arial, sans-serif;
57
+ color: #fff;
58
+ margin: 0;
59
+ padding: 0;
60
+ }
61
+
62
+ .container {
63
+ max-width: 500px;
64
+ margin: 60px auto;
65
+ background: rgba(0,0,0,0.35);
66
+ border-radius: 16px;
67
+ padding: 30px;
68
+ text-align: center;
69
+ }
70
+
71
+ h1 {
72
+ margin-bottom: 10px;
73
+ }
74
+
75
+ p {
76
+ opacity: 0.8;
77
+ font-size: 14px;
78
+ }
79
+
80
+ .upload-box {
81
+ border: 2px dashed #6dd5fa;
82
+ border-radius: 12px;
83
+ padding: 20px;
84
+ margin-top: 20px;
85
+ cursor: pointer;
86
+ }
87
+
88
+ .upload-box:hover {
89
+ background: rgba(255,255,255,0.05);
90
+ }
91
+
92
+ input[type=file] {
93
+ display: none;
94
+ }
95
+
96
+ button {
97
+ margin-top: 20px;
98
+ background: #6dd5fa;
99
+ color: #000;
100
+ border: none;
101
+ padding: 12px 20px;
102
+ border-radius: 10px;
103
+ font-size: 16px;
104
+ cursor: pointer;
105
+ }
106
+
107
+ button:hover {
108
+ background: #9ce5ff;
109
+ }
110
+
111
+ .status {
112
+ margin-top: 15px;
113
+ font-size: 14px;
114
+ }
115
+
116
+ audio {
117
+ margin-top: 20px;
118
+ width: 100%;
119
+ }
120
+ </style>
121
+ </head>
122
+
123
+ <body>
124
+ <div class="container">
125
+ <h1><i class="fa-solid fa-moon"></i> MONX AI</h1>
126
+ <p>Sube 2 a 4 canciones y Lunna hará un mix con crossfade inteligente ✨</p>
127
+
128
+ <label class="upload-box">
129
+ <i class="fa-solid fa-cloud-arrow-up fa-2x"></i><br><br>
130
+ Selecciona tus canciones
131
+ <input type="file" id="files" multiple accept=".mp3,.wav">
132
+ </label>
133
+
134
+ <button onclick="upload()">Crear Mix</button>
135
+
136
+ <div class="status" id="status"></div>
137
+ <audio id="player" controls></audio>
138
+ </div>
139
+
140
+ <script>
141
+ async function upload() {
142
+ const files = document.getElementById("files").files;
143
+ const status = document.getElementById("status");
144
+ const player = document.getElementById("player");
145
+
146
+ if (files.length < 2 || files.length > 4) {
147
+ status.innerText = "⚠️ Sube entre 2 y 4 canciones";
148
+ return;
149
+ }
150
+
151
+ const formData = new FormData();
152
+ for (let f of files) {
153
+ formData.append("files", f);
154
+ }
155
+
156
+ status.innerText = "⏳ Creando mix inteligente...";
157
+
158
+ const res = await fetch("/upload-mix", {
159
+ method: "POST",
160
+ body: formData
161
+ });
162
+
163
+ const data = await res.json();
164
+
165
+ if (data.error) {
166
+ status.innerText = "❌ " + data.error;
167
+ return;
168
+ }
169
+
170
+ status.innerText = "✅ Mix listo";
171
+ player.src = "/download?file=" + data.file;
172
+ player.load();
173
+ }
174
+ </script>
175
+
176
+ </body>
177
+ </html>
178
+ """
179
+
180
+ # ---------------------------
181
+ # API
182
+ # ---------------------------
183
+
184
+ @app.post("/upload-mix")
185
+ async def upload_and_mix(files: list[UploadFile] = File(...)):
186
+ if len(files) < 2 or len(files) > 4:
187
+ return JSONResponse({"error": "Sube entre 2 y 4 canciones"}, status_code=400)
188
+
189
+ paths = []
190
+
191
+ for file in files:
192
+ ext = file.filename.split(".")[-1].lower()
193
+ if ext not in ["mp3", "wav"]:
194
+ return JSONResponse({"error": "Formato no soportado"}, status_code=400)
195
+
196
+ filename = f"{uuid.uuid4().hex}.{ext}"
197
+ path = os.path.join(UPLOAD_DIR, filename)
198
+
199
+ with open(path, "wb") as f:
200
+ f.write(await file.read())
201
+
202
+ paths.append(path)
203
+
204
+ output_name = build_playlist(paths)
205
+
206
+ return {
207
+ "message": "Mix generado",
208
+ "file": output_name
209
+ }
210
+
211
+ @app.get("/download")
212
+ def download(file: str):
213
+ path = os.path.join(OUTPUT_DIR, file)
214
+ return FileResponse(path, media_type="audio/wav", filename="Monx_mix.wav")