Update app.py
Browse files
app.py
CHANGED
|
@@ -4,9 +4,9 @@ import numpy as np
|
|
| 4 |
from pydub import AudioSegment, effects
|
| 5 |
import uuid, os, json, time
|
| 6 |
|
| 7 |
-
# =============================
|
| 8 |
# DIRECTORIOS
|
| 9 |
-
# =============================
|
| 10 |
|
| 11 |
UPLOAD_DIR = "uploads"
|
| 12 |
OUTPUT_DIR = "outputs"
|
|
@@ -18,9 +18,9 @@ os.makedirs(DATA_DIR, exist_ok=True)
|
|
| 18 |
|
| 19 |
MODEL_PATH = os.path.join(DATA_DIR, "weights.json")
|
| 20 |
|
| 21 |
-
# =============================
|
| 22 |
-
# MODELO
|
| 23 |
-
# =============================
|
| 24 |
|
| 25 |
DEFAULT_WEIGHTS = {
|
| 26 |
"bpm": 0.35,
|
|
@@ -34,7 +34,7 @@ def load_weights():
|
|
| 34 |
try:
|
| 35 |
with open(MODEL_PATH, "r") as f:
|
| 36 |
return json.load(f)
|
| 37 |
-
except
|
| 38 |
pass
|
| 39 |
return DEFAULT_WEIGHTS.copy()
|
| 40 |
|
|
@@ -44,220 +44,136 @@ def save_weights(w):
|
|
| 44 |
|
| 45 |
weights = load_weights()
|
| 46 |
|
| 47 |
-
# =============================
|
| 48 |
-
# ANÁLISIS MUSICAL (ESTABLE
|
| 49 |
-
# =============================
|
| 50 |
|
| 51 |
def analyze_audio(path):
|
| 52 |
-
|
| 53 |
-
y, sr = librosa.load(path, mono=True)
|
| 54 |
-
|
| 55 |
-
# BPM APROXIMADO (sin beat_track → evita bug scipy)
|
| 56 |
-
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
|
| 57 |
-
tempo = float(librosa.beat.tempo(
|
| 58 |
-
onset_envelope=onset_env, sr=sr
|
| 59 |
-
)[0])
|
| 60 |
-
|
| 61 |
-
# Energía RMS normalizada
|
| 62 |
-
rms = librosa.feature.rms(y=y)[0]
|
| 63 |
-
rms = librosa.util.normalize(rms)
|
| 64 |
-
|
| 65 |
-
# Detección simple de drops (picos bruscos)
|
| 66 |
-
drops = []
|
| 67 |
-
for i in range(10, len(rms) - 10):
|
| 68 |
-
if rms[i] > np.mean(rms[i-10:i-1]) * 1.4:
|
| 69 |
-
drops.append(i)
|
| 70 |
-
|
| 71 |
-
return {
|
| 72 |
-
"tempo": tempo,
|
| 73 |
-
"energy": rms,
|
| 74 |
-
"drops": drops
|
| 75 |
-
}
|
| 76 |
-
|
| 77 |
-
except Exception:
|
| 78 |
-
# Fallback ultra seguro
|
| 79 |
-
return {
|
| 80 |
-
"tempo": 120.0,
|
| 81 |
-
"energy": np.ones(50),
|
| 82 |
-
"drops": []
|
| 83 |
-
}
|
| 84 |
-
|
| 85 |
-
# =========================================================
|
| 86 |
-
# MODELO DE DECISIÓN (IA REAL)
|
| 87 |
-
# =========================================================
|
| 88 |
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
-
|
| 94 |
-
energy_sim = max(0, energy_sim)
|
| 95 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
drop_penalty = 1 if t in a["drops"] else 0
|
| 97 |
|
| 98 |
-
|
| 99 |
weights["bpm"] * bpm_sim +
|
| 100 |
weights["energy"] * energy_sim +
|
| 101 |
weights["smooth"] * ((bpm_sim + energy_sim) / 2) -
|
| 102 |
weights["drop_penalty"] * drop_penalty
|
| 103 |
)
|
| 104 |
-
return score
|
| 105 |
|
| 106 |
-
# =============================
|
| 107 |
-
#
|
| 108 |
-
# =============================
|
| 109 |
|
| 110 |
def bpm_adjust(segment, from_bpm, to_bpm):
|
| 111 |
-
"""
|
| 112 |
-
Ajuste de BPM SOLO PARA TRANSICIÓN.
|
| 113 |
-
Permite cambio NOTABLE (±12%)
|
| 114 |
-
"""
|
| 115 |
-
if from_bpm <= 0 or to_bpm <= 0:
|
| 116 |
-
return segment
|
| 117 |
-
|
| 118 |
ratio = from_bpm / to_bpm
|
| 119 |
-
|
| 120 |
-
# Permitir empuje/freno claro
|
| 121 |
if abs(1 - ratio) > 0.12:
|
| 122 |
return segment
|
| 123 |
|
| 124 |
new_rate = int(segment.frame_rate * ratio)
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
overrides={"frame_rate": new_rate}
|
| 128 |
-
)
|
| 129 |
-
return adjusted.set_frame_rate(segment.frame_rate)
|
| 130 |
|
| 131 |
-
# =============================
|
| 132 |
-
#
|
| 133 |
-
# =============================
|
| 134 |
|
| 135 |
-
def auto_dj_mix(files, durations,
|
| 136 |
-
|
| 137 |
-
|
| 138 |
|
| 139 |
durs = [float(x.strip()) for x in durations.split(",")]
|
| 140 |
-
|
| 141 |
-
raise gr.Error("Debes indicar una duración por canción")
|
| 142 |
-
|
| 143 |
-
crossfade_ms = int(base_crossfade * 1000)
|
| 144 |
-
|
| 145 |
-
progress(0, desc="🎧 Analizando canciones…")
|
| 146 |
-
time.sleep(0.4)
|
| 147 |
|
| 148 |
-
tracks = []
|
| 149 |
-
analyses = []
|
| 150 |
|
| 151 |
-
for f in files:
|
| 152 |
-
|
| 153 |
-
|
| 154 |
|
|
|
|
| 155 |
with open(f.name, "rb") as src, open(path, "wb") as dst:
|
| 156 |
dst.write(src.read())
|
| 157 |
|
| 158 |
-
audio = AudioSegment.from_file(path)
|
| 159 |
-
audio = effects.normalize(audio)
|
| 160 |
-
|
| 161 |
tracks.append(audio)
|
| 162 |
analyses.append(analyze_audio(path))
|
| 163 |
|
| 164 |
mix = AudioSegment.silent(0)
|
| 165 |
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
for i, track in enumerate(tracks):
|
| 171 |
-
play_ms = min(int(durs[i] * 1000), len(track))
|
| 172 |
-
segment = track[:play_ms]
|
| 173 |
|
| 174 |
if i == 0:
|
| 175 |
-
mix =
|
| 176 |
continue
|
| 177 |
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
progress(30 + i * 10, desc="🧠 Decidiendo transición óptima…")
|
| 182 |
-
time.sleep(0.3)
|
| 183 |
|
|
|
|
| 184 |
candidates = range(5, min(len(prev["energy"]) - 1, 50))
|
| 185 |
-
best_t = max(
|
| 186 |
-
candidates,
|
| 187 |
-
key=lambda t: score_transition(prev, curr, t)
|
| 188 |
-
)
|
| 189 |
|
| 190 |
-
# 🔥 BPM OBJETIVO = BPM DE LA CANCIÓN QUE ENTRA
|
| 191 |
target_bpm = curr["tempo"]
|
| 192 |
|
| 193 |
-
|
| 194 |
-
|
| 195 |
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
mix,
|
| 199 |
-
prev["tempo"],
|
| 200 |
-
target_bpm
|
| 201 |
-
)
|
| 202 |
-
|
| 203 |
-
# B entra en su BPM natural
|
| 204 |
-
seg_adj = bpm_adjust(
|
| 205 |
-
segment,
|
| 206 |
-
curr["tempo"],
|
| 207 |
-
target_bpm
|
| 208 |
-
)
|
| 209 |
|
| 210 |
safe_cf = min(crossfade_ms, len(mix_adj), len(seg_adj))
|
| 211 |
|
| 212 |
-
|
| 213 |
-
|
| 214 |
|
| 215 |
mixed = mix_adj.append(seg_adj, crossfade=safe_cf)
|
|
|
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
mixed,
|
| 220 |
-
target_bpm,
|
| 221 |
-
curr["tempo"]
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
progress(85, desc="📦 Exportando mix…")
|
| 225 |
-
time.sleep(0.5)
|
| 226 |
-
|
| 227 |
-
out_name = f"monx_ai_dj_mix_{uuid.uuid4().hex}.m4a"
|
| 228 |
-
out_path = os.path.join(OUTPUT_DIR, out_name)
|
| 229 |
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
|
| 233 |
-
codec="aac",
|
| 234 |
-
bitrate="192k"
|
| 235 |
)
|
| 236 |
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
# =================================================
|
| 240 |
for k in weights:
|
| 241 |
weights[k] += 0.01 * weights[k]
|
| 242 |
save_weights(weights)
|
| 243 |
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
return out_path
|
| 247 |
|
| 248 |
-
# =============================
|
| 249 |
-
# UI
|
| 250 |
-
# =============================
|
| 251 |
|
| 252 |
with gr.Blocks(title="MONX AI DJ") as demo:
|
| 253 |
-
gr.Markdown(
|
| 254 |
-
"""
|
| 255 |
-
<div style="text-align:center">
|
| 256 |
-
<h1>🎚️ MONX AI DJ</h1>
|
| 257 |
-
<p>IA DJ automática con BPM dinámico PRO</p>
|
| 258 |
-
</div>
|
| 259 |
-
"""
|
| 260 |
-
)
|
| 261 |
|
| 262 |
files = gr.File(
|
| 263 |
label="Sube 2 a 4 canciones",
|
|
@@ -267,29 +183,20 @@ with gr.Blocks(title="MONX AI DJ") as demo:
|
|
| 267 |
|
| 268 |
durations = gr.Textbox(
|
| 269 |
label="Duración por canción (segundos)",
|
| 270 |
-
value="
|
| 271 |
)
|
| 272 |
|
| 273 |
-
crossfade = gr.Slider(
|
| 274 |
-
minimum=6,
|
| 275 |
-
maximum=20,
|
| 276 |
-
value=12,
|
| 277 |
-
step=1,
|
| 278 |
-
label="Crossfade (segundos)"
|
| 279 |
-
)
|
| 280 |
|
| 281 |
-
btn = gr.Button("🔥 Auto DJ Mix"
|
| 282 |
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
type="filepath"
|
| 286 |
-
)
|
| 287 |
|
| 288 |
btn.click(
|
| 289 |
-
|
| 290 |
inputs=[files, durations, crossfade],
|
| 291 |
-
outputs=output
|
| 292 |
)
|
| 293 |
|
| 294 |
-
|
| 295 |
-
demo.launch()
|
|
|
|
| 4 |
from pydub import AudioSegment, effects
|
| 5 |
import uuid, os, json, time
|
| 6 |
|
| 7 |
+
# =============================
|
| 8 |
# DIRECTORIOS
|
| 9 |
+
# =============================
|
| 10 |
|
| 11 |
UPLOAD_DIR = "uploads"
|
| 12 |
OUTPUT_DIR = "outputs"
|
|
|
|
| 18 |
|
| 19 |
MODEL_PATH = os.path.join(DATA_DIR, "weights.json")
|
| 20 |
|
| 21 |
+
# =============================
|
| 22 |
+
# MODELO IA (PESOS)
|
| 23 |
+
# =============================
|
| 24 |
|
| 25 |
DEFAULT_WEIGHTS = {
|
| 26 |
"bpm": 0.35,
|
|
|
|
| 34 |
try:
|
| 35 |
with open(MODEL_PATH, "r") as f:
|
| 36 |
return json.load(f)
|
| 37 |
+
except:
|
| 38 |
pass
|
| 39 |
return DEFAULT_WEIGHTS.copy()
|
| 40 |
|
|
|
|
| 44 |
|
| 45 |
weights = load_weights()
|
| 46 |
|
| 47 |
+
# =============================
|
| 48 |
+
# ANÁLISIS MUSICAL (ESTABLE)
|
| 49 |
+
# =============================
|
| 50 |
|
| 51 |
def analyze_audio(path):
|
| 52 |
+
y, sr = librosa.load(path, mono=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
+
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
|
| 55 |
+
tempo = float(librosa.beat.tempo(onset_envelope=onset_env, sr=sr)[0])
|
| 56 |
+
|
| 57 |
+
rms = librosa.feature.rms(y=y)[0]
|
| 58 |
+
rms = librosa.util.normalize(rms)
|
| 59 |
+
|
| 60 |
+
drops = []
|
| 61 |
+
for i in range(10, len(rms) - 10):
|
| 62 |
+
if rms[i] > np.mean(rms[i-10:i-1]) * 1.4:
|
| 63 |
+
drops.append(i)
|
| 64 |
|
| 65 |
+
return {"tempo": tempo, "energy": rms, "drops": drops}
|
|
|
|
| 66 |
|
| 67 |
+
# =============================
|
| 68 |
+
# IA DE DECISIÓN
|
| 69 |
+
# =============================
|
| 70 |
+
|
| 71 |
+
def score_transition(a, b, t):
|
| 72 |
+
bpm_sim = max(0, 1 - abs(a["tempo"] - b["tempo"]) / 30)
|
| 73 |
+
energy_sim = max(0, 1 - abs(a["energy"][t] - b["energy"][0]))
|
| 74 |
drop_penalty = 1 if t in a["drops"] else 0
|
| 75 |
|
| 76 |
+
return (
|
| 77 |
weights["bpm"] * bpm_sim +
|
| 78 |
weights["energy"] * energy_sim +
|
| 79 |
weights["smooth"] * ((bpm_sim + energy_sim) / 2) -
|
| 80 |
weights["drop_penalty"] * drop_penalty
|
| 81 |
)
|
|
|
|
| 82 |
|
| 83 |
+
# =============================
|
| 84 |
+
# BPM PUSH / PULL (DJ PRO)
|
| 85 |
+
# =============================
|
| 86 |
|
| 87 |
def bpm_adjust(segment, from_bpm, to_bpm):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
ratio = from_bpm / to_bpm
|
|
|
|
|
|
|
| 89 |
if abs(1 - ratio) > 0.12:
|
| 90 |
return segment
|
| 91 |
|
| 92 |
new_rate = int(segment.frame_rate * ratio)
|
| 93 |
+
seg = segment._spawn(segment.raw_data, overrides={"frame_rate": new_rate})
|
| 94 |
+
return seg.set_frame_rate(segment.frame_rate)
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# =============================
|
| 97 |
+
# MEZCLADOR CON MENSAJES EN VIVO
|
| 98 |
+
# =============================
|
| 99 |
|
| 100 |
+
def auto_dj_mix(files, durations, crossfade_sec):
|
| 101 |
+
status = "🎧 Iniciando mezcla...\n"
|
| 102 |
+
yield status, None
|
| 103 |
|
| 104 |
durs = [float(x.strip()) for x in durations.split(",")]
|
| 105 |
+
crossfade_ms = int(crossfade_sec * 1000)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 106 |
|
| 107 |
+
tracks, analyses = [], []
|
|
|
|
| 108 |
|
| 109 |
+
for i, f in enumerate(files):
|
| 110 |
+
status += f"🔍 Analizando canción {i+1}\n"
|
| 111 |
+
yield status, None
|
| 112 |
|
| 113 |
+
path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4().hex}.mp3")
|
| 114 |
with open(f.name, "rb") as src, open(path, "wb") as dst:
|
| 115 |
dst.write(src.read())
|
| 116 |
|
| 117 |
+
audio = effects.normalize(AudioSegment.from_file(path))
|
|
|
|
|
|
|
| 118 |
tracks.append(audio)
|
| 119 |
analyses.append(analyze_audio(path))
|
| 120 |
|
| 121 |
mix = AudioSegment.silent(0)
|
| 122 |
|
| 123 |
+
for i in range(len(tracks)):
|
| 124 |
+
play_ms = min(int(durs[i] * 1000), len(tracks[i]))
|
| 125 |
+
seg = tracks[i][:play_ms]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
if i == 0:
|
| 128 |
+
mix = seg
|
| 129 |
continue
|
| 130 |
|
| 131 |
+
status += f"\n🧠 Decidiendo transición {i} → {i+1}\n"
|
| 132 |
+
yield status, None
|
|
|
|
|
|
|
|
|
|
| 133 |
|
| 134 |
+
prev, curr = analyses[i-1], analyses[i]
|
| 135 |
candidates = range(5, min(len(prev["energy"]) - 1, 50))
|
| 136 |
+
best_t = max(candidates, key=lambda t: score_transition(prev, curr, t))
|
|
|
|
|
|
|
|
|
|
| 137 |
|
|
|
|
| 138 |
target_bpm = curr["tempo"]
|
| 139 |
|
| 140 |
+
status += f"🔄 Empujando BPM {prev['tempo']:.1f} → {target_bpm:.1f}\n"
|
| 141 |
+
yield status, None
|
| 142 |
|
| 143 |
+
mix_adj = bpm_adjust(mix, prev["tempo"], target_bpm)
|
| 144 |
+
seg_adj = bpm_adjust(seg, curr["tempo"], target_bpm)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 145 |
|
| 146 |
safe_cf = min(crossfade_ms, len(mix_adj), len(seg_adj))
|
| 147 |
|
| 148 |
+
status += f"🎚️ Mezclando ({safe_cf/1000:.1f}s crossfade)\n"
|
| 149 |
+
yield status, None
|
| 150 |
|
| 151 |
mixed = mix_adj.append(seg_adj, crossfade=safe_cf)
|
| 152 |
+
mix = bpm_adjust(mixed, target_bpm, curr["tempo"])
|
| 153 |
|
| 154 |
+
status += "\n📦 Exportando mix final...\n"
|
| 155 |
+
yield status, None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
+
out_path = os.path.join(
|
| 158 |
+
OUTPUT_DIR,
|
| 159 |
+
f"monx_ai_dj_mix_{uuid.uuid4().hex}.m4a"
|
|
|
|
|
|
|
| 160 |
)
|
| 161 |
|
| 162 |
+
mix.export(out_path, format="ipod", codec="aac", bitrate="192k")
|
| 163 |
+
|
|
|
|
| 164 |
for k in weights:
|
| 165 |
weights[k] += 0.01 * weights[k]
|
| 166 |
save_weights(weights)
|
| 167 |
|
| 168 |
+
status += "✅ Mix listo. ¡Disfrútalo! 🔥"
|
| 169 |
+
yield status, out_path
|
|
|
|
| 170 |
|
| 171 |
+
# =============================
|
| 172 |
+
# UI
|
| 173 |
+
# =============================
|
| 174 |
|
| 175 |
with gr.Blocks(title="MONX AI DJ") as demo:
|
| 176 |
+
gr.Markdown("## 🎚️ MONX AI DJ\nIA DJ automática con BPM dinámico PRO")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
|
| 178 |
files = gr.File(
|
| 179 |
label="Sube 2 a 4 canciones",
|
|
|
|
| 183 |
|
| 184 |
durations = gr.Textbox(
|
| 185 |
label="Duración por canción (segundos)",
|
| 186 |
+
value="90,90"
|
| 187 |
)
|
| 188 |
|
| 189 |
+
crossfade = gr.Slider(6, 20, value=12, step=1, label="Crossfade (segundos)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
+
btn = gr.Button("🔥 Auto DJ Mix")
|
| 192 |
|
| 193 |
+
status = gr.Markdown("🕒 Esperando acción...")
|
| 194 |
+
output = gr.Audio(label="Resultado (M4A)", type="filepath")
|
|
|
|
|
|
|
| 195 |
|
| 196 |
btn.click(
|
| 197 |
+
auto_dj_mix,
|
| 198 |
inputs=[files, durations, crossfade],
|
| 199 |
+
outputs=[status, output]
|
| 200 |
)
|
| 201 |
|
| 202 |
+
demo.launch()
|
|
|