varunkul commited on
Commit
7c3374a
·
verified ·
1 Parent(s): f993cdb

Upload calibrate_threshold_wav2vec.py

Browse files
scripts/calibrate_threshold_wav2vec.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, argparse, numpy as np
2
+ from glob import glob
3
+
4
+ try: from app.inference_wav2vec import Detector
5
+ except ImportError: from inference_wav2vec import Detector
6
+
7
+ def collect(root):
8
+ H = sorted(glob(os.path.join(root, "human", "*.wav")))
9
+ A = sorted(glob(os.path.join(root, "ai", "*.wav")))
10
+ return H, A
11
+
12
+ def main(a):
13
+ det = Detector(weights_path=a.weights)
14
+ H, A = collect(a.root)
15
+ ys, ps_mic, ps_up = [], [], []
16
+ for p in H:
17
+ ys.append(0)
18
+ ps_mic.append(det.predict_proba(p, source_hint="microphone")["ai"])
19
+ ps_up.append(det.predict_proba(p, source_hint="upload")["ai"])
20
+ for p in A:
21
+ ys.append(1)
22
+ ps_mic.append(det.predict_proba(p, source_hint="microphone")["ai"])
23
+ ps_up.append(det.predict_proba(p, source_hint="upload")["ai"])
24
+ ys = np.array(ys); ps_mic = np.array(ps_mic); ps_up = np.array(ps_up)
25
+
26
+ def sweep(ps):
27
+ best = (0.5, -1, 1e9)
28
+ for thr in np.linspace(0.5, 0.8, 61):
29
+ pred = (ps >= thr).astype(int)
30
+ tp = ((pred==1)&(ys==1)).sum(); fp = ((pred==1)&(ys==0)).sum()
31
+ fn = ((pred==0)&(ys==1)).sum()
32
+ prec = tp / max(tp+fp,1); rec = tp / max(tp+fn,1)
33
+ f1 = 2*prec*rec / max(prec+rec,1e-9)
34
+ if (f1 > best[1]) or (f1==best[1] and fp < best[2]):
35
+ best = (float(thr), float(f1), int(fp))
36
+ return best
37
+
38
+ mt, mf1, mfp = sweep(ps_mic)
39
+ ut, uf1, ufp = sweep(ps_up)
40
+ print(f"MIC threshold ~ {mt:.2f} (F1={mf1:.3f}, human_as_ai={mfp})")
41
+ print(f"UPLOAD threshold ~ {ut:.2f} (F1={uf1:.3f}, human_as_ai={ufp})")
42
+ print("Set:")
43
+ print(f' $env:DETECTOR_MIC_THRESHOLD="{mt:.2f}"')
44
+ print(f' $env:DETECTOR_UPLOAD_THRESHOLD="{ut:.2f}"')
45
+
46
+ if __name__ == "__main__":
47
+ ap = argparse.ArgumentParser()
48
+ ap.add_argument("--root", required=True, help="folder with human/ and ai/")
49
+ ap.add_argument("--weights", default="app/models/weights/wav2vec2_classifier.pth")
50
+ main(ap.parse_args())