teszenofficial commited on
Commit
5b091d7
·
verified ·
1 Parent(s): 474d6c7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +197 -288
app.py CHANGED
@@ -1,326 +1,235 @@
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(title="MONX AI")
8
 
9
  UPLOAD_DIR = "uploads"
10
  OUTPUT_DIR = "outputs"
11
- CROSSFADE_MS = 20_000 # 20 segundos
12
 
13
  os.makedirs(UPLOAD_DIR, exist_ok=True)
14
  os.makedirs(OUTPUT_DIR, exist_ok=True)
15
 
16
- # ======================
17
- # AUDIO ENGINE (Lógica Intacta)
18
- # ======================
19
-
20
- def smart_crossfade(track_a, track_b):
21
- return track_a.append(track_b, crossfade=CROSSFADE_MS)
22
-
23
- def build_mix(paths):
24
- current = AudioSegment.from_file(paths[0])
25
-
26
- for p in paths[1:]:
27
- nxt = AudioSegment.from_file(p)
28
- current = smart_crossfade(current, nxt)
29
-
30
- name = f"{uuid.uuid4().hex}.wav"
31
- path = os.path.join(OUTPUT_DIR, name)
32
- current.export(path, format="wav")
33
- return name
34
-
35
- # ======================
36
- # WEB UI (Mejorada)
37
- # ======================
38
-
 
 
 
 
 
 
 
 
 
 
39
  @app.get("/", response_class=HTMLResponse)
40
  def home():
