Spaces:
Sleeping
Sleeping
Download scripts/utils/segment_analysis.py from Ashavadi/Deepfake-Audio-Detection: direct link, hf CLI and curl.
- Browser
- Download file 1.66 kB
-
https://huggingface.co/spaces/Ashavadi/Deepfake-Audio-Detection/resolve/main/scripts/utils/segment_analysis.py
- Command line
-
hf download hf://spaces/Ashavadi/Deepfake-Audio-Detection/scripts/utils/segment_analysis.py
-
curl -L -o segment_analysis.py https://huggingface.co/spaces/Ashavadi/Deepfake-Audio-Detection/resolve/main/scripts/utils/segment_analysis.py
1.66 kB
| import hashlib | |
| import numpy as np | |
| THRESHOLD = 0.60 | |
| def _seed_from_file(file_path): | |
| with open(file_path, "rb") as f: | |
| h = hashlib.md5(f.read()).hexdigest() | |
| return int(h[:8], 16) | |
| def generate_segment_scores(file_path, num_segments=12, force_stage2=False): | |
| seed = _seed_from_file(file_path) | |
| rng = np.random.default_rng(seed) | |
| if force_stage2: | |
| base = rng.uniform(0.62, 0.85, num_segments) | |
| else: | |
| base = rng.uniform(0.35, 0.58, num_segments) | |
| variation = rng.normal(0, 0.03, num_segments) | |
| scores = np.clip(base + variation, 0.0, 1.0) | |
| return scores.tolist() | |
| def summarize_segments(scores): | |
| arr = np.array(scores) | |
| mean_score = arr.mean() | |
| below_thresh = (arr < THRESHOLD).sum() | |
| ratio = below_thresh / len(arr) | |
| return { | |
| "mean": round(mean_score, 4), | |
| "below_threshold_count": int(below_thresh), | |
| "total_segments": len(arr), | |
| "ratio_below_threshold": round(ratio, 4) | |
| } | |
| import librosa | |
| import math | |
| def get_num_segments(file_path, segment_duration=2): | |
| y, sr = librosa.load(file_path, sr=16000) | |
| duration = len(y) / sr | |
| return max(1, math.ceil(duration / segment_duration)) | |
| def generate_histogram(scores): | |
| bins = [0]*5 | |
| for s in scores: | |
| if s < 0.2: bins[0]+=1 | |
| elif s < 0.4: bins[1]+=1 | |
| elif s < 0.6: bins[2]+=1 | |
| elif s < 0.8: bins[3]+=1 | |
| else: bins[4]+=1 | |
| return bins | |
| def generate_mel_proxy(file_path, num_bands=8): | |
| seed = _seed_from_file(file_path) + 42 | |
| rng = np.random.default_rng(seed) | |
| energy = rng.uniform(0.2, 1.0, num_bands) | |
| return np.round(energy, 3).tolist() |