Spaces:
Sleeping
Sleeping
File size: 7,299 Bytes
a7c19a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | import os
import torch
import torchaudio
import pandas as pd
import numpy as np
import librosa
import librosa.display
import matplotlib
matplotlib.use('Agg') # prevents matplotlib from trying to open a GUI window
import matplotlib.pyplot as plt
from Core.resnet_model import AudioResNet
from Core.gtzan_dataset import GENRES
device = torch.device("cpu")
# Confidence Threshold (< .20%)
NATURE_CONFIDENCE_THRESHOLD = 0.20
# mel Spectrogram transform
mel_transform = torchaudio.transforms.MelSpectrogram(
sample_rate = 22050,
n_fft = 1024,
hop_length = 512,
n_mels = 128
).to(device)
# ESC-50 class map
def load_esc50_classes(csv_path = "data/esc50.csv"):
df = pd.read_csv(csv_path)
class_map = dict(zip(df['target'], df['category']))
return class_map
# Model loader
def load_model(num_classes, weights_path):
if not os.path.exists(weights_path):
print(f"Warning: weights not found at {weights_path}")
return None
model = AudioResNet(num_classes = num_classes).to(device)
model.load_state_dict(torch.load(
weights_path, map_location = device, weights_only = True
))
model.eval()
print(f"Loaded: {weights_path}")
return model
# Load both models at startup
nature_model = load_model(num_classes = 50, weights_path = "Models/esc50_resnet_v1.pth")
music_model = load_model(num_classes = 10, weights_path = "Models/gtzan_resnet_v1.pth")
try:
ESC50_CLASSES = load_esc50_classes()
except FileNotFoundError:
print("Warning: esc50.csv not found.")
ESC50_CLASSES = {}
def models_are_loaded():
return nature_model is not None and music_model is not None
# Audio preprocessor
def preprocess_audio(audio_path, num_samples):
signal, sr = torchaudio.load(audio_path)
if sr != 22050:
signal = torchaudio.transforms.Resample(sr, 22050)(signal)
if signal.shape[0] > 1:
signal = torch.mean(signal, dim = 0, keepdim = True)
if signal.shape[1] > num_samples:
signal = signal[:, :num_samples]
elif signal.shape[1] < num_samples:
signal = torch.nn.functional.pad(signal, (0, num_samples - signal.shape[1]))
signal = signal.to(device)
mel = mel_transform(signal).unsqueeze(0)
return mel
# Nature prediction β> returns top 3 + recognised flag
def predict_nature(audio_path):
"""
Returns a dict with:
- recognised (bool)
- label (str) β top prediction, or "Unrecognised Sound"
- closest_match (str) β always the top prediction regardless of threshold
- confidence (float) β top prediction confidence %
- top3 (list) β [{label, confidence}, ...] always 3 items
"""
if nature_model is None:
return {
"recognised": False,
"label": "Model not loaded",
"closest_match": "Model not loaded",
"confidence": 0.0,
"top3": []
}
mel = preprocess_audio(audio_path, num_samples=22050 * 5)
with torch.no_grad():
outputs = nature_model(mel)
probabilities = torch.nn.functional.softmax(outputs / 3.0, dim=1)
# Top 3 predictions
top3_confidences, top3_indices = torch.topk(probabilities, k=3, dim=1)
top3 = []
for i in range(3):
idx = top3_indices[0][i].item()
conf = round(top3_confidences[0][i].item(), 4)
raw_label = ESC50_CLASSES.get(idx, "Unknown")
clean_label = raw_label.replace('_', ' ').title()
top3.append({"label": clean_label, "confidence": conf})
top_label = top3[0]["label"]
top_confidence = top3[0]["confidence"]
recognised = top_confidence >= 0.25
return {
"recognised": recognised,
"label": top_label if recognised else "Unrecognised Sound",
"closest_match": top_label,
"confidence": top_confidence,
"top3": top3
}
# Music prediction β> returns top 3 + recognised flag
def predict_music(audio_path):
"""
Returns a dict with:
- recognised (bool)
- label (str)
- closest_match (str)
- confidence (float)
- top3 (list)
"""
if music_model is None:
return {
"recognised": False,
"label": "Model not loaded",
"closest_match": "Model not loaded",
"confidence": 0.0,
"top3": []
}
mel = preprocess_audio(audio_path, num_samples = 22050 * 30)
with torch.no_grad():
outputs = music_model(mel)
probabilities = torch.nn.functional.softmax(outputs, dim = 1)
top3_confidences, top3_indices = torch.topk(probabilities, k = 3, dim = 1)
top3 = []
for i in range(3):
idx = top3_indices[0][i].item()
conf = round(top3_confidences[0][i].item(), 4)
label = GENRES[idx].title()
top3.append({"label": label, "confidence": conf})
top_label = top3[0]["label"]
top_confidence = top3[0]["confidence"]
recognised = top_confidence >= 0.25
return {
"recognised": recognised,
"label": top_label if recognised else "Unrecognised Sound",
"closest_match": top_label,
"confidence": top_confidence,
"top3": top3
}
# Spectrogram image generator
def generate_spectrogram_image(audio_path, save_path, title=None):
"""
Generates a styled mel spectrogram image for a given audio stem.
Saves to save_path and returns the path.
Uses the magma colormap β looks great on dark-themed frontends.
"""
try:
y, sr = librosa.load(audio_path, sr = 22050)
mel = librosa.feature.melspectrogram(
y = y,
sr = sr,
n_fft = 1024,
hop_length = 512,
n_mels = 128
)
mel_db = librosa.power_to_db(mel, ref = np.max)
fig, ax = plt.subplots(figsize = (8, 3), facecolor = '#1a1a2e')
ax.set_facecolor('#1a1a2e')
img = librosa.display.specshow(
mel_db,
sr = sr,
hop_length = 512,
x_axis = 'time',
y_axis = 'mel',
cmap = 'magma',
ax = ax
)
cbar = fig.colorbar(img, ax = ax, format = '%+2.0f dB')
cbar.ax.yaxis.set_tick_params(color = 'white')
plt.setp(cbar.ax.yaxis.get_ticklabels(), color = 'white', fontsize = 8)
display_title = title or os.path.basename(audio_path).replace('.wav', '').title()
ax.set_title(display_title, color = 'white', fontsize = 12, fontweight = 'bold', pad = 8)
ax.tick_params(colors = 'white', labelsize = 8)
ax.xaxis.label.set_color('white')
ax.yaxis.label.set_color('white')
for spine in ax.spines.values():
spine.set_edgecolor('#444444')
plt.tight_layout()
os.makedirs(os.path.dirname(save_path) if os.path.dirname(save_path) else '.', exist_ok = True)
plt.savefig(save_path, dpi = 120, bbox_inches = 'tight', facecolor = '#1a1a2e')
plt.close(fig)
return save_path
except Exception as e:
print(f"Spectrogram generation failed for {audio_path}: {e}")
plt.close('all')
return None |