41
  return """
42
  <!DOCTYPE html>
43
  <html lang="es">
44
  <head>
45
- <meta charset="UTF-8">
46
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
47
- <title>MONX AI Studio</title>
48
- <!-- Tailwind CSS -->
49
- <script src="https://cdn.tailwindcss.com"></script>
50
- <!-- FontAwesome -->
51
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
52
- <!-- Google Fonts -->
53
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;500;700&display=swap" rel="stylesheet">
54
-
55
- <style>
56
- body {
57
- font-family: 'Inter', sans-serif;
58
- background-color: #0f172a;
59
- background-image:
60
- radial-gradient(at 0% 0%, hsla(253,16%,7%,1) 0, transparent 50%),
61
- radial-gradient(at 50% 0%, hsla(225,39%,30%,1) 0, transparent 50%),
62
- radial-gradient(at 100% 0%, hsla(339,49%,30%,1) 0, transparent 50%);
63
- height: 100vh;
64
- overflow: hidden;
65
- }
66
-
67
- /* Glassmorphism Card */
68
- .glass-panel {
69
- background: rgba(255, 255, 255, 0.05);
70
- backdrop-filter: blur(16px);
71
- -webkit-backdrop-filter: blur(16px);
72
- border: 1px solid rgba(255, 255, 255, 0.1);
73
- }
74
-
75
- /* Audio Visualizer Animation */
76
- .bar {
77
- width: 6px;
78
- background: linear-gradient(to top, #3b82f6, #8b5cf6);
79
- border-radius: 999px;
80
- animation: bounce 1s infinite ease-in-out;
81
- }
82
- .bar:nth-child(1) { height: 20px; animation-delay: 0.1s; }
83
- .bar:nth-child(2) { height: 35px; animation-delay: 0.2s; }
84
- .bar:nth-child(3) { height: 50px; animation-delay: 0.3s; }
85
- .bar:nth-child(4) { height: 30px; animation-delay: 0.4s; }
86
- .bar:nth-child(5) { height: 45px; animation-delay: 0.2s; }
87
-
88
- @keyframes bounce {
89
- 0%, 100% { transform: scaleY(1); }
90
- 50% { transform: scaleY(1.5); }
91
- }
92
-
93
- /* Custom Scrollbar */
94
- ::-webkit-scrollbar { width: 8px; }
95
- ::-webkit-scrollbar-track { background: transparent; }
96
- ::-webkit-scrollbar-thumb { background: #4b5563; border-radius: 4px; }
97
-
98
- /* Audio Player Styling */
99
- audio::-webkit-media-controls-panel {
100
- background-color: #e2e8f0;
101
- }
102
- </style>
 
 
 
 
 
 
103
  </head>
104
- <body class="flex items-center justify-center text-white">
105
-
106
- <div class="glass-panel w-full max-w-lg p-8 rounded-3xl shadow-2xl relative overflow-hidden m-4 transition-all duration-300 transform hover:scale-[1.01]">
107
-
108
- <!-- Header -->
109
- <div class="text-center mb-8 relative z-10">
110
- <div class="inline-flex items-center justify-center w-16 h-16 rounded-full bg-gradient-to-tr from-blue-500 to-purple-600 mb-4 shadow-lg shadow-purple-500/30">
111
- <i class="fa-solid fa-music text-2xl animate-pulse"></i>
112
- </div>
113
- <h1 class="text-4xl font-bold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-blue-400 to-purple-400">
114
- MONX AI
115
- </h1>
116
- <p class="text-gray-400 mt-2 text-sm font-light">Fusión de audio inteligente con crossfade</p>
117
- </div>
118
-
119
- <!-- Main Content -->
120
- <div class="space-y-6 relative z-10">
121
-
122
- <!-- Upload Area -->
123
- <div id="drop-zone" class="border-2 border-dashed border-gray-600 rounded-xl p-8 text-center hover:border-blue-400 hover:bg-white/5 transition-all cursor-pointer group">
124
- <input type="file" id="files" multiple accept=".mp3,.wav,.flac,.m4a" class="hidden">
125
- <div class="pointer-events-none">
126
- <i class="fa-solid fa-cloud-arrow-up text-4xl text-gray-500 mb-3 group-hover:text-blue-400 transition-colors"></i>
127
- <p class="text-sm text-gray-300">Arrastra tus archivos aquí o <span class="text-blue-400 font-semibold">haz clic</span></p>
128
- <p class="text-xs text-gray-500 mt-2">Sube de 2 a 4 canciones (MP3, WAV, FLAC)</p>
129
- </div>
130
- </div>
131
-
132
- <!-- File List (Dynamic) -->
133
- <div id="file-list" class="hidden space-y-2 max-h-32 overflow-y-auto">
134
- <!-- Items injected by JS -->
135
- </div>
136
-
137
- <!-- Generate Button -->
138
- <button onclick="send()" id="generate-btn" class="w-full py-4 rounded-xl bg-gradient-to-r from-blue-600 to-purple-600 font-bold text-lg shadow-lg shadow-blue-600/20 hover:shadow-blue-600/40 hover:from-blue-500 hover:to-purple-500 transition-all transform active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed">
139
- <i class="fa-solid fa-wand-magic-sparkles mr-2"></i> Crear Mix
140
- </button>
141
-
142
- <!-- Loading State -->
143
- <div id="loading" class="hidden text-center py-4">
144
- <div class="flex justify-center items-end space-x-2 h-12 mb-3">
145
- <div class="bar"></div><div class="bar"></div><div class="bar"></div><div class="bar"></div><div class="bar"></div>
146
- </div>
147
- <p class="text-blue-300 text-sm animate-pulse">Procesando audio de alta fidelidad...</p>
148
- </div>
149
-
150
- <!-- Error Message -->
151
- <div id="error-msg" class="hidden p-4 bg-red-500/20 border border-red-500/50 rounded-lg text-red-200 text-sm text-center"></div>
152
-
153
- <!-- Result Player -->
154
- <div id="result-area" class="hidden animate-fade-in-up">
155
- <div class="bg-white/10 p-4 rounded-xl border border-white/10">
156
- <div class="flex items-center justify-between mb-2">
157
- <span class="text-xs font-bold text-green-400 uppercase tracking-wider">Mix Generado</span>
158
- <a id="download-link" href="#" class="text-xs text-gray-300 hover:text-white"><i class="fa-solid fa-download"></i> Descargar</a>
159
- </div>
160
- <audio id="player" controls class="w-full h-10 rounded-lg opacity-90 hover:opacity-100 transition-opacity"></audio>
161
- </div>
162
- </div>
163
- </div>
164
-
165
- <!-- Decorative Blurs -->
166
- <div class="absolute top-0 left-0 w-32 h-32 bg-blue-500 rounded-full mix-blend-multiply filter blur-3xl opacity-20 -translate-x-10 -translate-y-10"></div>
167
- <div class="absolute bottom-0 right-0 w-32 h-32 bg-purple-500 rounded-full mix-blend-multiply filter blur-3xl opacity-20 translate-x-10 translate-y-10"></div>
168
- </div>
169
-
170
- <script>
171
- const fileInput = document.getElementById("files");
172
- const dropZone = document.getElementById("drop-zone");
173
- const fileList = document.getElementById("file-list");
174
- const btn = document.getElementById("generate-btn");
175
- const loading = document.getElementById("loading");
176
- const errorMsg = document.getElementById("error-msg");
177
- const resultArea = document.getElementById("result-area");
178
- const player = document.getElementById("player");
179
- const downloadLink = document.getElementById("download-link");
180
-
181
- // Drag & Drop Handling
182
- dropZone.addEventListener("click", () => fileInput.click());
183
- dropZone.addEventListener("dragover", (e) => {
184
- e.preventDefault();
185
- dropZone.classList.add("border-blue-400", "bg-white/10");
186
- });
187
- dropZone.addEventListener("dragleave", () => {
188
- dropZone.classList.remove("border-blue-400", "bg-white/10");
189
- });
190
- dropZone.addEventListener("drop", (e) => {
191
- e.preventDefault();
192
- dropZone.classList.remove("border-blue-400", "bg-white/10");
193
- fileInput.files = e.dataTransfer.files;
194
- updateFileList();
195
- });
196
- fileInput.addEventListener("change", updateFileList);
197
-
198
- function updateFileList() {
199
- fileList.innerHTML = "";
200
- const files = fileInput.files;
201
-
202
- if (files.length > 0) {
203
- fileList.classList.remove("hidden");
204
- Array.from(files).forEach((file, index) => {
205
- const div = document.createElement("div");
206
- div.className = "flex items-center bg-black/30 p-2 rounded border border-white/5 text-sm animate-[fadeIn_0.3s_ease-out]";
207
- div.innerHTML = `
208
- <div class="w-6 h-6 rounded-full bg-gradient-to-br from-blue-500 to-purple-600 flex items-center justify-center text-xs mr-3 font-bold">${index + 1}</div>
209
- <span class="truncate flex-1 text-gray-300">${file.name}</span>
210
- <span class="text-xs text-gray-500 ml-2">${(file.size / 1024 / 1024).toFixed(1)} MB</span>
211
- `;
212
- fileList.appendChild(div);
213
- });
214
- } else {
215
- fileList.classList.add("hidden");
216
- }
217
- }
218
-
219
- async function send() {
220
- const files = fileInput.files;
221
-
222
- // Reset UI
223
- errorMsg.classList.add("hidden");
224
- resultArea.classList.add("hidden");
225
-
226
- // Validate
227
- if (files.length < 2 || files.length > 4) {
228
- showError("⚠️ Por favor sube entre 2 y 4 canciones.");
229
- return;
230
- }
231
-
232
- // Prepare Data
233
- let fd = new FormData();
234
- for (let f of files) { fd.append("files", f); }
235
-
236
- // Loading State
237
- btn.disabled = true;
238
- btn.classList.add("opacity-50", "cursor-not-allowed");
239
- btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Subiendo...';
240
- loading.classList.remove("hidden");
241
-
242
- try {
243
- const r = await fetch("/upload-mix", { method: "POST", body: fd });
244
- const j = await r.json();
245
-
246
- if (!r.ok || j.error) {
247
- throw new Error(j.error || "Error en el servidor");
248
- }
249
-
250
- // Success
251
- const audioUrl = "/download?file=" + j.file;
252
- player.src = audioUrl;
253
- downloadLink.href = audioUrl;
254
- downloadLink.download = "MONX_Mix.wav";
255
-
256
- player.load();
257
-
258
- // Show Result
259
- loading.classList.add("hidden");
260
- resultArea.classList.remove("hidden");
261
-
262
- } catch (err) {
263
- loading.classList.add("hidden");
264
- showError("❌ " + err.message);
265
- } finally {
266
- btn.disabled = false;
267
- btn.classList.remove("opacity-50", "cursor-not-allowed");
268
- btn.innerHTML = '<i class="fa-solid fa-wand-magic-sparkles mr-2"></i> Crear Mix';
269
- }
270
- }
271
-
272
- function showError(msg) {
273
- errorMsg.innerText = msg;
274
- errorMsg.classList.remove("hidden");
275
- }
276
- </script>
277
  </body>
278
  </html>
279
  """
