Upload pipeline.py with huggingface_hub
Browse files- pipeline.py +30 -3
pipeline.py
CHANGED
|
@@ -1,5 +1,32 @@
|
|
| 1 |
-
import torch
|
|
|
|
|
|
|
| 2 |
|
| 3 |
class BioacousticEngine:
|
| 4 |
-
def __init__(self):
|
| 5 |
-
self.device = "cpu"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, sys, torch, joblib, importlib
|
| 2 |
+
import pandas as pd
|
| 3 |
+
import torchaudio.transforms as T
|
| 4 |
|
| 5 |
class BioacousticEngine:
|
| 6 |
+
def __init__(self, repo_dir="tiny-bird-diffusion"):
|
| 7 |
+
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 8 |
+
self.repo_dir = repo_dir
|
| 9 |
+
sys.path.append(os.path.abspath(repo_dir))
|
| 10 |
+
from cvt import cvt13
|
| 11 |
+
mel_module = importlib.import_module("mel_spectrogram")
|
| 12 |
+
self.preprocessor = mel_module.MelSpectrogramProcessor(device=self.device)
|
| 13 |
+
self.model = cvt13()
|
| 14 |
+
self.model.load_state_dict(torch.load(f"{repo_dir}/protoclr.pth", map_location="cpu"))
|
| 15 |
+
self.model = self.model.to(self.device).eval()
|
| 16 |
+
brain_data = joblib.load(f"{repo_dir}/trained_cluster_brain.joblib")
|
| 17 |
+
self.reducer = brain_data['umap']
|
| 18 |
+
self.df = pd.read_csv(f"{repo_dir}/acoustic_atlas_metadata.csv")
|
| 19 |
+
|
| 20 |
+
def process_waveform(self, waveform, sample_rate):
|
| 21 |
+
if sample_rate != 16000: waveform = T.Resample(orig_freq=sample_rate, new_freq=16000)(waveform)
|
| 22 |
+
if waveform.shape[0] > 1: waveform = torch.mean(waveform, dim=0, keepdim=True)
|
| 23 |
+
total_samples = waveform.shape[-1]
|
| 24 |
+
target_samples = 3 * 16000
|
| 25 |
+
if total_samples > target_samples:
|
| 26 |
+
step, max_energy, best_start = 4000, -1, 0
|
| 27 |
+
for start in range(0, total_samples - target_samples + 1, step):
|
| 28 |
+
energy = waveform[:, start:start + target_samples].abs().mean().item()
|
| 29 |
+
if energy > max_energy: max_energy, best_start = energy, start
|
| 30 |
+
waveform = waveform[:, best_start:best_start + target_samples]
|
| 31 |
+
if waveform.abs().max() > 0.02: waveform = waveform / waveform.abs().max()
|
| 32 |
+
return waveform.to(self.device)
|