online2-wav-nnet2-latgen-faster.cc File Reference
Include dependency graph for online2-wav-nnet2-latgen-faster.cc:

Go to the source code of this file.

Namespaces

 kaldi
 This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for mispronunciations detection tasks, the reference:
 

Functions

void GetDiagnosticsAndPrintOutput (const std::string &utt, const fst::SymbolTable *word_syms, const CompactLattice &clat, int64 *tot_num_frames, double *tot_like)
 
int main (int argc, char *argv[])
 

Function Documentation

◆ main()

int main ( int  argc,
char *  argv[] 
)

Definition at line 75 of file online2-wav-nnet2-latgen-faster.cc.

References DecodableNnet2OnlineOptions::acoustic_scale, fst::AcousticLatticeScale(), OnlineSilenceWeighting::Active(), SingleUtteranceNnet2Decoder::AdvanceDecoding(), OnlineSilenceWeighting::ComputeCurrentTraceback(), WaveData::Data(), OnlineNnet2DecodingConfig::decodable_opts, SingleUtteranceNnet2Decoder::Decoder(), SequentialTableReader< Holder >::Done(), SingleUtteranceNnet2Decoder::EndpointDetected(), SingleUtteranceNnet2Decoder::FinalizeDecoding(), kaldi::g_num_threads, ParseOptions::GetArg(), OnlineSilenceWeighting::GetDeltaWeights(), kaldi::GetDiagnosticsAndPrintOutput(), SingleUtteranceNnet2Decoder::GetLattice(), OnlineNnet2FeaturePipelineInfo::global_cmvn_stats_rxfilename, OnlineIvectorExtractionInfo::greedy_ivector_extractor, RandomAccessTableReader< Holder >::HasKey(), rnnlm::i, OnlineNnet2FeaturePipelineInfo::ivector_extractor_info, KALDI_ERR, KALDI_LOG, KALDI_WARN, SequentialTableReader< Holder >::Key(), SequentialTableReader< Holder >::Next(), ParseOptions::NumArgs(), OnlineTimer::OutputStats(), OnlineTimingStats::Print(), ParseOptions::PrintUsage(), AmNnet::Read(), ParseOptions::Read(), TransitionModel::Read(), fst::ReadFstKaldiGeneric(), kaldi::ReadKaldiObject(), OnlineNnet2DecodingConfig::Register(), ParseOptions::Register(), OnlineNnet2FeaturePipelineConfig::Register(), OnlineEndpointConfig::Register(), WaveData::SampFreq(), fst::ScaleLattice(), OnlineNnet2FeaturePipelineInfo::silence_weighting_config, Input::Stream(), OnlineIvectorExtractionInfo::use_most_recent_ivector, RandomAccessTableReader< Holder >::Value(), SequentialTableReader< Holder >::Value(), OnlineTimer::WaitUntil(), and TableWriter< Holder >::Write().

