#!/usr/bin/env python3 """Cache per-10ms frame logit differences (keyword - other) of a causal model on long audio files. python fa_cache.py CKPT TAG LIST.txt [workers] -> CACHE/TAG/.npy (float32) Any average length N / threshold / union can then be scored from the cache (fa_score.py).""" import os, subprocess, sys from concurrent.futures import ProcessPoolExecutor from multiprocessing import get_context from pathlib import Path import numpy as np sys.path.insert(0, "/home/user/Downloads/vita-kws/plans_local"); sys.path.insert(0, "/home/user/Downloads/vita-kws/src") CACHE = Path("/data/ext/vita_fa2/cache") CK, TAG, LST = sys.argv[1], sys.argv[2], sys.argv[3]; W = int(sys.argv[4]) if len(sys.argv) > 4 else 5 M = {} def init(): import torch; torch.set_num_threads(1) from bench_stream import StreamScorer; M["s"] = StreamScorer(CK) def job(path): from bench_stream import logmel_numpy out = CACHE / TAG / (Path(path).stem + ".npy") if out.exists(): return path, "skip" raw = subprocess.run(["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", "1", "-ar", "16000", "-"], capture_output=True).stdout w = np.frombuffer(raw, dtype=np.float32) if len(w) < 32000: return path, "short" d = [] S = 16000 * 600 # 10-min blocks with 3 s causal context so memory stays small for s in range(0, len(w), S): a = max(0, s - 48000); mel = logmel_numpy(w[a:s + S], M["s"].feat) L = M["s"].frame_logits(mel); x = (L[1] - L[0]).astype(np.float32) d.append(x[(s - a) // 160:] if s else x) np.save(out, np.concatenate(d)); return path, f"{len(w)/57600000:.2f}h" if __name__ == "__main__": (CACHE / TAG).mkdir(parents=True, exist_ok=True) files = [x.strip() for x in open(LST) if x.strip()] with ProcessPoolExecutor(W, mp_context=get_context("fork"), initializer=init) as ex: for p, s in ex.map(job, files): print(TAG, Path(p).name, s, flush=True) print("CACHE DONE", TAG, flush=True)