teszenofficial commited on
Commit
2b5e49a
·
verified ·
1 Parent(s): 217cbcf

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +85 -73
app.py CHANGED
@@ -1,73 +1,106 @@
1
  import gradio as gr
2
- from pydub import AudioSegment, effects
 
 
 
3
  import uuid, os
4
 
5
  UPLOAD_DIR = "uploads"
6
  OUTPUT_DIR = "outputs"
7
-
8
  os.makedirs(UPLOAD_DIR, exist_ok=True)
9
  os.makedirs(OUTPUT_DIR, exist_ok=True)
10
 
11
- # -------------------------
12
- # MOTOR DE MEZCLA PRO
13
- # -------------------------
14
-
15
- def create_mix(
16
- files,
17
- start_times,
18
- crossfade_sec,
19
- progress=gr.Progress()
20
- ):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
  if not files or len(files) < 2 or len(files) > 4:
22
  raise gr.Error("Sube entre 2 y 4 canciones")
23
 
24
- if len(start_times) != len(files):
25
- raise gr.Error("Los tiempos deben coincidir con el número de canciones")
26
-
27
- crossfade_ms = int(crossfade_sec * 1000)
28
-
29
- progress(0, desc="Cargando canciones…")
30
 
31
- segments = []
 
32
 
33
- # Preparar canciones
34
- for i, f in enumerate(files):
35
  ext = f.name.split(".")[-1].lower()
36
- if ext not in ["mp3", "wav", "flac", "m4a"]:
37
- raise gr.Error("Formato no soportado")
38
-
39
  path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4().hex}.{ext}")
 
40
  with open(f.name, "rb") as src, open(path, "wb") as dst:
41
  dst.write(src.read())
42
 
43
- audio = AudioSegment.from_file(path)
 
 
 
 
 
44
 
45
- start_ms = int(start_times[i] * 1000)
46
- if start_ms >= len(audio):
47
- raise gr.Error(f"El inicio de la canción {i+1} es mayor que su duración")
48
 
49
- audio = audio[start_ms:]
50
- audio = effects.normalize(audio) # volumen estable
51
 
52
- segments.append(audio)
 
53
 
54
- progress(20, desc="Mezclando…")
 
 
 
55
 
56
- # Mezcla secuencial con control
57
- mix = segments[0]
 
58
 
59
- step = 60 // (len(segments) - 1)
 
60
 
61
- for i in range(1, len(segments)):
62
- progress(20 + step * (i - 1), desc=f"Crossfade canción {i+1}")
63
- mix = mix.append(
64
- segments[i],
65
- crossfade=crossfade_ms
66
- )
67
 
68
- progress(90, desc="Exportando mix…")
 
69
 
70
- out_name = f"monx_ai_mix_{uuid.uuid4().hex}.m4a"
 
 
 
 
71
  out_path = os.path.join(OUTPUT_DIR, out_name)
72
 
73
  mix.export(
@@ -77,20 +110,20 @@ def create_mix(
77
  bitrate="192k"
78
  )
79
 
80
- progress(100, desc="Mix listo 🎶")
81
 
82
  return out_path
83
 
84
- # -------------------------
85
  # INTERFAZ GRADIO
86
- # -------------------------
87
 
88
- with gr.Blocks(title="MONX AI Pro Mix") as demo:
89
  gr.Markdown(
90
  """
91
  <div style="text-align:center">
92
- <h1>🎛️ MONX AI – Pro Mix</h1>
93
- <p>Control total de entradas, salidas y crossfade</p>
94
  </div>
95
  """
96
  )
@@ -101,39 +134,18 @@ with gr.Blocks(title="MONX AI Pro Mix") as demo:
101
  file_types=[".mp3", ".wav", ".flac", ".m4a"]
102
  )
103
 
104
- start_times = gr.Textbox(
105
- label="Segundos de inicio (ej: 0, 30, 45, 60)",
106
- placeholder="Uno por canción, separados por coma"
107
- )
108
-
109
- crossfade = gr.Slider(
110
- minimum=5,
111
- maximum=30,
112
- value=15,
113
- step=1,
114
- label="Duración del crossfade (segundos)"
115
- )
116
-
117
- btn = gr.Button("✨ Crear Mix", variant="primary")
118
 
119
  output = gr.Audio(
120
  label="Resultado (M4A)",
121
  type="filepath"
122
  )
123
 
124
- def wrapper(files, start_times, crossfade, progress=gr.Progress()):
125
- times = [float(t.strip()) for t in start_times.split(",")]
126
- return create_mix(files, times, crossfade, progress)
127
-
128
  btn.click(
129
- fn=wrapper,
130
- inputs=[files, start_times, crossfade],
131
  outputs=output
132
  )
133
 
134
- # -------------------------
135
- # HF ENTRYPOINT
136
- # -------------------------
137
-
138
  if __name__ == "__main__":
139
  demo.launch()
 
1
  import gradio as gr
2
+ import librosa
3
+ import numpy as np
4
+ from pydub import AudioSegment
5
+ from scipy.signal import resample
6
  import uuid, os
7
 
8
  UPLOAD_DIR = "uploads"
9
  OUTPUT_DIR = "outputs"
 
