Views
No views yet
1import torchaudio
2import torch
3import soundfile as sf
4import numpy as np
5from transformers import AutoModel
6
7model_id = "worstchan/EAT-base_epoch30_finetune_AS2M"
8model = AutoModel.from_pretrained(model_id, trust_remote_code=True).eval().cuda()
9
10source_file = "/path/to/input.wav"
11target_file = "/path/to/output.npy"
12target_length = 1024 # Recommended: 1024 for 10s audio
13norm_mean = -4.268
14norm_std = 4.569
15
16# Load and resample audio
17wav, sr = sf.read(source_file)
18waveform = torch.tensor(wav).float().cuda()
19if sr != 16000:
20 waveform = torchaudio.functional.resample(waveform, sr, 16000)
21
22# Normalize and convert to mel-spectrogram
23waveform = waveform - waveform.mean()
24mel = torchaudio.compliance.kaldi.fbank(
25 waveform.unsqueeze(0),
26 htk_compat=True,
27 sample_frequency=16000,
28 use_energy=False,
29 window_type='hanning',
30 num_mel_bins=128,
31 dither=0.0,
32 frame_shift=10
33).unsqueeze(0)
34
35# Pad or truncate
36n_frames = mel.shape[1]
37if n_frames < target_length:
38 mel = torch.nn.ZeroPad2d((0, 0, 0, target_length - n_frames))(mel)
39else:
40 mel = mel[:, :target_length, :]
41
42# Normalize
43mel = (mel - norm_mean) / (norm_std * 2)
44mel = mel.unsqueeze(0).cuda() # shape: [1, 1, T, F]
45
46# Extract features
47with torch.no_grad():
48 feat = model.extract_features(mel)
49
50feat = feat.squeeze(0).cpu().numpy()
51np.save(target_file, feat)
52print(f"Feature shape: {feat.shape}")
53print(f"Saved to: {target_file}")1@article{chen2024eat,
2 title={EAT: Self-supervised pre-training with efficient audio transformer},
3 author={Chen, Wenxi and Liang, Yuzhe and Ma, Ziyang and Zheng, Zhisheng and Chen, Xie},
4 journal={arXiv preprint arXiv:2401.03497},
5 year={2024}
6}