【Moonshine Onnx版本 语音识别】

## 安装环境

bash 复制代码
pip install onnxruntime numpy tokenizers librosa modelscope huggingface-hub

## 下载模型

huggingface

!huggingface-cli download UsefulSensors/moonshine --allow_patterns 'onnx/base/*.onnx' --local-dir ./models/

下载tokenizer.json

!wget https://github.com/usefulsensors/moonshine/blob/main/moonshine/assets/tokenizer.json -P './models/onnx/base/'

modelscope

!modelscope download --model manyeyes/moonshine-base-en-onnx --local_dir ./models/

## 运行

python 复制代码
import os
import wave
import numpy as np
import tokenizers
import onnxruntime

class MoonshineOnnxModel:
    def __init__(self, models_dir):

        preprocess, encode, uncached_decode, cached_decode = [
            f"{models_dir}/{x}.onnx"
            for x in ["preprocess", "encode", "uncached_decode", "cached_decode"]
        ]
        self.preprocess = onnxruntime.InferenceSession(preprocess)
        self.encode = onnxruntime.InferenceSession(encode)
        self.uncached_decode = onnxruntime.InferenceSession(uncached_decode)
        self.cached_decode = onnxruntime.InferenceSession(cached_decode)
        self.tokenizer = tokenizers.Tokenizer.from_file(
            os.path.join(models_dir, "tokenizer.json")
        )
        print('Successfully Load Model.')

    def _generate(self, audio, max_len=None):
        "audio has to be a numpy array of shape [1, num_audio_samples]"
        if max_len is None:
            # max 6 tokens per second of audio
            max_len = int((audio.shape[-1] / 16_000) * 6)
        preprocessed = self.preprocess.run([], dict(args_0=audio))[0]
        seq_len = [preprocessed.shape[-2]]

        context = self.encode.run([], dict(args_0=preprocessed, args_1=seq_len))[0]
        inputs = [[1]]
        seq_len = [1]

        tokens = [1]
        logits, *cache = self.uncached_decode.run(
            [], dict(args_0=inputs, args_1=context, args_2=seq_len)
        )
        for i in range(max_len):
            next_token = logits.squeeze().argmax()
            tokens.extend([next_token])
            if next_token == 2:
                break

            seq_len[0] += 1
            inputs = [[next_token]]
            logits, *cache = self.cached_decode.run(
                [],
                dict(
                    args_0=inputs,
                    args_1=context,
                    args_2=seq_len,
                    **{f"args_{i+3}": x for i, x in enumerate(cache)},
                ),
            )
        return [tokens]

    def generate(self, audio_paths: list[str] | str, max_len=None):
        if isinstance(audio_paths, str):
            audio_paths = [audio_paths]

        audios = []
        for audio_path in audio_paths:
          with wave.open(audio_path) as f:
              params = f.getparams()
              assert (
                  params.nchannels == 1
                  and params.framerate == 16_000
                  and params.sampwidth == 2
              ), f"wave file should have 1 channel, 16KHz, and int16"
              audio = f.readframes(params.nframes)
          audio = np.frombuffer(audio, np.int16) / 32768.0
          audio = audio.astype(np.float32)[None, ...]
          audios.append(audio)

        audios = np.concatenate(audios, axis=0)
        tokens = self._generate(audios, max_len)
        texts = self.tokenizer.decode_batch(tokens)

        return texts


if __name__ == "__main__":
    model_dir = f"models/onnx/base/"
    client = MoonshineOnnxModel(model_dir)
    audio_path = "beckett.wav"
    text = client.generate(audio_path)
    print(text)
相关推荐
william️_Aaron18 小时前
语音识别核心模型的数学原理和公式
人工智能·语音识别
andyguo18 小时前
语音识别的速度革命:从 Whisper 到 Whisper-CTranslate2,我经历了什么?
人工智能·学习·ai·whisper·语音识别·xcode·ai测评
uncle_ll21 小时前
李宏毅NLP-9-语音转换
自然语言处理·nlp·语音识别·tts·语音变换
yergen21 小时前
【具身智能】本地实时语音识别kaldi在正点原子RK3588上部署
人工智能·语音识别
番茄老夫子1 天前
OpenAI推出的语音识别系统Whisper简析
人工智能·whisper·语音识别
Blossom.1181 天前
用一张“冰裂纹”石墨烯薄膜,让被动散热也能做 AI 推理——基于亚波长裂纹等离激元的零功耗温度-逻辑门
人工智能·深度学习·神经网络·目标检测·机器学习·机器人·语音识别
声网3 天前
从语音识别到智能助手:Voice Agent 的技术进化与交互变革丨Voice Agent 学习笔记
学习·交互·语音识别
自出洞来无敌手(曾令瑶)4 天前
浏览器 实时监听音量 实时语音识别 vue js
前端·javascript·vue.js·语音识别
biubiubiu07064 天前
微软云语音识别ASR示例Demo
人工智能·语音识别
唯创知音4 天前
玩具语音方案选型决策OTP vs Flash 的成本功耗与灵活性
人工智能·语音识别