Merge pull request #1740 from zh794390558/fix

[speechx] fix nnet input and output name
pull/1743/head
Hui Zhang 3 years ago committed by GitHub
commit fe8a14dd50
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -12,6 +12,8 @@ exclude =
.git, .git,
# python cache # python cache
__pycache__, __pycache__,
# third party
utils/compute-wer.py,
third_party/, third_party/,
# Provide a comma-separate list of glob patterns to include for checks. # Provide a comma-separate list of glob patterns to include for checks.
filename = filename =

@ -40,6 +40,7 @@ from paddlespeech.s2t.utils.utility import UpdateConfig
__all__ = ['ASRExecutor'] __all__ = ['ASRExecutor']
@cli_register( @cli_register(
name='paddlespeech.asr', description='Speech to text infer command.') name='paddlespeech.asr', description='Speech to text infer command.')
class ASRExecutor(BaseExecutor): class ASRExecutor(BaseExecutor):
@ -278,7 +279,8 @@ class ASRExecutor(BaseExecutor):
self._outputs["result"] = result_transcripts[0] self._outputs["result"] = result_transcripts[0]
elif "conformer" in model_type or "transformer" in model_type: elif "conformer" in model_type or "transformer" in model_type:
logger.info(f"we will use the transformer like model : {model_type}") logger.info(
f"we will use the transformer like model : {model_type}")
try: try:
result_transcripts = self.model.decode( result_transcripts = self.model.decode(
audio, audio,

@ -12,7 +12,9 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
from collections import defaultdict from collections import defaultdict
import paddle import paddle
from paddlespeech.cli.log import logger from paddlespeech.cli.log import logger
from paddlespeech.s2t.utils.utility import log_add from paddlespeech.s2t.utils.utility import log_add

@ -20,11 +20,11 @@ A few sklearn functions are modified in this script as per requirement.
import argparse import argparse
import copy import copy
import warnings import warnings
from distutils.util import strtobool
import numpy as np import numpy as np
import scipy import scipy
import sklearn import sklearn
from distutils.util import strtobool
from scipy import linalg from scipy import linalg
from scipy import sparse from scipy import sparse
from scipy.sparse.csgraph import connected_components from scipy.sparse.csgraph import connected_components

@ -34,10 +34,12 @@ DEFINE_int32(receptive_field_length,
DEFINE_int32(downsampling_rate, DEFINE_int32(downsampling_rate,
4, 4,
"two CNN(kernel=5) module downsampling rate."); "two CNN(kernel=5) module downsampling rate.");
DEFINE_string(
model_input_names,
"audio_chunk,audio_chunk_lens,chunk_state_h_box,chunk_state_c_box",
"model input names");
DEFINE_string(model_output_names, DEFINE_string(model_output_names,
"save_infer_model/scale_0.tmp_1,save_infer_model/" "softmax_0.tmp_0,tmp_5,concat_0.tmp_0,concat_1.tmp_0",
"scale_1.tmp_1,save_infer_model/scale_2.tmp_1,save_infer_model/"
"scale_3.tmp_1",
"model output names"); "model output names");
DEFINE_string(model_cache_names, "5-1-1024,5-1-1024", "model cache names"); DEFINE_string(model_cache_names, "5-1-1024,5-1-1024", "model cache names");
@ -76,6 +78,7 @@ int main(int argc, char* argv[]) {
model_opts.model_path = model_path; model_opts.model_path = model_path;
model_opts.params_path = model_params; model_opts.params_path = model_params;
model_opts.cache_shape = FLAGS_model_cache_names; model_opts.cache_shape = FLAGS_model_cache_names;
model_opts.input_names = FLAGS_model_input_names;
model_opts.output_names = FLAGS_model_output_names; model_opts.output_names = FLAGS_model_output_names;
std::shared_ptr<ppspeech::PaddleNnet> nnet( std::shared_ptr<ppspeech::PaddleNnet> nnet(
new ppspeech::PaddleNnet(model_opts)); new ppspeech::PaddleNnet(model_opts));

@ -48,7 +48,6 @@ if [ ! -f $lm ]; then
popd popd
fi fi
feat_wspecifier=$exp_dir/feats.ark feat_wspecifier=$exp_dir/feats.ark
cmvn=$exp_dir/cmvn.ark cmvn=$exp_dir/cmvn.ark
@ -57,7 +56,7 @@ export GLOG_logtostderr=1
# dump json cmvn to kaldi # dump json cmvn to kaldi
cmvn-json2kaldi \ cmvn-json2kaldi \
--json_file $ckpt_dir/data/mean_std.json \ --json_file $ckpt_dir/data/mean_std.json \
--cmvn_write_path $exp_dir/cmvn.ark \ --cmvn_write_path $cmvn \
--binary=false --binary=false
echo "convert json cmvn to kaldi ark." echo "convert json cmvn to kaldi ark."
@ -66,7 +65,7 @@ echo "convert json cmvn to kaldi ark."
linear-spectrogram-wo-db-norm-ol \ linear-spectrogram-wo-db-norm-ol \
--wav_rspecifier=scp:$data/wav.scp \ --wav_rspecifier=scp:$data/wav.scp \
--feature_wspecifier=ark,t:$feat_wspecifier \ --feature_wspecifier=ark,t:$feat_wspecifier \
--cmvn_file=$exp_dir/cmvn.ark --cmvn_file=$cmvn
echo "compute linear spectrogram feature." echo "compute linear spectrogram feature."
# run ctc beam search decoder as streaming # run ctc beam search decoder as streaming

@ -37,10 +37,12 @@ DEFINE_int32(receptive_field_length,
DEFINE_int32(downsampling_rate, DEFINE_int32(downsampling_rate,
4, 4,
"two CNN(kernel=5) module downsampling rate."); "two CNN(kernel=5) module downsampling rate.");
DEFINE_string(
model_input_names,
"audio_chunk,audio_chunk_lens,chunk_state_h_box,chunk_state_c_box",
"model input names");
DEFINE_string(model_output_names, DEFINE_string(model_output_names,
"save_infer_model/scale_0.tmp_1,save_infer_model/" "softmax_0.tmp_0,tmp_5,concat_0.tmp_0,concat_1.tmp_0",
"scale_1.tmp_1,save_infer_model/scale_2.tmp_1,save_infer_model/"
"scale_3.tmp_1",
"model output names"); "model output names");
DEFINE_string(model_cache_names, "5-1-1024,5-1-1024", "model cache names"); DEFINE_string(model_cache_names, "5-1-1024,5-1-1024", "model cache names");
@ -79,6 +81,7 @@ int main(int argc, char* argv[]) {
model_opts.model_path = model_graph; model_opts.model_path = model_graph;
model_opts.params_path = model_params; model_opts.params_path = model_params;
model_opts.cache_shape = FLAGS_model_cache_names; model_opts.cache_shape = FLAGS_model_cache_names;
model_opts.input_names = FLAGS_model_input_names;
model_opts.output_names = FLAGS_model_output_names; model_opts.output_names = FLAGS_model_output_names;
std::shared_ptr<ppspeech::PaddleNnet> nnet( std::shared_ptr<ppspeech::PaddleNnet> nnet(
new ppspeech::PaddleNnet(model_opts)); new ppspeech::PaddleNnet(model_opts));

@ -9,4 +9,4 @@ target_link_libraries(${bin_name} frontend kaldi-util kaldi-feat-common gflags g
set(bin_name cmvn-json2kaldi) set(bin_name cmvn-json2kaldi)
add_executable(${bin_name} ${CMAKE_CURRENT_SOURCE_DIR}/${bin_name}.cc) add_executable(${bin_name} ${CMAKE_CURRENT_SOURCE_DIR}/${bin_name}.cc)
target_include_directories(${bin_name} PRIVATE ${SPEECHX_ROOT} ${SPEECHX_ROOT}/kaldi) target_include_directories(${bin_name} PRIVATE ${SPEECHX_ROOT} ${SPEECHX_ROOT}/kaldi)
target_link_libraries(${bin_name} utils kaldi-util kaldi-matrix gflags glog) target_link_libraries(${bin_name} utils kaldi-util kaldi-matrix gflags glog ${DEPS})

@ -14,18 +14,20 @@
// Note: Do not print/log ondemand object. // Note: Do not print/log ondemand object.
#include "base/common.h"
#include "base/flags.h" #include "base/flags.h"
#include "base/log.h" #include "base/log.h"
#include "kaldi/matrix/kaldi-matrix.h" #include "kaldi/matrix/kaldi-matrix.h"
#include "kaldi/util/kaldi-io.h" #include "kaldi/util/kaldi-io.h"
#include "utils/file_utils.h" #include "utils/file_utils.h"
#include "utils/simdjson.h" // #include "boost/json.hpp"
#include <boost/json/src.hpp>
DEFINE_string(json_file, "", "cmvn json file"); DEFINE_string(json_file, "", "cmvn json file");
DEFINE_string(cmvn_write_path, "./cmvn.ark", "write cmvn"); DEFINE_string(cmvn_write_path, "./cmvn.ark", "write cmvn");
DEFINE_bool(binary, true, "write cmvn in binary (true) or text(false)"); DEFINE_bool(binary, true, "write cmvn in binary (true) or text(false)");
using namespace simdjson; using namespace boost::json; // from <boost/json.hpp>
int main(int argc, char* argv[]) { int main(int argc, char* argv[]) {
gflags::ParseCommandLineFlags(&argc, &argv, false); gflags::ParseCommandLineFlags(&argc, &argv, false);
@ -33,49 +35,51 @@ int main(int argc, char* argv[]) {
LOG(INFO) << "cmvn josn path: " << FLAGS_json_file; LOG(INFO) << "cmvn josn path: " << FLAGS_json_file;
try { auto ifs = std::ifstream(FLAGS_json_file);
padded_string json = padded_string::load(FLAGS_json_file); std::string json_str = ppspeech::ReadFile2String(FLAGS_json_file);
auto value = boost::json::parse(json_str);
ondemand::parser parser; if (!value.is_object()) {
ondemand::document doc = parser.iterate(json); LOG(ERROR) << "Input json file format error.";
ondemand::value val = doc; }
ondemand::array mean_stat = val["mean_stat"]; for (auto obj : value.as_object()) {
std::vector<kaldi::BaseFloat> mean_stat_vec; if (obj.key() == "mean_stat") {
for (double x : mean_stat) { LOG(INFO) << "mean_stat:" << obj.value();
mean_stat_vec.push_back(x);
} }
// LOG(INFO) << mean_stat; this line will casue if (obj.key() == "var_stat") {
// simdjson::simdjson_error("Objects and arrays can only be iterated LOG(INFO) << "var_stat: " << obj.value();
// when
// they are first encountered")
ondemand::array var_stat = val["var_stat"];
std::vector<kaldi::BaseFloat> var_stat_vec;
for (double x : var_stat) {
var_stat_vec.push_back(x);
} }
if (obj.key() == "frame_num") {
kaldi::int32 frame_num = uint64_t(val["frame_num"]); LOG(INFO) << "frame_num: " << obj.value();
LOG(INFO) << "nframe: " << frame_num;
size_t mean_size = mean_stat_vec.size();
kaldi::Matrix<double> cmvn_stats(2, mean_size + 1);
for (size_t idx = 0; idx < mean_size; ++idx) {
cmvn_stats(0, idx) = mean_stat_vec[idx];
cmvn_stats(1, idx) = var_stat_vec[idx];
} }
cmvn_stats(0, mean_size) = frame_num; }
LOG(INFO) << cmvn_stats;
boost::json::array mean_stat = value.at("mean_stat").as_array();
std::vector<kaldi::BaseFloat> mean_stat_vec;
for (auto it = mean_stat.begin(); it != mean_stat.end(); it++) {
mean_stat_vec.push_back(it->as_double());
}
kaldi::WriteKaldiObject( boost::json::array var_stat = value.at("var_stat").as_array();
cmvn_stats, FLAGS_cmvn_write_path, FLAGS_binary); std::vector<kaldi::BaseFloat> var_stat_vec;
LOG(INFO) << "cmvn stats have write into: " << FLAGS_cmvn_write_path; for (auto it = var_stat.begin(); it != var_stat.end(); it++) {
LOG(INFO) << "Binary: " << FLAGS_binary; var_stat_vec.push_back(it->as_double());
} catch (simdjson::simdjson_error& err) {
LOG(ERROR) << err.what();
} }
kaldi::int32 frame_num = uint64_t(value.at("frame_num").as_int64());
LOG(INFO) << "nframe: " << frame_num;
size_t mean_size = mean_stat_vec.size();
kaldi::Matrix<double> cmvn_stats(2, mean_size + 1);
for (size_t idx = 0; idx < mean_size; ++idx) {
cmvn_stats(0, idx) = mean_stat_vec[idx];
cmvn_stats(1, idx) = var_stat_vec[idx];
}
cmvn_stats(0, mean_size) = frame_num;
LOG(INFO) << cmvn_stats;
kaldi::WriteKaldiObject(cmvn_stats, FLAGS_cmvn_write_path, FLAGS_binary);
LOG(INFO) << "cmvn stats have write into: " << FLAGS_cmvn_write_path;
LOG(INFO) << "Binary: " << FLAGS_binary;
return 0; return 0;
} }

@ -2,6 +2,7 @@
import argparse import argparse
from collections import Counter from collections import Counter
def main(args): def main(args):
counter = Counter() counter = Counter()
with open(args.text, 'r') as fin, open(args.lexicon, 'w') as fout: with open(args.text, 'r') as fin, open(args.lexicon, 'w') as fout:
@ -20,21 +21,16 @@ def main(args):
fout.write(f"{word}\t{val}\n") fout.write(f"{word}\t{val}\n")
fout.flush() fout.flush()
if __name__ == '__main__': if __name__ == '__main__':
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(
description='text(line:utt1 中国 人) to lexiconline:中国 中 国).') description='text(line:utt1 中国 人) to lexiconline:中国 中 国).')
parser.add_argument( parser.add_argument(
'--has_key', '--has_key', default=True, help='text path, with utt or not')
default=True,
help='text path, with utt or not')
parser.add_argument( parser.add_argument(
'--text', '--text', required=True, help='text path. line: utt1 中国 人 or 中国 人')
required=True,
help='text path. line: utt1 中国 人 or 中国 人')
parser.add_argument( parser.add_argument(
'--lexicon', '--lexicon', required=True, help='lexicon path. line:中国 中 国')
required=True,
help='lexicon path. line:中国 中 国')
args = parser.parse_args() args = parser.parse_args()
print(args) print(args)

@ -1,15 +1,16 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
# modify from https://sites.google.com/site/homepageoffuyanwei/Home/remarksandexcellentdiscussion/page-2 # modify from https://sites.google.com/site/homepageoffuyanwei/Home/remarksandexcellentdiscussion/page-2
class Word: class Word:
def __init__(self,text = '',freq = 0): def __init__(self, text='', freq=0):
self.text = text self.text = text
self.freq = freq self.freq = freq
self.length = len(text) self.length = len(text)
class Chunk: class Chunk:
def __init__(self,w1,w2 = None,w3 = None): def __init__(self, w1, w2=None, w3=None):
self.words = [] self.words = []
self.words.append(w1) self.words.append(w1)
if w2: if w2:
@ -44,8 +45,8 @@ class Chunk:
sum += word.freq sum += word.freq
return sum return sum
class ComplexCompare:
class ComplexCompare:
def takeHightest(self, chunks, comparator): def takeHightest(self, chunks, comparator):
i = 1 i = 1
for j in range(1, len(chunks)): for j in range(1, len(chunks)):
@ -59,23 +60,27 @@ class ComplexCompare:
#以下四个函数是mmseg算法的四种过滤原则核心算法 #以下四个函数是mmseg算法的四种过滤原则核心算法
def mmFilter(self, chunks): def mmFilter(self, chunks):
def comparator(a,b): def comparator(a, b):
return a.totalWordLength() - b.totalWordLength() return a.totalWordLength() - b.totalWordLength()
return self.takeHightest(chunks, comparator) return self.takeHightest(chunks, comparator)
def lawlFilter(self,chunks): def lawlFilter(self, chunks):
def comparator(a,b): def comparator(a, b):
return a.averageWordLength() - b.averageWordLength() return a.averageWordLength() - b.averageWordLength()
return self.takeHightest(chunks,comparator)
def svmlFilter(self,chunks): return self.takeHightest(chunks, comparator)
def comparator(a,b):
def svmlFilter(self, chunks):
def comparator(a, b):
return b.standardDeviation() - a.standardDeviation() return b.standardDeviation() - a.standardDeviation()
return self.takeHightest(chunks, comparator) return self.takeHightest(chunks, comparator)
def logFreqFilter(self,chunks): def logFreqFilter(self, chunks):
def comparator(a,b): def comparator(a, b):
return a.wordFrequency() - b.wordFrequency() return a.wordFrequency() - b.wordFrequency()
return self.takeHightest(chunks, comparator) return self.takeHightest(chunks, comparator)
@ -83,6 +88,7 @@ class ComplexCompare:
dictWord = {} dictWord = {}
maxWordLength = 0 maxWordLength = 0
def loadDictChars(filepath): def loadDictChars(filepath):
global maxWordLength global maxWordLength
fsock = open(filepath) fsock = open(filepath)
@ -90,18 +96,22 @@ def loadDictChars(filepath):
freq, word = line.split() freq, word = line.split()
word = word.strip() word = word.strip()
dictWord[word] = (len(word), int(freq)) dictWord[word] = (len(word), int(freq))
maxWordLength = len(word) if maxWordLength < len(word) else maxWordLength maxWordLength = len(word) if maxWordLength < len(
word) else maxWordLength
fsock.close() fsock.close()
def loadDictWords(filepath): def loadDictWords(filepath):
global maxWordLength global maxWordLength
fsock = open(filepath) fsock = open(filepath)
for line in fsock.readlines(): for line in fsock.readlines():
word = line.strip() word = line.strip()
dictWord[word] = (len(word), 0) dictWord[word] = (len(word), 0)
maxWordLength = len(word) if maxWordLength < len(word) else maxWordLength maxWordLength = len(word) if maxWordLength < len(
word) else maxWordLength
fsock.close() fsock.close()
#判断该词word是否在字典dictWord中 #判断该词word是否在字典dictWord中
def getDictWord(word): def getDictWord(word):
result = dictWord.get(word) result = dictWord.get(word)
@ -109,14 +119,15 @@ def getDictWord(word):
return Word(word, result[1]) return Word(word, result[1])
return None return None
#开始加载字典 #开始加载字典
def run(): def run():
from os.path import join, dirname from os.path import join, dirname
loadDictChars(join(dirname(__file__), 'data', 'chars.dic')) loadDictChars(join(dirname(__file__), 'data', 'chars.dic'))
loadDictWords(join(dirname(__file__), 'data', 'words.dic')) loadDictWords(join(dirname(__file__), 'data', 'words.dic'))
class Analysis:
class Analysis:
def __init__(self, text): def __init__(self, text):
self.text = text self.text = text
self.cacheSize = 3 self.cacheSize = 3
@ -134,11 +145,10 @@ class Analysis:
if not dictWord: if not dictWord:
run() run()
def __iter__(self): def __iter__(self):
while True: while True:
token = self.getNextToken() token = self.getNextToken()
if token == None: if token is None:
raise StopIteration raise StopIteration
yield token yield token
@ -146,7 +156,7 @@ class Analysis:
return self.text[self.pos] return self.text[self.pos]
#判断该字符是否是中文字符(不包括中文标点) #判断该字符是否是中文字符(不包括中文标点)
def isChineseChar(self,charater): def isChineseChar(self, charater):
return 0x4e00 <= ord(charater) < 0x9fa6 return 0x4e00 <= ord(charater) < 0x9fa6
#判断是否是ASCII码 #判断是否是ASCII码
@ -163,8 +173,8 @@ class Analysis:
while self.pos < self.textLength: while self.pos < self.textLength:
if self.isChineseChar(self.getNextChar()): if self.isChineseChar(self.getNextChar()):
token = self.getChineseWords() token = self.getChineseWords()
else : else:
token = self.getASCIIWords()+'/' token = self.getASCIIWords() + '/'
if len(token) > 0: if len(token) > 0:
return token return token
return None return None
@ -211,7 +221,7 @@ class Analysis:
chunks = self.complexCompare.svmlFilter(chunks) chunks = self.complexCompare.svmlFilter(chunks)
if len(chunks) > 1: if len(chunks) > 1:
chunks = self.complexCompare.logFreqFilter(chunks) chunks = self.complexCompare.logFreqFilter(chunks)
if len(chunks) == 0 : if len(chunks) == 0:
return '' return ''
#最后只有一种切割方法 #最后只有一种切割方法
@ -242,13 +252,13 @@ class Analysis:
for word3 in words3: for word3 in words3:
# print(word3.length, word3.text) # print(word3.length, word3.text)
if word3.length == -1: if word3.length == -1:
chunk = Chunk(word1,word2) chunk = Chunk(word1, word2)
# print("Ture") # print("Ture")
else : else:
chunk = Chunk(word1,word2,word3) chunk = Chunk(word1, word2, word3)
chunks.append(chunk) chunks.append(chunk)
elif self.pos == self.textLength: elif self.pos == self.textLength:
chunks.append(Chunk(word1,word2)) chunks.append(Chunk(word1, word2))
self.pos -= len(word2.text) self.pos -= len(word2.text)
elif self.pos == self.textLength: elif self.pos == self.textLength:
chunks.append(Chunk(word1)) chunks.append(Chunk(word1))
@ -268,7 +278,7 @@ class Analysis:
words = [] words = []
index = 0 index = 0
while self.pos < self.textLength: while self.pos < self.textLength:
if index >= maxWordLength : if index >= maxWordLength:
break break
if not self.isChineseChar(self.getNextChar()): if not self.isChineseChar(self.getNextChar()):
break break
@ -288,18 +298,18 @@ class Analysis:
word.text = 'X' word.text = 'X'
words.append(word) words.append(word)
self.cache[self.cacheIndex] = (self.pos,words) self.cache[self.cacheIndex] = (self.pos, words)
self.cacheIndex += 1 self.cacheIndex += 1
if self.cacheIndex >= self.cacheSize: if self.cacheIndex >= self.cacheSize:
self.cacheIndex = 0 self.cacheIndex = 0
return words return words
if __name__=="__main__": if __name__ == "__main__":
def cuttest(text): def cuttest(text):
#cut = Analysis(text) #cut = Analysis(text)
tmp="" tmp = ""
try: try:
for word in iter(Analysis(text)): for word in iter(Analysis(text)):
tmp += word tmp += word
@ -375,6 +385,8 @@ if __name__=="__main__":
cuttest(u"好人使用了它就可以解决一些问题") cuttest(u"好人使用了它就可以解决一些问题")
cuttest(u"是因为和国家") cuttest(u"是因为和国家")
cuttest(u"老年搜索还支持") cuttest(u"老年搜索还支持")
cuttest(u"干脆就把那部蒙人的闲法给废了拉倒RT @laoshipukong : 27日全国人大常委会第三次审议侵权责任法草案删除了有关医疗损害责任“举证倒置”的规定。在医患纠纷中本已处于弱势地位的消费者由此将陷入万劫不复的境地。 ") cuttest(
u"干脆就把那部蒙人的闲法给废了拉倒RT @laoshipukong : 27日全国人大常委会第三次审议侵权责任法草案删除了有关医疗损害责任“举证倒置”的规定。在医患纠纷中本已处于弱势地位的消费者由此将陷入万劫不复的境地。 "
)
cuttest("2022年12月30日是星期几") cuttest("2022年12月30日是星期几")
cuttest("二零二二年十二月三十日是星期几?") cuttest("二零二二年十二月三十日是星期几?")

@ -26,9 +26,9 @@ import argparse
import os import os
import re import re
import subprocess import subprocess
from distutils.util import strtobool
import numpy as np import numpy as np
from distutils.util import strtobool
FILE_IDS = re.compile(r"(?<=Speaker Diarization for).+(?=\*\*\*)") FILE_IDS = re.compile(r"(?<=Speaker Diarization for).+(?=\*\*\*)")
SCORED_SPEAKER_TIME = re.compile(r"(?<=SCORED SPEAKER TIME =)[\d.]+") SCORED_SPEAKER_TIME = re.compile(r"(?<=SCORED SPEAKER TIME =)[\d.]+")

File diff suppressed because it is too large Load Diff

@ -1,11 +1,21 @@
import os # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse import argparse
import jsonlines import jsonlines
def trans_hyp(origin_hyp, def trans_hyp(origin_hyp, trans_hyp=None, trans_hyp_sclite=None):
trans_hyp = None,
trans_hyp_sclite = None):
""" """
Args: Args:
origin_hyp: The input json file which contains the model output origin_hyp: The input json file which contains the model output
@ -24,12 +34,11 @@ def trans_hyp(origin_hyp,
if trans_hyp_sclite is not None: if trans_hyp_sclite is not None:
with open(trans_hyp_sclite, "w+") as f: with open(trans_hyp_sclite, "w+") as f:
for key in input_dict.keys(): for key in input_dict.keys():
line = input_dict[key] + "(" + key + ".wav" +")" + "\n" line = input_dict[key] + "(" + key + ".wav" + ")" + "\n"
f.write(line) f.write(line)
def trans_ref(origin_ref,
trans_ref = None, def trans_ref(origin_ref, trans_ref=None, trans_ref_sclite=None):
trans_ref_sclite = None):
""" """
Args: Args:
origin_hyp: The input json file which contains the model output origin_hyp: The input json file which contains the model output
@ -49,42 +58,48 @@ def trans_ref(origin_ref,
if trans_ref_sclite is not None: if trans_ref_sclite is not None:
with open(trans_ref_sclite, "w") as f: with open(trans_ref_sclite, "w") as f:
for key in input_dict.keys(): for key in input_dict.keys():
line = input_dict[key] + "(" + key + ".wav" +")" + "\n" line = input_dict[key] + "(" + key + ".wav" + ")" + "\n"
f.write(line) f.write(line)
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser(prog='format hyp file for compute CER/WER', add_help=True) parser = argparse.ArgumentParser(
prog='format hyp file for compute CER/WER', add_help=True)
parser.add_argument( parser.add_argument(
'--origin_hyp', '--origin_hyp', type=str, default=None, help='origin hyp file')
type=str,
default = None,
help='origin hyp file')
parser.add_argument( parser.add_argument(
'--trans_hyp', type=str, default = None, help='hyp file for caculating CER/WER') '--trans_hyp',
type=str,
default=None,
help='hyp file for caculating CER/WER')
parser.add_argument( parser.add_argument(
'--trans_hyp_sclite', type=str, default = None, help='hyp file for caculating CER/WER by sclite') '--trans_hyp_sclite',
type=str,
default=None,
help='hyp file for caculating CER/WER by sclite')
parser.add_argument( parser.add_argument(
'--origin_ref', '--origin_ref', type=str, default=None, help='origin ref file')
type=str,
default = None,
help='origin ref file')
parser.add_argument( parser.add_argument(
'--trans_ref', type=str, default = None, help='ref file for caculating CER/WER') '--trans_ref',
type=str,
default=None,
help='ref file for caculating CER/WER')
parser.add_argument( parser.add_argument(
'--trans_ref_sclite', type=str, default = None, help='ref file for caculating CER/WER by sclite') '--trans_ref_sclite',
type=str,
default=None,
help='ref file for caculating CER/WER by sclite')
parser_args = parser.parse_args() parser_args = parser.parse_args()
if parser_args.origin_hyp is not None: if parser_args.origin_hyp is not None:
trans_hyp( trans_hyp(
origin_hyp = parser_args.origin_hyp, origin_hyp=parser_args.origin_hyp,
trans_hyp = parser_args.trans_hyp, trans_hyp=parser_args.trans_hyp,
trans_hyp_sclite = parser_args.trans_hyp_sclite, ) trans_hyp_sclite=parser_args.trans_hyp_sclite, )
if parser_args.origin_ref is not None: if parser_args.origin_ref is not None:
trans_ref( trans_ref(
origin_ref = parser_args.origin_ref, origin_ref=parser_args.origin_ref,
trans_ref = parser_args.trans_ref, trans_ref=parser_args.trans_ref,
trans_ref_sclite = parser_args.trans_ref_sclite, ) trans_ref_sclite=parser_args.trans_ref_sclite, )

@ -35,7 +35,7 @@ def main(args):
# used to filter polyphone and invalid word # used to filter polyphone and invalid word
lexicon_table = set() lexicon_table = set()
in_n = 0 # in lexicon word count in_n = 0 # in lexicon word count
out_n = 0 # out lexicon word cout out_n = 0 # out lexicon word cout
with open(args.in_lexicon, 'r') as fin, \ with open(args.in_lexicon, 'r') as fin, \
open(args.out_lexicon, 'w') as fout: open(args.out_lexicon, 'w') as fout:
for line in fin: for line in fin:
@ -82,7 +82,10 @@ def main(args):
lexicon_table.add(word) lexicon_table.add(word)
out_n += 1 out_n += 1
print(f"Filter lexicon by unit table: filter out {in_n - out_n}, {out_n}/{in_n}") print(
f"Filter lexicon by unit table: filter out {in_n - out_n}, {out_n}/{in_n}"
)
if __name__ == '__main__': if __name__ == '__main__':
parser = argparse.ArgumentParser( parser = argparse.ArgumentParser(

Loading…
Cancel
Save