Delete app.py
Browse files
app.py
DELETED
|
@@ -1,255 +0,0 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
-
import librosa
|
| 3 |
-
import numpy as np
|
| 4 |
-
from pydub import AudioSegment, effects
|
| 5 |
-
import uuid, os, json
|
| 6 |
-
|
| 7 |
-
# =====================================================
|
| 8 |
-
# CONFIG
|
| 9 |
-
# =====================================================
|
| 10 |
-
|
| 11 |
-
STATE_PATH = "monx_dj_state.json"
|
| 12 |
-
UPLOAD_DIR = "uploads"
|
| 13 |
-
OUTPUT_DIR = "outputs"
|
| 14 |
-
|
| 15 |
-
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 16 |
-
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 17 |
-
|
| 18 |
-
# =====================================================
|
| 19 |
-
# UTILIDAD JSON
|
| 20 |
-
# =====================================================
|
| 21 |
-
|
| 22 |
-
def to_python(obj):
|
| 23 |
-
if isinstance(obj, dict):
|
| 24 |
-
return {k: to_python(v) for k, v in obj.items()}
|
| 25 |
-
if isinstance(obj, list):
|
| 26 |
-
return [to_python(v) for v in obj]
|
| 27 |
-
if isinstance(obj, np.generic):
|
| 28 |
-
return obj.item()
|
| 29 |
-
return obj
|
| 30 |
-
|
| 31 |
-
# =====================================================
|
| 32 |
-
# ESTADO DEL MODELO
|
| 33 |
-
# =====================================================
|
| 34 |
-
|
| 35 |
-
DEFAULT_STATE = {
|
| 36 |
-
"weights": {
|
| 37 |
-
"bpm": 0.35,
|
| 38 |
-
"energy": 0.30,
|
| 39 |
-
"smooth": 0.20,
|
| 40 |
-
"drop_penalty": 0.15
|
| 41 |
-
},
|
| 42 |
-
"avg_score": 0.5,
|
| 43 |
-
"runs": 0
|
| 44 |
-
}
|
| 45 |
-
|
| 46 |
-
def load_state():
|
| 47 |
-
if os.path.exists(STATE_PATH):
|
| 48 |
-
try:
|
| 49 |
-
with open(STATE_PATH, "r") as f:
|
| 50 |
-
return json.load(f)
|
| 51 |
-
except:
|
| 52 |
-
pass
|
| 53 |
-
return DEFAULT_STATE.copy()
|
| 54 |
-
|
| 55 |
-
def save_state(state):
|
| 56 |
-
with open(STATE_PATH, "w") as f:
|
| 57 |
-
json.dump(to_python(state), f, indent=2)
|
| 58 |
-
|
| 59 |
-
state = load_state()
|
| 60 |
-
weights = state["weights"]
|
| 61 |
-
|
| 62 |
-
# =====================================================
|
| 63 |
-
# ANÁLISIS MUSICAL (ROBUSTO)
|
| 64 |
-
# =====================================================
|
| 65 |
-
|
| 66 |
-
def analyze_audio(path):
|
| 67 |
-
y, sr = librosa.load(path, mono=True)
|
| 68 |
-
|
| 69 |
-
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
|
| 70 |
-
|
| 71 |
-
try:
|
| 72 |
-
tempo = float(librosa.beat.tempo(
|
| 73 |
-
onset_envelope=onset_env, sr=sr
|
| 74 |
-
)[0])
|
| 75 |
-
except Exception:
|
| 76 |
-
tempo = float(np.mean(onset_env) * 60)
|
| 77 |
-
|
| 78 |
-
if tempo <= 0 or np.isnan(tempo):
|
| 79 |
-
tempo = 120.0
|
| 80 |
-
|
| 81 |
-
rms = librosa.feature.rms(y=y)[0]
|
| 82 |
-
rms = librosa.util.normalize(rms)
|
| 83 |
-
|
| 84 |
-
drops = [
|
| 85 |
-
i for i in range(10, len(rms) - 10)
|
| 86 |
-
if rms[i] > np.mean(rms[i-10:i-1]) * 1.4
|
| 87 |
-
]
|
| 88 |
-
|
| 89 |
-
return {"tempo": tempo, "energy": rms, "drops": drops}
|
| 90 |
-
|
| 91 |
-
# =====================================================
|
| 92 |
-
# IA – FUNCIÓN DE DECISIÓN
|
| 93 |
-
# =====================================================
|
| 94 |
-
|
| 95 |
-
def score_transition(a, b, t):
|
| 96 |
-
bpm_sim = max(0, 1 - abs(a["tempo"] - b["tempo"]) / 35)
|
| 97 |
-
energy_sim = max(0, 1 - abs(a["energy"][t] - b["energy"][0]))
|
| 98 |
-
drop_penalty = 1 if t in a["drops"] else 0
|
| 99 |
-
|
| 100 |
-
return (
|
| 101 |
-
weights["bpm"] * bpm_sim +
|
| 102 |
-
weights["energy"] * energy_sim +
|
| 103 |
-
weights["smooth"] * ((bpm_sim + energy_sim) / 2) -
|
| 104 |
-
weights["drop_penalty"] * drop_penalty
|
| 105 |
-
)
|
| 106 |
-
|
| 107 |
-
# =====================================================
|
| 108 |
-
# TIME STRETCH
|
| 109 |
-
# =====================================================
|
| 110 |
-
|
| 111 |
-
def bpm_adjust(segment, from_bpm, to_bpm):
|
| 112 |
-
if from_bpm <= 0 or to_bpm <= 0:
|
| 113 |
-
return segment
|
| 114 |
-
|
| 115 |
-
ratio = from_bpm / to_bpm
|
| 116 |
-
if abs(1 - ratio) > 0.20:
|
| 117 |
-
return segment
|
| 118 |
-
|
| 119 |
-
new_rate = int(segment.frame_rate * ratio)
|
| 120 |
-
return segment._spawn(
|
| 121 |
-
segment.raw_data,
|
| 122 |
-
overrides={"frame_rate": new_rate}
|
| 123 |
-
).set_frame_rate(segment.frame_rate)
|
| 124 |
-
|
| 125 |
-
# =====================================================
|
| 126 |
-
# CORE MIXER (UI + API)
|
| 127 |
-
# =====================================================
|
| 128 |
-
|
| 129 |
-
def auto_dj_mix(files, durations="90,90", crossfade_sec=12):
|
| 130 |
-
log = "🎧 MONX DJ iniciado\n"
|
| 131 |
-
yield log, None
|
| 132 |
-
|
| 133 |
-
durs = [float(x.strip()) for x in durations.split(",")]
|
| 134 |
-
crossfade_ms = int(crossfade_sec * 1000)
|
| 135 |
-
|
| 136 |
-
tracks, analyses, scores = [], [], []
|
| 137 |
-
|
| 138 |
-
for i, f in enumerate(files):
|
| 139 |
-
log += f"\n🔍 Analizando pista {i+1}\n"
|
| 140 |
-
yield log, None
|
| 141 |
-
|
| 142 |
-
ext = f.name.split(".")[-1]
|
| 143 |
-
path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4().hex}.{ext}")
|
| 144 |
-
|
| 145 |
-
with open(f.name, "rb") as src, open(path, "wb") as dst:
|
| 146 |
-
dst.write(src.read())
|
| 147 |
-
|
| 148 |
-
audio = effects.normalize(AudioSegment.from_file(path))
|
| 149 |
-
tracks.append(audio)
|
| 150 |
-
analyses.append(analyze_audio(path))
|
| 151 |
-
|
| 152 |
-
mix = AudioSegment.silent(0)
|
| 153 |
-
|
| 154 |
-
for i in range(len(tracks)):
|
| 155 |
-
play_ms = min(int(durs[i] * 1000), len(tracks[i]))
|
| 156 |
-
segment = tracks[i][:play_ms]
|
| 157 |
-
|
| 158 |
-
if i == 0:
|
| 159 |
-
mix = segment
|
| 160 |
-
continue
|
| 161 |
-
|
| 162 |
-
prev, curr = analyses[i - 1], analyses[i]
|
| 163 |
-
|
| 164 |
-
candidates = range(5, min(len(prev["energy"]) - 1, 50))
|
| 165 |
-
best_t = max(candidates, key=lambda t: score_transition(prev, curr, t))
|
| 166 |
-
scores.append(score_transition(prev, curr, best_t))
|
| 167 |
-
|
| 168 |
-
target_bpm = curr["tempo"]
|
| 169 |
-
|
| 170 |
-
mix_adj = bpm_adjust(mix, prev["tempo"], target_bpm)
|
| 171 |
-
seg_adj = bpm_adjust(segment, curr["tempo"], target_bpm)
|
| 172 |
-
|
| 173 |
-
safe_cf = min(crossfade_ms, len(mix_adj), len(seg_adj))
|
| 174 |
-
mix = bpm_adjust(
|
| 175 |
-
mix_adj.append(seg_adj, crossfade=safe_cf),
|
| 176 |
-
target_bpm, curr["tempo"]
|
| 177 |
-
)
|
| 178 |
-
|
| 179 |
-
out_path = os.path.join(
|
| 180 |
-
OUTPUT_DIR, f"monx_dj_mix_{uuid.uuid4().hex}.m4a"
|
| 181 |
-
)
|
| 182 |
-
mix.export(out_path, format="ipod", codec="aac", bitrate="192k")
|
| 183 |
-
|
| 184 |
-
# -------- APRENDIZAJE --------
|
| 185 |
-
if scores:
|
| 186 |
-
new_avg = sum(scores) / len(scores)
|
| 187 |
-
reward = 1 if new_avg > state["avg_score"] else -1
|
| 188 |
-
lr = 0.05
|
| 189 |
-
|
| 190 |
-
for k in weights:
|
| 191 |
-
weights[k] += reward * lr * abs(weights[k])
|
| 192 |
-
|
| 193 |
-
total = sum(abs(v) for v in weights.values())
|
| 194 |
-
for k in weights:
|
| 195 |
-
weights[k] /= total
|
| 196 |
-
|
| 197 |
-
state["avg_score"] = new_avg
|
| 198 |
-
state["runs"] += 1
|
| 199 |
-
state["weights"] = weights
|
| 200 |
-
save_state(state)
|
| 201 |
-
|
| 202 |
-
log += "\n✅ Mix listo"
|
| 203 |
-
yield log, out_path
|
| 204 |
-
|
| 205 |
-
# =====================================================
|
| 206 |
-
# FEEDBACK HUMANO
|
| 207 |
-
# =====================================================
|
| 208 |
-
|
| 209 |
-
def feedback(reward):
|
| 210 |
-
lr = 0.08
|
| 211 |
-
for k in weights:
|
| 212 |
-
weights[k] += reward * lr * abs(weights[k])
|
| 213 |
-
|
| 214 |
-
total = sum(abs(v) for v in weights.values())
|
| 215 |
-
for k in weights:
|
| 216 |
-
weights[k] /= total
|
| 217 |
-
|
| 218 |
-
state["weights"] = weights
|
| 219 |
-
save_state(state)
|
| 220 |
-
return "🧠 Feedback aplicado. MONX DJ aprendió."
|
| 221 |
-
|
| 222 |
-
# =====================================================
|
| 223 |
-
# UI BONITA + API
|
| 224 |
-
# =====================================================
|
| 225 |
-
|
| 226 |
-
with gr.Blocks(css="""
|
| 227 |
-
body { background:#0b0b0b; color:white; }
|
| 228 |
-
button { background:#ff0055 !important; border-radius:8px; }
|
| 229 |
-
""") as demo:
|
| 230 |
-
|
| 231 |
-
gr.Markdown("""
|
| 232 |
-
<h1 style="text-align:center">🎚️ MONX DJ</h1>
|
| 233 |
-
<p style="text-align:center">IA DJ automática con aprendizaje real</p>
|
| 234 |
-
""")
|
| 235 |
-
|
| 236 |
-
files = gr.File(file_count="multiple", label="Canciones")
|
| 237 |
-
durations = gr.Textbox(value="90,90", label="Duración (seg)")
|
| 238 |
-
crossfade = gr.Slider(6, 20, value=12, step=1, label="Crossfade")
|
| 239 |
-
|
| 240 |
-
btn = gr.Button("🔥 Mezclar")
|
| 241 |
-
status = gr.Markdown()
|
| 242 |
-
output = gr.Audio(type="filepath")
|
| 243 |
-
|
| 244 |
-
btn.click(auto_dj_mix, [files, durations, crossfade], [status, output])
|
| 245 |
-
|
| 246 |
-
gr.Markdown("### ¿Te gustó el mix?")
|
| 247 |
-
like = gr.Button("👍 Sí")
|
| 248 |
-
dislike = gr.Button("👎 No")
|
| 249 |
-
fb_status = gr.Markdown()
|
| 250 |
-
|
| 251 |
-
like.click(lambda: feedback(1), None, fb_status)
|
| 252 |
-
dislike.click(lambda: feedback(-1), None, fb_status)
|
| 253 |
-
|
| 254 |
-
demo.queue()
|
| 255 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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