【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)
相关推荐
智慧景区与市集主理人2 天前
巨有科技景区智能导览告别传统讲解,打造沉浸式智慧游览体验
人工智能·科技·语音识别
feifeigo1233 天前
基于隐马尔可夫模型(HMM)的孤立词语音识别系统
人工智能·语音识别·xcode
2601_958352903 天前
AP-0316 语音模块实测效果与能力边界展示
语音识别·硬件开发·ai降噪·音频处理模块
Luke Ewin3 天前
从零开始部署Fun-ASR-Nano实时语音识别并区分说话人教程 | 私有化部署开源的实时语音转写项目
人工智能·语音识别·funasr·实时语音识别·fun-asr
王文?问3 天前
ESP32-S3 实战教程:本地语音识别控制 Web 塔防游戏,从固件到前端完整跑通
前端·游戏·语音识别
瓷tun3 天前
小白也能懂:Qwen3-ASR-0.6B语音识别入门教程
语音识别·asr·qwen3·星图gpu
杜连涛3 天前
5分钟部署Whisper语音识别:多语言大模型一键启动Web服务
whisper·语音识别·ai应用·多语言处理
胡耀超3 天前
告别ModelScope魔搭联网依赖!sherpa-onnx + SenseVoice 完全离线语音识别部署指南(2026版,离线语音识别、声纹鉴定、sherpa-onnx、SenseVoice)
语音识别·funasr·语音转文字·sherpa-onnx·声纹鉴定·声纹比对·说话人识别
唯创知音3 天前
理疗仪语音控制芯片选型:离线语音识别模块方案对比
语音识别·离线语音识别芯片·理疗仪语音控制芯片选型
憨波个3 天前
【语音识别】Conformer: Convolution-augmented Transformer for Speech Recognition
人工智能·深度学习·transformer·语音识别