sukriramli commited on
Commit
5fcc49e
·
verified ·
1 Parent(s): 149dda1

Upload api.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. api.py +47 -0
api.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, io, torchaudio
2
+ import numpy as np
3
+ from pipeline import BioacousticEngine
4
+
5
+ engine = None
6
+
7
+ def get_engine():
8
+ global engine
9
+ if engine is None:
10
+ engine = BioacousticEngine()
11
+ return engine
12
+
13
+ def predict_bird(audio_bytes, distance_threshold=0.8):
14
+ """Clean API Endpoint mapping raw bytes directly to spatial taxonomy clusters."""
15
+ try:
16
+ ae = get_engine()
17
+ waveform, sample_rate = torchaudio.load(io.BytesIO(audio_bytes))
18
+ processed_wave = ae.process_waveform(waveform, sample_rate)
19
+
20
+ with torch.no_grad():
21
+ mel_spec = ae.preprocessor.process(processed_wave).unsqueeze(0)
22
+ mel_spec = mel_spec[:, :, :, :184] if mel_spec.shape[-1] >= 184 else torch.nn.functional.pad(mel_spec, (0, 184 - mel_spec.shape[-1]))
23
+ embedding = ae.model(mel_spec).cpu().numpy().flatten().reshape(1, -1)
24
+
25
+ coords = ae.reducer.transform(embedding)
26
+ x, y = coords[0][0], coords[0][1]
27
+
28
+ valid_df = ae.df[ae.df['Cluster_ID'] != -1].copy()
29
+ distances = np.sqrt((valid_df['UMAP_X'] - x)**2 + (valid_df['UMAP_Y'] - y)**2)
30
+ min_dist = distances.min()
31
+
32
+ if min_dist > distance_threshold:
33
+ return {"status": "NO_BIRD_DETECTED", "x": float(x), "y": float(y), "distance": float(min_dist)}
34
+
35
+ match_row = valid_df.loc[distances.idxmin()]
36
+ confidence = max(0.0, (distance_threshold - min_dist) / distance_threshold) * 100
37
+
38
+ return {
39
+ "status": "SUCCESS",
40
+ "species": match_row['Target_Bird'].upper(),
41
+ "confidence": round(confidence, 2),
42
+ "x": float(x),
43
+ "y": float(y),
44
+ "anchor_id": match_row['File_ID']
45
+ }
46
+ except Exception as e:
47
+ return {"status": "ERROR", "message": str(f"Pipeline failure: {e}")}