10
  os.makedirs(UPLOAD_DIR, exist_ok=True)
11
  os.makedirs(OUTPUT_DIR, exist_ok=True)
12
 
13
+ # -----------------------------
14
+ # UTILIDADES MUSICALES
15
+ # -----------------------------
16
+
17
+ def analyze_audio(path):
18
+ y, sr = librosa.load(path, mono=True)
19
+ tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
20
+ beat_times = librosa.frames_to_time(beats, sr=sr)
21
+
22
+ # Detectar frases (cada 8 beats)
23
+ phrases = beat_times[::8] if len(beat_times) >= 8 else beat_times
24
+
25
+ return {
26
+ "tempo": tempo,
27
+ "beats": beat_times,
28
+ "phrases": phrases,
29
+ "sr": sr,
30
+ "y": y
31
+ }
32
+
33
+ def time_stretch_segment(audio, rate):
34
+ samples = np.array(audio.get_array_of_samples())
35
+ stretched = resample(samples, int(len(samples) / rate))
36
+ new_audio = audio._spawn(stretched.astype(np.int16).tobytes())
37
+ return new_audio.set_frame_rate(audio.frame_rate)
38
+
39
+ def dj_crossfade(a, b, crossfade_ms):
40
+ a = a.fade_out(crossfade_ms)
41
+ b = b.fade_in(crossfade_ms)
42
+ return a.append(b, crossfade=crossfade_ms)
43
+
44
+ # -----------------------------
45
+ # MEZCLADOR DJ REAL
46
+ # -----------------------------
47
+
48
+ def auto_dj_mix(files, progress=gr.Progress()):
49
  if not files or len(files) < 2 or len(files) > 4:
50
  raise gr.Error("Sube entre 2 y 4 canciones")
51
 
52
+ progress(0, desc="Analizando canciones…")
 
 
 
 
 
53
 
54
+ tracks = []
55
+ analyses = []
56
 
57
+ # Guardar y analizar
58
+ for f in files:
59
  ext = f.name.split(".")[-1].lower()
 
 
 
60
  path = os.path.join(UPLOAD_DIR, f"{uuid.uuid4().hex}.{ext}")
61
+
62
  with open(f.name, "rb") as src, open(path, "wb") as dst:
63
  dst.write(src.read())
64
 
65
+ tracks.append(AudioSegment.from_file(path))
66
+ analyses.append(analyze_audio(path))
67
+
68
+ progress(20, desc="Calculando estrategia de mezcla…")
69
+
70
+ mix = tracks[0]
71
 
72
+ for i in range(1, len(tracks)):
73
+ a = tracks[i - 1]
74
+ b = tracks[i]
75
 
76
+ info_a = analyses[i - 1]
77
+ info_b = analyses[i]
78
 
79
+ # BPM target (promedio)
80
+ target_bpm = (info_a["tempo"] + info_b["tempo"]) / 2
81
 
82
+ # Beatmatch SOLO B
83
+ rate = info_b["tempo"] / target_bpm
84
+ if abs(rate - 1) < 0.06:
85
+ b = time_stretch_segment(b, rate)
86
 
87
+ # Elegir puntos musicales
88
+ exit_point = int(info_a["phrases"][-1] * 1000)
89
+ entry_point = int(info_b["phrases"][0] * 1000)
90
 
91
+ a_seg = a[:exit_point]
92
+ b_seg = b[entry_point:]
93
 
94
+ crossfade_ms = 16_000 # 16 beats aprox
 
 
 
 
 
95
 
96
+ progress(20 + int((i / len(tracks)) * 60),
97
+ desc=f"Mezclando canción {i+1}")
98
 
99
+ mix = dj_crossfade(a_seg, b_seg, crossfade_ms)
100
+
101
+ progress(90, desc="Exportando mix DJ…")
102
+
103
+ out_name = f"monx_ai_dj_mix_{uuid.uuid4().hex}.m4a"
104
  out_path = os.path.join(OUTPUT_DIR, out_name)
105
 
106
  mix.export(
 
110
  bitrate="192k"
111
  )
112
 
113
+ progress(100, desc="Mix DJ listo 🎚️🔥")
114
 
115
  return out_path
116
 
117
+ # -----------------------------
118
  # INTERFAZ GRADIO
119
+ # -----------------------------
120
 
121
+ with gr.Blocks(title="MONX AI DJ") as demo:
122
  gr.Markdown(
123
  """
124
  <div style="text-align:center">
125
+ <h1>🎚�� MONX AI DJ</h1>
126
+ <p>Mezcladora inteligente con beatmatching real</p>
127
  </div>
128
  """
129
  )
 
134
  file_types=[".mp3", ".wav", ".flac", ".m4a"]
135
  )
136
 
137
+ btn = gr.Button("🔥 Auto DJ Mix", variant="primary")
 
 
 
 
 
 
 
 
 
 
 
 
 
138
 
139
  output = gr.Audio(
140
  label="Resultado (M4A)",
141
  type="filepath"
142
  )
143
 
 
 
 
 
144
  btn.click(
145
+ fn=auto_dj_mix,
146
+ inputs=files,
147
  outputs=output
148
  )
149
 
 
 
 
 
150
  if __name__ == "__main__":
151
  demo.launch()