280
 
281
- # ======================
282
- # API (Lógica Intacta)
283
- # ======================
284
-
285
- @app.post("/upload-mix")
286
- async def upload_and_mix(files=File(...)):
287
  if len(files) < 2 or len(files) > 4:
288
- return JSONResponse({"error": "Sube entre 2 y 4 canciones"}, status_code=400)
289
-
290
- paths = []
291
 
 
292
  for f in files:
293
- ext = f.filename.split(".")[-1].lower()
294
- if ext not in ["mp3", "wav", "flac", "m4a"]:
295
- return JSONResponse(
296
- {"error": "Formato no soportado"},
297
- status_code=400
298
- )
299
 
300
- name = f"{uuid.uuid4().hex}.{ext}"
301
- path = os.path.join(UPLOAD_DIR, name)
302
-
303
- with open(path, "wb") as out:
304
  out.write(await f.read())
305
-
306
  paths.append(path)
307
 
308
- out = build_mix(paths)
309
- return {"file": out}
 
 
 
 
 
 
 
 
 
 
 
 
310
 
311
  @app.get("/download")
312
- def download(file: str):
313
  return FileResponse(
314
- os.path.join(OUTPUT_DIR, file),
315
  media_type="audio/wav",
316
  filename="monx_ai_mix.wav"
317
  )
