File size: 9,749 Bytes
198d6d5 0195699 198d6d5 0195699 198d6d5 0195699 198d6d5 0195699 198d6d5 0195699 198d6d5 0195699 198d6d5 0195699 198d6d5 | 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 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | """
Marine1 Underwater Acoustic Classifier - Inference Script
Simple example for using the model with Hugging Face
Supports both .pth (pickle) and .safetensors formats
"""
import torch
import librosa
import numpy as np
from typing import Dict, Tuple
import warnings
warnings.filterwarnings('ignore')
try:
from safetensors.torch import load_file
SAFETENSORS_AVAILABLE = True
except ImportError:
SAFETENSORS_AVAILABLE = False
print("Warning: safetensors not installed. Install with: pip install safetensors")
class Marine1Classifier:
"""Underwater acoustic classifier using Marine1 model"""
def __init__(self, model_path: str, device: str = None):
"""
Initialize the classifier
Args:
model_path: Path to the model file (.pth or .safetensors)
device: Device to run on ('cuda', 'cpu', or 'mps'). Auto-detected if None.
"""
if device is None:
if torch.cuda.is_available():
device = 'cuda'
elif torch.backends.mps.is_available():
device = 'mps'
else:
device = 'cpu'
self.device = torch.device(device)
print(f"Using device: {self.device}")
# Determine file format
is_safetensors = model_path.endswith('.safetensors')
if is_safetensors:
if not SAFETENSORS_AVAILABLE:
raise ImportError("safetensors not installed. Install with: pip install safetensors")
print(f"Loading safetensors model (secure format)...")
# Load safetensors
state_dict = load_file(model_path, device=str(self.device))
# Parse metadata
from safetensors import safe_open
with safe_open(model_path, framework="pt", device=str(self.device)) as f:
metadata = f.metadata()
# Get class mapping from metadata
import ast
self.class_to_id = ast.literal_eval(metadata.get('class_to_id', "{}"))
if not self.class_to_id:
# Default mapping
self.class_to_id = {
'vessel': 0, 'marine_animal': 1,
'natural_sound': 2, 'other_anthropogenic': 3
}
else:
print(f"Loading PyTorch model (.pth format)...")
# Load checkpoint
checkpoint = torch.load(model_path, map_location=self.device, weights_only=False)
# Get class mapping
self.class_to_id = checkpoint['class_to_id']
state_dict = checkpoint['model_state_dict']
self.id_to_class = {v: k for k, v in self.class_to_id.items()}
self.class_names = [self.id_to_class[i] for i in range(len(self.id_to_class))]
# Load model architecture (custom fine-tuned ResNet18)
self.model = self._create_model_architecture(len(self.class_names))
# Load weights
self.model.load_state_dict(state_dict)
self.model.to(self.device)
self.model.eval()
format_type = "safetensors (secure)" if is_safetensors else "PyTorch (.pth)"
print(f"✅ Model loaded successfully ({format_type})")
print(f" Classes: {len(self.class_names)}")
def _create_model_architecture(self, num_classes: int):
"""Create the model architecture matching the trained model"""
import torch.nn as nn
from torchvision import models
class LightweightFineTuned(nn.Module):
def __init__(self, num_classes=4):
super(LightweightFineTuned, self).__init__()
resnet = models.resnet18(weights=None)
# Adapt first layer for grayscale spectrograms
self.conv1 = nn.Conv2d(1, 64, kernel_size=7, stride=2, padding=3, bias=False)
self.bn1 = resnet.bn1
self.relu = resnet.relu
self.maxpool = resnet.maxpool
self.layer1 = resnet.layer1
self.layer2 = resnet.layer2
self.layer3 = resnet.layer3
self.layer4 = resnet.layer4
self.avgpool = resnet.avgpool
self.classifier = nn.Sequential(
nn.Dropout(0.5),
nn.Linear(512, 256),
nn.ReLU(),
nn.Dropout(0.25),
nn.Linear(256, num_classes)
)
self.confidence_head = nn.Sequential(
nn.Linear(512, 1),
nn.Sigmoid()
)
def forward(self, x, return_confidence=False):
if len(x.shape) == 3:
x = x.unsqueeze(1)
x = self.conv1(x)
x = self.bn1(x)
x = self.relu(x)
x = self.maxpool(x)
x = self.layer1(x)
x = self.layer2(x)
x = self.layer3(x)
x = self.layer4(x)
x = self.avgpool(x)
features = torch.flatten(x, 1)
logits = self.classifier(features)
if return_confidence:
confidence = self.confidence_head(features)
return logits, confidence
return logits
return LightweightFineTuned(num_classes=num_classes)
def process_audio(self, audio_path: str, sr: int = 16000, duration: float = 10.0) -> np.ndarray:
"""
Process audio file into mel spectrogram
Args:
audio_path: Path to audio file
sr: Target sample rate
duration: Maximum duration in seconds
Returns:
Log mel spectrogram as numpy array
"""
# Load audio
y, _ = librosa.load(audio_path, sr=sr, duration=duration)
# Pad if too short
target_length = int(sr * duration)
if len(y) < target_length:
y = np.pad(y, (0, target_length - len(y)), mode='constant')
# Create mel spectrogram
mel_spec = librosa.feature.melspectrogram(
y=y,
sr=sr,
n_mels=128,
n_fft=2048,
hop_length=512,
fmax=8000
)
# Convert to log scale
log_mel_spec = librosa.power_to_db(mel_spec, ref=np.max)
return log_mel_spec
def predict(self, audio_path: str) -> Dict[str, any]:
"""
Predict the class of an audio file
Args:
audio_path: Path to audio file
Returns:
Dictionary with prediction results
"""
# Process audio
log_mel_spec = self.process_audio(audio_path)
# Prepare input tensor
input_tensor = torch.FloatTensor(log_mel_spec).unsqueeze(0).unsqueeze(0).to(self.device)
# Predict
with torch.no_grad():
outputs = self.model(input_tensor)
probabilities = torch.nn.functional.softmax(outputs, dim=1)[0]
# Get results
predicted_idx = probabilities.argmax().item()
predicted_class = self.class_names[predicted_idx]
confidence = probabilities[predicted_idx].item()
# Get all class probabilities
all_probs = {
self.class_names[i]: probabilities[i].item()
for i in range(len(self.class_names))
}
return {
'predicted_class': predicted_class,
'confidence': confidence,
'all_probabilities': all_probs,
'predicted_class_id': predicted_idx
}
def predict_batch(self, audio_paths: list) -> list:
"""
Predict classes for multiple audio files
Args:
audio_paths: List of paths to audio files
Returns:
List of prediction dictionaries
"""
results = []
for audio_path in audio_paths:
try:
result = self.predict(audio_path)
result['audio_path'] = audio_path
results.append(result)
except Exception as e:
print(f"Error processing {audio_path}: {e}")
results.append({
'audio_path': audio_path,
'error': str(e)
})
return results
def main():
"""Example usage"""
import sys
if len(sys.argv) < 3:
print("Usage: python inference.py <model_path> <audio_path>")
print("Example: python inference.py best_model_finetuned.pth underwater_sound.wav")
sys.exit(1)
model_path = sys.argv[1]
audio_path = sys.argv[2]
# Initialize classifier
classifier = Marine1Classifier(model_path)
# Make prediction
print(f"\nProcessing: {audio_path}")
result = classifier.predict(audio_path)
# Display results
print(f"\n{'='*50}")
print(f"Prediction: {result['predicted_class'].replace('_', ' ').title()}")
print(f"Confidence: {result['confidence']*100:.2f}%")
print(f"\nAll Probabilities:")
for class_name, prob in sorted(result['all_probabilities'].items(), key=lambda x: x[1], reverse=True):
print(f" {class_name.replace('_', ' ').title():25s}: {prob*100:6.2f}%")
print(f"{'='*50}\n")
if __name__ == "__main__":
main()
|