| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327 |
- # Copyright (c) Alibaba, Inc. and its affiliates.
- import os
- import struct
- from typing import Any, Dict, List, Union
- import librosa
- import numpy as np
- import pkg_resources
- from modelscope.utils.logger import get_logger
- logger = get_logger()
- green_color = '\033[1;32m'
- red_color = '\033[0;31;40m'
- yellow_color = '\033[0;33;40m'
- end_color = '\033[0m'
- global_asr_language = 'zh-cn'
- def get_version():
- return float(pkg_resources.get_distribution('easyasr').version)
- def sample_rate_checking(audio_in: Union[str, bytes], audio_format: str):
- r_audio_fs = None
- if audio_format == 'wav':
- r_audio_fs = get_sr_from_wav(audio_in)
- elif audio_format == 'pcm' and isinstance(audio_in, bytes):
- r_audio_fs = get_sr_from_bytes(audio_in)
- return r_audio_fs
- def type_checking(audio_in: Union[str, bytes],
- audio_fs: int = None,
- recog_type: str = None,
- audio_format: str = None):
- r_recog_type = recog_type
- r_audio_format = audio_format
- r_wav_path = audio_in
- if isinstance(audio_in, str):
- assert os.path.exists(audio_in), f'wav_path:{audio_in} does not exist'
- elif isinstance(audio_in, bytes):
- assert len(audio_in) > 0, 'audio in is empty'
- r_audio_format = 'pcm'
- r_recog_type = 'wav'
- if r_recog_type is None:
- # audio_in is wav, recog_type is wav_file
- if os.path.isfile(audio_in):
- if audio_in.endswith('.wav') or audio_in.endswith('.WAV'):
- r_recog_type = 'wav'
- r_audio_format = 'wav'
- # recog_type is datasets_file
- elif os.path.isdir(audio_in):
- dir_name = os.path.basename(audio_in)
- if 'test' in dir_name:
- r_recog_type = 'test'
- elif 'dev' in dir_name:
- r_recog_type = 'dev'
- elif 'train' in dir_name:
- r_recog_type = 'train'
- if r_audio_format is None:
- if find_file_by_ends(audio_in, '.ark'):
- r_audio_format = 'kaldi_ark'
- elif find_file_by_ends(audio_in, '.wav') or find_file_by_ends(
- audio_in, '.WAV'):
- r_audio_format = 'wav'
- elif find_file_by_ends(audio_in, '.records'):
- r_audio_format = 'tfrecord'
- if r_audio_format == 'kaldi_ark' and r_recog_type != 'wav':
- # datasets with kaldi_ark file
- r_wav_path = os.path.abspath(os.path.join(r_wav_path, '../'))
- elif r_audio_format == 'tfrecord' and r_recog_type != 'wav':
- # datasets with tensorflow records file
- r_wav_path = os.path.abspath(os.path.join(r_wav_path, '../'))
- elif r_audio_format == 'wav' and r_recog_type != 'wav':
- # datasets with waveform files
- r_wav_path = os.path.abspath(os.path.join(r_wav_path, '../../'))
- return r_recog_type, r_audio_format, r_wav_path
- def get_sr_from_bytes(wav: bytes):
- sr = None
- data = wav
- if len(data) > 44:
- try:
- header_fields = {}
- header_fields['ChunkID'] = str(data[0:4], 'UTF-8')
- header_fields['Format'] = str(data[8:12], 'UTF-8')
- header_fields['Subchunk1ID'] = str(data[12:16], 'UTF-8')
- if header_fields['ChunkID'] == 'RIFF' and header_fields[
- 'Format'] == 'WAVE' and header_fields[
- 'Subchunk1ID'] == 'fmt ':
- header_fields['SampleRate'] = struct.unpack('<I',
- data[24:28])[0]
- sr = header_fields['SampleRate']
- except Exception:
- # no treatment
- pass
- else:
- logger.warn('audio bytes is ' + str(len(data)) + ' is invalid.')
- return sr
- def get_sr_from_wav(fname: str):
- fs = None
- if os.path.isfile(fname):
- audio, fs = librosa.load(fname, sr=None)
- return fs
- elif os.path.isdir(fname):
- dir_files = os.listdir(fname)
- for file in dir_files:
- file_path = os.path.join(fname, file)
- if os.path.isfile(file_path):
- if file_path.endswith('.wav') or file_path.endswith('.WAV'):
- fs = get_sr_from_wav(file_path)
- elif os.path.isdir(file_path):
- fs = get_sr_from_wav(file_path)
- if fs is not None:
- break
- return fs
- def find_file_by_ends(dir_path: str, ends: str):
- dir_files = os.listdir(dir_path)
- for file in dir_files:
- file_path = os.path.join(dir_path, file)
- if os.path.isfile(file_path):
- if file_path.endswith(ends):
- return True
- elif os.path.isdir(file_path):
- if find_file_by_ends(file_path, ends):
- return True
- return False
- def recursion_dir_all_wav(wav_list, dir_path: str) -> List[str]:
- dir_files = os.listdir(dir_path)
- for file in dir_files:
- file_path = os.path.join(dir_path, file)
- if os.path.isfile(file_path):
- if file_path.endswith('.wav') or file_path.endswith('.WAV'):
- wav_list.append(file_path)
- elif os.path.isdir(file_path):
- recursion_dir_all_wav(wav_list, file_path)
- return wav_list
- def set_parameters(language: str = None):
- if language is not None:
- global global_asr_language
- global_asr_language = language
- def compute_wer(hyp_list: List[Any],
- ref_list: List[Any],
- lang: str = None) -> Dict[str, Any]:
- assert len(hyp_list) > 0, 'hyp list is empty'
- assert len(ref_list) > 0, 'ref list is empty'
- if lang is not None:
- global global_asr_language
- global_asr_language = lang
- rst = {
- 'Wrd': 0,
- 'Corr': 0,
- 'Ins': 0,
- 'Del': 0,
- 'Sub': 0,
- 'Snt': 0,
- 'Err': 0.0,
- 'S.Err': 0.0,
- 'wrong_words': 0,
- 'wrong_sentences': 0
- }
- for h_item in hyp_list:
- for r_item in ref_list:
- if h_item['key'] == r_item['key']:
- out_item = compute_wer_by_line(h_item['value'],
- r_item['value'],
- global_asr_language)
- rst['Wrd'] += out_item['nwords']
- rst['Corr'] += out_item['cor']
- rst['wrong_words'] += out_item['wrong']
- rst['Ins'] += out_item['ins']
- rst['Del'] += out_item['del']
- rst['Sub'] += out_item['sub']
- rst['Snt'] += 1
- if out_item['wrong'] > 0:
- rst['wrong_sentences'] += 1
- print_wrong_sentence(key=h_item['key'],
- hyp=h_item['value'],
- ref=r_item['value'])
- else:
- print_correct_sentence(key=h_item['key'],
- hyp=h_item['value'],
- ref=r_item['value'])
- break
- if rst['Wrd'] > 0:
- rst['Err'] = round(rst['wrong_words'] * 100 / rst['Wrd'], 2)
- if rst['Snt'] > 0:
- rst['S.Err'] = round(rst['wrong_sentences'] * 100 / rst['Snt'], 2)
- return rst
- def compute_wer_by_line(hyp: List[str],
- ref: List[str],
- lang: str = 'zh-cn') -> Dict[str, Any]:
- if lang != 'zh-cn':
- hyp = hyp.split()
- ref = ref.split()
- hyp = list(map(lambda x: x.lower(), hyp))
- ref = list(map(lambda x: x.lower(), ref))
- len_hyp = len(hyp)
- len_ref = len(ref)
- cost_matrix = np.zeros((len_hyp + 1, len_ref + 1), dtype=np.int16)
- ops_matrix = np.zeros((len_hyp + 1, len_ref + 1), dtype=np.int8)
- for i in range(len_hyp + 1):
- cost_matrix[i][0] = i
- for j in range(len_ref + 1):
- cost_matrix[0][j] = j
- for i in range(1, len_hyp + 1):
- for j in range(1, len_ref + 1):
- if hyp[i - 1] == ref[j - 1]:
- cost_matrix[i][j] = cost_matrix[i - 1][j - 1]
- else:
- substitution = cost_matrix[i - 1][j - 1] + 1
- insertion = cost_matrix[i - 1][j] + 1
- deletion = cost_matrix[i][j - 1] + 1
- compare_val = [substitution, insertion, deletion]
- min_val = min(compare_val)
- operation_idx = compare_val.index(min_val) + 1
- cost_matrix[i][j] = min_val
- ops_matrix[i][j] = operation_idx
- match_idx = []
- i = len_hyp
- j = len_ref
- rst = {
- 'nwords': len_ref,
- 'cor': 0,
- 'wrong': 0,
- 'ins': 0,
- 'del': 0,
- 'sub': 0
- }
- while i >= 0 or j >= 0:
- i_idx = max(0, i)
- j_idx = max(0, j)
- if ops_matrix[i_idx][j_idx] == 0: # correct
- if i - 1 >= 0 and j - 1 >= 0:
- match_idx.append((j - 1, i - 1))
- rst['cor'] += 1
- i -= 1
- j -= 1
- elif ops_matrix[i_idx][j_idx] == 2: # insert
- i -= 1
- rst['ins'] += 1
- elif ops_matrix[i_idx][j_idx] == 3: # delete
- j -= 1
- rst['del'] += 1
- elif ops_matrix[i_idx][j_idx] == 1: # substitute
- i -= 1
- j -= 1
- rst['sub'] += 1
- if i < 0 and j >= 0:
- rst['del'] += 1
- elif j < 0 and i >= 0:
- rst['ins'] += 1
- match_idx.reverse()
- wrong_cnt = cost_matrix[len_hyp][len_ref]
- rst['wrong'] = wrong_cnt
- return rst
- def print_wrong_sentence(key: str, hyp: str, ref: str):
- space = len(key)
- print(key + yellow_color + ' ref: ' + ref)
- print(' ' * space + red_color + ' hyp: ' + hyp + end_color)
- def print_correct_sentence(key: str, hyp: str, ref: str):
- space = len(key)
- print(key + yellow_color + ' ref: ' + ref)
- print(' ' * space + green_color + ' hyp: ' + hyp + end_color)
- def print_progress(percent):
- if percent > 1:
- percent = 1
- res = int(50 * percent) * '#'
- print('\r[%-50s] %d%%' % (res, int(100 * percent)), end='')
|