318
 
319
- # ======================
320
- # HF SPACE ENTRYPOINT
321
- # ======================
322
-
323
- if __name__ == "__main__":
324
  import uvicorn
325
- uvicorn.run(app, host="0.0.0.0", port=7860)
326
-
 
1
  from fastapi import FastAPI, UploadFile, File
2
  from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
3
  from pydub import AudioSegment
4
+ import os, uuid, threading, time
 
5
 
6
  app = FastAPI(title="MONX AI")
7
 
8
  UPLOAD_DIR = "uploads"
9
  OUTPUT_DIR = "outputs"
10
+ CROSSFADE_MS = 20_000
11
 
12
  os.makedirs(UPLOAD_DIR, exist_ok=True)
13
  os.makedirs(OUTPUT_DIR, exist_ok=True)
14
 
15
+ # --------------------
16
+ # Estado de tareas
17
+ # --------------------
18
+ tasks = {}
19
+
20
+ # --------------------
21
+ # Audio engine
22
+ # --------------------
23
+ def process_mix(task_id, paths):
24
+ try:
25
+ tasks[task_id]["progress"] = 10
26
+ current = AudioSegment.from_file(paths[0])
27
+
28
+ step = 80 // (len(paths) - 1)
29
+
30
+ for i, p in enumerate(paths[1:], start=1):
31
+ next_track = AudioSegment.from_file(p)
32
+ current = current.append(next_track, crossfade=CROSSFADE_MS)
33
+ tasks[task_id]["progress"] = 10 + step * i
34
+ time.sleep(0.5) # da tiempo a mostrar progreso
35
+
36
+ name = f"{uuid.uuid4().hex}.wav"
37
+ out_path = os.path.join(OUTPUT_DIR, name)
38
+ current.export(out_path, format="wav")
39
+
40
+ tasks[task_id]["progress"] = 100
41
+ tasks[task_id]["file"] = name
42
+ except Exception as e:
43
+ tasks[task_id]["error"] = str(e)
44
+
45
+ # --------------------
46
+ # UI
47
+ # --------------------
48
  @app.get("/", response_class=HTMLResponse)
49
  def home():
