david174's picture
Update app.py
579ca65 verified
import gradio as gr
import librosa
import numpy as np
from pydub import AudioSegment
# Núcleo de Inteligencia TITAN
ghost_titan = {
"key": "--", "bpm": 0, "crest": 0, "phase": "Mono Compatible",
"harmonics": [], "spectral_density": {}, "analyzed": False
}
def engine_v28_titan(t, r, p, active_fix, active_master):
global ghost_titan
if t is None:
return None, "ESTADO: OFFLINE", "NO SIGNAL", "--", "0", None
try:
# 1. ESCANEO DE ADN SÓNICO (120 seg)
y, sr = librosa.load(t, duration=120)
# Detección de BPM con Voto de Confianza
onset_env = librosa.onset.onset_strength(y=y, sr=sr)
tempo = librosa.feature.tempo(onset_envelope=onset_env, sr=sr)
bpm = int(np.atleast_1d(tempo)[0])
if bpm < 115: bpm *= 2 # Optimizador DnB/Techno
# Detección de KEY por Cromatografía FFT
chroma = librosa.feature.chroma_stft(y=y, sr=sr, n_fft=4096)
notes = ["C","C#","D","D#","E","F","F#","G","G#","A","A#","B"]
k = notes[np.argmax(np.mean(chroma, axis=1))]
f_fund = librosa.note_to_hz(k+'1')
# Análisis de Fase y Crest Factor (Punch)
rms = librosa.feature.rms(y=y)
crest = 20 * np.log10(np.max(np.abs(y)) / (np.mean(rms) + 1e-6))
S = np.abs(librosa.stft(y))
f = librosa.fft_frequencies(sr=sr)
ghost_titan.update({
"key": k, "bpm": bpm, "crest": crest,
"harmonics": [round(f_fund * i, 1) for i in range(1, 6)],
"spectral_density": {
"sub": np.mean(S[f < 60]),
"punch": np.mean(S[(f >= 100) & (f < 250)]),
"mud": np.mean(S[(f >= 250) & (f < 500)]),
"harsh": np.mean(S[(f >= 3000) & (f < 5000)]),
"air": np.mean(S[f > 12000])
},
"analyzed": True
})
audio = AudioSegment.from_file(t)
log = f"--- GHOST TITAN V28 SYSTEM LOG ---\n\n"
if active_fix:
audio = audio.high_pass_filter(34)
if ghost_titan["spectral_density"]["mud"] > ghost_titan["spectral_density"]["punch"] * 1.3:
audio = audio.low_pass_filter(4500)
log += "[!] AUTO-FIX: Resonancia de 'lodo' detectada. Filtro adaptativo aplicado.\n"
if active_master:
# Cadena de Mastering: Glue -> Soft Clipping -> Maximization
audio = audio.compressor_dynamic_range(threshold=-14.0, ratio=4.2, attack=12.0, release=140.0)
audio = audio.apply_gain((p / 10) - 2.8)
log += "[+] MASTER: Cadena Titan activada (Target: -9 LUFS).\n"
audio.export("ghost_titan_v28.wav", format="wav")
log += f"\n▶ DIAGNÓSTICO: Key {k} | BPM {bpm} | Crest {round(crest,1)}dB\n"
log += f"▶ RECOMENDACIÓN: En {k}, limpia la banda de {ghost_titan['harmonics'][2]}Hz para dar espacio a la voz."
return "ghost_titan_v28.wav", log, "Análisis de Fase y Armónicos completado.", k, str(bpm), "https://images.unsplash.com/photo-1514474959185-1472d4c4e0d4?q=80&w=500"
except Exception as e:
return None, f"FATAL ERROR: {str(e)}", "ERROR", "!", "0", None
def titan_mentor_ai(pregunta):
if not ghost_titan["analyzed"]: return "Inicia el escaneo primero, Ghost."
msg = pregunta.lower()
k, b, sd = ghost_titan["key"], ghost_titan["bpm"], ghost_titan["spectral_density"]
h = ghost_titan["harmonics"]
# RESPUESTAS DE INGENIERÍA DE ALTA PRECISIÓN
if "bajo" in msg or "sub" in msg:
return f"Para tu nota {k}, el sub real está en {h[0]}Hz. He detectado que tu zona de punch ({h[1]}Hz) está " + ("débil" if sd["punch"] < sd["sub"] else "fuerte") + f". Sugerencia: Usa un EQ dinámico en {h[0]}Hz encadenado al Kick."
if "pegada" in msg or "punch" in msg:
ms_release = round(60000 / b / 2, 1)
return f"A {b} BPM, el compresor debe respirar. Pon el Attack en 30ms y el Release en {ms_release}ms. Esto evitará que el limitador destruya el transiente de tus drums."
if "lodo" in msg or "limpiar" in msg:
return f"El conflicto está en {h[3]}Hz. Es el 4º armónico de {k}. Baja -3dB ahí con un Q de 1.4 en tus leads y sintes. Notarás una claridad instantánea."
if "brillo" in msg or "aire" in msg:
if sd["air"] < 0.005:
return "Tu mezcla es demasiado oscura. Añade un High Shelf en 10kHz con +2dB, pero usa un saturador de cinta (Tape) para que no suene digital."
return "El aire está bien equilibrado. No toques los agudos o fatigarás el oído."
return f"Status {k} @ {b} BPM: Tienes un Crest Factor de {round(ghost_titan['crest'], 1)}dB. Tienes margen para subir +3dB de ganancia en el master antes de que pierdas el punch."
# --- INTERFAZ "TITAN CONSOLE" ---
css = """
body, .gradio-container {background: #020202 !important; color: #00e5ff !important; font-family: 'JetBrains Mono', monospace;}
.gr-box {border: 2px solid #00e5ff !important; background: #080808 !important; box-shadow: 0 0 15px #00e5ff33;}
.gr-button-primary {background: linear-gradient(180deg, #00e5ff, #007cff) !important; color: #000 !important; font-weight: bold; border: none;}
.gr-button-primary:hover {box-shadow: 0 0 25px #00e5ff; transform: scale(1.02);}
.gr-label {color: #ff0055 !important; font-size: 0.9em;}
.gr-textbox textarea {background: #000 !important; color: #00ff88 !important; border: 1px solid #00e5ff22 !important;}
"""
with gr.Blocks(theme=gr.themes.Monochrome(), css=css) as demo:
gr.HTML("<h1 style='text-align:center; letter-spacing:15px; color:#00e5ff; text-shadow: 0 0 10px #00e5ff;'>GHOST TITAN v28</h1>")
with gr.Row():
with gr.Column(scale=1):
with gr.Row():
out_k = gr.Label(label="KEY (DETECCIÓN FFT)")
out_b = gr.Label(label="BPM (ANALYSIS)")
in_audio = gr.Audio(label="SOURCE AUDIO", type="filepath")
in_ref = gr.Audio(label="MASTER REFERENCE", type="filepath")
with gr.Row():
fix_btn = gr.Checkbox(label="ADAPTIVE MIX REPAIR", value=False)
mst_btn = gr.Checkbox(label="TITAN MASTERING", value=False)
in_pwr = gr.Slider(0, 100, label="MASTER PRESSURE (LUFS TARGET)", value=85)
exec_btn = gr.Button("ENGAGE SYSTEM", variant="primary")
with gr.Column(scale=2):
out_audio = gr.Audio(label="MONITOR OUTPUT (32-BIT)")
out_diag = gr.Textbox(label="SISTEMA DE DIAGNÓSTICO PROFUNDO", lines=10)
with gr.Group():
gr.Markdown("### 🎙️ TITAN MENTOR (IA de Ingeniería Avanzada)")
user_msg = gr.Textbox(placeholder="Pregunta por la pegada, el lodo, los armónicos o la fase...", label="Consulta técnica")
chat_btn = gr.Button("CONSULTAR INGENIERO TITAN")
chat_out = gr.Textbox(label="SOLUCIÓN TÉCNICA CALCULADA", lines=6)
exec_btn.click(engine_v28_titan, [in_audio, in_ref, in_pwr, fix_btn, mst_btn], [out_audio, out_diag, out_k, out_b])
chat_btn.click(titan_mentor_ai, [user_msg], [chat_out])
demo.launch()