#!/usr/bin/env python3 """Like fa_cache.py, but one log-mel pass per file feeds several models, run on the GPU. python fa_cache_multi.py LIST.txt WORKERS CKPT:TAG [CKPT:TAG ...]""" import 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") M = {} def init(pairs): import torch; torch.set_num_threads(2) from bench_stream import StreamScorer for ck, tag in pairs: s = StreamScorer(ck); s.m.cuda(); M[tag] = s def logits(s, mel): import torch with torch.no_grad(): x = torch.from_numpy(mel).float().cuda()[None, None] return s.m.frame_logits(x)[0].float().cpu().numpy() def job(path): from bench_stream import logmel_numpy todo = [t for t in M if not (CACHE / t / (Path(path).stem + ".npy")).exists()] if not todo: 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" out = {t: [] for t in todo}; S = 16000 * 150 for s in range(0, len(w), S): a = max(0, s - 48000); mel = logmel_numpy(w[a:s + S], M[todo[0]].feat) for t in todo: L = logits(M[t], mel); x = (L[1] - L[0]).astype(np.float32); out[t].append(x[(s - a) // 160:] if s else x) for t in todo: np.save(CACHE / t / (Path(path).stem + ".npy"), np.concatenate(out[t])) return path, f"{len(w)/57600000:.2f}h {todo}" if __name__ == "__main__": lst, nw = sys.argv[1], int(sys.argv[2]); pairs = [tuple(x.rsplit(":", 1)) for x in sys.argv[3:]] for _, t in pairs: (CACHE / t).mkdir(parents=True, exist_ok=True) files = [x.strip() for x in open(lst) if x.strip()] with ProcessPoolExecutor(nw, mp_context=get_context("spawn"), initializer=init, initargs=(pairs,)) as ex: for p, s in ex.map(job, files): print(Path(p).name, s, flush=True) print("MULTI DONE", lst, flush=True)