Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -35,23 +35,24 @@ cnn.eval()
|
|
| 35 |
# --- Carga etiquetas y umbrales ---
|
| 36 |
with open(enc_path, "rb") as f:
|
| 37 |
data = pickle.load(f)
|
|
|
|
|
|
|
| 38 |
if isinstance(data, dict):
|
| 39 |
if 'labels' in data and data['labels'] is not None:
|
| 40 |
LABELS = data['labels']
|
| 41 |
elif 'label_encoder' in data and data['label_encoder'] is not None:
|
| 42 |
-
|
|
|
|
| 43 |
else:
|
| 44 |
LABELS = [k for k in data.keys() if k not in ('thresholds',)]
|
| 45 |
THRESHOLDS = data.get('thresholds', 0.5)
|
| 46 |
elif isinstance(data, (list, tuple)) and len(data) == 2:
|
| 47 |
-
|
| 48 |
-
LABELS =
|
| 49 |
-
THRESHOLDS = thr
|
| 50 |
else:
|
| 51 |
raise ValueError(f"Formato desconocido en etiquetas: {type(data)}")
|
| 52 |
|
| 53 |
# --- Feature extractors ---
|
| 54 |
-
# SVM: extrae y aplana MFCC, ajustando al tamaño del scaler
|
| 55 |
def extract_mfcc_vector(audio, sr=22050, n_mfcc=13):
|
| 56 |
mfccs = librosa.feature.mfcc(y=audio, sr=sr, n_mfcc=n_mfcc)
|
| 57 |
vec = mfccs.flatten()
|
|
@@ -62,7 +63,6 @@ def extract_mfcc_vector(audio, sr=22050, n_mfcc=13):
|
|
| 62 |
vec = vec[:target_len]
|
| 63 |
return vec
|
| 64 |
|
| 65 |
-
# CNN: extrae mel-spectrograma 2D
|
| 66 |
def extract_spectrogram(audio, sr=22050, n_mels=128, hop_length=512):
|
| 67 |
mel = librosa.feature.melspectrogram(y=audio, sr=sr, n_mels=n_mels, hop_length=hop_length)
|
| 68 |
log_mel = librosa.power_to_db(mel, ref=np.max)
|
|
@@ -76,17 +76,15 @@ def predict(model_name, audio_file, threshold):
|
|
| 76 |
if model_name == "SVM":
|
| 77 |
feats = extract_mfcc_vector(audio, sr)
|
| 78 |
feats_scaled = scaler.transform([feats])
|
| 79 |
-
|
| 80 |
# Convierte índice a etiqueta
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
except Exception:
|
| 85 |
-
# si LABELS es lista de labels directamente
|
| 86 |
try:
|
| 87 |
-
name = LABELS[int(
|
| 88 |
except Exception:
|
| 89 |
-
name = str(
|
| 90 |
return f"🔊 Especie detectada (SVM): **{name}**"
|
| 91 |
|
| 92 |
# CNN multi-label
|
|
@@ -95,10 +93,13 @@ def predict(model_name, audio_file, threshold):
|
|
| 95 |
with torch.no_grad():
|
| 96 |
probs = torch.sigmoid(cnn(x)).cpu().numpy().flatten()
|
| 97 |
|
| 98 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
detected = []
|
| 101 |
-
# Asegura no exceder etiquetas
|
| 102 |
for i, p in enumerate(probs):
|
| 103 |
if i >= len(LABELS):
|
| 104 |
break
|
|
@@ -111,9 +112,7 @@ def predict(model_name, audio_file, threshold):
|
|
| 111 |
|
| 112 |
if not detected:
|
| 113 |
return "❌ No se detectó ninguna especie con el umbral dado."
|
| 114 |
-
return "🔊 Especies detectadas (CNN):
|
| 115 |
-
" + "
|
| 116 |
-
".join(detected) (CNN):\n" + "\n".join(detected)
|
| 117 |
|
| 118 |
# --- Interfaz Gradio ---
|
| 119 |
demo = gr.Interface(
|
|
|
|
| 35 |
# --- Carga etiquetas y umbrales ---
|
| 36 |
with open(enc_path, "rb") as f:
|
| 37 |
data = pickle.load(f)
|
| 38 |
+
# Inicializa label_encoder opcional
|
| 39 |
+
label_encoder = None
|
| 40 |
if isinstance(data, dict):
|
| 41 |
if 'labels' in data and data['labels'] is not None:
|
| 42 |
LABELS = data['labels']
|
| 43 |
elif 'label_encoder' in data and data['label_encoder'] is not None:
|
| 44 |
+
label_encoder = data['label_encoder']
|
| 45 |
+
LABELS = label_encoder.classes_.tolist()
|
| 46 |
else:
|
| 47 |
LABELS = [k for k in data.keys() if k not in ('thresholds',)]
|
| 48 |
THRESHOLDS = data.get('thresholds', 0.5)
|
| 49 |
elif isinstance(data, (list, tuple)) and len(data) == 2:
|
| 50 |
+
label_encoder, THRESHOLDS = data
|
| 51 |
+
LABELS = label_encoder.classes_.tolist()
|
|
|
|
| 52 |
else:
|
| 53 |
raise ValueError(f"Formato desconocido en etiquetas: {type(data)}")
|
| 54 |
|
| 55 |
# --- Feature extractors ---
|
|
|
|
| 56 |
def extract_mfcc_vector(audio, sr=22050, n_mfcc=13):
|
| 57 |
mfccs = librosa.feature.mfcc(y=audio, sr=sr, n_mfcc=n_mfcc)
|
| 58 |
vec = mfccs.flatten()
|
|
|
|
| 63 |
vec = vec[:target_len]
|
| 64 |
return vec
|
| 65 |
|
|
|
|
| 66 |
def extract_spectrogram(audio, sr=22050, n_mels=128, hop_length=512):
|
| 67 |
mel = librosa.feature.melspectrogram(y=audio, sr=sr, n_mels=n_mels, hop_length=hop_length)
|
| 68 |
log_mel = librosa.power_to_db(mel, ref=np.max)
|
|
|
|
| 76 |
if model_name == "SVM":
|
| 77 |
feats = extract_mfcc_vector(audio, sr)
|
| 78 |
feats_scaled = scaler.transform([feats])
|
| 79 |
+
pred_idx = svm.predict(feats_scaled)[0]
|
| 80 |
# Convierte índice a etiqueta
|
| 81 |
+
if label_encoder is not None:
|
| 82 |
+
name = label_encoder.inverse_transform([pred_idx])[0]
|
| 83 |
+
else:
|
|
|
|
|
|
|
| 84 |
try:
|
| 85 |
+
name = LABELS[int(pred_idx)]
|
| 86 |
except Exception:
|
| 87 |
+
name = str(pred_idx)
|
| 88 |
return f"🔊 Especie detectada (SVM): **{name}**"
|
| 89 |
|
| 90 |
# CNN multi-label
|
|
|
|
| 93 |
with torch.no_grad():
|
| 94 |
probs = torch.sigmoid(cnn(x)).cpu().numpy().flatten()
|
| 95 |
|
| 96 |
+
# Umbral por etiqueta o global
|
| 97 |
+
if isinstance(THRESHOLDS, (dict, list, np.ndarray)):
|
| 98 |
+
thr = np.array([THRESHOLDS.get(lbl, threshold) for lbl in LABELS])
|
| 99 |
+
else:
|
| 100 |
+
thr = threshold
|
| 101 |
|
| 102 |
detected = []
|
|
|
|
| 103 |
for i, p in enumerate(probs):
|
| 104 |
if i >= len(LABELS):
|
| 105 |
break
|
|
|
|
| 112 |
|
| 113 |
if not detected:
|
| 114 |
return "❌ No se detectó ninguna especie con el umbral dado."
|
| 115 |
+
return "🔊 Especies detectadas (CNN):\n" + "\n".join(detected)
|
|
|
|
|
|
|
| 116 |
|
| 117 |
# --- Interfaz Gradio ---
|
| 118 |
demo = gr.Interface(
|