| """ |
| 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 |
|
|
|
|
| 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) |
|
|