75  {
76  try {
77  using namespace kaldi;
78  using namespace fst;
79 
80  typedef kaldi::int32 int32;
81  typedef kaldi::int64 int64;
82 
83  const char *usage =
84  "Reads in wav file(s) and simulates online decoding with neural nets\n"
85  "(nnet2 setup), with optional iVector-based speaker adaptation and\n"
86  "optional endpointing. Note: some configuration values and inputs are\n"
87  "set via config files whose filenames are passed as options\n"
88  "\n"
89  "Usage: online2-wav-nnet2-latgen-faster [options] <nnet2-in> <fst-in> "
90  "<spk2utt-rspecifier> <wav-rspecifier> <lattice-wspecifier>\n"
91  "The spk2utt-rspecifier can just be <utterance-id> <utterance-id> if\n"
92  "you want to decode utterance by utterance.\n"
93  "See egs/rm/s5/local/run_online_decoding_nnet2.sh for example\n"
94  "See also online2-wav-nnet2-latgen-threaded\n";
95 
96  ParseOptions po(usage);
97 
98  std::string word_syms_rxfilename;
99 
100  OnlineEndpointConfig endpoint_config;
101 
102  // feature_config includes configuration for the iVector adaptation,
103  // as well as the basic features.
104  OnlineNnet2FeaturePipelineConfig feature_config;
105  OnlineNnet2DecodingConfig nnet2_decoding_config;
106 
107  BaseFloat chunk_length_secs = 0.05;
108  bool do_endpointing = false;
109  bool online = true;
110 
111  po.Register("chunk-length", &chunk_length_secs,
112  "Length of chunk size in seconds, that we process. Set to <= 0 "
113  "to use all input in one chunk.");
114  po.Register("word-symbol-table", &word_syms_rxfilename,
115  "Symbol table for words [for debug output]");
116  po.Register("do-endpointing", &do_endpointing,
117  "If true, apply endpoint detection");
118  po.Register("online", &online,
119  "You can set this to false to disable online iVector estimation "
120  "and have all the data for each utterance used, even at "
121  "utterance start. This is useful where you just want the best "
122  "results and don't care about online operation. Setting this to "
123  "false has the same effect as setting "
124  "--use-most-recent-ivector=true and --greedy-ivector-extractor=true "
125  "in the file given to --ivector-extraction-config, and "
126  "--chunk-length=-1.");
127  po.Register("num-threads-startup", &g_num_threads,
128  "Number of threads used when initializing iVector extractor.");
129 
130  feature_config.Register(&po);
131  nnet2_decoding_config.Register(&po);
132  endpoint_config.Register(&po);
133 
134  po.Read(argc, argv);
135 
136  if (po.NumArgs() != 5) {
137  po.PrintUsage();
138  return 1;
139  }
140 
141  std::string nnet2_rxfilename = po.GetArg(1),
142  fst_rxfilename = po.GetArg(2),
143  spk2utt_rspecifier = po.GetArg(3),
144  wav_rspecifier = po.GetArg(4),
145  clat_wspecifier = po.GetArg(5);
146 
147  OnlineNnet2FeaturePipelineInfo feature_info(feature_config);
148  if (!online) {
149  feature_info.ivector_extractor_info.use_most_recent_ivector = true;
150  feature_info.ivector_extractor_info.greedy_ivector_extractor = true;
151  chunk_length_secs = -1.0;
152  }
153 
154  Matrix<double> global_cmvn_stats;
155  if (feature_info.global_cmvn_stats_rxfilename != "")
156  ReadKaldiObject(feature_info.global_cmvn_stats_rxfilename,
157  &global_cmvn_stats);
158 
159  TransitionModel trans_model;
160  nnet2::AmNnet nnet;
161  {
162  bool binary;
163  Input ki(nnet2_rxfilename, &binary);
164  trans_model.Read(ki.Stream(), binary);
165  nnet.Read(ki.Stream(), binary);
166  }
167 
168  fst::Fst<fst::StdArc> *decode_fst = ReadFstKaldiGeneric(fst_rxfilename);
169 
170  fst::SymbolTable *word_syms = NULL;
171  if (word_syms_rxfilename != "")
172  if (!(word_syms = fst::SymbolTable::ReadText(word_syms_rxfilename)))
173  KALDI_ERR << "Could not read symbol table from file "
174  << word_syms_rxfilename;
175 
176  int32 num_done = 0, num_err = 0;
177  double tot_like = 0.0;
178  int64 num_frames = 0;
179 
180  SequentialTokenVectorReader spk2utt_reader(spk2utt_rspecifier);
181  RandomAccessTableReader<WaveHolder> wav_reader(wav_rspecifier);
182  CompactLatticeWriter clat_writer(clat_wspecifier);
183 
184  OnlineTimingStats timing_stats;
185 
186  for (; !spk2utt_reader.Done(); spk2utt_reader.Next()) {
187  std::string spk = spk2utt_reader.Key();
188  const std::vector<std::string> &uttlist = spk2utt_reader.Value();
189 
190  OnlineIvectorExtractorAdaptationState adaptation_state(
191  feature_info.ivector_extractor_info);
192  OnlineCmvnState cmvn_state(global_cmvn_stats);
193 
194  for (size_t i = 0; i < uttlist.size(); i++) {
195  std::string utt = uttlist[i];
196  if (!wav_reader.HasKey(utt)) {
197  KALDI_WARN << "Did not find audio for utterance " << utt;
198  num_err++;
199  continue;
200  }
201  const WaveData &wave_data = wav_reader.Value(utt);
202  // get the data for channel zero (if the signal is not mono, we only
203  // take the first channel).
204  SubVector<BaseFloat> data(wave_data.Data(), 0);
205 
206  OnlineNnet2FeaturePipeline feature_pipeline(feature_info);
207  feature_pipeline.SetAdaptationState(adaptation_state);
208  feature_pipeline.SetCmvnState(cmvn_state);
209 
210  OnlineSilenceWeighting silence_weighting(
211  trans_model,
212  feature_info.silence_weighting_config);
213 
214  SingleUtteranceNnet2Decoder decoder(nnet2_decoding_config,
215  trans_model,
216  nnet,
217  *decode_fst,
218  &feature_pipeline);
219  OnlineTimer decoding_timer(utt);
220 
221  BaseFloat samp_freq = wave_data.SampFreq();
222  int32 chunk_length;
223  if (chunk_length_secs > 0) {
224  chunk_length = int32(samp_freq * chunk_length_secs);
225  if (chunk_length == 0) chunk_length = 1;
226  } else {
227  chunk_length = std::numeric_limits<int32>::max();
228  }
229 
230  int32 samp_offset = 0;
231  std::vector<std::pair<int32, BaseFloat> > delta_weights;
232 
233  while (samp_offset < data.Dim()) {
234  int32 samp_remaining = data.Dim() - samp_offset;
235  int32 num_samp = chunk_length < samp_remaining ? chunk_length
236  : samp_remaining;
237 
238  SubVector<BaseFloat> wave_part(data, samp_offset, num_samp);
239  feature_pipeline.AcceptWaveform(samp_freq, wave_part);
240 
241  samp_offset += num_samp;
242  decoding_timer.WaitUntil(samp_offset / samp_freq);
243  if (samp_offset == data.Dim()) {
244  // no more input. flush out last frames
245  feature_pipeline.InputFinished();
246  }
247 
248  if (silence_weighting.Active() &&
249  feature_pipeline.IvectorFeature() != NULL) {
250  silence_weighting.ComputeCurrentTraceback(decoder.Decoder());
251  silence_weighting.GetDeltaWeights(
252  feature_pipeline.IvectorFeature()->NumFramesReady(),
253  &delta_weights);
254  feature_pipeline.IvectorFeature()->UpdateFrameWeights(
255  delta_weights);
256  }
257 
258  decoder.AdvanceDecoding();
259 
260  if (do_endpointing && decoder.EndpointDetected(endpoint_config))
261  break;
262  }
263  decoder.FinalizeDecoding();
264 
265  CompactLattice clat;
266  bool end_of_utterance = true;
267  decoder.GetLattice(end_of_utterance, &clat);
268 
269  GetDiagnosticsAndPrintOutput(utt, word_syms, clat,
270  &num_frames, &tot_like);
271 
272  decoding_timer.OutputStats(&timing_stats);
273 
274  // In an application you might avoid updating the adaptation state if
275  // you felt the utterance had low confidence. See lat/confidence.h
276  feature_pipeline.GetAdaptationState(&adaptation_state);
277  feature_pipeline.GetCmvnState(&cmvn_state);
278 
279  // we want to output the lattice with un-scaled acoustics.
280  BaseFloat inv_acoustic_scale =
281  1.0 / nnet2_decoding_config.decodable_opts.acoustic_scale;
282  ScaleLattice(AcousticLatticeScale(inv_acoustic_scale), &clat);
283 
284  clat_writer.Write(utt, clat);
285  KALDI_LOG << "Decoded utterance " << utt;
286  num_done++;
287  }
288  }
289  timing_stats.Print(online);
290 
291  KALDI_LOG << "Decoded " << num_done << " utterances, "
292  << num_err << " with errors.";
293  KALDI_LOG << "Overall likelihood per frame was " << (tot_like / num_frames)
294  << " per frame over " << num_frames << " frames.";
295  delete decode_fst;
296  delete word_syms; // will delete if non-NULL.
297  return (num_done != 0 ? 0 : 1);
298  } catch(const std::exception& e) {
299  std::cerr << e.what();
300  return -1;
301  }
302 } // main()
nnet2::DecodableNnet2OnlineOptions decodable_opts
This code computes Goodness of Pronunciation (GOP) and extracts phone-level pronunciation feature for...
Definition: chain.dox:20
class OnlineTimer is used to test real-time decoding algorithms and evaluate how long the decoding of...
Definition: online-timing.h:88
This configuration class is to set up OnlineNnet2FeaturePipelineInfo, which in turn is the configurat...
Fst< StdArc > * ReadFstKaldiGeneric(std::string rxfilename, bool throw_on_err)
Definition: kaldi-fst-io.cc:45
For an extended explanation of the framework of which grammar-fsts are a part, please see Support for...
Definition: graph.dox:21
int32 g_num_threads
Definition: kaldi-thread.cc:25
This class stores the adaptation state from the online iVector extractor, which can help you to initi...
void Read(std::istream &is, bool binary)
Definition: am-nnet.cc:39
A templated class for writing objects to an archive or script file; see The Table concept...
Definition: kaldi-table.h:368
kaldi::int32 int32
BaseFloat SampFreq() const
Definition: wave-reader.h:126
const Matrix< BaseFloat > & Data() const
Definition: wave-reader.h:124
void Register(OptionsItf *opts)
void GetDiagnosticsAndPrintOutput(const std::string &utt, const fst::SymbolTable *word_syms, const CompactLattice &clat, int64 *tot_num_frames, double *tot_like)
This class is responsible for storing configuration variables, objects and options for OnlineNnet2Fea...
void ReadKaldiObject(const std::string &filename, Matrix< float > *m)
Definition: kaldi-io.cc:832
Allows random access to a collection of objects in an archive or script file; see The Table concept...
Definition: kaldi-table.h:233
std::vector< std::vector< double > > AcousticLatticeScale(double acwt)
float BaseFloat
Definition: kaldi-types.h:29
The class ParseOptions is for parsing command-line options; see Parsing command-line options for more...
Definition: parse-options.h:36
void Print(bool online=true)
Here, if "online == false" we take into account that the setup was used in not-really-online mode whe...
You will instantiate this class when you want to decode a single utterance using the online-decoding ...
void ScaleLattice(const std::vector< std::vector< ScaleFloat > > &scale, MutableFst< ArcTpl< Weight > > *fst)
Scales the pairs of weights in LatticeWeight or CompactLatticeWeight by viewing the pair (a...
void Read(std::istream &is, bool binary)
Struct OnlineCmvnState stores the state of CMVN adaptation between utterances (but not the state of t...
A templated class for reading objects sequentially from an archive or script file; see The Table conc...
Definition: kaldi-table.h:287
#define KALDI_ERR
Definition: kaldi-error.h:147
#define KALDI_WARN
Definition: kaldi-error.h:150
fst::VectorFst< CompactLatticeArc > CompactLattice
Definition: kaldi-lattice.h:46
This class&#39;s purpose is to read in Wave files.
Definition: wave-reader.h:106
OnlineNnet2FeaturePipeline is a class that&#39;s responsible for putting together the various parts of th...
class OnlineTimingStats stores statistics from timing of online decoding, which will enable the Print...
Definition: online-timing.h:41
#define KALDI_LOG
Definition: kaldi-error.h:153
Represents a non-allocating general vector which can be defined as a sub-vector of higher-level vecto...
Definition: kaldi-vector.h:501