teszenofficial commited on
Commit
a8c9e9c
·
verified ·
1 Parent(s): 33f2ac1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -37
app.py CHANGED
@@ -5,11 +5,10 @@ from pydub import AudioSegment, effects
5
  import uuid, os, json
6
 
7
  # =====================================================
8
- # ESTADO DEL MODELO (MISMA CARPETA QUE app.py)
9
  # =====================================================
10
 
11
  STATE_PATH = "monx_dj_state.json"
12
-
13
  UPLOAD_DIR = "uploads"
14
  OUTPUT_DIR = "outputs"
15
 
@@ -17,7 +16,7 @@ os.makedirs(UPLOAD_DIR, exist_ok=True)
17
  os.makedirs(OUTPUT_DIR, exist_ok=True)
18
 
19
  # =====================================================
20
- # UTILIDAD: CONVERSIÓN SEGURA A JSON
21
  # =====================================================
22
 
23
  def to_python(obj):
@@ -30,7 +29,7 @@ def to_python(obj):
30
  return obj
31
 
32
  # =====================================================
33
- # ESTADO DEL MODELO (IA REAL)
34
  # =====================================================
35
 
36
  DEFAULT_STATE = {
@@ -61,13 +60,12 @@ state = load_state()
61
  weights = state["weights"]
62
 
63
  # =====================================================
64
- # ANÁLISIS MUSICAL (ROBUSTO, SIN DEPENDER DE VERSIONES)
65
  # =====================================================
66
 
67
  def analyze_audio(path):
68
  y, sr = librosa.load(path, mono=True)
69
 
70
- # ---------- BPM SEGURO ----------
71
  onset_env = librosa.onset.onset_strength(y=y, sr=sr)
72
 
73
  try:
@@ -78,26 +76,20 @@ def analyze_audio(path):
78
  tempo = float(np.mean(onset_env) * 60)
79
 
80
  if tempo <= 0 or np.isnan(tempo):
81
- tempo = 120.0 # BPM seguro por defecto
82
 
83
- # ---------- ENERGÍA ----------
84
  rms = librosa.feature.rms(y=y)[0]
85
  rms = librosa.util.normalize(rms)
86
 
87
- # ---------- DROPS ----------
88
  drops = [
89
  i for i in range(10, len(rms) - 10)
90
  if rms[i] > np.mean(rms[i-10:i-1]) * 1.4
91
  ]
92
 
93
- return {
94
- "tempo": tempo,
95
- "energy": rms,
96
- "drops": drops
97
- }
98
 
99
  # =====================================================
100
- # FUNCIÓN DE DECISIÓN (IA)
101
  # =====================================================
102
 
103
  def score_transition(a, b, t):
@@ -113,7 +105,7 @@ def score_transition(a, b, t):
113
  )
114
 
115
  # =====================================================
116
- # TIME-STRETCH
117
  # =====================================================
118
 
119
  def bpm_adjust(segment, from_bpm, to_bpm):
@@ -131,11 +123,11 @@ def bpm_adjust(segment, from_bpm, to_bpm):
131
  ).set_frame_rate(segment.frame_rate)
132
 
133
  # =====================================================
134
- # IA DJ MIXER
135
  # =====================================================
136
 
137
- def auto_dj_mix(files, durations, crossfade_sec):
138
- log = "🎧 Iniciando MONX DJ (IA)\n"
139
  yield log, None
140
 
141
  durs = [float(x.strip()) for x in durations.split(",")]
@@ -144,7 +136,7 @@ def auto_dj_mix(files, durations, crossfade_sec):
144
  tracks, analyses, scores = [], [], []
145
 
146
  for i, f in enumerate(files):
147
- log += f"\n🔍 Analizando canción {i+1}\n"
148
  yield log, None
149
 
150
  ext = f.name.split(".")[-1]
@@ -189,7 +181,7 @@ def auto_dj_mix(files, durations, crossfade_sec):
189
  )
190
  mix.export(out_path, format="ipod", codec="aac", bitrate="192k")
191
 
192
- # ---------- APRENDIZAJE AUTOMÁTICO ----------
193
  if scores:
194
  new_avg = sum(scores) / len(scores)
195
  reward = 1 if new_avg > state["avg_score"] else -1
@@ -207,7 +199,7 @@ def auto_dj_mix(files, durations, crossfade_sec):
207
  state["weights"] = weights
208
  save_state(state)
209
 
210
- log += "\n✅ Mix listo. Da feedback para que MONX DJ aprenda."
211
  yield log, out_path
212
 
213
  # =====================================================
@@ -225,28 +217,27 @@ def feedback(reward):
225
 
226
  state["weights"] = weights
227
  save_state(state)
228
- return "🧠 Feedback recibido. MONX DJ ha aprendido."
229
 
230
  # =====================================================
231
- # UI
232
  # =====================================================
233
 
234
- with gr.Blocks(title="MONX DJ") as demo:
235
- gr.Markdown(
236
- "<h1 style='text-align:center'>🎚️ MONX DJ</h1>"
237
- "<p style='text-align:center'>IA DJ con aprendizaje real</p>"
238
- )
239
 
240
- files = gr.File(
241
- label="Sube 2 a 4 canciones",
242
- file_count="multiple",
243
- file_types=[".mp3", ".wav", ".flac", ".m4a"]
244
- )
245
 
246
- durations = gr.Textbox(label="Duración por canción (seg)", value="90,90")
247
- crossfade = gr.Slider(6, 20, value=12, step=1, label="Crossfade (seg)")
 
248
 
249
- btn = gr.Button("🔥 Auto Mix")
250
  status = gr.Markdown()
251
  output = gr.Audio(type="filepath")
252
 
@@ -260,4 +251,5 @@ with gr.Blocks(title="MONX DJ") as demo:
260
  like.click(lambda: feedback(1), None, fb_status)
261
  dislike.click(lambda: feedback(-1), None, fb_status)
262
 
 
263
  demo.launch()
 
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
 
 
16
  os.makedirs(OUTPUT_DIR, exist_ok=True)
17
 
18
  # =====================================================
19
+ # UTILIDAD JSON
20
  # =====================================================
21
 
22
  def to_python(obj):
 
29
  return obj
30
 
31
  # =====================================================
32
+ # ESTADO DEL MODELO
33
  # =====================================================
34
 
35
  DEFAULT_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:
 
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):
 
105
  )
106
 
107
  # =====================================================
108
+ # TIME STRETCH
109
  # =====================================================
110
 
111
  def bpm_adjust(segment, from_bpm, to_bpm):
 
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(",")]
 
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]
 
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
 
199
  state["weights"] = weights
200
  save_state(state)
201
 
202
+ log += "\n✅ Mix listo"
203
  yield log, out_path
204
 
205
  # =====================================================
 
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
 
 
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()