---
title: "kaidi-wasm学习笔记（一）的两个重要文件"
author: "haoningabc"
date: "2021-02-08T20:18:53Z"
tags: []
categories: ["开源软件"]
slug: "kaidi-wasm"
draft: false
lastmod: "2021-02-08T20:19:28Z"
id: 2519135
url: "https://haoningabc.iteye.com/blog/2519135"
---

最近在看kaldi-wasm 两个重要文件备份一下，总结以后再写： src/workers/asrWorker.js \[code="javascript"] import JSZip from 'jszip'; import kaldiJS from '../computations/kaldiJS'; import kaldiWasm from '../computations/kaldiJS.wasm'; import KaldiConfigParser from '../utils/kaldiConfigParser'; const kaldiModule = kaldiJS({ locateFile(path) { if (path.endsWith('.wasm')){ console.log("hao-asrWorer.js---kaldiJS:"+path); return kaldiWasm; } // if (path.endsWith('.wasm')) return kaldiJS; return path; }, }); const MODEL\_STORE = { NAME: 'models', KEY\_PATH: 'language', }; let asr = null; let parser = null; function mkdirExistOK(fileSystem, path) { console.log("hao:asrWorker.js---mkdirExistOK,path:" +path+",fileSystem:") console.log(fileSystem); try { //fileSystem.mkdir(path); fileSystem.mkdir(path); } catch (e) { console.log("hao--mkdirExistOK--error..$$$$$$$$$$$$$$$$$$$$"); if (e.code !== 'EEXIST') throw e; } } function initEMFS(fileSystem, modelName) { console.log("hao-asrWorker---initEMFS--fileSystem:"); console.log(fileSystem); mkdirExistOK(fileSystem, MODEL\_STORE.NAME); console.log("hao-asrWorker---initEMFS--MODEL\_STORE.NAME:"+MODEL\_STORE.NAME); fileSystem.mount(fileSystem.filesystems.IDBFS, {}, MODEL\_STORE.NAME); fileSystem.chdir(MODEL\_STORE.NAME); fileSystem.mkdir(modelName); fileSystem.chdir(modelName); console.log("hao-asrWorker---initEMFS--over."); } async function unzip(zipfile) { // console.log("hao-asrWorker---unzip--:"); // console.log(zipfile); const zip = new JSZip(); const unzipped = await zip.loadAsync(zipfile); return unzipped; } function dirname(path) { const dirs = path.match(/.\*\\//); if (dirs === null) return ''; // without trailing '/' return dirs\[0].slice(0, dirs\[0].length - 1); } function mkdirp(fileSystem, path) { console.log("hao-asrWorker-----mkdirp--path:"+path); console.log(fileSystem); const dirBoundary = '/'; const startIndex = path\[0] === dirBoundary ? 1 : 0; for (let i = startIndex; i &lt; path.length; i += 1) { if (path\[i] === dirBoundary) mkdirExistOK(fileSystem, path.slice(0, i)); } mkdirExistOK(fileSystem, path); } async function writeToFileSystem(fileSystem, path, fileObj) { console.log("asrWorker.js---writeToFileSystem---fileSystem:"); console.log(fileSystem); const content = await fileObj.async('arraybuffer'); console.log("content:"+content); try { //fileSystem.writeFile(path, new Uint8Array(content)); fileSystem.writeFile(path, new Uint8Array(content),function(err){ console.log("writefile-----error:"+err); }); console.log("asrWorker.js---writeToFileSystem---writeFile----over.path:"+fileSystem.cwd()+"/"+path); console.log("asrWorker.js---writeToFileSystem---isDir----models:"+fileSystem.isDir("/models")); console.log("asrWorker.js---writeToFileSystem---isDir:::"+fileSystem.isDir(fileSystem.cwd())); console.log("asrWorker.js---writeToFileSystem---final.mdl---isFile:"+fileSystem.isFile("final.mdl")); console.log("asrWorker.js---writeToFileSystem---end----------"); return; } catch (e) { console.log("hao---error:--&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;writeToFileSystem......&gt;"); if (e.code === 'ENOENT') { const dirName = dirname(path); mkdirp(fileSystem, dirName); // eslint-disable-next-line consistent-return return writeToFileSystem(fileSystem, path, fileObj); } throw e; } } var thisModule; async function loadToFS(modelName, zip) { // console.log("hao-asrWorker---loadToFS--begin----kaldiModule:"); // console.log(kaldiModule); console.log("hao-asrWorker---loadToFS---unzip begin") const unzipped = await unzip(zip); console.log("hao-asrWorker---loadToFS--unzip over...."); await kaldiModule.then( function(result){ console.log("hao---hao-asrWorker---loadToFS----kaldiModule.then:") console.log(result.FS); thisModule=result; initEMFS(thisModule.FS, modelName); }); //initEMFS(kaldiModule.FS, modelName); //const unzipped = await unzip(zip); //const unzipped = unzip(zip); // hack to wait for model saving on Emscripten fileSystem // unzipped.forEach does not allow to wait for end of async calls const files = Object.keys(unzipped.files); await Promise.all( files.map(async (file) =&gt; { console.log("asrWorker----loadToFS---Promise.all...files.map---&gt;"+file); const content = unzipped.file(file); if (content !== null) { //await writeToFileSystem(kaldiModule.FS, content.name, content); //await writeToFileSystem(thisModule.FS, content.name, content); console.log(" hao -----asrWorker----content.name---&gt;"+content.name); const cwd = thisModule.FS.cwd(); console.log(" hao------asrWorker-----cwd------&gt;"+cwd); await writeToFileSystem(thisModule.FS, content.name, content); } }) ); // } // ); // .then( // function(endResult){ // asr = startASR(endResult); // // asr = startASR(); // } // ); // asr = startASR(thisModule); console.log("asrWorker----loadToFS---end-----------------------&lt;"); return true; } /* * Assumes that we are in the directory with the requested model \*/ //function startASR() { // console.log("hao-asrWorker---startASR"); // parser = new KaldiConfigParser(kaldiModule.FS, kaldiModule.FS.cwd()); // const args = parser.createArgs(); // const cppArgs = args.reduce((wasmArgs, arg) =&gt; { // wasmArgs.push\_back(arg); // return wasmArgs; // }, new kaldiModule.StringList()); // return new kaldiModule.OnlineASR(cppArgs); //} //function startASR(asrModule) { function startASR() { console.log("hao-asrWorker---startASR----------&gt;thisModule.FS:"); console.log(thisModule.FS); //parser = new KaldiConfigParser(kaldiModule.FS, kaldiModule.FS.cwd()); parser = new KaldiConfigParser(thisModule.FS, thisModule.FS.cwd()); console.log("hao-asrWorker---startASR--------------------------&gt; cwd"); const args = parser.createArgs(); const cppArgs = args.reduce((wasmArgs, arg) =&gt; { wasmArgs.push\_back(arg); return wasmArgs; }, //new kaldiModule.StringList()); new thisModule.StringList()); //return new kaldiModule.OnlineASR(cppArgs); return new thisModule.OnlineASR(cppArgs); } const helper = { async init(msg) { console.log("hao-asrWoker---init:"+msg+",msg:"); console.log(msg); await loadToFS(msg.data.modelName, msg.data.zip); asr = startASR(); //asr = startASR(thisModule); }, async process(msg) { if (asr === null) throw new Error('ASR not ready'); const asrOutput = asr.processBuffer(msg.data.pcm); if (asrOutput === '') return null; return { isFinal: asrOutput.endsWith('\\n'), text: asrOutput.trim(), }; }, async samplerate() { if (parser === null) throw new Error('ASR not ready'); return parser.getSampleRate(); }, async reset() { if (asr === null) throw new Error('ASR not ready'); const asrOutput = asr.reset(); const result = { isFinal: asrOutput.endsWith('\\n'), text: asrOutput.trim(), }; return result; }, async terminate() { if (asr !== null) asr.delete(); asr = null; }, }; onmessage = (msg) =&gt; { const { command } = msg.data; const response = { command, ok: true }; if (command in helper) { helper\[command](msg) .then((value) =&gt; { response.value = value; }) .catch((e) =&gt; { response.ok = false; response.value = e; }) .finally(() =&gt; { postMessage(response); }); } else { response.ok = false; response.value = new Error(\`Unknown command '${command}'\`); postMessage(response); } }; \[/code] ./kaldi/src/online2bin/online2-tcp-nnet3-decode-faster-reorganized.cc \[code="c++"] // online2bin/online2-tcp-nnet3-decode-faster.cc // Copyright 2014 Johns Hopkins University (author: Daniel Povey) // 2016 Api.ai (Author: Ilya Platonov) // 2018 Polish-Japanese Academy of Information Technology (Author: Danijel Korzinek) // See ../../COPYING for clarification regarding multiple authors // // 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 // // THIS CODE IS PROVIDED \*AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED // WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // See the Apache 2 License for the specific language governing permissions and // limitations under the License. #include #include #include #include #include #include #include #include #include "feat/wave-reader.h" #include "online2/online-nnet3-decoding.h" #include "online2/online-nnet2-feature-pipeline.h" #include "online2/onlinebin-util.h" #include "online2/online-timing.h" #include "online2/online-endpoint.h" #include "fstext/fstext-lib.h" #include "lat/lattice-functions.h" #include "util/kaldi-thread.h" #include "nnet3/nnet-utils.h" namespace kaldi { class TcpServer { public: explicit TcpServer(int read\_timeout); ~TcpServer(); bool Listen(int32 port); // start listening on a given port int32 Accept(); // accept a client and return its descriptor // get more data and return false if end-of-stream bool ReadChunk(size\_t len); Vector GetChunk(); // get the data read by above method // write to accepted client bool Write(const std::string &msg); bool WriteLn(const std::string &msg, const std::string &eol = "\\n"); void Disconnect(); private: struct ::sockaddr\_in h\_addr\_; int32 server\_desc\_, client\_desc\_; int16 \*samp\_buf\_; size\_t buf\_len\_, has\_read\_; pollfd client\_set\_\[1]; int read\_timeout\_; }; std::string LatticeToString( const Lattice &lat, const fst::SymbolTable &word\_syms ) { LatticeWeight weight; std::vector alignment; std::vector words; GetLinearSymbolSequence(lat, &alignment, &words, &weight); std::ostringstream msg; for (size\_t i = 0; i &lt; words.size(); i++) { std::string s = word\_syms.Find(words\[i]); if (s.empty()) { KALDI\_WARN &lt;&lt; "Word-id " &lt;&lt; words\[i] &lt;&lt; " not in symbol table."; msg &lt;&lt; "&lt;#" &lt;&lt; std::to\_string(i) &lt;&lt; "&gt; "; } else { msg &lt;&lt; s &lt;&lt; " "; } } return msg.str(); } std::string GetTimeString(int32 t\_beg, int32 t\_end, BaseFloat time\_unit) { constexpr size\_t kBufferLen { 100 }; char buffer\[kBufferLen]; double t\_beg2 = t\_beg * time\_unit; double t\_end2 = t\_end * time\_unit; snprintf(buffer, kBufferLen, "%.2f %.2f", t\_beg2, t\_end2); return std::string(buffer); } int32 GetLatticeTimeSpan(const Lattice& lat) { std::vector times; LatticeStateTimes(lat, ×); return times.back(); } std::string LatticeToString( const CompactLattice &clat, const fst::SymbolTable &word\_syms ) { if (clat.NumStates() == 0) { KALDI\_WARN &lt;&lt; "Empty lattice."; return ""; } CompactLattice best\_path\_clat; CompactLatticeShortestPath(clat, &best\_path\_clat); Lattice best\_path\_lat; ConvertLattice(best\_path\_clat, &best\_path\_lat); return LatticeToString(best\_path\_lat, word\_syms); } struct OnlineASROptionParser: public ParseOptions { OnlineASROptionParser(); explicit OnlineASROptionParser(int argc, const char* const* argv); int Read(int, const char* const\*); // Members static constexpr const char \*usage = "Reads in audio from a network socket and performs online\\n" "decoding with neural nets (nnet3 setup), with iVector-based\\n" "speaker adaptation and endpointing.\\n" "Note: some configuration values and inputs are set via config\\n" "files whose filenames are passed as options\\n" "\\n" "Usage: online2-tcp-nnet3-decode-faster \[options] " " \\n"; // ASR stuff BaseFloat output\_period = 1; bool produce\_time = false; BaseFloat samp\_freq = 16000.0; OnlineEndpointConfig endpoint\_opts; OnlineNnet2FeaturePipelineConfig feature\_opts; nnet3::NnetSimpleLoopedComputationOptions decodable\_opts; LatticeFasterDecoderConfig decoder\_opts; std::string nnet3\_rxfilename; std::string fst\_rxfilename; std::string word\_syms\_filename; // TCP stuff BaseFloat chunk\_length\_secs = 0.18; int port\_num = 5050; int read\_timeout = 3; }; class OnlineASR { public: static constexpr const char eou {'\\n'}; static constexpr const char tmp\_eou {'\\r'}; explicit OnlineASR(int argc, const char \*const argv\[]); explicit OnlineASR(const std::vector &args); explicit OnlineASR(const OnlineASROptionParser& po); std::string ProcessBuffer(int16 \*, size\_t); std::string ProcessSTLVector(const std::vector&); std::string ProcessVector(const Vector&); std::string Reset(); ~OnlineASR(); private: BaseFloat samp\_freq; int32 frame\_offset {0}; int32 check\_period; int32 samp\_count {0}; bool produce\_time {false}; // Model related members nnet3::DecodableNnetSimpleLoopedInfo \*decodable\_info = nullptr; OnlineNnet2FeaturePipelineInfo \*feature\_info = nullptr; LatticeFasterDecoderConfig decoder\_opts; nnet3::NnetSimpleLoopedComputationOptions decodable\_opts; fst::Fst \*decode\_fst = nullptr; TransitionModel trans\_model; nnet3::AmNnetSimple am\_nnet; fst::SymbolTable \*word\_syms = nullptr; OnlineEndpointConfig endpoint\_opts; // Stream parameters OnlineNnet2FeaturePipeline \*feature\_pipeline = nullptr; SingleUtteranceNnet3Decoder \*decoder = nullptr; // Utterance parameters OnlineSilenceWeighting \*silence\_weighting = nullptr; std::vector &gt; delta\_weights; // private methods void InitClass(const OnlineASROptionParser& parser); void InitWords(const std::string& filename); void UpdateDecoder(const Vector&); std::string CheckDecoderOutput(); std::string PrependTimestamps(const std::string&); void ResetStreamDecoder(); void ResetUtteranceDecoder(); }; } // end kaldi namespace #ifndef \_\_EMSCRIPTEN\__ int main(int argc, const char* const* argv) { using kaldi::int32; using kaldi::int64; using kaldi::OnlineASR; using kaldi::OnlineASROptionParser; using kaldi::Vector; using kaldi::BaseFloat; using kaldi::TcpServer; OnlineASROptionParser po; try { po.Read(argc, argv); OnlineASR onlineASR(po); // ignore SIGPIPE to avoid crashing when socket forcefully disconnected signal(SIGPIPE, SIG\_IGN); size\_t chunk\_len = static\_cast(po.chunk\_length\_secs * po.samp\_freq); TcpServer server(po.read\_timeout); server.Listen(po.port\_num); while (true) { server.Accept(); bool eos {false}; while (!eos) { while (true) { eos = !server.ReadChunk(chunk\_len); if (eos) { std::string msg { onlineASR.Reset() }; KALDI\_VLOG(1) &lt;&lt; "EndOfAudio, sending message: " &lt;&lt; msg; server.Write(msg); server.Disconnect(); break; } Vector wave\_part = server.GetChunk(); std::string msg { onlineASR.ProcessVector(wave\_part) }; if (msg != "") { server.Write(msg); if (msg\[msg.length() - 1] == onlineASR.tmp\_eou) { KALDI\_VLOG(1) &lt;&lt; "Temporary transcript: " &lt;&lt; msg; } else { KALDI\_VLOG(1) &lt;&lt; "Endpoint, sending message: " &lt;&lt; msg; break; } } } } } } catch (const std::invalid\_argument& e) { po.PrintUsage(); return 1; } catch (const std::exception &e) { std::cerr &lt;&lt; e.what(); return -1; } } #else #include #include #include using std::vector; using kaldi::int16; using emscripten::val; using emscripten::class\_; using emscripten::optional\_override; using emscripten::register\_vector; /* Convert JS Int16Array to C++ std::vector without copy of data \*/ vector typed\_array\_to\_vector(const val &int16\_array) { unsigned int length = int16\_array\["length"].as(); vector vec(length); val memory = val::module\_property("HEAP16")\["buffer"]; val memoryView = val::global("Int16Array").new\_(memory, reinterpret\_cast(vec.data()), length); memoryView.call("set", int16\_array); return vec; } EMSCRIPTEN\_BINDINGS(asr) { class\_("OnlineASR") .constructor& &gt;() // Inject lambda before class method call to adapt I/O types .function("processBuffer", optional\_override( \[](kaldi::OnlineASR& self, const val& int16\_array) { vector vect\_array = typed\_array\_to\_vector(int16\_array); return self.ProcessSTLVector(vect\_array); }) ) .function("reset", &kaldi::OnlineASR::Reset) ; // Define JS class StringList to be understood as vector in C++ register\_vector("StringList"); } #endif namespace kaldi { TcpServer::TcpServer(int read\_timeout) { server\_desc_ = -1; client\_desc_ = -1; samp\_buf_ = NULL; buf\_len_ = 0; read\_timeout_ = 1000 * read\_timeout; } bool TcpServer::Listen(int32 port) { h\_addr\_.sin\_addr.s\_addr = INADDR\_ANY; h\_addr\_.sin\_port = htons(port); h\_addr\_.sin\_family = AF\_INET; server\_desc_ = socket(AF\_INET, SOCK\_STREAM, 0); if (server\_desc_ == -1) { KALDI\_ERR &lt;&lt; "Cannot create TCP socket!"; return false; } int32 flag = 1; int32 len = sizeof(int32); if (setsockopt(server\_desc\_, SOL\_SOCKET, SO\_REUSEADDR, &flag, len) == -1) { KALDI\_ERR &lt;&lt; "Cannot set socket options!"; return false; } if (bind(server\_desc\_, (struct sockaddr \*) &h\_addr\_, sizeof(h\_addr\_)) == -1) { KALDI\_ERR &lt;&lt; "Cannot bind to port: " &lt;&lt; port &lt;&lt; " (is it taken?)"; return false; } if (listen(server\_desc\_, 1) == -1) { KALDI\_ERR &lt;&lt; "Cannot listen on port!"; return false; } KALDI\_LOG &lt;&lt; "TcpServer: Listening on port: " &lt;&lt; port; return true; } TcpServer::~TcpServer() { Disconnect(); if (server\_desc_ != -1) close(server\_desc\_); delete\[] samp\_buf\_; } int32 TcpServer::Accept() { KALDI\_LOG &lt;&lt; "Waiting for client..."; socklen\_t len; len = sizeof(struct sockaddr); client\_desc_ = accept(server\_desc\_, (struct sockaddr \*) &h\_addr\_, &len); struct sockaddr\_storage addr; char ipstr\[20]; len = sizeof addr; getpeername(client\_desc\_, (struct sockaddr \*) &addr, &len); struct sockaddr\_in \*s = (struct sockaddr\_in \*) &addr; inet\_ntop(AF\_INET, &s-&gt;sin\_addr, ipstr, sizeof ipstr); client\_set\_\[0].fd = client\_desc\_; client\_set\_\[0].events = POLLIN; KALDI\_LOG &lt;&lt; "Accepted connection from: " &lt;&lt; ipstr; return client\_desc\_; } bool TcpServer::ReadChunk(size\_t len) { if (buf\_len_ != len) { buf\_len_ = len; delete\[] samp\_buf\_; samp\_buf_ = new int16\[len]; } ssize\_t ret; int poll\_ret; size\_t to\_read = len; has\_read_ = 0; while (to\_read &gt; 0) { poll\_ret = poll(client\_set\_, 1, read\_timeout\_); if (poll\_ret == 0) { KALDI\_WARN &lt;&lt; "Socket timeout! Disconnecting..."; break; } if (poll\_ret &lt; 0) { KALDI\_WARN &lt;&lt; "Socket error! Disconnecting..."; break; } ret = read(client\_desc\_, static\_cast(samp\_buf_ + has\_read\_), to\_read * sizeof(int16)); if (ret &lt;= 0) { KALDI\_WARN &lt;&lt; "Stream over..."; break; } to\_read -= ret / sizeof(int16); has\_read_ += ret / sizeof(int16); } return has\_read_ &gt; 0; } Vector TcpServer::GetChunk() { Vector buf; buf.Resize(static\_cast(has\_read\_)); for (int i = 0; i &lt; has\_read\_; i++) buf(i) = static\_cast(samp\_buf\_\[i]); return buf; } bool TcpServer::Write(const std::string &msg) { const char \*p = msg.c\_str(); size\_t to\_write = msg.size(); size\_t wrote = 0; while (to\_write &gt; 0) { ssize\_t ret = write(client\_desc\_, static\_cast(p + wrote), to\_write); if (ret &lt;= 0) return false; to\_write -= ret; wrote += ret; } return true; } bool TcpServer::WriteLn(const std::string &msg, const std::string &eol) { if (Write(msg)) return Write(eol); else return false; } void TcpServer::Disconnect() { if (client\_desc_ != -1) { close(client\_desc\_); client\_desc_ = -1; } } OnlineASROptionParser::OnlineASROptionParser(): ParseOptions{usage} { g\_num\_threads = 0; Register("samp-freq", &samp\_freq, "Sampling frequency of the input signal (coded as 16-bit slinear)."); Register("chunk-length", &chunk\_length\_secs, "Length of chunk size in seconds, that we process."); Register("output-period", &output\_period, "How often in seconds, do we check for changes in output."); Register("num-threads-startup", &g\_num\_threads, "Number of threads used when initializing iVector extractor."); Register("read-timeout", &read\_timeout, "Number of seconds of timout for TCP audio data to appear on the " "stream. Use -1 for blocking."); Register("port-num", &port\_num, "Portnumber the server will listen on."); Register("produce-time", &produce\_time, "Prepend begin/end times between endpoints (e.g. '5.46 6.81" " ', in seconds)"); endpoint\_opts.Register(this); feature\_opts.Register(this); decodable\_opts.Register(this); decoder\_opts.Register(this); } OnlineASROptionParser::OnlineASROptionParser(int argc, const char* const * argv): OnlineASROptionParser() { Read(argc, argv); } int OnlineASROptionParser::Read(int argc, const char* const* argv) { int read\_value = ParseOptions::Read(argc, argv); if (NumArgs() != 3) throw std::invalid\_argument("Wrong number of arguments\\n"); nnet3\_rxfilename = GetArg(1); fst\_rxfilename = GetArg(2); word\_syms\_filename = GetArg(3); return read\_value; } OnlineASR::OnlineASR(int argc, const char \*const argv\[]): OnlineASR(OnlineASROptionParser(argc, argv)) { } OnlineASR::OnlineASR(const std::vector &args) { // Convert args to const char* const * std::vector char\_array; char\_array.reserve(args.size()); for (int i = 0; i &lt; args.size(); ++i) char\_array.push\_back(const\_cast(args\[i].c\_str())); int argc { static\_cast(char\_array.size()) }; OnlineASROptionParser parser {argc, &char\_array\[0]}; InitClass(parser); } OnlineASR::OnlineASR(const OnlineASROptionParser& parser) { InitClass(parser); } void OnlineASR::InitClass(const OnlineASROptionParser& parser) { decodable\_opts = parser.decodable\_opts; decoder\_opts = parser.decoder\_opts; endpoint\_opts = parser.endpoint\_opts; samp\_freq = parser.samp\_freq; check\_period = static\_cast(samp\_freq * parser.output\_period); produce\_time = parser.produce\_time; feature\_info = new OnlineNnet2FeaturePipelineInfo(parser.feature\_opts); InitWords(parser.word\_syms\_filename); KALDI\_VLOG(1) &lt;&lt; "Loading AM..."; { bool binary; Input ki(parser.nnet3\_rxfilename, &binary); trans\_model.Read(ki.Stream(), binary); am\_nnet.Read(ki.Stream(), binary); SetBatchnormTestMode(true, &(am\_nnet.GetNnet())); SetDropoutTestMode(true, &(am\_nnet.GetNnet())); nnet3::CollapseModel(nnet3::CollapseModelConfig(), &(am\_nnet.GetNnet())); } KALDI\_VLOG(1) &lt;&lt; "Loading FST..."; decode\_fst = fst::ReadFstKaldiGeneric(parser.fst\_rxfilename); // this object contains precomputed stuff that is used by all decodable // objects. It takes a pointer to am\_nnet because if it has iVectors it has // to modify the nnet to accept iVectors at intervals. decodable\_info = new nnet3::DecodableNnetSimpleLoopedInfo(decodable\_opts, &am\_nnet); ResetStreamDecoder(); } void OnlineASR::ResetStreamDecoder() { frame\_offset = 0; delete feature\_pipeline; feature\_pipeline = new OnlineNnet2FeaturePipeline(\*feature\_info); delete decoder; decoder = new SingleUtteranceNnet3Decoder(decoder\_opts, trans\_model, \*decodable\_info, \*decode\_fst, feature\_pipeline); ResetUtteranceDecoder(); } void OnlineASR::InitWords(const std::string &filename) { if (!filename.empty()) if (!(word\_syms = fst::SymbolTable::ReadText(filename))) KALDI\_ERR &lt;&lt; "Could not read symbol table from file " &lt;&lt; filename; } void OnlineASR::ResetUtteranceDecoder() { decoder-&gt;InitDecoding(frame\_offset); delete silence\_weighting; silence\_weighting = new OnlineSilenceWeighting( trans\_model, feature\_info-&gt;silence\_weighting\_config, decodable\_opts.frame\_subsampling\_factor); delta\_weights = std::vector &gt;(); } std::string OnlineASR::ProcessBuffer(int16 \*samp\_buf, size\_t buf\_len) { Vector buf; buf.Resize(static\_cast(buf\_len)); for (int i = 0; i &lt; buf\_len; ++i) buf(i) = static\_cast(samp\_buf\[i]); return ProcessVector(buf); } std::string OnlineASR::ProcessVector(const Vector& buf) { UpdateDecoder(buf); return CheckDecoderOutput(); } void OnlineASR::UpdateDecoder(const Vector& buf) { feature\_pipeline-&gt;AcceptWaveform(samp\_freq, buf); samp\_count += buf.Dim(); if (silence\_weighting-&gt;Active() && feature\_pipeline-&gt;IvectorFeature() != NULL) { silence\_weighting-&gt;ComputeCurrentTraceback(decoder-&gt;Decoder()); silence\_weighting-&gt;GetDeltaWeights(feature\_pipeline-&gt;NumFramesReady(), frame\_offset * decodable\_opts.frame\_subsampling\_factor, &delta\_weights); feature\_pipeline-&gt;UpdateFrameWeights(delta\_weights); } decoder-&gt;AdvanceDecoding(); } std::string OnlineASR::CheckDecoderOutput() { if (decoder-&gt;EndpointDetected(endpoint\_opts)) { samp\_count %= check\_period; decoder-&gt;FinalizeDecoding(); frame\_offset += decoder-&gt;NumFramesDecoded(); CompactLattice lat; decoder-&gt;GetLattice(true, &lat); std::string msg = LatticeToString(lat, \*word\_syms); if (produce\_time) msg = PrependTimestamps(msg); ResetUtteranceDecoder(); return msg + eou; } // Force temporary result if (samp\_count &gt; check\_period) { samp\_count %= check\_period; if (decoder-&gt;NumFramesDecoded() &gt; 0) { Lattice lat; decoder-&gt;GetBestPath(false, &lat); TopSort(&lat); // for LatticeStateTimes(), std::string msg = LatticeToString(lat, \*word\_syms); if (produce\_time) { int32 frame\_subsampling { decodable\_opts.frame\_subsampling\_factor }; BaseFloat frame\_shift { feature\_info-&gt;FrameShiftInSeconds() }; int32 t\_beg = frame\_offset; int32 t\_end = frame\_offset + GetLatticeTimeSpan(lat); msg = GetTimeString(t\_beg, t\_end, frame\_shift * frame\_subsampling) + " " + msg; } return msg + tmp\_eou; } } return ""; } std::string OnlineASR::PrependTimestamps(const std::string& msg) { int32 frame\_subsampling { decodable\_opts.frame\_subsampling\_factor }; BaseFloat frame\_shift { feature\_info-&gt;FrameShiftInSeconds() }; int32 t\_beg = frame\_offset - decoder-&gt;NumFramesDecoded(); int32 t\_end = frame\_offset; return GetTimeString(t\_beg, t\_end, frame\_shift * frame\_subsampling) + " " + msg; } std::string OnlineASR::ProcessSTLVector(const std::vector& samp\_buf) { // cast input to float Vector buf; size\_t buf\_len = samp\_buf.size(); buf.Resize(static\_cast(buf\_len)); for (int i = 0; i &lt; buf\_len; ++i) buf(i) = static\_cast(samp\_buf\[i]); return ProcessVector(buf); } std::string OnlineASR::Reset() { feature\_pipeline-&gt;InputFinished(); decoder-&gt;AdvanceDecoding(); decoder-&gt;FinalizeDecoding(); std::string msg {""}; frame\_offset += decoder-&gt;NumFramesDecoded(); if (decoder-&gt;NumFramesDecoded() &gt; 0) { CompactLattice lat; decoder-&gt;GetLattice(true, &lat); msg = LatticeToString(lat, \*word\_syms); if (produce\_time) msg = PrependTimestamps(msg); } ResetStreamDecoder(); return msg + eou; } OnlineASR::~OnlineASR() { delete feature\_info; delete feature\_pipeline; delete decoder; delete decodable\_info; delete word\_syms; delete silence\_weighting; delete decode\_fst; } } // namespace kaldi \[/code]