Datasets:
File size: 1,571 Bytes
7032ae4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | """
Standalone example: turn a raw audio file into a HuBERT discrete-unit
sequence, using only the two model folders in this repo.
Usage:
python extract_units.py path/to/audio.wav
Requirements:
pip install transformers torchaudio joblib numpy
"""
import sys
import numpy as np
import torch
import torchaudio
import joblib
from transformers import AutoModel
TARGET_SR = 16000
LAYER = 6 # must match the layer this repo's k-means model was fit on -- see unit-discovery-model/config.txt
def load_hubert(checkpoint_dir):
model = AutoModel.from_pretrained(checkpoint_dir)
model.eval()
return model
def extract_features(model, wav_path, layer):
waveform, sr = torchaudio.load(wav_path)
if waveform.shape[0] > 1:
waveform = waveform.mean(dim=0, keepdim=True)
if sr != TARGET_SR:
waveform = torchaudio.functional.resample(waveform, sr, TARGET_SR)
with torch.no_grad():
out = model(waveform, output_hidden_states=True)
feats = out.hidden_states[layer].squeeze(0).numpy()
return feats
def dedup(sequence):
out = []
for x in sequence:
if not out or out[-1] != x:
out.append(x)
return out
if __name__ == "__main__":
audio_path = sys.argv[1]
hubert_model = load_hubert("../hubert-model")
km = joblib.load("../unit-discovery-model/kmeans.joblib")
feats = extract_features(hubert_model, audio_path, LAYER)
unit_ids = km.predict(feats).tolist()
deduped = dedup(unit_ids)
print("Raw units: ", unit_ids)
print("Deduped units:", deduped)
|