【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)
相关推荐
烟雨江南7852 小时前
精度与速度的终极博弈:语音识别本地部署中的 INT8 量化与 TensorRT 插件级加速全流程
人工智能·语音识别
工作log2 小时前
10分钟搭建本地语音识别服务 (Whisper large-v3-turbo)
人工智能·whisper·语音识别
烟雨江南7852 小时前
苟富拒绝方言“滑铁卢”:语音识别本地部署中的领域增量微调(Fine-tuning)与样本自动标注全流程贵受到广泛发生过施工方
人工智能·语音识别
Prannt4 小时前
星朗智能语音识别——视频转文字
人工智能·音视频·语音识别
唯创知音1 天前
产后康复器械语音播报语音识别解决方案
人工智能·语音识别·产后康复器械·语音播报方案·语音方案
大龄程序员狗哥1 天前
第46篇:语音识别入门——让AI“听懂”人类语言(概念入门)
人工智能·语音识别
byte轻骑兵1 天前
【LE Audio】BASS精讲[5]: 状态特征解析,广播接收状态实时可视全流程
人工智能·算法·音视频·语音识别·le audio·低功耗音频
开开心心就好1 天前
支持批量添加水印的实用工具推荐
人工智能·游戏·ci/cd·docker·音视频·语音识别·媒体
shao9185161 天前
第11章 Streaming(中):高级音频应用(1)——项目六:语音克隆、变声器与文本转录器
语音识别·tts·语音克隆·elevenlabs·stt·变声器·音乐api
俊基科技1 天前
PI‑36 双麦降噪拾音模块|医院高清语音解决方案
人工智能·语音识别