Tachiwin-Audio-ID / inference.py
Luis J Camargo
docs: rewrite the model card, add Spanish version, rename to Tachiwin-Audio-ID
1edf2f7
Raw History Blame Contribute Delete
4.14 kB
"""Tachiwin spoken-language ID: inference.
from inference import TachiwinLID
lid = TachiwinLID("tachiwin/Tachiwin-Audio-ID") # HF repo id or a local folder
print(lid.predict("audio.wav", top_k=5))
The architecture/feature front-end come from the SpeechBrain base model named in config.json;
the fine-tuned weights come from model.safetensors.
"""
import json, os, sys
import numpy as np
import soundfile as sf
import torch
import torch.nn.functional as F
import torchaudio
from huggingface_hub import snapshot_download
from safetensors.torch import load_file
try:
from speechbrain.inference.classifiers import EncoderClassifier
except ImportError:
from speechbrain.pretrained import EncoderClassifier
class TachiwinLID:
def __init__(self, repo_or_path, device=None, token=None):
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
path = repo_or_path if os.path.isdir(repo_or_path) else snapshot_download(repo_or_path, token=token)
self.cfg = json.load(open(os.path.join(path, "config.json")))
labels = json.load(open(os.path.join(path, "labels.json")))
self.classes, self.info = labels["classes"], labels["info"]
base_dir = snapshot_download(self.cfg["base_model"], token=token)
cache = os.path.join(os.path.expanduser("~"), ".cache", "tachiwin_lid", "base")
self.lid = EncoderClassifier.from_hparams(source=base_dir, savedir=cache, run_opts={"device": self.device})
self.lid.mods.eval()
self.emb = self.lid.mods.embedding_model
sd = load_file(os.path.join(path, "model.safetensors"))
self.emb.load_state_dict({k[4:]: v for k, v in sd.items() if k.startswith("emb.")})
self.emb.to(self.device).eval()
self.head_w = F.normalize(sd["head.weight"].float(), dim=-1).to(self.device)
def _load(self, audio, sr=None):
if isinstance(audio, (str, os.PathLike)):
data, sr = sf.read(audio, dtype="float32", always_2d=False)
else:
data = np.asarray(audio, dtype=np.float32)
if data.ndim == 2:
data = data.mean(axis=1)
w = torch.from_numpy(np.nan_to_num(data))
target = self.cfg["sample_rate"]
if sr is not None and sr != target:
w = torchaudio.functional.resample(w, sr, target)
return w
@torch.no_grad()
def _cos_logits(self, wavs):
lens = torch.tensor([w.numel() for w in wavs])
m = int(lens.max())
x = torch.zeros(len(wavs), m)
for i, w in enumerate(wavs):
x[i, : w.numel()] = w
x, rel = x.to(self.device), (lens.float() / m).to(self.device)
feats = self.lid.mods.mean_var_norm(self.lid.mods.compute_features(x), rel)
emb = self.emb(feats, rel).squeeze(1)
return self.cfg["scale"] * F.linear(F.normalize(emb, dim=-1), self.head_w)
@torch.no_grad()
def predict(self, audio, top_k=5, sr=None):
"""audio: file path or 1-D float array (give `sr` for arrays that are not 16 kHz)."""
w = self._load(audio, sr)
sr_ = self.cfg["sample_rate"]
win, hop = int(self.cfg["window_sec"] * sr_), int(self.cfg["hop_sec"] * sr_)
w = F.pad(w, (0, max(0, int(0.5 * sr_) - w.numel())))
if w.numel() <= int(self.cfg["eval_max_sec"] * sr_):
chunks = [w]
else:
starts = list(range(0, w.numel() - win + 1, hop))
if starts[-1] + win < w.numel():
starts.append(w.numel() - win)
chunks = [w[s:s + win] for s in starts]
logits = self._cos_logits(chunks)
logp = F.log_softmax(logits / self.cfg["temperature"], dim=-1).mean(0)
probs = F.softmax(logp, dim=-1)
p, i = probs.topk(min(top_k, probs.numel()))
return [{"code": self.classes[j], "prob": float(pp), **self.info[self.classes[j]]} for pp, j in zip(p.cpu(), i.cpu())]
if __name__ == "__main__":
repo, wav = sys.argv[1], sys.argv[2]
for r in TachiwinLID(repo).predict(wav):
print(f"{r['prob']:.3f} {r['code']} {r['language']} ({r['superlanguage']} / {r['family']})")