Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[cli] paraformer support batch infer #2648

Merged
merged 2 commits into from
Oct 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
101 changes: 64 additions & 37 deletions wenet/cli/paraformer_model.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
import io
import os
from typing import Dict, List, Union

import torch
import torchaudio
import torchaudio.compliance.kaldi as kaldi

from wenet.cli.hub import Hub
from wenet.paraformer.search import (gen_timestamps_from_peak,
paraformer_greedy_search)
from wenet.text.paraformer_tokenizer import ParaformerTokenizer
from wenet.utils.common import TORCH_NPU_AVAILABLE # noqa just ensure to check torch-npu


class Paraformer:
Expand All @@ -22,46 +22,73 @@ def __init__(self, model_dir: str, resample_rate: int = 16000) -> None:
self.device = torch.device("cpu")
self.tokenizer = ParaformerTokenizer(symbol_table=units_path)

def transcribe(self, audio_file: str, tokens_info: bool = False) -> dict:
waveform, sample_rate = torchaudio.load(audio_file, normalize=False)
waveform = waveform.to(torch.float).to(self.device)
if sample_rate != self.resample_rate:
waveform = torchaudio.transforms.Resample(
orig_freq=sample_rate, new_freq=self.resample_rate)(waveform)
feats = kaldi.fbank(waveform,
num_mel_bins=80,
frame_length=25,
frame_shift=10,
energy_floor=0.0,
sample_frequency=self.resample_rate,
window_type="hamming")
feats = feats.unsqueeze(0)
feats_lens = torch.tensor([feats.size(1)],
dtype=torch.int64,
device=feats.device)
@torch.inference_mode()
def transcribe_batch(self,
audio_files: List[Union[str, bytes]],
tokens_info: bool = False) -> List[Dict]:
feats_lst = []
feats_lens_lst = []
for audio in audio_files:
if isinstance(audio, bytes):
with io.BytesIO(audio) as fobj:
waveform, sample_rate = torchaudio.load(fobj,
normalize=False)
else:
waveform, sample_rate = torchaudio.load(audio, normalize=False)
if sample_rate != self.resample_rate:
waveform = torchaudio.transforms.Resample(
orig_freq=sample_rate,
new_freq=self.resample_rate)(waveform)

waveform = waveform.to(torch.float)
feats = kaldi.fbank(waveform,
num_mel_bins=80,
frame_length=25,
frame_shift=10,
energy_floor=0.0,
sample_frequency=self.resample_rate,
window_type="hamming")
feats_lst.append(feats)
feats_lens_lst.append(
torch.tensor(feats.shape[0], dtype=torch.int64))
feats_tensor = torch.nn.utils.rnn.pad_sequence(
feats_lst, batch_first=True).to(device=self.device)
feats_lens_tensor = torch.tensor(feats_lens_lst, device=self.device)

decoder_out, token_num, tp_alphas = self.model.forward_paraformer(
feats, feats_lens)
feats_tensor, feats_lens_tensor)
cif_peaks = self.model.forward_cif_peaks(tp_alphas, token_num)
res = paraformer_greedy_search(decoder_out, token_num, cif_peaks)[0]
result = {}
result['confidence'] = res.confidence
result['text'] = self.tokenizer.detokenize(res.tokens)[0]
if tokens_info:
tokens_info = []
times = gen_timestamps_from_peak(res.times,
num_frames=tp_alphas.size(1),
frame_rate=0.02)

for i, x in enumerate(res.tokens):
tokens_info.append({
'token': self.tokenizer.char_dict[x],
'start': round(times[i][0], 3),
'end': round(times[i][1], 3),
'confidence': round(res.tokens_confidence[i], 2)
})
result['tokens'] = tokens_info
results = paraformer_greedy_search(decoder_out, token_num, cif_peaks)

r = []
for res in results:
result = {}
result['confidence'] = res.confidence
result['text'] = self.tokenizer.detokenize(res.tokens)[0]
if tokens_info:
tokens_info_l = []
times = gen_timestamps_from_peak(res.times,
num_frames=tp_alphas.size(1),
frame_rate=0.02)

for i, x in enumerate(res.tokens):
tokens_info_l.append({
'token':
self.tokenizer.char_dict[x],
'start':
round(times[i][0], 3),
'end':
round(times[i][1], 3),
'confidence':
round(res.tokens_confidence[i], 2)
})
result['tokens'] = tokens_info_l
r.append(result)
return r

def transcribe(self, audio_file: str, tokens_info: bool = False) -> dict:
result = self.transcribe_batch([audio_file], tokens_info)[0]
return result

def align(self, audio_file: str, label: str) -> dict:
Expand Down
Loading