95 lines
3.2 KiB
Python
95 lines
3.2 KiB
Python
import torch
|
|
import torchaudio
|
|
import torch.nn.functional as F
|
|
import soundfile as sf
|
|
import librosa
|
|
from datasets import load_dataset
|
|
from transformers import Wav2Vec2FeatureExtractor, Wav2Vec2Model
|
|
from pathlib import Path
|
|
import numpy as np
|
|
|
|
|
|
LANG_ID = "zh-CN"
|
|
MODEL_ID = "jonatasgrosman/wav2vec2-large-xlsr-53-chinese-zh-cn"
|
|
SAMPLES = 2
|
|
|
|
print("load model ...")
|
|
processor = Wav2Vec2FeatureExtractor.from_pretrained(MODEL_ID)
|
|
# model = Wav2Vec2ForCTC.from_pretrained(MODEL_ID)
|
|
model = Wav2Vec2Model.from_pretrained(MODEL_ID)
|
|
|
|
|
|
# processor = Wav2Vec2Processor.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt")
|
|
# model = Wav2Vec2ForCTC.from_pretrained("ydshieh/wav2vec2-large-xlsr-53-chinese-zh-cn-gpt")
|
|
|
|
# # Preprocessing the datasets.
|
|
# # We need to read the audio files as arrays
|
|
# def speech_file_to_array_fn(batch):
|
|
# speech_array, sampling_rate = librosa.load(batch["path"], sr=16_000)
|
|
# batch["speech"] = speech_array
|
|
# batch["sentence"] = batch["sentence"].upper()
|
|
|
|
# return batch
|
|
|
|
# print("load dataest ...")
|
|
# test_dataset = load_dataset("common_voice", LANG_ID, split=f"test[:{SAMPLES}]")
|
|
# test_dataset = test_dataset.map(speech_file_to_array_fn)
|
|
# inputs = processor(test_dataset["speech"], sampling_rate=16_000, return_tensors="pt", padding=True)
|
|
|
|
|
|
librispeech_samples_ds = load_dataset("patrickvonplaten/librispeech_asr_dummy", "clean", split="validation")
|
|
path_file = librispeech_samples_ds[0]["file"]
|
|
# path_file = '/yrfs/lsen/DATA/LuoXData/processing2/2021-P01/audio/audio_trim.wav'
|
|
# print("file = ", path_file)
|
|
|
|
|
|
# load audio
|
|
# audio_input, sample_rate = sf.read(path_file)
|
|
audio_input, sample_rate = torchaudio.load(path_file)
|
|
if len(audio_input.shape) == 2:
|
|
audio_input = audio_input[0]
|
|
|
|
print(f"audio_input shape = {audio_input.shape}, sr = {sample_rate}, duration = {(len(audio_input)/sample_rate)}")
|
|
|
|
if sample_rate != 16000:
|
|
resampler = torchaudio.transforms.Resample(sample_rate, 16_000)
|
|
audio_input = resampler(audio_input).squeeze().numpy()
|
|
print(f"audio_input shape = {audio_input.shape}, sr = {16000}, duration = {(len(audio_input)/16000)}")
|
|
|
|
|
|
# Preprocessing the datasets.
|
|
# We need to read the aduio files as arrays
|
|
print(f"audio_input shap={audio_input.shape}, dtype={audio_input.dtype}")
|
|
# pad input values and return pt tensor
|
|
inputs = processor(audio_input, sampling_rate=16000, return_tensors="pt")
|
|
|
|
|
|
print("predict ...")
|
|
with torch.no_grad():
|
|
output = model(**inputs)
|
|
|
|
|
|
# print(f"hidden_states = {output.hidden_states}")
|
|
print(f"extract_features = {output.extract_features.shape}")
|
|
print(f"last_hidden_state = {output.last_hidden_state.shape}")
|
|
# print(f"attentions = {output.attentions.shape}")
|
|
|
|
|
|
# print(f"logits shape = {logits.shape}")
|
|
|
|
# logits = F.softmax(logits, dim=-1)
|
|
# print(f"logits reshape = {logits.shape}")
|
|
|
|
# # padding last vector by last (0,0), model (0,1)
|
|
# logits = F.pad(logits, (0,0,0,1), mode='replicate')
|
|
# logits = torch.squeeze(logits)
|
|
# print(f"pad reshape = {logits.shape}")
|
|
|
|
# # convert to numpy
|
|
# logits = logits.cpu().numpy()
|
|
# path_save = Path(path_file).parent.joinpath(f"{Path(path_file).stem}_wav2vec2.npy")
|
|
# np.save(path_save, logits)
|
|
|
|
|
|
|