`
haoningabc
  • 浏览: 1446334 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

kaidi-wasm学习笔记(二)重构promise

阅读更多
kaldi-wasm/src/workers/asrWorker.js
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)
//  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 < 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:"+path);
  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:-->>>>>>>>>>>>>>>>>>>>>>>writeToFileSystem......>path--->"+path);
    console.log(e);
    console.log(e.code);
    if (e.code === 'ENOENT') {
    //if (e.errno == 44) {
      const dirName = dirname(path);

      console.log("hao---error:-->dirname--writeToFileSystem......>"+dirName);
      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) => {
        console.log("asrWorker----loadToFS---Promise.all...files.map--->"+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--->"+content.name);
          const cwd = thisModule.FS.cwd();
//          console.log(" hao------asrWorker-----cwd------>"+cwd);
          await writeToFileSystem(thisModule.FS, content.name, content);
        }
      })
  );

  //  }
 // );
   // .then(
   // function(endResult){
   //     asr = startASR(endResult);
   //    // asr = startASR();
   // }
   // );
//  asr = startASR(thisModule);
  console.log("asrWorker----loadToFS---end-----------------------<");
  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) => {
//    wasmArgs.push_back(arg);
//    return wasmArgs;
//  }, new kaldiModule.StringList());
//  return new kaldiModule.OnlineASR(cppArgs);
//}
//function startASR(asrModule) {
function startASR() {
  console.log("hao-asrWorker---startASR---------->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--------------------------> cwd");
  const args = parser.createArgs();
  const cppArgs = args.reduce((wasmArgs, arg) => {
    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) {
    console.log("hao--->asrWorker--->process---msg:");
    console.log(msg);
    if (asr === null) throw new Error('ASR not ready');
    const asrOutput = asr.processBuffer(msg.data.pcm);//pcm undefined
	console.log("hao--->asrWorker--->process:"+asrOutput);
    if (asrOutput === ''){
		console.log("hao:asrWorker.js ##############error this will null!!!!!!");
		return null;
	}
    return {
      isFinal: asrOutput.endsWith('\n'),
      text: asrOutput.trim(),
    };
  },
  async samplerate() {
    console.log("hao--->asrWorker---->samplerate:");
	console.log("parser:");
	console.log(parser);
    if (parser === null) throw new Error('ASR not ready');
	console.log(parser.getSampleRate());
    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) => {
  const { command } = msg.data;
  const response = { command, ok: true };

  if (command in helper) {
    helper[command](msg)
      .then((value) => { response.value = value; })
      .catch((e) => {
        response.ok = false;
        response.value = e;
      })
      .finally(() => { postMessage(response); });
  } else {
    response.ok = false;
    response.value = new Error(`Unknown command '${command}'`);
    postMessage(response);
  }
};


resamplerWorker.js

/* eslint-disable no-restricted-globals */
import resampleJS from '../computations/resampleTo16bint';
import resampleWasm from '../computations/resampleTo16bint.wasm';

let resample = () => {};
let outputInputSampleRateRatio = 1 / 3;

/* Webpack renames resources which makes the locateFile function inside
resampleJS break. The function below replaces locateFile so as to give the
right name when loading the wasm binary.
*/
const resampleMod = resampleJS({
  locateFile(path) {
	console.log("hao---------->resamplerWorker.js----------->locateFile resampleMod--->>>>>>");
    if (path.endsWith('.wasm')) return resampleWasm;
    return path;
  },
});
var thisresampleMod;
const helper = {
  //setConversionRatio(msg) {
  async setConversionRatio(msg) {
	await  resampleMod.then(
	    function(result){
	       console.log("hao--->>>>>resamplerWorker.js----thisresampleMod.then>>>>>>")
	       thisresampleMod=result;
		    thisresampleMod.init();
		//  resample = resampleMod.resampleTo16bint;
			resample = thisresampleMod.resampleTo16bint;
	       //initEMFS(thisModule.FS, modelName);
	    }
    );

	console.log("hao---------->resamplerWorker.js----------->helper-->setConversionRatio msg:");
	console.log(msg);
    outputInputSampleRateRatio = msg.data.conversionRatio;
    return outputInputSampleRateRatio;
  },
  async resample(msg) {
	console.log("hao---------->resamplerWorker.js----------->helper-->resample ,msg:");
	console.log(msg);
    return resample(msg.data.buffer, outputInputSampleRateRatio);
  },
  async reset() {
//    resampleMod.reset();
	thisresampleMod.reset();
    return '';
  },
  async terminate() {
	console.log("hao---------->resamplerWorker.js----------->helper-->terminate >>");
    //resampleMod.terminate();
    thisresampleMod.terminate();
    close();
    return '';
  },
};

onmessage = (msg) => {
  const { command } = msg.data;
  const response = { command, ok: true };
  if (command in helper) {
    helper[command](msg)
      .then((value) => { response.value = value; })
      .catch((e) => {
        response.ok = false;
        response.value = e;
      })
      .finally(() => { postMessage(response); });
  } else {
    response.ok = false;
    response.value = new Error(`Unknown command '${command}'`);
    postMessage(response);
  }
//  if (command in helper){
//		console.log("hao---------->resamplerWorker.js--->onmessage command:"+command)
//		response.value = helper[command](msg);
//  }
//  else {
//    response.ok = false;
//    response.value = new Error(`Unknown command '${command}'`);
//  }
//  postMessage(response);
};

//resampleMod.onRuntimeInitialized = () => {
//  console.log("hao---->resamplerWorker.js-->>>resampleMod.onRuntimeInitialized");
//  resampleMod.init();
//  resample = resampleMod.resampleTo16bint;
//};



分享到:
评论

相关推荐

    kaldi详细资料_kadi语音识别工具_

    语音识别工具kaldi及其应用,kaidi全部资料,适合新手使用

    comet:[ICLR 2021]少量学习的概念学习者

    凯迪(Kaidi Cao)*,玛丽亚(MariaBrbić)*,尤里(Jure Leskovec) 此存储库包含COMET算法的PyTorch中的参考源代码。 COMET是一种元学习方法,可沿人类可理解的概念维度学习可概括的表示形式。 有关更多详细信息...

    GCN_ADV_Train:图神经网络的对抗训练

    基于优化的GNN攻防在这项...(*平等贡献) @inproceedings{xu2019topology, title={Topology Attack and Defense for Graph Neural Networks: An Optimization Perspective}, author={Xu, Kaidi and Chen, Hongge and

    node_tasted:Node.js 浅尝辄止——分享至我仍未知道名字的十楼公司

    By Kaidi, ZHU, R&D Engineer of and . 正确打开姿势 预备工作:请确保已安装 Node.js 在你的电脑。 安装 依赖。执行 $ npm install。 启动它,执行 $ npm start 。 在弹出的浏览器窗口中点击 tasted.md 即可。 若非...

    单片机开发资源:基于51单片机的开发程序

    单片机开发资源,基于51单片机的开发程序,供学习参考。

    node-v9.4.0-linux-armv7l.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    基于固件库新建工程模板工程源码

    【工程源码】

    node-v9.1.0-linux-ppc64.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    node-v8.9.0-linux-armv7l.tar.xz

    Node.js,简称Node,是一个开源且跨平台的JavaScript运行时环境,它允许在浏览器外运行JavaScript代码。Node.js于2009年由Ryan Dahl创立,旨在创建高性能的Web服务器和网络应用程序。它基于Google Chrome的V8 JavaScript引擎,可以在Windows、Linux、Unix、Mac OS X等操作系统上运行。 Node.js的特点之一是事件驱动和非阻塞I/O模型,这使得它非常适合处理大量并发连接,从而在构建实时应用程序如在线游戏、聊天应用以及实时通讯服务时表现卓越。此外,Node.js使用了模块化的架构,通过npm(Node package manager,Node包管理器),社区成员可以共享和复用代码,极大地促进了Node.js生态系统的发展和扩张。 Node.js不仅用于服务器端开发。随着技术的发展,它也被用于构建工具链、开发桌面应用程序、物联网设备等。Node.js能够处理文件系统、操作数据库、处理网络请求等,因此,开发者可以用JavaScript编写全栈应用程序,这一点大大提高了开发效率和便捷性。 在实践中,许多大型企业和组织已经采用Node.js作为其Web应用程序的开发平台,如Netflix、PayPal和Walmart等。它们利用Node.js提高了应用性能,简化了开发流程,并且能更快地响应市场需求。

    2024-2030中国板端光伏连接器市场现状研究分析与发展前景预测报告.docx

    2024-2030中国板端光伏连接器市场现状研究分析与发展前景预测报告

    基于QT+C++实现的随机图形验证码,带有一些可人的交互与动画+源码

    用法链接:https://menghui666.blog.csdn.net/article/details/138544047?spm=1001.2014.3001.5502 基于QT+C++实现的随机图形验证码,带有一些可人的交互与动画+源码 基于QT+C++实现的随机图形验证码,带有一些可人的交互与动画+源码 基于QT+C++实现的随机图形验证码,带有一些可人的交互与动画+源码 该项目实现了可交互的动画验证码控件,趣味性十足: 字符变换动画 噪音动画 可拖动交互

    操作系统实验-基于uCore OS内含源码以及说明书可以自己运行复现.zip

    操作系统实验-基于uCore OS内含源码以及说明书可以自己运行复现.zip

    2024-2030中国半导体零件清洗机市场现状研究分析与发展前景预测报告.docx

    2024-2030中国半导体零件清洗机市场现状研究分析与发展前景预测报告

    python教程-04-获取和设置标签内容(innerHTML).ev4.rar

    python教程-04-获取和设置标签内容(innerHTML).ev4.rar

    Qt数据可视化多种实现

    s 气泡图 s 面积图 s 雷达图 s 玫瑰图 s 3D图表

    windows10开始菜单磁贴背景是灰色的

    去白底图标

    001 定期同步mysql数据到es 删除数据库记录同时删除es记录 es全文搜索分词和高亮

    001 定期同步mysql数据到es 删除数据库记录同时删除es记录 es全文搜索分词和高亮

    汉字点阵滚动指示牌源程序.rar

    单片机学习代码资料

Global site tag (gtag.js) - Google Analytics