sukriramli commited on
Commit
a258719
·
verified ·
1 Parent(s): bb29705

Upload api.py with huggingface_hub

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