50
  return """
51
  <!DOCTYPE html>
52
  <html lang="es">
53
  <head>
54
+ <meta charset="UTF-8">
55
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
56
+ <title>MONX AI</title>
57
+ <link rel="stylesheet"
58
+ href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
59
+ <style>
60
+ body{
61
+ margin:0;
62
+ min-height:100vh;
63
+ background:linear-gradient(135deg,#0f0c29,#302b63,#24243e);
64
+ font-family:system-ui,Arial;
65
+ color:#fff;
66
+ display:flex;
67
+ justify-content:center;
68
+ align-items:center;
69
+ }
70
+ .card{
71
+ width:100%;
72
+ max-width:420px;
73
+ margin:16px;
74
+ background:rgba(0,0,0,.45);
75
+ border-radius:20px;
76
+ padding:24px;
77
+ text-align:center;
78
+ box-shadow:0 20px 40px rgba(0,0,0,.4);
79
+ }
80
+ h1{margin:0;font-size:28px}
81
+ p{opacity:.8;font-size:14px}
82
+ .upload{
83
+ margin-top:20px;
84
+ border:2px dashed #7fdbff;
85
+ border-radius:16px;
86
+ padding:22px;
87
+ cursor:pointer;
88
+ }
89
+ input{display:none}
90
+ button{
91
+ width:100%;
92
+ margin-top:18px;
93
+ padding:14px;
94
+ border:none;
95
+ border-radius:14px;
96
+ font-size:16px;
97
+ background:linear-gradient(135deg,#7fdbff,#9f7aea);
98
+ color:#000;
99
+ cursor:pointer;
100
+ }
101
+ .progress{
102
+ margin-top:18px;
103
+ height:10px;
104
+ background:#222;
105
+ border-radius:6px;
106
+ overflow:hidden;
107
+ display:none;
108
+ }
109
+ .progress-bar{
110
+ height:100%;
111
+ width:0%;
112
+ background:linear-gradient(90deg,#7fdbff,#9f7aea);
113
+ transition:width .3s;
114
+ }
115
+ audio{margin-top:18px;width:100%}
116
+ .status{margin-top:10px;font-size:14px}
117
+ </style>
118
  </head>
119
+
120
+ <body>
121
+ <div class="card">
122
+ <h1>🎵 MONX AI</h1>
123
+ <p>Fusión de audio inteligente con crossfade</p>
124
+
125
+ <label class="upload">
126
+ <i class="fa-solid fa-cloud-arrow-up fa-2x"></i><br><br>
127
+ Selecciona 2 a 4 canciones
128
+ <input id="files" type="file" multiple accept=".mp3,.wav,.flac,.m4a">
129
+ </label>
130
+
131
+ <button onclick="start()">✨ Crear Mix</button>
132
+
133
+ <div class="progress" id="progressBox">
134
+ <div class="progress-bar" id="bar"></div>
135
+ </div>
136
+
137
+ <div class="status" id="status"></div>
138
+ <audio id="player" controls></audio>
139
+ </div>
140
+
141
+ <script>
142
+ let taskId=null;
143
+
144
+ async function start(){
145
+ const files=document.getElementById("files").files;
146
+ const status=document.getElementById("status");
147
+
148
+ if(files.length<2||files.length>4){
149
+ status.innerText="⚠️ Sube entre 2 y 4 canciones";
150
+ return;
151
+ }
152
+
153
+ let fd=new FormData();
154
+ for(let f of files){fd.append("files",f)}
155
+
156
+ status.innerText="Subiendo archivos...";
157
+ document.getElementById("progressBox").style.display="block";
158
+
159
+ const r=await fetch("/upload",{method:"POST",body:fd});
160
+ const j=await r.json();
161
+
162
+ if(j.error){status.innerText="❌ "+j.error;return;}
163
+
164
+ taskId=j.task_id;
165
+ poll();
166
+ }
167
+
168
+ async function poll(){
169
+ const r=await fetch("/progress/"+taskId);
170
+ const j=await r.json();
171
+
172
+ document.getElementById("bar").style.width=j.progress+"%";
173
+ document.getElementById("status").innerText="Procesando: "+j.progress+"%";
174
+
175
+ if(j.progress<100){
176
+ setTimeout(poll,800);
177
+ }else{
178
+ document.getElementById("status").innerText="✅ Mix listo";
179
+ document.getElementById("player").src="/download?file="+j.file;
180
+ }
181
+ }
182
+ </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183
  </body>
184
  </html>
185
  """
186
 
187
+ # --------------------
188
+ # API
189
+ # --------------------
190
+ @app.post("/upload")
191
+ async def upload(files=File(...)):
 
192
  if len(files) < 2 or len(files) > 4:
193
+ return JSONResponse({"error": "Sube entre 2 y 4 canciones"}, 400)
 
 
194
 
195
+ paths=[]
196
  for f in files:
197
+ ext=f.filename.split(".")[-1].lower()
198
+ if ext not in ["mp3","wav","flac","m4a"]:
199
+ return JSONResponse({"error":"Formato no soportado"},400)
 
 
 
200
 
201
+ name=f"{uuid.uuid4().hex}.{ext}"
202
+ path=os.path.join(UPLOAD_DIR,name)
203
+ with open(path,"wb") as out:
 
204
  out.write(await f.read())
 
205
  paths.append(path)
206
 
207
+ task_id=uuid.uuid4().hex
208
+ tasks[task_id]={"progress":0}
209
+
210
+ threading.Thread(
211
+ target=process_mix,
212
+ args=(task_id,paths),
213
+ daemon=True
214
+ ).start()
215
+
216
+ return {"task_id":task_id}
217
+
218
+ @app.get("/progress/{task_id}")
219
+ def progress(task_id:str):
220
+ return tasks.get(task_id,{"progress":0})
221
 
222
  @app.get("/download")
223
+ def download(file:str):
224
  return FileResponse(
225
+ os.path.join(OUTPUT_DIR,file),
226
  media_type="audio/wav",
227
  filename="monx_ai_mix.wav"
228
  )
229
 
230
+ # --------------------
231
+ # HF entrypoint
232
+ # --------------------
233
+ if __name__=="__main__":
 
234
  import uvicorn
235
+ uvicorn.run(app,host="0.0.0.0",port=7860)